diff --git a/.clang-format b/.clang-format new file mode 100644 index 0000000000000000000000000000000000000000..1bdc80ff8929a640ee9753cb3249805508b9259b --- /dev/null +++ b/.clang-format @@ -0,0 +1,133 @@ +--- +Language: Cpp +# BasedOnStyle: LLVM +AccessModifierOffset: -4 +AlignAfterOpenBracket: Align +AlignConsecutiveMacros: false +AlignConsecutiveAssignments: true +AlignConsecutiveDeclarations: false +AlignEscapedNewlines: Right +AlignOperands: true +AlignTrailingComments: true +AllowAllArgumentsOnNextLine: true +AllowAllConstructorInitializersOnNextLine: true +AllowAllParametersOfDeclarationOnNextLine: true +AllowShortBlocksOnASingleLine: Never +AllowShortCaseLabelsOnASingleLine: false +AllowShortFunctionsOnASingleLine: All +AllowShortLambdasOnASingleLine: All +AllowShortIfStatementsOnASingleLine: Never +AllowShortLoopsOnASingleLine: false +AlwaysBreakAfterDefinitionReturnType: None +AlwaysBreakAfterReturnType: None +AlwaysBreakBeforeMultilineStrings: false +AlwaysBreakTemplateDeclarations: Yes +BinPackArguments: true +BinPackParameters: true +BraceWrapping: + AfterCaseLabel: false + AfterClass: true + AfterControlStatement: Never + AfterEnum: false + AfterFunction: true + AfterNamespace: false + AfterObjCDeclaration: false + AfterStruct: true + AfterUnion: true + AfterExternBlock: false + BeforeCatch: false + BeforeElse: false + IndentBraces: false + SplitEmptyFunction: true + SplitEmptyRecord: true + SplitEmptyNamespace: true +BreakBeforeBinaryOperators: None +BreakBeforeBraces: Linux +BreakBeforeInheritanceComma: false +BreakInheritanceList: BeforeColon +BreakBeforeTernaryOperators: true +BreakConstructorInitializersBeforeComma: false +BreakConstructorInitializers: BeforeColon +BreakAfterJavaFieldAnnotations: false +BreakStringLiterals: true +ColumnLimit: 120 +CommentPragmas: '^ IWYU pragma:' +CompactNamespaces: false +ConstructorInitializerAllOnOneLineOrOnePerLine: false +ConstructorInitializerIndentWidth: 4 +ContinuationIndentWidth: 4 +Cpp11BracedListStyle: false +DeriveLineEnding: true +DerivePointerAlignment: false +DisableFormat: false +ExperimentalAutoDetectBinPacking: false +FixNamespaceComments: true +ForEachMacros: + - foreach + - Q_FOREACH + - BOOST_FOREACH +IncludeBlocks: Preserve +IncludeCategories: + - Regex: '^"(llvm|llvm-c|clang|clang-c)/' + Priority: 2 + SortPriority: 0 + - Regex: '^(<|"(gtest|gmock|isl|json)/)' + Priority: 3 + SortPriority: 0 + - Regex: '.*' + Priority: 1 + SortPriority: 0 +IncludeIsMainRegex: '(Test)?$' +IncludeIsMainSourceRegex: '' +IndentCaseLabels: true +IndentGotoLabels: true +IndentPPDirectives: None +IndentWidth: 4 +IndentWrappedFunctionNames: false +JavaScriptQuotes: Leave +JavaScriptWrapImports: true +KeepEmptyLinesAtTheStartOfBlocks: true +MacroBlockBegin: '' +MacroBlockEnd: '' +MaxEmptyLinesToKeep: 1 +NamespaceIndentation: None +PenaltyBreakAssignment: 2 +PenaltyBreakBeforeFirstCallParameter: 19 +PenaltyBreakComment: 300 +PenaltyBreakFirstLessLess: 120 +PenaltyBreakString: 1000 +PenaltyBreakTemplateDeclaration: 10 +PenaltyExcessCharacter: 1000000 +PenaltyReturnTypeOnItsOwnLine: 60 +PointerAlignment: Right +ReflowComments: true +SortIncludes: true +SortUsingDeclarations: true +SpaceAfterCStyleCast: false +SpaceAfterLogicalNot: false +SpaceAfterTemplateKeyword: true +SpaceBeforeAssignmentOperators: true +SpaceBeforeCpp11BracedList: false +SpaceBeforeCtorInitializerColon: true +SpaceBeforeInheritanceColon: true +SpaceBeforeParens: ControlStatements +SpaceBeforeRangeBasedForLoopColon: true +SpaceInEmptyBlock: false +SpaceInEmptyParentheses: false +SpacesBeforeTrailingComments: 1 +SpacesInAngles: false +SpacesInConditionalStatement: false +SpacesInContainerLiterals: true +SpacesInCStyleCastParentheses: false +SpacesInParentheses: false +SpacesInSquareBrackets: false +SpaceBeforeSquareBrackets: false +Standard: Latest +StatementMacros: + - Q_UNUSED + - QT_REQUIRE_VERSION +TabWidth: 4 +UseCRLF: false +UseTab: Never +... + diff --git a/3rdParty/metis/metis-5.1.1/libmetis/CMakeLists.txt b/3rdParty/metis/metis-5.1.1/libmetis/CMakeLists.txt index 4732b645ea354ada4a61540e12f73bff90540cb5..356afd750e7bd9aa19f536a6f31bbc29f85bf890 100644 --- a/3rdParty/metis/metis-5.1.1/libmetis/CMakeLists.txt +++ b/3rdParty/metis/metis-5.1.1/libmetis/CMakeLists.txt @@ -6,6 +6,8 @@ file(GLOB metis_sources *.c) add_library(metis ${METIS_LIBRARY_TYPE} ${GKlib_sources} ${metis_sources}) if(UNIX) target_link_libraries(metis m) + + target_compile_options(metis PRIVATE "-Wno-format") endif() if(MSVC) diff --git a/src/basics/Core/ArrayTypes.h b/src/basics/Core/ArrayTypes.h index 2e50298ce5ba8ceb6b27743eb1842427c89a3af1..7d5d70374b04d7ad29a6443fbcac0263fd8d0ad6 100644 --- a/src/basics/Core/ArrayTypes.h +++ b/src/basics/Core/ArrayTypes.h @@ -5,58 +5,58 @@ #include "DataTypes.h" -typedef std::array< uint, 2 > uint_2 ; -typedef std::array< uint, 3 > uint_3 ; -typedef std::array< uint, 4 > uint_4 ; -typedef std::array< uint, 5 > uint_5 ; -typedef std::array< uint, 6 > uint_6 ; -typedef std::array< uint, 7 > uint_7 ; -typedef std::array< uint, 8 > uint_8 ; -typedef std::array< uint, 9 > uint_9 ; -typedef std::array< uint, 10 > uint_10; -typedef std::array< uint, 11 > uint_11; -typedef std::array< uint, 12 > uint_12; -typedef std::array< uint, 13 > uint_13; -typedef std::array< uint, 14 > uint_14; -typedef std::array< uint, 15 > uint_15; -typedef std::array< uint, 16 > uint_16; -typedef std::array< uint, 17 > uint_17; -typedef std::array< uint, 18 > uint_18; -typedef std::array< uint, 19 > uint_19; -typedef std::array< uint, 20 > uint_20; -typedef std::array< uint, 21 > uint_21; -typedef std::array< uint, 22 > uint_22; -typedef std::array< uint, 23 > uint_23; -typedef std::array< uint, 24 > uint_24; -typedef std::array< uint, 25 > uint_25; -typedef std::array< uint, 26 > uint_26; -typedef std::array< uint, 27 > uint_27; +typedef std::array<uint, 2> uint_2; +typedef std::array<uint, 3> uint_3; +typedef std::array<uint, 4> uint_4; +typedef std::array<uint, 5> uint_5; +typedef std::array<uint, 6> uint_6; +typedef std::array<uint, 7> uint_7; +typedef std::array<uint, 8> uint_8; +typedef std::array<uint, 9> uint_9; +typedef std::array<uint, 10> uint_10; +typedef std::array<uint, 11> uint_11; +typedef std::array<uint, 12> uint_12; +typedef std::array<uint, 13> uint_13; +typedef std::array<uint, 14> uint_14; +typedef std::array<uint, 15> uint_15; +typedef std::array<uint, 16> uint_16; +typedef std::array<uint, 17> uint_17; +typedef std::array<uint, 18> uint_18; +typedef std::array<uint, 19> uint_19; +typedef std::array<uint, 20> uint_20; +typedef std::array<uint, 21> uint_21; +typedef std::array<uint, 22> uint_22; +typedef std::array<uint, 23> uint_23; +typedef std::array<uint, 24> uint_24; +typedef std::array<uint, 25> uint_25; +typedef std::array<uint, 26> uint_26; +typedef std::array<uint, 27> uint_27; -typedef std::array< bool, 2 > bool_2 ; -typedef std::array< bool, 3 > bool_3 ; -typedef std::array< bool, 4 > bool_4 ; -typedef std::array< bool, 5 > bool_5 ; -typedef std::array< bool, 6 > bool_6 ; -typedef std::array< bool, 7 > bool_7 ; -typedef std::array< bool, 8 > bool_8 ; -typedef std::array< bool, 9 > bool_9 ; -typedef std::array< bool, 10 > bool_10; -typedef std::array< bool, 11 > bool_11; -typedef std::array< bool, 12 > bool_12; -typedef std::array< bool, 13 > bool_13; -typedef std::array< bool, 14 > bool_14; -typedef std::array< bool, 15 > bool_15; -typedef std::array< bool, 16 > bool_16; -typedef std::array< bool, 17 > bool_17; -typedef std::array< bool, 18 > bool_18; -typedef std::array< bool, 19 > bool_19; -typedef std::array< bool, 20 > bool_20; -typedef std::array< bool, 21 > bool_21; -typedef std::array< bool, 22 > bool_22; -typedef std::array< bool, 23 > bool_23; -typedef std::array< bool, 24 > bool_24; -typedef std::array< bool, 25 > bool_25; -typedef std::array< bool, 26 > bool_26; -typedef std::array< bool, 27 > bool_27; +typedef std::array<bool, 2> bool_2; +typedef std::array<bool, 3> bool_3; +typedef std::array<bool, 4> bool_4; +typedef std::array<bool, 5> bool_5; +typedef std::array<bool, 6> bool_6; +typedef std::array<bool, 7> bool_7; +typedef std::array<bool, 8> bool_8; +typedef std::array<bool, 9> bool_9; +typedef std::array<bool, 10> bool_10; +typedef std::array<bool, 11> bool_11; +typedef std::array<bool, 12> bool_12; +typedef std::array<bool, 13> bool_13; +typedef std::array<bool, 14> bool_14; +typedef std::array<bool, 15> bool_15; +typedef std::array<bool, 16> bool_16; +typedef std::array<bool, 17> bool_17; +typedef std::array<bool, 18> bool_18; +typedef std::array<bool, 19> bool_19; +typedef std::array<bool, 20> bool_20; +typedef std::array<bool, 21> bool_21; +typedef std::array<bool, 22> bool_22; +typedef std::array<bool, 23> bool_23; +typedef std::array<bool, 24> bool_24; +typedef std::array<bool, 25> bool_25; +typedef std::array<bool, 26> bool_26; +typedef std::array<bool, 27> bool_27; #endif diff --git a/src/basics/Core/DataTypes.h b/src/basics/Core/DataTypes.h index b4fa3a0d96e10bd4e04a809c075e49e0f9867f05..1ea72d2a8ace038b5ef8de84f33aef4cff239b50 100644 --- a/src/basics/Core/DataTypes.h +++ b/src/basics/Core/DataTypes.h @@ -3,7 +3,6 @@ #include <string> - #ifdef VF_DOUBLE_ACCURACY typedef double real; #else @@ -11,6 +10,6 @@ using real = float; #endif using uint = unsigned int; -#define INVALID_INDEX 4294967295 //max uint +#define INVALID_INDEX 4294967295 // max uint #endif diff --git a/src/basics/Core/Input/ConfigData/ConfigData.h b/src/basics/Core/Input/ConfigData/ConfigData.h index 16f789ef9f0104ce12caa630bc00181d80f06fa6..44d50557608817bff889ba9aa4316861d8ce2bca 100644 --- a/src/basics/Core/Input/ConfigData/ConfigData.h +++ b/src/basics/Core/Input/ConfigData/ConfigData.h @@ -11,177 +11,175 @@ class ConfigData public: virtual ~ConfigData() = default; - virtual real getViscosity() = 0; - virtual uint getNumberOfDevices() = 0; - virtual std::vector<uint> getDevices() = 0; - virtual std::string getOutputPath() = 0; - virtual std::string getPrefix() = 0; - virtual std::string getGridPath() = 0; - virtual bool getPrintOutputFiles() = 0; - virtual bool getGeometryValues() = 0; - virtual bool getCalc2ndOrderMoments() = 0; - virtual bool getCalc3rdOrderMoments() = 0; - virtual bool getCalcHighOrderMoments() = 0; - virtual bool getReadGeo() = 0; - virtual bool getCalcMedian() = 0; - virtual bool getCalcDragLift() = 0; - virtual bool getCalcCp() = 0; - virtual bool getWriteVeloASCIIfiles() = 0; - virtual bool getCalcPlaneConc() = 0; - virtual bool getConcFile() = 0; - virtual bool getStreetVelocityFile() = 0; - virtual bool getUseMeasurePoints() = 0; - virtual bool getUseWale() = 0; - virtual bool getUseInitNeq() = 0; - virtual bool getSimulatePorousMedia() = 0; - virtual uint getD3Qxx() = 0; - virtual uint getTEnd() = 0; - virtual uint getTOut() = 0; - virtual uint getTStartOut() = 0; - virtual uint getTimeCalcMedStart() = 0; - virtual uint getTimeCalcMedEnd() = 0; - virtual uint getPressInID() = 0; - virtual uint getPressOutID() = 0; - virtual uint getPressInZ() = 0; - virtual uint getPressOutZ() = 0; - virtual bool getDiffOn() = 0; - virtual uint getDiffMod() = 0; - virtual real getDiffusivity() = 0; - virtual real getTemperatureInit() = 0; - virtual real getTemperatureBC() = 0; - virtual real getVelocity() = 0; - virtual real getViscosityRatio() = 0; - virtual real getVelocityRatio() = 0; - virtual real getDensityRatio() = 0; - virtual real getPressRatio() = 0; - virtual real getRealX() = 0; - virtual real getRealY() = 0; - virtual real getFactorPressBC() = 0; - virtual std::string getGeometryFileC() = 0; - virtual std::string getGeometryFileM() = 0; - virtual std::string getGeometryFileF() = 0; - virtual uint getClockCycleForMP() = 0; - virtual uint getTimestepForMP() = 0; - virtual real getForcingX() = 0; - virtual real getForcingY() = 0; - virtual real getForcingZ() = 0; - virtual real getQuadricLimiterP() = 0; - virtual real getQuadricLimiterM() = 0; - virtual real getQuadricLimiterD() = 0; - virtual bool getCalcParticles() = 0; - virtual int getParticleBasicLevel() = 0; - virtual int getParticleInitLevel() = 0; - virtual int getNumberOfParticles() = 0; - virtual real getStartXHotWall() = 0; - virtual real getEndXHotWall() = 0; - virtual std::vector<std::string> getPossNeighborFilesX() = 0; - virtual std::vector<std::string> getPossNeighborFilesY() = 0; - virtual std::vector<std::string> getPossNeighborFilesZ() = 0; - //virtual std::vector<std::string> getPossNeighborFilesX() = 0; - //virtual std::vector<std::string> getPossNeighborFilesY() = 0; - //virtual std::vector<std::string> getPossNeighborFilesZ() = 0; - virtual int getTimeDoCheckPoint() = 0; - virtual int getTimeDoRestart() = 0; - virtual bool getDoCheckPoint() = 0; - virtual bool getDoRestart() = 0; - virtual uint getMaxLevel() = 0; - virtual std::vector<int> getGridX() = 0; - virtual std::vector<int> getGridY() = 0; - virtual std::vector<int> getGridZ() = 0; - virtual std::vector<int> getDistX() = 0; - virtual std::vector<int> getDistY() = 0; - virtual std::vector<int> getDistZ() = 0; - virtual std::vector<bool> getNeedInterface() = 0; - virtual std::string getMainKernel() = 0; - virtual bool getMultiKernelOn() = 0; - virtual std::vector<int> getMultiKernelLevel() = 0; - virtual std::vector<std::string>getMultiKernelName() = 0; - - virtual bool isViscosityInConfigFile() = 0; - virtual bool isNumberOfDevicesInConfigFile() = 0; - virtual bool isDevicesInConfigFile() = 0; - virtual bool isOutputPathInConfigFile() = 0; - virtual bool isPrefixInConfigFile() = 0; - virtual bool isGridPathInConfigFile() = 0; - virtual bool isPrintOutputFilesInConfigFile() = 0; - virtual bool isGeometryValuesInConfigFile() = 0; - virtual bool isCalc2ndOrderMomentsInConfigFile() = 0; - virtual bool isCalc3rdOrderMomentsInConfigFile() = 0; - virtual bool isCalcHighOrderMomentsInConfigFile() = 0; - virtual bool isReadGeoInConfigFile() = 0; - virtual bool isCalcMedianInConfigFile() = 0; - virtual bool isCalcDragLiftInConfigFile() = 0; - virtual bool isCalcCpInConfigFile() = 0; - virtual bool isWriteVeloASCIIfilesInConfigFile() = 0; - virtual bool isCalcPlaneConcInConfigFile() = 0; - virtual bool isConcFileInConfigFile() = 0; - virtual bool isStreetVelocityFileInConfigFile() = 0; - virtual bool isUseMeasurePointsInConfigFile() = 0; - virtual bool isUseWaleInConfigFile() = 0; - virtual bool isUseInitNeqInConfigFile() = 0; - virtual bool isSimulatePorousMediaInConfigFile() = 0; - virtual bool isD3QxxInConfigFile() = 0; - virtual bool isTEndInConfigFile() = 0; - virtual bool isTOutInConfigFile() = 0; - virtual bool isTStartOutInConfigFile() = 0; - virtual bool isTimeCalcMedStartInConfigFile() = 0; - virtual bool isTimeCalcMedEndInConfigFile() = 0; - virtual bool isPressInIDInConfigFile() = 0; - virtual bool isPressOutIDInConfigFile() = 0; - virtual bool isPressInZInConfigFile() = 0; - virtual bool isPressOutZInConfigFile() = 0; - virtual bool isDiffOnInConfigFile() = 0; - virtual bool isDiffModInConfigFile() = 0; - virtual bool isDiffusivityInConfigFile() = 0; - virtual bool isTemperatureInitInConfigFile() = 0; - virtual bool isTemperatureBCInConfigFile() = 0; - //virtual bool isViscosityInConfigFile() = 0; - virtual bool isVelocityInConfigFile() = 0; - virtual bool isViscosityRatioInConfigFile() = 0; - virtual bool isVelocityRatioInConfigFile() = 0; - virtual bool isDensityRatioInConfigFile() = 0; - virtual bool isPressRatioInConfigFile() = 0; - virtual bool isRealXInConfigFile() = 0; - virtual bool isRealYInConfigFile() = 0; - virtual bool isFactorPressBCInConfigFile() = 0; - virtual bool isGeometryFileCInConfigFile() = 0; - virtual bool isGeometryFileMInConfigFile() = 0; - virtual bool isGeometryFileFInConfigFile() = 0; - virtual bool isClockCycleForMPInConfigFile() = 0; - virtual bool isTimestepForMPInConfigFile() = 0; - virtual bool isForcingXInConfigFile() = 0; - virtual bool isForcingYInConfigFile() = 0; - virtual bool isForcingZInConfigFile() = 0; - virtual bool isQuadricLimiterPInConfigFile() = 0; - virtual bool isQuadricLimiterMInConfigFile() = 0; - virtual bool isQuadricLimiterDInConfigFile() = 0; - virtual bool isCalcParticlesInConfigFile() = 0; - virtual bool isParticleBasicLevelInConfigFile() = 0; - virtual bool isParticleInitLevelInConfigFile() = 0; - virtual bool isNumberOfParticlesInConfigFile() = 0; - virtual bool isNeighborWSBInConfigFile() = 0; - virtual bool isStartXHotWallInConfigFile() = 0; - virtual bool isEndXHotWallInConfigFile() = 0; - virtual bool isPossNeighborFilesXInConfigFile() = 0; - virtual bool isPossNeighborFilesYInConfigFile() = 0; - virtual bool isPossNeighborFilesZInConfigFile() = 0; - virtual bool isTimeDoCheckPointInConfigFile() = 0; - virtual bool isTimeDoRestartInConfigFile() = 0; - virtual bool isDoCheckPointInConfigFile() = 0; - virtual bool isDoRestartInConfigFile() = 0; - virtual bool isMaxLevelInConfigFile() = 0; - virtual bool isGridXInConfigFile() = 0; - virtual bool isGridYInConfigFile() = 0; - virtual bool isGridZInConfigFile() = 0; - virtual bool isDistXInConfigFile() = 0; - virtual bool isDistYInConfigFile() = 0; - virtual bool isDistZInConfigFile() = 0; - virtual bool isNeedInterfaceInConfigFile() = 0; - virtual bool isMainKernelInConfigFile() = 0; - virtual bool isMultiKernelOnInConfigFile() = 0; - virtual bool isMultiKernelLevelInConfigFile() = 0; - virtual bool isMultiKernelNameInConfigFile() = 0; - + virtual real getViscosity() = 0; + virtual uint getNumberOfDevices() = 0; + virtual std::vector<uint> getDevices() = 0; + virtual std::string getOutputPath() = 0; + virtual std::string getPrefix() = 0; + virtual std::string getGridPath() = 0; + virtual bool getPrintOutputFiles() = 0; + virtual bool getGeometryValues() = 0; + virtual bool getCalc2ndOrderMoments() = 0; + virtual bool getCalc3rdOrderMoments() = 0; + virtual bool getCalcHighOrderMoments() = 0; + virtual bool getReadGeo() = 0; + virtual bool getCalcMedian() = 0; + virtual bool getCalcDragLift() = 0; + virtual bool getCalcCp() = 0; + virtual bool getWriteVeloASCIIfiles() = 0; + virtual bool getCalcPlaneConc() = 0; + virtual bool getConcFile() = 0; + virtual bool getStreetVelocityFile() = 0; + virtual bool getUseMeasurePoints() = 0; + virtual bool getUseWale() = 0; + virtual bool getUseInitNeq() = 0; + virtual bool getSimulatePorousMedia() = 0; + virtual uint getD3Qxx() = 0; + virtual uint getTEnd() = 0; + virtual uint getTOut() = 0; + virtual uint getTStartOut() = 0; + virtual uint getTimeCalcMedStart() = 0; + virtual uint getTimeCalcMedEnd() = 0; + virtual uint getPressInID() = 0; + virtual uint getPressOutID() = 0; + virtual uint getPressInZ() = 0; + virtual uint getPressOutZ() = 0; + virtual bool getDiffOn() = 0; + virtual uint getDiffMod() = 0; + virtual real getDiffusivity() = 0; + virtual real getTemperatureInit() = 0; + virtual real getTemperatureBC() = 0; + virtual real getVelocity() = 0; + virtual real getViscosityRatio() = 0; + virtual real getVelocityRatio() = 0; + virtual real getDensityRatio() = 0; + virtual real getPressRatio() = 0; + virtual real getRealX() = 0; + virtual real getRealY() = 0; + virtual real getFactorPressBC() = 0; + virtual std::string getGeometryFileC() = 0; + virtual std::string getGeometryFileM() = 0; + virtual std::string getGeometryFileF() = 0; + virtual uint getClockCycleForMP() = 0; + virtual uint getTimestepForMP() = 0; + virtual real getForcingX() = 0; + virtual real getForcingY() = 0; + virtual real getForcingZ() = 0; + virtual real getQuadricLimiterP() = 0; + virtual real getQuadricLimiterM() = 0; + virtual real getQuadricLimiterD() = 0; + virtual bool getCalcParticles() = 0; + virtual int getParticleBasicLevel() = 0; + virtual int getParticleInitLevel() = 0; + virtual int getNumberOfParticles() = 0; + virtual real getStartXHotWall() = 0; + virtual real getEndXHotWall() = 0; + virtual std::vector<std::string> getPossNeighborFilesX() = 0; + virtual std::vector<std::string> getPossNeighborFilesY() = 0; + virtual std::vector<std::string> getPossNeighborFilesZ() = 0; + // virtual std::vector<std::string> getPossNeighborFilesX() = 0; + // virtual std::vector<std::string> getPossNeighborFilesY() = 0; + // virtual std::vector<std::string> getPossNeighborFilesZ() = 0; + virtual int getTimeDoCheckPoint() = 0; + virtual int getTimeDoRestart() = 0; + virtual bool getDoCheckPoint() = 0; + virtual bool getDoRestart() = 0; + virtual uint getMaxLevel() = 0; + virtual std::vector<int> getGridX() = 0; + virtual std::vector<int> getGridY() = 0; + virtual std::vector<int> getGridZ() = 0; + virtual std::vector<int> getDistX() = 0; + virtual std::vector<int> getDistY() = 0; + virtual std::vector<int> getDistZ() = 0; + virtual std::vector<bool> getNeedInterface() = 0; + virtual std::string getMainKernel() = 0; + virtual bool getMultiKernelOn() = 0; + virtual std::vector<int> getMultiKernelLevel() = 0; + virtual std::vector<std::string> getMultiKernelName() = 0; + virtual bool isViscosityInConfigFile() = 0; + virtual bool isNumberOfDevicesInConfigFile() = 0; + virtual bool isDevicesInConfigFile() = 0; + virtual bool isOutputPathInConfigFile() = 0; + virtual bool isPrefixInConfigFile() = 0; + virtual bool isGridPathInConfigFile() = 0; + virtual bool isPrintOutputFilesInConfigFile() = 0; + virtual bool isGeometryValuesInConfigFile() = 0; + virtual bool isCalc2ndOrderMomentsInConfigFile() = 0; + virtual bool isCalc3rdOrderMomentsInConfigFile() = 0; + virtual bool isCalcHighOrderMomentsInConfigFile() = 0; + virtual bool isReadGeoInConfigFile() = 0; + virtual bool isCalcMedianInConfigFile() = 0; + virtual bool isCalcDragLiftInConfigFile() = 0; + virtual bool isCalcCpInConfigFile() = 0; + virtual bool isWriteVeloASCIIfilesInConfigFile() = 0; + virtual bool isCalcPlaneConcInConfigFile() = 0; + virtual bool isConcFileInConfigFile() = 0; + virtual bool isStreetVelocityFileInConfigFile() = 0; + virtual bool isUseMeasurePointsInConfigFile() = 0; + virtual bool isUseWaleInConfigFile() = 0; + virtual bool isUseInitNeqInConfigFile() = 0; + virtual bool isSimulatePorousMediaInConfigFile() = 0; + virtual bool isD3QxxInConfigFile() = 0; + virtual bool isTEndInConfigFile() = 0; + virtual bool isTOutInConfigFile() = 0; + virtual bool isTStartOutInConfigFile() = 0; + virtual bool isTimeCalcMedStartInConfigFile() = 0; + virtual bool isTimeCalcMedEndInConfigFile() = 0; + virtual bool isPressInIDInConfigFile() = 0; + virtual bool isPressOutIDInConfigFile() = 0; + virtual bool isPressInZInConfigFile() = 0; + virtual bool isPressOutZInConfigFile() = 0; + virtual bool isDiffOnInConfigFile() = 0; + virtual bool isDiffModInConfigFile() = 0; + virtual bool isDiffusivityInConfigFile() = 0; + virtual bool isTemperatureInitInConfigFile() = 0; + virtual bool isTemperatureBCInConfigFile() = 0; + // virtual bool isViscosityInConfigFile() = 0; + virtual bool isVelocityInConfigFile() = 0; + virtual bool isViscosityRatioInConfigFile() = 0; + virtual bool isVelocityRatioInConfigFile() = 0; + virtual bool isDensityRatioInConfigFile() = 0; + virtual bool isPressRatioInConfigFile() = 0; + virtual bool isRealXInConfigFile() = 0; + virtual bool isRealYInConfigFile() = 0; + virtual bool isFactorPressBCInConfigFile() = 0; + virtual bool isGeometryFileCInConfigFile() = 0; + virtual bool isGeometryFileMInConfigFile() = 0; + virtual bool isGeometryFileFInConfigFile() = 0; + virtual bool isClockCycleForMPInConfigFile() = 0; + virtual bool isTimestepForMPInConfigFile() = 0; + virtual bool isForcingXInConfigFile() = 0; + virtual bool isForcingYInConfigFile() = 0; + virtual bool isForcingZInConfigFile() = 0; + virtual bool isQuadricLimiterPInConfigFile() = 0; + virtual bool isQuadricLimiterMInConfigFile() = 0; + virtual bool isQuadricLimiterDInConfigFile() = 0; + virtual bool isCalcParticlesInConfigFile() = 0; + virtual bool isParticleBasicLevelInConfigFile() = 0; + virtual bool isParticleInitLevelInConfigFile() = 0; + virtual bool isNumberOfParticlesInConfigFile() = 0; + virtual bool isNeighborWSBInConfigFile() = 0; + virtual bool isStartXHotWallInConfigFile() = 0; + virtual bool isEndXHotWallInConfigFile() = 0; + virtual bool isPossNeighborFilesXInConfigFile() = 0; + virtual bool isPossNeighborFilesYInConfigFile() = 0; + virtual bool isPossNeighborFilesZInConfigFile() = 0; + virtual bool isTimeDoCheckPointInConfigFile() = 0; + virtual bool isTimeDoRestartInConfigFile() = 0; + virtual bool isDoCheckPointInConfigFile() = 0; + virtual bool isDoRestartInConfigFile() = 0; + virtual bool isMaxLevelInConfigFile() = 0; + virtual bool isGridXInConfigFile() = 0; + virtual bool isGridYInConfigFile() = 0; + virtual bool isGridZInConfigFile() = 0; + virtual bool isDistXInConfigFile() = 0; + virtual bool isDistYInConfigFile() = 0; + virtual bool isDistZInConfigFile() = 0; + virtual bool isNeedInterfaceInConfigFile() = 0; + virtual bool isMainKernelInConfigFile() = 0; + virtual bool isMultiKernelOnInConfigFile() = 0; + virtual bool isMultiKernelLevelInConfigFile() = 0; + virtual bool isMultiKernelNameInConfigFile() = 0; }; #endif diff --git a/src/basics/Core/Input/ConfigData/ConfigDataImp.cpp b/src/basics/Core/Input/ConfigData/ConfigDataImp.cpp index 35652c2eb74a7d2c91123ab83c04753e648828d7..7e0e093610b6f1decde482abddb9ba331213810d 100644 --- a/src/basics/Core/Input/ConfigData/ConfigDataImp.cpp +++ b/src/basics/Core/Input/ConfigData/ConfigDataImp.cpp @@ -1,731 +1,483 @@ #include "ConfigDataImp.h" - std::shared_ptr<ConfigDataImp> ConfigDataImp::getNewInstance() { - return std::shared_ptr<ConfigDataImp>(new ConfigDataImp()); + return std::shared_ptr<ConfigDataImp>(new ConfigDataImp()); } ConfigDataImp::ConfigDataImp() { - this->isViscosity=false; - this->isNumberOfDevices=false; - this->isDevices=false; - this->isOutputPath=false; - this->isPrefix=false; - this->isGridPath=false; - this->isPrintOutputFiles=false; - this->isGeometryValues=false; - this->isCalc2ndOrderMoments=false; - this->isCalc3rdOrderMoments=false; - this->isCalcHighOrderMoments=false; - this->isReadGeo=false; - this->isCalcMedian=false; - this->isCalcDragLift = false; - this->isCalcCp = false; - this->isConcFile=false; - this->isUseMeasurePoints=false; - this->isUseWale=false; - this->isSimulatePorousMedia=false; - this->isD3Qxx=false; - this->isTEnd=false; - this->isTOut=false; - this->isTStartOut=false; - this->isTimeCalcMedStart=false; - this->isTimeCalcMedEnd=false; - this->isPressInID=false; - this->isPressOutID=false; - this->isPressInZ=false; - this->isPressOutZ=false; - this->isDiffOn=false; - this->isDiffMod=false; - this->isDiffusivity=false; - this->isTemperatureInit=false; - this->isTemperatureBC=false; - this->isVelocity=false; - this->isViscosityRatio=false; - this->isVelocityRatio=false; - this->isDensityRatio=false; - this->isPressRatio=false; - this->isRealX=false; - this->isRealY=false; - this->isFactorPressBC=false; - this->isGeometryFileC=false; - this->isGeometryFileM=false; - this->isGeometryFileF=false; - this->isClockCycleForMP=false; - this->isTimestepForMP=false; - this->isForcingX=false; - this->isForcingY=false; - this->isForcingZ=false; - this->isCalcParticles=false; - this->isParticleBasicLevel=false; - this->isParticleInitLevel=false; - this->isNumberOfParticles=false; - this->isNeighborWSB=false; - this->isStartXHotWall=false; - this->isEndXHotWall=false; - this->isPossNeighborFilesX=false; - this->isPossNeighborFilesY=false; - this->isPossNeighborFilesZ=false; - this->isTimeDoCheckPoint=false; - this->isTimeDoRestart=false; - this->isDoCheckPoint=false; - this->isDoRestart=false; - this->isMaxLevel=false; - this->isGridX=false; - this->isGridY=false; - this->isGridZ=false; - this->isDistX=false; - this->isDistY=false; - this->isDistZ=false; - this->isNeedInterface=false; - this->isMainKernel=false; - this->isMultiKernelOn=false; - this->isMultiKernelLevel=false; - this->isMultiKernelName=false; - + this->isViscosity = false; + this->isNumberOfDevices = false; + this->isDevices = false; + this->isOutputPath = false; + this->isPrefix = false; + this->isGridPath = false; + this->isPrintOutputFiles = false; + this->isGeometryValues = false; + this->isCalc2ndOrderMoments = false; + this->isCalc3rdOrderMoments = false; + this->isCalcHighOrderMoments = false; + this->isReadGeo = false; + this->isCalcMedian = false; + this->isCalcDragLift = false; + this->isCalcCp = false; + this->isConcFile = false; + this->isUseMeasurePoints = false; + this->isUseWale = false; + this->isSimulatePorousMedia = false; + this->isD3Qxx = false; + this->isTEnd = false; + this->isTOut = false; + this->isTStartOut = false; + this->isTimeCalcMedStart = false; + this->isTimeCalcMedEnd = false; + this->isPressInID = false; + this->isPressOutID = false; + this->isPressInZ = false; + this->isPressOutZ = false; + this->isDiffOn = false; + this->isDiffMod = false; + this->isDiffusivity = false; + this->isTemperatureInit = false; + this->isTemperatureBC = false; + this->isVelocity = false; + this->isViscosityRatio = false; + this->isVelocityRatio = false; + this->isDensityRatio = false; + this->isPressRatio = false; + this->isRealX = false; + this->isRealY = false; + this->isFactorPressBC = false; + this->isGeometryFileC = false; + this->isGeometryFileM = false; + this->isGeometryFileF = false; + this->isClockCycleForMP = false; + this->isTimestepForMP = false; + this->isForcingX = false; + this->isForcingY = false; + this->isForcingZ = false; + this->isCalcParticles = false; + this->isParticleBasicLevel = false; + this->isParticleInitLevel = false; + this->isNumberOfParticles = false; + this->isNeighborWSB = false; + this->isStartXHotWall = false; + this->isEndXHotWall = false; + this->isPossNeighborFilesX = false; + this->isPossNeighborFilesY = false; + this->isPossNeighborFilesZ = false; + this->isTimeDoCheckPoint = false; + this->isTimeDoRestart = false; + this->isDoCheckPoint = false; + this->isDoRestart = false; + this->isMaxLevel = false; + this->isGridX = false; + this->isGridY = false; + this->isGridZ = false; + this->isDistX = false; + this->isDistY = false; + this->isDistZ = false; + this->isNeedInterface = false; + this->isMainKernel = false; + this->isMultiKernelOn = false; + this->isMultiKernelLevel = false; + this->isMultiKernelName = false; } -real ConfigDataImp::getViscosity() -{ - return this->viscosity; -} +real ConfigDataImp::getViscosity() { return this->viscosity; } -uint ConfigDataImp::getNumberOfDevices() -{ - return this->numberOfDevices; -} +uint ConfigDataImp::getNumberOfDevices() { return this->numberOfDevices; } -std::vector<uint> ConfigDataImp::getDevices() -{ - return this->devices; -} +std::vector<uint> ConfigDataImp::getDevices() { return this->devices; } -std::string ConfigDataImp::getOutputPath() -{ - return this->outputPath; -} +std::string ConfigDataImp::getOutputPath() { return this->outputPath; } -std::string ConfigDataImp::getPrefix() -{ - return this->prefix; -} +std::string ConfigDataImp::getPrefix() { return this->prefix; } -std::string ConfigDataImp::getGridPath() -{ - return this->gridPath; -} +std::string ConfigDataImp::getGridPath() { return this->gridPath; } -bool ConfigDataImp::getPrintOutputFiles() -{ - return this->printOutputFiles; -} +bool ConfigDataImp::getPrintOutputFiles() { return this->printOutputFiles; } -bool ConfigDataImp::getGeometryValues() -{ - return this->geometryValues; -} +bool ConfigDataImp::getGeometryValues() { return this->geometryValues; } -bool ConfigDataImp::getCalc2ndOrderMoments() -{ - return this->calc2ndOrderMoments; -} +bool ConfigDataImp::getCalc2ndOrderMoments() { return this->calc2ndOrderMoments; } -bool ConfigDataImp::getCalc3rdOrderMoments() -{ - return this->calc3rdOrderMoments; -} +bool ConfigDataImp::getCalc3rdOrderMoments() { return this->calc3rdOrderMoments; } -bool ConfigDataImp::getCalcHighOrderMoments() -{ - return this->calcHighOrderMoments; -} +bool ConfigDataImp::getCalcHighOrderMoments() { return this->calcHighOrderMoments; } -bool ConfigDataImp::getReadGeo() -{ - return this->readGeo; -} +bool ConfigDataImp::getReadGeo() { return this->readGeo; } -bool ConfigDataImp::getCalcMedian() -{ - return this->calcMedian; -} +bool ConfigDataImp::getCalcMedian() { return this->calcMedian; } -bool ConfigDataImp::getCalcDragLift() -{ - return this->calcDragLift; -} +bool ConfigDataImp::getCalcDragLift() { return this->calcDragLift; } -bool ConfigDataImp::getCalcCp() -{ - return this->calcCp; -} +bool ConfigDataImp::getCalcCp() { return this->calcCp; } -bool ConfigDataImp::getWriteVeloASCIIfiles() -{ - return this->writeVeloASCIIfiles; -} +bool ConfigDataImp::getWriteVeloASCIIfiles() { return this->writeVeloASCIIfiles; } -bool ConfigDataImp::getCalcPlaneConc() -{ - return this->calcPlaneConc; -} +bool ConfigDataImp::getCalcPlaneConc() { return this->calcPlaneConc; } -bool ConfigDataImp::getConcFile() -{ - return this->concFile; -} +bool ConfigDataImp::getConcFile() { return this->concFile; } -bool ConfigDataImp::getStreetVelocityFile() -{ - return this->streetVelocityFile; -} +bool ConfigDataImp::getStreetVelocityFile() { return this->streetVelocityFile; } -bool ConfigDataImp::getUseMeasurePoints() -{ - return this->useMeasurePoints; -} +bool ConfigDataImp::getUseMeasurePoints() { return this->useMeasurePoints; } -bool ConfigDataImp::getUseWale() -{ - return this->useWale; -} +bool ConfigDataImp::getUseWale() { return this->useWale; } -bool ConfigDataImp::getUseInitNeq() -{ - return this->useInitNeq; -} +bool ConfigDataImp::getUseInitNeq() { return this->useInitNeq; } -bool ConfigDataImp::getSimulatePorousMedia() -{ - return this->simulatePorousMedia; -} +bool ConfigDataImp::getSimulatePorousMedia() { return this->simulatePorousMedia; } -uint ConfigDataImp::getD3Qxx() -{ - return this->d3Qxx; -} +uint ConfigDataImp::getD3Qxx() { return this->d3Qxx; } -uint ConfigDataImp::getTEnd() -{ - return this->tEnd; -} +uint ConfigDataImp::getTEnd() { return this->tEnd; } -uint ConfigDataImp::getTOut() -{ - return this->tOut; -} +uint ConfigDataImp::getTOut() { return this->tOut; } -uint ConfigDataImp::getTStartOut() -{ - return this->tStartOut; -} +uint ConfigDataImp::getTStartOut() { return this->tStartOut; } -uint ConfigDataImp::getTimeCalcMedStart() -{ - return this->timeCalcMedStart; -} +uint ConfigDataImp::getTimeCalcMedStart() { return this->timeCalcMedStart; } -uint ConfigDataImp::getTimeCalcMedEnd() -{ - return this->timeCalcMedEnd; -} +uint ConfigDataImp::getTimeCalcMedEnd() { return this->timeCalcMedEnd; } -uint ConfigDataImp::getPressInID() -{ - return this->pressInID; -} +uint ConfigDataImp::getPressInID() { return this->pressInID; } -uint ConfigDataImp::getPressOutID() -{ - return this->pressOutID; -} +uint ConfigDataImp::getPressOutID() { return this->pressOutID; } -uint ConfigDataImp::getPressInZ() -{ - return this->pressInZ; -} +uint ConfigDataImp::getPressInZ() { return this->pressInZ; } -uint ConfigDataImp::getPressOutZ() -{ - return this->pressOutZ; -} +uint ConfigDataImp::getPressOutZ() { return this->pressOutZ; } -bool ConfigDataImp::getDiffOn() -{ - return this->diffOn; -} +bool ConfigDataImp::getDiffOn() { return this->diffOn; } -uint ConfigDataImp::getDiffMod() -{ - return this->diffMod; -} +uint ConfigDataImp::getDiffMod() { return this->diffMod; } -real ConfigDataImp::getDiffusivity() -{ - return this->diffusivity; -} +real ConfigDataImp::getDiffusivity() { return this->diffusivity; } -real ConfigDataImp::getTemperatureInit() -{ - return this->temperatureInit; -} +real ConfigDataImp::getTemperatureInit() { return this->temperatureInit; } -real ConfigDataImp::getTemperatureBC() -{ - return this->temperatureBC; -} +real ConfigDataImp::getTemperatureBC() { return this->temperatureBC; } -real ConfigDataImp::getVelocity() -{ - return this->velocity; -} +real ConfigDataImp::getVelocity() { return this->velocity; } -real ConfigDataImp::getViscosityRatio() -{ - return this->viscosityRatio; -} +real ConfigDataImp::getViscosityRatio() { return this->viscosityRatio; } -real ConfigDataImp::getVelocityRatio() -{ - return this->velocityRatio; -} +real ConfigDataImp::getVelocityRatio() { return this->velocityRatio; } -real ConfigDataImp::getDensityRatio() -{ - return this->densityRatio; -} +real ConfigDataImp::getDensityRatio() { return this->densityRatio; } -real ConfigDataImp::getPressRatio() -{ - return this->pressRatio; -} +real ConfigDataImp::getPressRatio() { return this->pressRatio; } -real ConfigDataImp::getRealX() -{ - return this->realX; -} +real ConfigDataImp::getRealX() { return this->realX; } -real ConfigDataImp::getRealY() -{ - return this->realY; -} +real ConfigDataImp::getRealY() { return this->realY; } -real ConfigDataImp::getFactorPressBC() -{ - return this->factorPressBC; -} +real ConfigDataImp::getFactorPressBC() { return this->factorPressBC; } -std::string ConfigDataImp::getGeometryFileC() -{ - return this->geometryFileC; -} +std::string ConfigDataImp::getGeometryFileC() { return this->geometryFileC; } -std::string ConfigDataImp::getGeometryFileM() -{ - return this->geometryFileM; -} +std::string ConfigDataImp::getGeometryFileM() { return this->geometryFileM; } -std::string ConfigDataImp::getGeometryFileF() -{ - return this->geometryFileF; -} +std::string ConfigDataImp::getGeometryFileF() { return this->geometryFileF; } -uint ConfigDataImp::getClockCycleForMP() -{ - return this->clockCycleForMP; -} +uint ConfigDataImp::getClockCycleForMP() { return this->clockCycleForMP; } -uint ConfigDataImp::getTimestepForMP() -{ - return this->timestepForMP; -} +uint ConfigDataImp::getTimestepForMP() { return this->timestepForMP; } -real ConfigDataImp::getForcingX() -{ - return this->forcingX; -} +real ConfigDataImp::getForcingX() { return this->forcingX; } -real ConfigDataImp::getForcingY() -{ - return this->forcingY; -} +real ConfigDataImp::getForcingY() { return this->forcingY; } -real ConfigDataImp::getForcingZ() -{ - return this->forcingZ; -} +real ConfigDataImp::getForcingZ() { return this->forcingZ; } -real ConfigDataImp::getQuadricLimiterP() -{ - return this->quadricLimiterP; -} +real ConfigDataImp::getQuadricLimiterP() { return this->quadricLimiterP; } -real ConfigDataImp::getQuadricLimiterM() -{ - return this->quadricLimiterM; -} +real ConfigDataImp::getQuadricLimiterM() { return this->quadricLimiterM; } -real ConfigDataImp::getQuadricLimiterD() -{ - return this->quadricLimiterD; -} +real ConfigDataImp::getQuadricLimiterD() { return this->quadricLimiterD; } -bool ConfigDataImp::getCalcParticles() -{ - return this->calcParticles; -} +bool ConfigDataImp::getCalcParticles() { return this->calcParticles; } -int ConfigDataImp::getParticleBasicLevel() -{ - return this->particleBasicLevel; -} +int ConfigDataImp::getParticleBasicLevel() { return this->particleBasicLevel; } -int ConfigDataImp::getParticleInitLevel() -{ - return this->particleInitLevel; -} +int ConfigDataImp::getParticleInitLevel() { return this->particleInitLevel; } -int ConfigDataImp::getNumberOfParticles() -{ - return this->numberOfParticles; -} +int ConfigDataImp::getNumberOfParticles() { return this->numberOfParticles; } -real ConfigDataImp::getStartXHotWall() -{ - return this->startXHotWall; -} +real ConfigDataImp::getStartXHotWall() { return this->startXHotWall; } -real ConfigDataImp::getEndXHotWall() -{ - return this->endXHotWall; -} +real ConfigDataImp::getEndXHotWall() { return this->endXHotWall; } -std::vector<std::string> ConfigDataImp::getPossNeighborFilesX() -{ - return this->possNeighborFilesX; -} +std::vector<std::string> ConfigDataImp::getPossNeighborFilesX() { return this->possNeighborFilesX; } -std::vector<std::string> ConfigDataImp::getPossNeighborFilesY() -{ - return this->possNeighborFilesY; -} +std::vector<std::string> ConfigDataImp::getPossNeighborFilesY() { return this->possNeighborFilesY; } -std::vector<std::string> ConfigDataImp::getPossNeighborFilesZ() -{ - return this->possNeighborFilesZ; -} +std::vector<std::string> ConfigDataImp::getPossNeighborFilesZ() { return this->possNeighborFilesZ; } -int ConfigDataImp::getTimeDoCheckPoint() -{ - return this->timeDoCheckPoint; -} +int ConfigDataImp::getTimeDoCheckPoint() { return this->timeDoCheckPoint; } -int ConfigDataImp::getTimeDoRestart() -{ - return this->timeDoRestart; -} +int ConfigDataImp::getTimeDoRestart() { return this->timeDoRestart; } -bool ConfigDataImp::getDoCheckPoint() -{ - return this->doCheckPoint; -} +bool ConfigDataImp::getDoCheckPoint() { return this->doCheckPoint; } -bool ConfigDataImp::getDoRestart() -{ - return this->doRestart; -} +bool ConfigDataImp::getDoRestart() { return this->doRestart; } -uint ConfigDataImp::getMaxLevel() -{ - return this->maxLevel; -} +uint ConfigDataImp::getMaxLevel() { return this->maxLevel; } -std::vector<int> ConfigDataImp::getGridX() -{ - return this->gridX; -} +std::vector<int> ConfigDataImp::getGridX() { return this->gridX; } -std::vector<int> ConfigDataImp::getGridY() -{ - return this->gridY; -} +std::vector<int> ConfigDataImp::getGridY() { return this->gridY; } -std::vector<int> ConfigDataImp::getGridZ() -{ - return this->gridZ; -} +std::vector<int> ConfigDataImp::getGridZ() { return this->gridZ; } -std::vector<int> ConfigDataImp::getDistX() -{ - return this->distX; -} +std::vector<int> ConfigDataImp::getDistX() { return this->distX; } -std::vector<int> ConfigDataImp::getDistY() -{ - return this->distY; -} +std::vector<int> ConfigDataImp::getDistY() { return this->distY; } -std::vector<int> ConfigDataImp::getDistZ() -{ - return this->distZ; -} +std::vector<int> ConfigDataImp::getDistZ() { return this->distZ; } -std::vector<bool> ConfigDataImp::getNeedInterface() -{ - return this->needInterface; -} +std::vector<bool> ConfigDataImp::getNeedInterface() { return this->needInterface; } -std::string ConfigDataImp::getMainKernel() -{ - return this->mainKernel; -} +std::string ConfigDataImp::getMainKernel() { return this->mainKernel; } -bool ConfigDataImp::getMultiKernelOn() -{ - return this->multiKernelOn; -} +bool ConfigDataImp::getMultiKernelOn() { return this->multiKernelOn; } -std::vector<int> ConfigDataImp::getMultiKernelLevel() -{ - return this->multiKernelLevel; -} +std::vector<int> ConfigDataImp::getMultiKernelLevel() { return this->multiKernelLevel; } -std::vector<std::string> ConfigDataImp::getMultiKernelName() -{ - return this->multiKernelName; -} +std::vector<std::string> ConfigDataImp::getMultiKernelName() { return this->multiKernelName; } void ConfigDataImp::setViscosity(real viscosity) { - this->viscosity = viscosity; - this->isViscosity = true; + this->viscosity = viscosity; + this->isViscosity = true; } void ConfigDataImp::setNumberOfDevices(uint numberOfDevices) { - this->numberOfDevices = numberOfDevices; - this->isNumberOfDevices = true; + this->numberOfDevices = numberOfDevices; + this->isNumberOfDevices = true; } void ConfigDataImp::setDevices(std::vector<uint> devices) { - this->devices = devices; - this->isDevices = true; + this->devices = devices; + this->isDevices = true; } void ConfigDataImp::setOutputPath(std::string outputPath) { - this->outputPath = outputPath; - this->isOutputPath = true; + this->outputPath = outputPath; + this->isOutputPath = true; } void ConfigDataImp::setPrefix(std::string prefix) { - this->prefix = prefix; - this->isPrefix = true; + this->prefix = prefix; + this->isPrefix = true; } void ConfigDataImp::setGridPath(std::string gridPath) { - this->gridPath = gridPath; - this->isGridPath = true; + this->gridPath = gridPath; + this->isGridPath = true; } void ConfigDataImp::setPrintOutputFiles(bool printOutputFiles) { - this->printOutputFiles = printOutputFiles; - this->isPrintOutputFiles = true; + this->printOutputFiles = printOutputFiles; + this->isPrintOutputFiles = true; } void ConfigDataImp::setGeometryValues(bool geometryValues) { - this->geometryValues = geometryValues; - this->isGeometryValues = true; + this->geometryValues = geometryValues; + this->isGeometryValues = true; } void ConfigDataImp::setCalc2ndOrderMoments(bool calc2ndOrderMoments) { - this->calc2ndOrderMoments = calc2ndOrderMoments; - this->isCalc2ndOrderMoments = true; + this->calc2ndOrderMoments = calc2ndOrderMoments; + this->isCalc2ndOrderMoments = true; } void ConfigDataImp::setCalc3rdOrderMoments(bool calc3rdOrderMoments) { - this->calc3rdOrderMoments = calc3rdOrderMoments; - this->isCalc3rdOrderMoments = true; + this->calc3rdOrderMoments = calc3rdOrderMoments; + this->isCalc3rdOrderMoments = true; } void ConfigDataImp::setCalcHighOrderMoments(bool calcHighOrderMoments) { - this->calcHighOrderMoments = calcHighOrderMoments; - this->isCalcHighOrderMoments = true; + this->calcHighOrderMoments = calcHighOrderMoments; + this->isCalcHighOrderMoments = true; } void ConfigDataImp::setReadGeo(bool readGeo) { - this->readGeo = readGeo; - this->isReadGeo = true; + this->readGeo = readGeo; + this->isReadGeo = true; } void ConfigDataImp::setCalcMedian(bool calcMedian) { - this->calcMedian = calcMedian; - this->isCalcMedian = true; + this->calcMedian = calcMedian; + this->isCalcMedian = true; } void ConfigDataImp::setCalcDragLift(bool calcDragLift) { - this->calcDragLift = calcDragLift; - this->isCalcDragLift = true; + this->calcDragLift = calcDragLift; + this->isCalcDragLift = true; } void ConfigDataImp::setCalcCp(bool calcCp) { - this->calcCp = calcCp; - this->isCalcCp = true; + this->calcCp = calcCp; + this->isCalcCp = true; } void ConfigDataImp::setWriteVeloASCIIfiles(bool writeVeloASCIIfiles) { - this->writeVeloASCIIfiles = writeVeloASCIIfiles; - this->isWriteVeloASCII = true; + this->writeVeloASCIIfiles = writeVeloASCIIfiles; + this->isWriteVeloASCII = true; } void ConfigDataImp::setCalcPlaneConc(bool calcPlaneConc) { - this->calcPlaneConc = calcPlaneConc; - this->isCalcPlaneConc = true; + this->calcPlaneConc = calcPlaneConc; + this->isCalcPlaneConc = true; } void ConfigDataImp::setConcFile(bool concFile) { - this->concFile = concFile; - this->isConcFile = true; + this->concFile = concFile; + this->isConcFile = true; } void ConfigDataImp::setStreetVelocityFile(bool streetVelocityFile) { - this->streetVelocityFile = streetVelocityFile; - this->isStreetVelocityFile = true; + this->streetVelocityFile = streetVelocityFile; + this->isStreetVelocityFile = true; } void ConfigDataImp::setUseMeasurePoints(bool useMeasurePoints) { - this->useMeasurePoints = useMeasurePoints; - this->isUseMeasurePoints = true; + this->useMeasurePoints = useMeasurePoints; + this->isUseMeasurePoints = true; } void ConfigDataImp::setUseWale(bool useWale) { - this->useWale = useWale; - this->isUseWale = true; + this->useWale = useWale; + this->isUseWale = true; } void ConfigDataImp::setUseInitNeq(bool useInitNeq) { - this->useInitNeq = useInitNeq; - this->isUseInitNeq = true; + this->useInitNeq = useInitNeq; + this->isUseInitNeq = true; } void ConfigDataImp::setSimulatePorousMedia(bool simulatePorousMedia) { - this->simulatePorousMedia = simulatePorousMedia; - this->isSimulatePorousMedia = true; + this->simulatePorousMedia = simulatePorousMedia; + this->isSimulatePorousMedia = true; } void ConfigDataImp::setD3Qxx(uint d3Qxx) { - this->d3Qxx = d3Qxx; - this->isD3Qxx = true; + this->d3Qxx = d3Qxx; + this->isD3Qxx = true; } void ConfigDataImp::setTEnd(uint tEnd) { - this->tEnd = tEnd; - this->isTEnd = true; + this->tEnd = tEnd; + this->isTEnd = true; } void ConfigDataImp::setTOut(uint tOut) { - this->tOut = tOut; - this->isTOut = true; + this->tOut = tOut; + this->isTOut = true; } void ConfigDataImp::setTStartOut(uint tStartOut) { - this->tStartOut = tStartOut; - this->isTStartOut = true; + this->tStartOut = tStartOut; + this->isTStartOut = true; } void ConfigDataImp::setTimeCalcMedStart(uint timeCalcMedStart) { - this->timeCalcMedStart = timeCalcMedStart; - this->isTimeCalcMedStart = true; + this->timeCalcMedStart = timeCalcMedStart; + this->isTimeCalcMedStart = true; } void ConfigDataImp::setTimeCalcMedEnd(uint timeCalcMedEnd) { - this->timeCalcMedEnd = timeCalcMedEnd; - this->isTimeCalcMedEnd = true; + this->timeCalcMedEnd = timeCalcMedEnd; + this->isTimeCalcMedEnd = true; } void ConfigDataImp::setPressInID(uint pressInID) { - this->pressInID = pressInID; - this->isPressInID = true; + this->pressInID = pressInID; + this->isPressInID = true; } void ConfigDataImp::setPressOutID(uint pressOutID) { - this->pressOutID = pressOutID; - this->isPressOutID = true; + this->pressOutID = pressOutID; + this->isPressOutID = true; } void ConfigDataImp::setPressInZ(uint pressInZ) { - this->pressInZ = pressInZ; - this->isPressInZ = true; + this->pressInZ = pressInZ; + this->isPressInZ = true; } void ConfigDataImp::setPressOutZ(uint pressOutZ) { - this->pressOutZ = pressOutZ; - this->isPressOutZ = true; + this->pressOutZ = pressOutZ; + this->isPressOutZ = true; } void ConfigDataImp::setDiffOn(bool diffOn) { - this->diffOn = diffOn; - this->isDiffOn = true; + this->diffOn = diffOn; + this->isDiffOn = true; } void ConfigDataImp::setDiffMod(uint diffMod) { - this->diffMod = diffMod; - this->isDiffMod = true; + this->diffMod = diffMod; + this->isDiffMod = true; } void ConfigDataImp::setDiffusivity(real diffusivity) { - this->diffusivity = diffusivity; - this->isDiffusivity = true; + this->diffusivity = diffusivity; + this->isDiffusivity = true; } void ConfigDataImp::setTemperatureInit(real temperatureInit) { - this->temperatureInit = temperatureInit; - this->isTemperatureInit = true; + this->temperatureInit = temperatureInit; + this->isTemperatureInit = true; } void ConfigDataImp::setTemperatureBC(real temperatureBC) { - this->temperatureBC = temperatureBC; - this->isTemperatureBC = true; + this->temperatureBC = temperatureBC; + this->isTemperatureBC = true; } -//void ConfigDataImp::setViscosity(real viscosity) +// void ConfigDataImp::setViscosity(real viscosity) //{ // this->viscosity = viscosity; // this->isViscosity = true; @@ -733,681 +485,430 @@ void ConfigDataImp::setTemperatureBC(real temperatureBC) void ConfigDataImp::setVelocity(real velocity) { - this->velocity = velocity; - this->isVelocity = true; + this->velocity = velocity; + this->isVelocity = true; } void ConfigDataImp::setViscosityRatio(real viscosityRatio) { - this->viscosityRatio = viscosityRatio; - this->isViscosityRatio = true; + this->viscosityRatio = viscosityRatio; + this->isViscosityRatio = true; } void ConfigDataImp::setVelocityRatio(real velocityRatio) { - this->velocityRatio = velocityRatio; - this->isVelocityRatio = true; + this->velocityRatio = velocityRatio; + this->isVelocityRatio = true; } void ConfigDataImp::setDensityRatio(real densityRatio) { - this->densityRatio = densityRatio; - this->isDensityRatio = true; + this->densityRatio = densityRatio; + this->isDensityRatio = true; } void ConfigDataImp::setPressRatio(real pressRatio) { - this->pressRatio = pressRatio; - this->isPressRatio = true; + this->pressRatio = pressRatio; + this->isPressRatio = true; } void ConfigDataImp::setRealX(real realX) { - this->realX = realX; - this->isRealX = true; + this->realX = realX; + this->isRealX = true; } void ConfigDataImp::setRealY(real realY) { - this->realY = realY; - this->isRealY = true; + this->realY = realY; + this->isRealY = true; } void ConfigDataImp::setFactorPressBC(real factorPressBC) { - this->factorPressBC = factorPressBC; - this->isFactorPressBC = true; + this->factorPressBC = factorPressBC; + this->isFactorPressBC = true; } void ConfigDataImp::setGeometryFileC(std::string geometryFileC) { - this->geometryFileC = geometryFileC; - this->isGeometryFileC = true; + this->geometryFileC = geometryFileC; + this->isGeometryFileC = true; } void ConfigDataImp::setGeometryFileM(std::string geometryFileM) { - this->geometryFileM = geometryFileM; - this->isGeometryFileM = true; + this->geometryFileM = geometryFileM; + this->isGeometryFileM = true; } void ConfigDataImp::setGeometryFileF(std::string geometryFileF) { - this->geometryFileF = geometryFileF; - this->isGeometryFileF = true; + this->geometryFileF = geometryFileF; + this->isGeometryFileF = true; } void ConfigDataImp::setClockCycleForMP(uint clockCycleForMP) { - this->clockCycleForMP = clockCycleForMP; - this->isClockCycleForMP = true; + this->clockCycleForMP = clockCycleForMP; + this->isClockCycleForMP = true; } void ConfigDataImp::setTimestepForMP(uint timestepForMP) { - this->timestepForMP = timestepForMP; - this->isTimestepForMP = true; + this->timestepForMP = timestepForMP; + this->isTimestepForMP = true; } void ConfigDataImp::setForcingX(real forcingX) { - this->forcingX = forcingX; - this->isForcingX = true; + this->forcingX = forcingX; + this->isForcingX = true; } void ConfigDataImp::setForcingY(real forcingY) { - this->forcingY = forcingY; - this->isForcingY = true; + this->forcingY = forcingY; + this->isForcingY = true; } void ConfigDataImp::setForcingZ(real forcingZ) { - this->forcingZ = forcingZ; - this->isForcingZ = true; + this->forcingZ = forcingZ; + this->isForcingZ = true; } void ConfigDataImp::setQuadricLimiterP(real quadricLimiterP) { - this->quadricLimiterP = quadricLimiterP; - this->isQuadricLimiterP = true; + this->quadricLimiterP = quadricLimiterP; + this->isQuadricLimiterP = true; } void ConfigDataImp::setQuadricLimiterM(real quadricLimiterM) { - this->quadricLimiterM = quadricLimiterM; - this->isQuadricLimiterM = true; + this->quadricLimiterM = quadricLimiterM; + this->isQuadricLimiterM = true; } void ConfigDataImp::setQuadricLimiterD(real quadricLimiterD) { - this->quadricLimiterD = quadricLimiterD; - this->isQuadricLimiterD = true; + this->quadricLimiterD = quadricLimiterD; + this->isQuadricLimiterD = true; } void ConfigDataImp::setCalcParticles(bool calcParticles) { - this->calcParticles = calcParticles; - this->isCalcParticles = true; + this->calcParticles = calcParticles; + this->isCalcParticles = true; } void ConfigDataImp::setParticleBasicLevel(int particleBasicLevel) { - this->particleBasicLevel = particleBasicLevel; - this->isParticleBasicLevel = true; + this->particleBasicLevel = particleBasicLevel; + this->isParticleBasicLevel = true; } void ConfigDataImp::setParticleInitLevel(int particleInitLevel) { - this->particleInitLevel = particleInitLevel; - this->isParticleInitLevel = true; + this->particleInitLevel = particleInitLevel; + this->isParticleInitLevel = true; } void ConfigDataImp::setNumberOfParticles(int numberOfParticles) { - this->numberOfParticles = numberOfParticles; - this->isNumberOfParticles = true; + this->numberOfParticles = numberOfParticles; + this->isNumberOfParticles = true; } void ConfigDataImp::setStartXHotWall(real startXHotWall) { - this->startXHotWall = startXHotWall; - this->isStartXHotWall = true; + this->startXHotWall = startXHotWall; + this->isStartXHotWall = true; } void ConfigDataImp::setEndXHotWall(real endXHotWall) { - this->endXHotWall = endXHotWall; - this->isEndXHotWall = true; + this->endXHotWall = endXHotWall; + this->isEndXHotWall = true; } void ConfigDataImp::setPossNeighborFilesX(std::vector<std::string> possNeighborFilesX) { - this->possNeighborFilesX = possNeighborFilesX; - this->isPossNeighborFilesX = true; + this->possNeighborFilesX = possNeighborFilesX; + this->isPossNeighborFilesX = true; } void ConfigDataImp::setPossNeighborFilesY(std::vector<std::string> possNeighborFilesY) { - this->possNeighborFilesY = possNeighborFilesY; - this->isPossNeighborFilesY = true; + this->possNeighborFilesY = possNeighborFilesY; + this->isPossNeighborFilesY = true; } void ConfigDataImp::setPossNeighborFilesZ(std::vector<std::string> possNeighborFilesZ) { - this->possNeighborFilesZ = possNeighborFilesZ; - this->isPossNeighborFilesZ = true; + this->possNeighborFilesZ = possNeighborFilesZ; + this->isPossNeighborFilesZ = true; } void ConfigDataImp::setTimeDoCheckPoint(int timeDoCheckPoint) { - this->timeDoCheckPoint = timeDoCheckPoint; - this->isTimeDoCheckPoint = true; + this->timeDoCheckPoint = timeDoCheckPoint; + this->isTimeDoCheckPoint = true; } void ConfigDataImp::setTimeDoRestart(int timeDoRestart) { - this->timeDoRestart = timeDoRestart; - this->isTimeDoRestart = true; + this->timeDoRestart = timeDoRestart; + this->isTimeDoRestart = true; } void ConfigDataImp::setDoCheckPoint(bool doCheckPoint) { - this->doCheckPoint = doCheckPoint; - this->isDoCheckPoint = true; + this->doCheckPoint = doCheckPoint; + this->isDoCheckPoint = true; } void ConfigDataImp::setDoRestart(bool doRestart) { - this->doRestart = doRestart; - this->isDoRestart = true; + this->doRestart = doRestart; + this->isDoRestart = true; } void ConfigDataImp::setMaxLevel(uint maxLevel) { - this->maxLevel = maxLevel; - this->isMaxLevel = true; + this->maxLevel = maxLevel; + this->isMaxLevel = true; } void ConfigDataImp::setGridX(std::vector<int> gridX) { - this->gridX = gridX; - this->isGridX = true; + this->gridX = gridX; + this->isGridX = true; } void ConfigDataImp::setGridY(std::vector<int> gridY) { - this->gridY = gridY; - this->isGridY = true; + this->gridY = gridY; + this->isGridY = true; } void ConfigDataImp::setGridZ(std::vector<int> gridZ) { - this->gridZ = gridZ; - this->isGridZ = true; + this->gridZ = gridZ; + this->isGridZ = true; } void ConfigDataImp::setDistX(std::vector<int> distX) { - this->distX = distX; - this->isDistX = true; + this->distX = distX; + this->isDistX = true; } void ConfigDataImp::setDistY(std::vector<int> distY) { - this->distY = distY; - this->isDistY = true; + this->distY = distY; + this->isDistY = true; } void ConfigDataImp::setDistZ(std::vector<int> distZ) { - this->distZ = distZ; - this->isDistZ = true; + this->distZ = distZ; + this->isDistZ = true; } void ConfigDataImp::setNeedInterface(std::vector<bool> needInterface) { - this->needInterface = needInterface; - this->isNeedInterface = true; + this->needInterface = needInterface; + this->isNeedInterface = true; } void ConfigDataImp::setMainKernel(std::string mainKernel) { - this->mainKernel = mainKernel; - this->isMainKernel = true; + this->mainKernel = mainKernel; + this->isMainKernel = true; } void ConfigDataImp::setMultiKernelOn(bool multiKernelOn) { - this->multiKernelOn = multiKernelOn; - this->isMultiKernelOn = true; + this->multiKernelOn = multiKernelOn; + this->isMultiKernelOn = true; } void ConfigDataImp::setMultiKernelLevel(std::vector<int> multiKernelLevel) { - this->multiKernelLevel = multiKernelLevel; - this->isMultiKernelLevel = true; + this->multiKernelLevel = multiKernelLevel; + this->isMultiKernelLevel = true; } void ConfigDataImp::setMultiKernelName(std::vector<std::string> multiKernelName) { - this->multiKernelName = multiKernelName; - this->isMultiKernelName = true; -} - -bool ConfigDataImp::isCalc2ndOrderMomentsInConfigFile() -{ - return this->isCalc2ndOrderMoments; + this->multiKernelName = multiKernelName; + this->isMultiKernelName = true; } -bool ConfigDataImp::isCalc3rdOrderMomentsInConfigFile() -{ - return this->isCalc2ndOrderMoments; -} +bool ConfigDataImp::isCalc2ndOrderMomentsInConfigFile() { return this->isCalc2ndOrderMoments; } -bool ConfigDataImp::isCalcHighOrderMomentsInConfigFile() -{ - return this->isCalcHighOrderMoments; -} +bool ConfigDataImp::isCalc3rdOrderMomentsInConfigFile() { return this->isCalc2ndOrderMoments; } -bool ConfigDataImp::isReadGeoInConfigFile() -{ - return this->isReadGeo; -} +bool ConfigDataImp::isCalcHighOrderMomentsInConfigFile() { return this->isCalcHighOrderMoments; } -bool ConfigDataImp::isCalcMedianInConfigFile() -{ - return this->isCalcMedian; -} +bool ConfigDataImp::isReadGeoInConfigFile() { return this->isReadGeo; } -bool ConfigDataImp::isCalcDragLiftInConfigFile() -{ - return this->isCalcDragLift; -} +bool ConfigDataImp::isCalcMedianInConfigFile() { return this->isCalcMedian; } -bool ConfigDataImp::isCalcCpInConfigFile() -{ - return this->isCalcCp; -} +bool ConfigDataImp::isCalcDragLiftInConfigFile() { return this->isCalcDragLift; } -bool ConfigDataImp::isWriteVeloASCIIfilesInConfigFile() -{ - return this->isWriteVeloASCII; -} +bool ConfigDataImp::isCalcCpInConfigFile() { return this->isCalcCp; } -bool ConfigDataImp::isCalcPlaneConcInConfigFile() -{ - return this->isCalcPlaneConc; -} +bool ConfigDataImp::isWriteVeloASCIIfilesInConfigFile() { return this->isWriteVeloASCII; } -bool ConfigDataImp::isConcFileInConfigFile() -{ - return this->isConcFile; -} +bool ConfigDataImp::isCalcPlaneConcInConfigFile() { return this->isCalcPlaneConc; } -bool ConfigDataImp::isStreetVelocityFileInConfigFile() -{ - return this->isStreetVelocityFile; -} +bool ConfigDataImp::isConcFileInConfigFile() { return this->isConcFile; } -bool ConfigDataImp::isUseMeasurePointsInConfigFile() -{ - return this->isUseMeasurePoints; -} +bool ConfigDataImp::isStreetVelocityFileInConfigFile() { return this->isStreetVelocityFile; } -bool ConfigDataImp::isUseWaleInConfigFile() -{ - return this->isUseWale; -} +bool ConfigDataImp::isUseMeasurePointsInConfigFile() { return this->isUseMeasurePoints; } -bool ConfigDataImp::isUseInitNeqInConfigFile() -{ - return this->isUseInitNeq; -} +bool ConfigDataImp::isUseWaleInConfigFile() { return this->isUseWale; } -bool ConfigDataImp::isSimulatePorousMediaInConfigFile() -{ - return this->isSimulatePorousMedia; -} +bool ConfigDataImp::isUseInitNeqInConfigFile() { return this->isUseInitNeq; } -bool ConfigDataImp::isD3QxxInConfigFile() -{ - return this->isD3Qxx; -} +bool ConfigDataImp::isSimulatePorousMediaInConfigFile() { return this->isSimulatePorousMedia; } -bool ConfigDataImp::isTEndInConfigFile() -{ - return this->isTEnd; -} +bool ConfigDataImp::isD3QxxInConfigFile() { return this->isD3Qxx; } -bool ConfigDataImp::isTOutInConfigFile() -{ - return this->isTOut; -} +bool ConfigDataImp::isTEndInConfigFile() { return this->isTEnd; } -bool ConfigDataImp::isTStartOutInConfigFile() -{ - return this->isTStartOut; -} +bool ConfigDataImp::isTOutInConfigFile() { return this->isTOut; } -bool ConfigDataImp::isTimeCalcMedStartInConfigFile() -{ - return this->isTimeCalcMedStart; -} +bool ConfigDataImp::isTStartOutInConfigFile() { return this->isTStartOut; } -bool ConfigDataImp::isTimeCalcMedEndInConfigFile() -{ - return this->isTimeCalcMedEnd; -} +bool ConfigDataImp::isTimeCalcMedStartInConfigFile() { return this->isTimeCalcMedStart; } -bool ConfigDataImp::isPressInIDInConfigFile() -{ - return this->isPressInID; -} +bool ConfigDataImp::isTimeCalcMedEndInConfigFile() { return this->isTimeCalcMedEnd; } -bool ConfigDataImp::isPressOutIDInConfigFile() -{ - return this->isPressOutID; -} +bool ConfigDataImp::isPressInIDInConfigFile() { return this->isPressInID; } -bool ConfigDataImp::isPressInZInConfigFile() -{ - return this->isPressInZ; -} +bool ConfigDataImp::isPressOutIDInConfigFile() { return this->isPressOutID; } -bool ConfigDataImp::isPressOutZInConfigFile() -{ - return this->isPressOutZ; -} +bool ConfigDataImp::isPressInZInConfigFile() { return this->isPressInZ; } -bool ConfigDataImp::isDiffOnInConfigFile() -{ - return this->isDiffOn; -} +bool ConfigDataImp::isPressOutZInConfigFile() { return this->isPressOutZ; } -bool ConfigDataImp::isDiffModInConfigFile() -{ - return this->isDiffMod; -} +bool ConfigDataImp::isDiffOnInConfigFile() { return this->isDiffOn; } -bool ConfigDataImp::isDiffusivityInConfigFile() -{ - return this->isDiffusivity; -} +bool ConfigDataImp::isDiffModInConfigFile() { return this->isDiffMod; } -bool ConfigDataImp::isTemperatureInitInConfigFile() -{ - return this->isTemperatureInit; -} +bool ConfigDataImp::isDiffusivityInConfigFile() { return this->isDiffusivity; } -bool ConfigDataImp::isTemperatureBCInConfigFile() -{ - return this->isTemperatureBC; -} +bool ConfigDataImp::isTemperatureInitInConfigFile() { return this->isTemperatureInit; } -bool ConfigDataImp::isViscosityInConfigFile() -{ - return this->isViscosity; -} +bool ConfigDataImp::isTemperatureBCInConfigFile() { return this->isTemperatureBC; } -bool ConfigDataImp::isNumberOfDevicesInConfigFile() -{ - return this->isNumberOfDevices; -} +bool ConfigDataImp::isViscosityInConfigFile() { return this->isViscosity; } -bool ConfigDataImp::isDevicesInConfigFile() -{ - return this->isDevices; -} +bool ConfigDataImp::isNumberOfDevicesInConfigFile() { return this->isNumberOfDevices; } -bool ConfigDataImp::isOutputPathInConfigFile() -{ - return this->isOutputPath; -} +bool ConfigDataImp::isDevicesInConfigFile() { return this->isDevices; } -bool ConfigDataImp::isPrefixInConfigFile() -{ - return this->isPrefix; -} +bool ConfigDataImp::isOutputPathInConfigFile() { return this->isOutputPath; } -bool ConfigDataImp::isGridPathInConfigFile() -{ - return this->isGridPath; -} +bool ConfigDataImp::isPrefixInConfigFile() { return this->isPrefix; } -bool ConfigDataImp::isPrintOutputFilesInConfigFile() -{ - return this->isPrintOutputFiles; -} +bool ConfigDataImp::isGridPathInConfigFile() { return this->isGridPath; } -bool ConfigDataImp::isGeometryValuesInConfigFile() -{ - return this->isGeometryValues; -} +bool ConfigDataImp::isPrintOutputFilesInConfigFile() { return this->isPrintOutputFiles; } -bool ConfigDataImp::isVelocityInConfigFile() -{ - return this->isVelocity; -} +bool ConfigDataImp::isGeometryValuesInConfigFile() { return this->isGeometryValues; } -bool ConfigDataImp::isViscosityRatioInConfigFile() -{ - return this->isViscosityRatio; -} +bool ConfigDataImp::isVelocityInConfigFile() { return this->isVelocity; } -bool ConfigDataImp::isVelocityRatioInConfigFile() -{ - return this->isVelocityRatio; -} +bool ConfigDataImp::isViscosityRatioInConfigFile() { return this->isViscosityRatio; } -bool ConfigDataImp::isDensityRatioInConfigFile() -{ - return this->isDensityRatio; -} +bool ConfigDataImp::isVelocityRatioInConfigFile() { return this->isVelocityRatio; } -bool ConfigDataImp::isPressRatioInConfigFile() -{ - return this->isPressRatio; -} +bool ConfigDataImp::isDensityRatioInConfigFile() { return this->isDensityRatio; } -bool ConfigDataImp::isRealXInConfigFile() -{ - return this->isRealX; -} +bool ConfigDataImp::isPressRatioInConfigFile() { return this->isPressRatio; } -bool ConfigDataImp::isRealYInConfigFile() -{ - return this->isRealY; -} +bool ConfigDataImp::isRealXInConfigFile() { return this->isRealX; } -bool ConfigDataImp::isFactorPressBCInConfigFile() -{ - return this->isFactorPressBC; -} +bool ConfigDataImp::isRealYInConfigFile() { return this->isRealY; } -bool ConfigDataImp::isGeometryFileCInConfigFile() -{ - return this->isGeometryFileC; -} +bool ConfigDataImp::isFactorPressBCInConfigFile() { return this->isFactorPressBC; } -bool ConfigDataImp::isGeometryFileMInConfigFile() -{ - return this->isGeometryFileM; -} +bool ConfigDataImp::isGeometryFileCInConfigFile() { return this->isGeometryFileC; } -bool ConfigDataImp::isGeometryFileFInConfigFile() -{ - return this->isGeometryFileF; -} +bool ConfigDataImp::isGeometryFileMInConfigFile() { return this->isGeometryFileM; } -bool ConfigDataImp::isClockCycleForMPInConfigFile() -{ - return this->isClockCycleForMP; -} +bool ConfigDataImp::isGeometryFileFInConfigFile() { return this->isGeometryFileF; } -bool ConfigDataImp::isTimestepForMPInConfigFile() -{ - return this->isTimestepForMP; -} +bool ConfigDataImp::isClockCycleForMPInConfigFile() { return this->isClockCycleForMP; } -bool ConfigDataImp::isForcingXInConfigFile() -{ - return this->isForcingX; -} +bool ConfigDataImp::isTimestepForMPInConfigFile() { return this->isTimestepForMP; } -bool ConfigDataImp::isForcingYInConfigFile() -{ - return this->isForcingY; -} +bool ConfigDataImp::isForcingXInConfigFile() { return this->isForcingX; } -bool ConfigDataImp::isForcingZInConfigFile() -{ - return this->isForcingZ; -} +bool ConfigDataImp::isForcingYInConfigFile() { return this->isForcingY; } -bool ConfigDataImp::isQuadricLimiterPInConfigFile() -{ - return this->isQuadricLimiterP; -} +bool ConfigDataImp::isForcingZInConfigFile() { return this->isForcingZ; } -bool ConfigDataImp::isQuadricLimiterMInConfigFile() -{ - return this->isQuadricLimiterM; -} +bool ConfigDataImp::isQuadricLimiterPInConfigFile() { return this->isQuadricLimiterP; } -bool ConfigDataImp::isQuadricLimiterDInConfigFile() -{ - return this->isQuadricLimiterD; -} +bool ConfigDataImp::isQuadricLimiterMInConfigFile() { return this->isQuadricLimiterM; } -bool ConfigDataImp::isCalcParticlesInConfigFile() -{ - return this->isCalcParticles; -} +bool ConfigDataImp::isQuadricLimiterDInConfigFile() { return this->isQuadricLimiterD; } -bool ConfigDataImp::isParticleBasicLevelInConfigFile() -{ - return this->isParticleBasicLevel; -} +bool ConfigDataImp::isCalcParticlesInConfigFile() { return this->isCalcParticles; } -bool ConfigDataImp::isParticleInitLevelInConfigFile() -{ - return this->isParticleInitLevel; -} +bool ConfigDataImp::isParticleBasicLevelInConfigFile() { return this->isParticleBasicLevel; } -bool ConfigDataImp::isNumberOfParticlesInConfigFile() -{ - return this->isNumberOfParticles; -} +bool ConfigDataImp::isParticleInitLevelInConfigFile() { return this->isParticleInitLevel; } -bool ConfigDataImp::isNeighborWSBInConfigFile() -{ - return this->isNeighborWSB; -} +bool ConfigDataImp::isNumberOfParticlesInConfigFile() { return this->isNumberOfParticles; } -bool ConfigDataImp::isStartXHotWallInConfigFile() -{ - return this->isStartXHotWall; -} +bool ConfigDataImp::isNeighborWSBInConfigFile() { return this->isNeighborWSB; } -bool ConfigDataImp::isEndXHotWallInConfigFile() -{ - return this->isEndXHotWall; -} +bool ConfigDataImp::isStartXHotWallInConfigFile() { return this->isStartXHotWall; } -bool ConfigDataImp::isPossNeighborFilesXInConfigFile() -{ - return this->isPossNeighborFilesX; -} +bool ConfigDataImp::isEndXHotWallInConfigFile() { return this->isEndXHotWall; } -bool ConfigDataImp::isPossNeighborFilesYInConfigFile() -{ - return this->isPossNeighborFilesY; -} +bool ConfigDataImp::isPossNeighborFilesXInConfigFile() { return this->isPossNeighborFilesX; } -bool ConfigDataImp::isPossNeighborFilesZInConfigFile() -{ - return this->isPossNeighborFilesZ; -} +bool ConfigDataImp::isPossNeighborFilesYInConfigFile() { return this->isPossNeighborFilesY; } -bool ConfigDataImp::isTimeDoCheckPointInConfigFile() -{ - return this->isTimeDoCheckPoint; -} +bool ConfigDataImp::isPossNeighborFilesZInConfigFile() { return this->isPossNeighborFilesZ; } -bool ConfigDataImp::isTimeDoRestartInConfigFile() -{ - return this->isTimeDoCheckPoint; -} +bool ConfigDataImp::isTimeDoCheckPointInConfigFile() { return this->isTimeDoCheckPoint; } -bool ConfigDataImp::isDoCheckPointInConfigFile() -{ - return this->isDoCheckPoint; -} +bool ConfigDataImp::isTimeDoRestartInConfigFile() { return this->isTimeDoCheckPoint; } -bool ConfigDataImp::isDoRestartInConfigFile() -{ - return this->isDoRestart; -} +bool ConfigDataImp::isDoCheckPointInConfigFile() { return this->isDoCheckPoint; } -bool ConfigDataImp::isMaxLevelInConfigFile() -{ - return this->isMaxLevel; -} +bool ConfigDataImp::isDoRestartInConfigFile() { return this->isDoRestart; } -bool ConfigDataImp::isGridXInConfigFile() -{ - return this->isGridX; -} +bool ConfigDataImp::isMaxLevelInConfigFile() { return this->isMaxLevel; } -bool ConfigDataImp::isGridYInConfigFile() -{ - return this->isGridY; -} +bool ConfigDataImp::isGridXInConfigFile() { return this->isGridX; } -bool ConfigDataImp::isGridZInConfigFile() -{ - return this->isGridZ; -} - -bool ConfigDataImp::isDistXInConfigFile() -{ - return this->isDistX; -} +bool ConfigDataImp::isGridYInConfigFile() { return this->isGridY; } -bool ConfigDataImp::isDistYInConfigFile() -{ - return this->isDistY; -} +bool ConfigDataImp::isGridZInConfigFile() { return this->isGridZ; } -bool ConfigDataImp::isDistZInConfigFile() -{ - return this->isDistZ; -} +bool ConfigDataImp::isDistXInConfigFile() { return this->isDistX; } -bool ConfigDataImp::isNeedInterfaceInConfigFile() -{ - return this->isNeedInterface; -} +bool ConfigDataImp::isDistYInConfigFile() { return this->isDistY; } -bool ConfigDataImp::isMainKernelInConfigFile() -{ - return this->isMainKernel; -} +bool ConfigDataImp::isDistZInConfigFile() { return this->isDistZ; } -bool ConfigDataImp::isMultiKernelOnInConfigFile() -{ - return this->isMultiKernelOn; -} +bool ConfigDataImp::isNeedInterfaceInConfigFile() { return this->isNeedInterface; } -bool ConfigDataImp::isMultiKernelLevelInConfigFile() -{ - return this->isMultiKernelLevel; -} +bool ConfigDataImp::isMainKernelInConfigFile() { return this->isMainKernel; } -bool ConfigDataImp::isMultiKernelNameInConfigFile() -{ - return this->isMultiKernelName; -} +bool ConfigDataImp::isMultiKernelOnInConfigFile() { return this->isMultiKernelOn; } +bool ConfigDataImp::isMultiKernelLevelInConfigFile() { return this->isMultiKernelLevel; } +bool ConfigDataImp::isMultiKernelNameInConfigFile() { return this->isMultiKernelName; } diff --git a/src/basics/Core/Input/ConfigData/ConfigDataImp.h b/src/basics/Core/Input/ConfigData/ConfigDataImp.h index 94d503b78c25eb980b4f1972cfb99fc159fb3dd5..34a2a95b919f9ccd23072d0a0608aa269386ef80 100644 --- a/src/basics/Core/Input/ConfigData/ConfigDataImp.h +++ b/src/basics/Core/Input/ConfigData/ConfigDataImp.h @@ -6,444 +6,442 @@ #include <memory> #include <string> -class ConfigDataImp : public ConfigData +class ConfigDataImp : public ConfigData { public: static std::shared_ptr<ConfigDataImp> getNewInstance(); - real getViscosity() override; - uint getNumberOfDevices() override; - std::vector<uint> getDevices() override; - std::string getOutputPath() override; - std::string getPrefix() override; - std::string getGridPath() override; - bool getPrintOutputFiles() override; - bool getGeometryValues() override; - bool getCalc2ndOrderMoments() override; - bool getCalc3rdOrderMoments() override; - bool getCalcHighOrderMoments() override; - bool getReadGeo() override; - bool getCalcMedian() override; - bool getCalcDragLift() override; - bool getCalcCp() override; - bool getWriteVeloASCIIfiles() override; - bool getCalcPlaneConc() override; - bool getConcFile() override; - bool getStreetVelocityFile() override; - bool getUseMeasurePoints() override; - bool getUseWale() override; - bool getUseInitNeq() override; - bool getSimulatePorousMedia() override; - uint getD3Qxx() override; - uint getTEnd() override; - uint getTOut() override; - uint getTStartOut() override; - uint getTimeCalcMedStart() override; - uint getTimeCalcMedEnd() override; - uint getPressInID() override; - uint getPressOutID() override; - uint getPressInZ() override; - uint getPressOutZ() override; - bool getDiffOn() override; - uint getDiffMod() override; - real getDiffusivity() override; - real getTemperatureInit() override; - real getTemperatureBC() override; - real getVelocity() override; - real getViscosityRatio() override; - real getVelocityRatio() override; - real getDensityRatio() override; - real getPressRatio() override; - real getRealX() override; - real getRealY() override; - real getFactorPressBC() override; - std::string getGeometryFileC() override; - std::string getGeometryFileM() override; - std::string getGeometryFileF() override; - uint getClockCycleForMP() override; - uint getTimestepForMP() override; - real getForcingX() override; - real getForcingY() override; - real getForcingZ() override; + real getViscosity() override; + uint getNumberOfDevices() override; + std::vector<uint> getDevices() override; + std::string getOutputPath() override; + std::string getPrefix() override; + std::string getGridPath() override; + bool getPrintOutputFiles() override; + bool getGeometryValues() override; + bool getCalc2ndOrderMoments() override; + bool getCalc3rdOrderMoments() override; + bool getCalcHighOrderMoments() override; + bool getReadGeo() override; + bool getCalcMedian() override; + bool getCalcDragLift() override; + bool getCalcCp() override; + bool getWriteVeloASCIIfiles() override; + bool getCalcPlaneConc() override; + bool getConcFile() override; + bool getStreetVelocityFile() override; + bool getUseMeasurePoints() override; + bool getUseWale() override; + bool getUseInitNeq() override; + bool getSimulatePorousMedia() override; + uint getD3Qxx() override; + uint getTEnd() override; + uint getTOut() override; + uint getTStartOut() override; + uint getTimeCalcMedStart() override; + uint getTimeCalcMedEnd() override; + uint getPressInID() override; + uint getPressOutID() override; + uint getPressInZ() override; + uint getPressOutZ() override; + bool getDiffOn() override; + uint getDiffMod() override; + real getDiffusivity() override; + real getTemperatureInit() override; + real getTemperatureBC() override; + real getVelocity() override; + real getViscosityRatio() override; + real getVelocityRatio() override; + real getDensityRatio() override; + real getPressRatio() override; + real getRealX() override; + real getRealY() override; + real getFactorPressBC() override; + std::string getGeometryFileC() override; + std::string getGeometryFileM() override; + std::string getGeometryFileF() override; + uint getClockCycleForMP() override; + uint getTimestepForMP() override; + real getForcingX() override; + real getForcingY() override; + real getForcingZ() override; real getQuadricLimiterP() override; real getQuadricLimiterM() override; real getQuadricLimiterD() override; - bool getCalcParticles() override; - int getParticleBasicLevel() override; - int getParticleInitLevel() override; - int getNumberOfParticles() override; - real getStartXHotWall() override; - real getEndXHotWall() override; - std::vector<std::string> getPossNeighborFilesX() override; - std::vector<std::string> getPossNeighborFilesY() override; - std::vector<std::string> getPossNeighborFilesZ() override; - //std::vector<std::string> getPossNeighborFilesX(); - //std::vector<std::string> getPossNeighborFilesY(); - //std::vector<std::string> getPossNeighborFilesZ(); - int getTimeDoCheckPoint() override; - int getTimeDoRestart() override; - bool getDoCheckPoint() override; - bool getDoRestart() override; - uint getMaxLevel() override; - std::vector<int> getGridX() override; - std::vector<int> getGridY() override; - std::vector<int> getGridZ() override; - std::vector<int> getDistX() override; - std::vector<int> getDistY() override; - std::vector<int> getDistZ() override; - std::vector<bool> getNeedInterface() override; - std::string getMainKernel() override; - bool getMultiKernelOn() override; - std::vector<int> getMultiKernelLevel() override; - std::vector<std::string> getMultiKernelName() override; + bool getCalcParticles() override; + int getParticleBasicLevel() override; + int getParticleInitLevel() override; + int getNumberOfParticles() override; + real getStartXHotWall() override; + real getEndXHotWall() override; + std::vector<std::string> getPossNeighborFilesX() override; + std::vector<std::string> getPossNeighborFilesY() override; + std::vector<std::string> getPossNeighborFilesZ() override; + // std::vector<std::string> getPossNeighborFilesX(); + // std::vector<std::string> getPossNeighborFilesY(); + // std::vector<std::string> getPossNeighborFilesZ(); + int getTimeDoCheckPoint() override; + int getTimeDoRestart() override; + bool getDoCheckPoint() override; + bool getDoRestart() override; + uint getMaxLevel() override; + std::vector<int> getGridX() override; + std::vector<int> getGridY() override; + std::vector<int> getGridZ() override; + std::vector<int> getDistX() override; + std::vector<int> getDistY() override; + std::vector<int> getDistZ() override; + std::vector<bool> getNeedInterface() override; + std::string getMainKernel() override; + bool getMultiKernelOn() override; + std::vector<int> getMultiKernelLevel() override; + std::vector<std::string> getMultiKernelName() override; - void setViscosity(real viscosity); - void setNumberOfDevices(uint numberOfDevices); - void setDevices(std::vector<uint> devices); - void setOutputPath(std::string outputPath); - void setPrefix(std::string prefix); - void setGridPath(std::string gridPath); - void setPrintOutputFiles(bool printOutputFiles); - void setGeometryValues(bool geometryValues); - void setCalc2ndOrderMoments(bool calc2ndOrderMoments); - void setCalc3rdOrderMoments(bool calc3rdOrderMoments); - void setCalcHighOrderMoments(bool calcHighOrderMoment); - void setReadGeo(bool readGeo); - void setCalcMedian(bool calcMedian); - void setCalcDragLift(bool calcDragLift); - void setCalcCp(bool calcCp); - void setWriteVeloASCIIfiles(bool writeVeloASCIIfiles); - void setCalcPlaneConc(bool calcPlaneConc); - void setConcFile(bool concFile); - void setStreetVelocityFile(bool streetVelocityFile); - void setUseMeasurePoints(bool useMeasurePoints); - void setUseWale(bool useWale); - void setUseInitNeq(bool useInitNeq); - void setSimulatePorousMedia(bool simulatePorousMedia); - void setD3Qxx(uint d3Qxx); - void setTEnd(uint tEnd); - void setTOut(uint tOut); - void setTStartOut(uint tStartOut); - void setTimeCalcMedStart(uint timeCalcMedStart); - void setTimeCalcMedEnd(uint timeCalcMedEnd); - void setPressInID(uint pressInID); - void setPressOutID(uint pressOutID); - void setPressInZ(uint pressInZ); - void setPressOutZ(uint pressOutZ); - void setDiffOn(bool diffOn); - void setDiffMod(uint diffMod); - void setDiffusivity(real diffusivity); - void setTemperatureInit(real temperatureInit); - void setTemperatureBC(real temperatureBC); - //void setViscosity(real viscosity); - void setVelocity(real velocity); - void setViscosityRatio(real viscosityRatio); - void setVelocityRatio(real velocityRatio); - void setDensityRatio(real fensityRatio); - void setPressRatio(real pressRatio); - void setRealX(real realX); - void setRealY(real realY); - void setFactorPressBC(real factorPressBC); - void setGeometryFileC(std::string geometryFileC); - void setGeometryFileM(std::string geometryFileM); - void setGeometryFileF(std::string geometryFileF); - void setClockCycleForMP(uint clockCycleForMP); - void setTimestepForMP(uint timestepForMP); - void setForcingX(real forcingX); - void setForcingY(real forcingY); - void setForcingZ(real forcingZ); - void setQuadricLimiterP(real quadricLimiterP); - void setQuadricLimiterM(real quadricLimiterM); - void setQuadricLimiterD(real quadricLimiterD); - void setCalcParticles(bool calcParticles); - void setParticleBasicLevel(int particleBasicLevel); - void setParticleInitLevel(int particleInitLevel); - void setNumberOfParticles(int numberOfParticles); - void setStartXHotWall(real startXHotWall); - void setEndXHotWall(real endXHotWall); - void setPossNeighborFilesX(std::vector<std::string> possNeighborFilesX); - void setPossNeighborFilesY(std::vector<std::string> possNeighborFilesY); - void setPossNeighborFilesZ(std::vector<std::string> possNeighborFilesZ); - //void setPossNeighborFilesX(std::vector<std::string> possNeighborFilesX); - //void setPossNeighborFilesY(std::vector<std::string> possNeighborFilesY); - //void setPossNeighborFilesZ(std::vector<std::string> possNeighborFilesZ); - void setTimeDoCheckPoint(int timeDoCheckPoint); - void setTimeDoRestart(int timeDoRestart); - void setDoCheckPoint(bool doCheckPoint); - void setDoRestart(bool doRestart); - void setMaxLevel(uint maxLevel); - void setGridX(std::vector<int> gridX); - void setGridY(std::vector<int> gridY); - void setGridZ(std::vector<int> gridZ); - void setDistX(std::vector<int> distX); - void setDistY(std::vector<int> distY); - void setDistZ(std::vector<int> distZ); - void setNeedInterface(std::vector<bool> needInterface); - void setMainKernel(std::string mainKernel); - void setMultiKernelOn(bool multiKernelOn); - void setMultiKernelLevel(std::vector<int> multiKernelLevel); - void setMultiKernelName(std::vector<std::string> multiKernelName); - - bool isViscosityInConfigFile() override; - bool isNumberOfDevicesInConfigFile() override; - bool isDevicesInConfigFile() override; - bool isOutputPathInConfigFile() override; - bool isPrefixInConfigFile() override; - bool isGridPathInConfigFile() override; - bool isPrintOutputFilesInConfigFile() override; - bool isGeometryValuesInConfigFile() override; - bool isCalc2ndOrderMomentsInConfigFile() override; - bool isCalc3rdOrderMomentsInConfigFile() override; - bool isCalcHighOrderMomentsInConfigFile() override; - bool isReadGeoInConfigFile() override; - bool isCalcMedianInConfigFile() override; - bool isCalcDragLiftInConfigFile() override; - bool isCalcCpInConfigFile() override; - bool isWriteVeloASCIIfilesInConfigFile() override; - bool isCalcPlaneConcInConfigFile() override; - bool isConcFileInConfigFile() override; - bool isStreetVelocityFileInConfigFile() override; - bool isUseMeasurePointsInConfigFile() override; - bool isUseWaleInConfigFile() override; - bool isUseInitNeqInConfigFile() override; - bool isSimulatePorousMediaInConfigFile() override; - bool isD3QxxInConfigFile() override; - bool isTEndInConfigFile() override; - bool isTOutInConfigFile() override; - bool isTStartOutInConfigFile() override; - bool isTimeCalcMedStartInConfigFile() override; - bool isTimeCalcMedEndInConfigFile() override; - bool isPressInIDInConfigFile() override; - bool isPressOutIDInConfigFile() override; - bool isPressInZInConfigFile() override; - bool isPressOutZInConfigFile() override; - bool isDiffOnInConfigFile() override; - bool isDiffModInConfigFile() override; - bool isDiffusivityInConfigFile() override; - bool isTemperatureInitInConfigFile() override; - bool isTemperatureBCInConfigFile() override; - //bool isViscosityInConfigFile(); - bool isVelocityInConfigFile() override; - bool isViscosityRatioInConfigFile() override; - bool isVelocityRatioInConfigFile() override; - bool isDensityRatioInConfigFile() override; - bool isPressRatioInConfigFile() override; - bool isRealXInConfigFile() override; - bool isRealYInConfigFile() override; - bool isFactorPressBCInConfigFile() override; - bool isGeometryFileCInConfigFile() override; - bool isGeometryFileMInConfigFile() override; - bool isGeometryFileFInConfigFile() override; - bool isClockCycleForMPInConfigFile() override; - bool isTimestepForMPInConfigFile() override; - bool isForcingXInConfigFile() override; - bool isForcingYInConfigFile() override; - bool isForcingZInConfigFile() override; - bool isQuadricLimiterPInConfigFile() override; - bool isQuadricLimiterMInConfigFile() override; - bool isQuadricLimiterDInConfigFile() override; - bool isCalcParticlesInConfigFile() override; - bool isParticleBasicLevelInConfigFile() override; - bool isParticleInitLevelInConfigFile() override; - bool isNumberOfParticlesInConfigFile() override; - bool isNeighborWSBInConfigFile() override; - bool isStartXHotWallInConfigFile() override; - bool isEndXHotWallInConfigFile() override; - bool isPossNeighborFilesXInConfigFile() override; - bool isPossNeighborFilesYInConfigFile() override; - bool isPossNeighborFilesZInConfigFile() override; - bool isTimeDoCheckPointInConfigFile() override; - bool isTimeDoRestartInConfigFile() override; - bool isDoCheckPointInConfigFile() override; - bool isDoRestartInConfigFile() override; - bool isMaxLevelInConfigFile() override; - bool isGridXInConfigFile() override; - bool isGridYInConfigFile() override; - bool isGridZInConfigFile() override; - bool isDistXInConfigFile() override; - bool isDistYInConfigFile() override; - bool isDistZInConfigFile() override; - bool isNeedInterfaceInConfigFile() override; - bool isMainKernelInConfigFile() override; - bool isMultiKernelOnInConfigFile() override; - bool isMultiKernelLevelInConfigFile() override; - bool isMultiKernelNameInConfigFile() override; + void setViscosity(real viscosity); + void setNumberOfDevices(uint numberOfDevices); + void setDevices(std::vector<uint> devices); + void setOutputPath(std::string outputPath); + void setPrefix(std::string prefix); + void setGridPath(std::string gridPath); + void setPrintOutputFiles(bool printOutputFiles); + void setGeometryValues(bool geometryValues); + void setCalc2ndOrderMoments(bool calc2ndOrderMoments); + void setCalc3rdOrderMoments(bool calc3rdOrderMoments); + void setCalcHighOrderMoments(bool calcHighOrderMoment); + void setReadGeo(bool readGeo); + void setCalcMedian(bool calcMedian); + void setCalcDragLift(bool calcDragLift); + void setCalcCp(bool calcCp); + void setWriteVeloASCIIfiles(bool writeVeloASCIIfiles); + void setCalcPlaneConc(bool calcPlaneConc); + void setConcFile(bool concFile); + void setStreetVelocityFile(bool streetVelocityFile); + void setUseMeasurePoints(bool useMeasurePoints); + void setUseWale(bool useWale); + void setUseInitNeq(bool useInitNeq); + void setSimulatePorousMedia(bool simulatePorousMedia); + void setD3Qxx(uint d3Qxx); + void setTEnd(uint tEnd); + void setTOut(uint tOut); + void setTStartOut(uint tStartOut); + void setTimeCalcMedStart(uint timeCalcMedStart); + void setTimeCalcMedEnd(uint timeCalcMedEnd); + void setPressInID(uint pressInID); + void setPressOutID(uint pressOutID); + void setPressInZ(uint pressInZ); + void setPressOutZ(uint pressOutZ); + void setDiffOn(bool diffOn); + void setDiffMod(uint diffMod); + void setDiffusivity(real diffusivity); + void setTemperatureInit(real temperatureInit); + void setTemperatureBC(real temperatureBC); + // void setViscosity(real viscosity); + void setVelocity(real velocity); + void setViscosityRatio(real viscosityRatio); + void setVelocityRatio(real velocityRatio); + void setDensityRatio(real fensityRatio); + void setPressRatio(real pressRatio); + void setRealX(real realX); + void setRealY(real realY); + void setFactorPressBC(real factorPressBC); + void setGeometryFileC(std::string geometryFileC); + void setGeometryFileM(std::string geometryFileM); + void setGeometryFileF(std::string geometryFileF); + void setClockCycleForMP(uint clockCycleForMP); + void setTimestepForMP(uint timestepForMP); + void setForcingX(real forcingX); + void setForcingY(real forcingY); + void setForcingZ(real forcingZ); + void setQuadricLimiterP(real quadricLimiterP); + void setQuadricLimiterM(real quadricLimiterM); + void setQuadricLimiterD(real quadricLimiterD); + void setCalcParticles(bool calcParticles); + void setParticleBasicLevel(int particleBasicLevel); + void setParticleInitLevel(int particleInitLevel); + void setNumberOfParticles(int numberOfParticles); + void setStartXHotWall(real startXHotWall); + void setEndXHotWall(real endXHotWall); + void setPossNeighborFilesX(std::vector<std::string> possNeighborFilesX); + void setPossNeighborFilesY(std::vector<std::string> possNeighborFilesY); + void setPossNeighborFilesZ(std::vector<std::string> possNeighborFilesZ); + // void setPossNeighborFilesX(std::vector<std::string> possNeighborFilesX); + // void setPossNeighborFilesY(std::vector<std::string> possNeighborFilesY); + // void setPossNeighborFilesZ(std::vector<std::string> possNeighborFilesZ); + void setTimeDoCheckPoint(int timeDoCheckPoint); + void setTimeDoRestart(int timeDoRestart); + void setDoCheckPoint(bool doCheckPoint); + void setDoRestart(bool doRestart); + void setMaxLevel(uint maxLevel); + void setGridX(std::vector<int> gridX); + void setGridY(std::vector<int> gridY); + void setGridZ(std::vector<int> gridZ); + void setDistX(std::vector<int> distX); + void setDistY(std::vector<int> distY); + void setDistZ(std::vector<int> distZ); + void setNeedInterface(std::vector<bool> needInterface); + void setMainKernel(std::string mainKernel); + void setMultiKernelOn(bool multiKernelOn); + void setMultiKernelLevel(std::vector<int> multiKernelLevel); + void setMultiKernelName(std::vector<std::string> multiKernelName); + bool isViscosityInConfigFile() override; + bool isNumberOfDevicesInConfigFile() override; + bool isDevicesInConfigFile() override; + bool isOutputPathInConfigFile() override; + bool isPrefixInConfigFile() override; + bool isGridPathInConfigFile() override; + bool isPrintOutputFilesInConfigFile() override; + bool isGeometryValuesInConfigFile() override; + bool isCalc2ndOrderMomentsInConfigFile() override; + bool isCalc3rdOrderMomentsInConfigFile() override; + bool isCalcHighOrderMomentsInConfigFile() override; + bool isReadGeoInConfigFile() override; + bool isCalcMedianInConfigFile() override; + bool isCalcDragLiftInConfigFile() override; + bool isCalcCpInConfigFile() override; + bool isWriteVeloASCIIfilesInConfigFile() override; + bool isCalcPlaneConcInConfigFile() override; + bool isConcFileInConfigFile() override; + bool isStreetVelocityFileInConfigFile() override; + bool isUseMeasurePointsInConfigFile() override; + bool isUseWaleInConfigFile() override; + bool isUseInitNeqInConfigFile() override; + bool isSimulatePorousMediaInConfigFile() override; + bool isD3QxxInConfigFile() override; + bool isTEndInConfigFile() override; + bool isTOutInConfigFile() override; + bool isTStartOutInConfigFile() override; + bool isTimeCalcMedStartInConfigFile() override; + bool isTimeCalcMedEndInConfigFile() override; + bool isPressInIDInConfigFile() override; + bool isPressOutIDInConfigFile() override; + bool isPressInZInConfigFile() override; + bool isPressOutZInConfigFile() override; + bool isDiffOnInConfigFile() override; + bool isDiffModInConfigFile() override; + bool isDiffusivityInConfigFile() override; + bool isTemperatureInitInConfigFile() override; + bool isTemperatureBCInConfigFile() override; + // bool isViscosityInConfigFile(); + bool isVelocityInConfigFile() override; + bool isViscosityRatioInConfigFile() override; + bool isVelocityRatioInConfigFile() override; + bool isDensityRatioInConfigFile() override; + bool isPressRatioInConfigFile() override; + bool isRealXInConfigFile() override; + bool isRealYInConfigFile() override; + bool isFactorPressBCInConfigFile() override; + bool isGeometryFileCInConfigFile() override; + bool isGeometryFileMInConfigFile() override; + bool isGeometryFileFInConfigFile() override; + bool isClockCycleForMPInConfigFile() override; + bool isTimestepForMPInConfigFile() override; + bool isForcingXInConfigFile() override; + bool isForcingYInConfigFile() override; + bool isForcingZInConfigFile() override; + bool isQuadricLimiterPInConfigFile() override; + bool isQuadricLimiterMInConfigFile() override; + bool isQuadricLimiterDInConfigFile() override; + bool isCalcParticlesInConfigFile() override; + bool isParticleBasicLevelInConfigFile() override; + bool isParticleInitLevelInConfigFile() override; + bool isNumberOfParticlesInConfigFile() override; + bool isNeighborWSBInConfigFile() override; + bool isStartXHotWallInConfigFile() override; + bool isEndXHotWallInConfigFile() override; + bool isPossNeighborFilesXInConfigFile() override; + bool isPossNeighborFilesYInConfigFile() override; + bool isPossNeighborFilesZInConfigFile() override; + bool isTimeDoCheckPointInConfigFile() override; + bool isTimeDoRestartInConfigFile() override; + bool isDoCheckPointInConfigFile() override; + bool isDoRestartInConfigFile() override; + bool isMaxLevelInConfigFile() override; + bool isGridXInConfigFile() override; + bool isGridYInConfigFile() override; + bool isGridZInConfigFile() override; + bool isDistXInConfigFile() override; + bool isDistYInConfigFile() override; + bool isDistZInConfigFile() override; + bool isNeedInterfaceInConfigFile() override; + bool isMainKernelInConfigFile() override; + bool isMultiKernelOnInConfigFile() override; + bool isMultiKernelLevelInConfigFile() override; + bool isMultiKernelNameInConfigFile() override; private: - ConfigDataImp(); - - real viscosity; - uint numberOfDevices; - std::vector<uint> devices; - std::string outputPath; - std::string prefix; - std::string gridPath; - bool printOutputFiles; - bool geometryValues; - bool calc2ndOrderMoments; - bool calc3rdOrderMoments; - bool calcHighOrderMoments; - bool readGeo; - bool calcMedian; - bool calcDragLift; - bool calcCp; - bool writeVeloASCIIfiles; - bool calcPlaneConc; - bool concFile; - bool streetVelocityFile; - bool useMeasurePoints; - bool useWale; - bool useInitNeq; - bool simulatePorousMedia; - uint d3Qxx; - uint tEnd; - uint tOut; - uint tStartOut; - uint timeCalcMedStart; - uint timeCalcMedEnd; - uint pressInID; - uint pressOutID; - uint pressInZ; - uint pressOutZ; - bool diffOn; - uint diffMod; - real diffusivity; - real temperatureInit; - real temperatureBC; - //real viscosity; - real velocity; - real viscosityRatio; - real velocityRatio; - real densityRatio; - real pressRatio; - real realX; - real realY; - real factorPressBC; - std::string geometryFileC; - std::string geometryFileM; - std::string geometryFileF; - uint clockCycleForMP; - uint timestepForMP; - real forcingX; - real forcingY; - real forcingZ; - real quadricLimiterP; - real quadricLimiterM; - real quadricLimiterD; - bool calcParticles; - int particleBasicLevel; - int particleInitLevel; - int numberOfParticles; - real startXHotWall; - real endXHotWall; - std::vector<std::string> possNeighborFilesX; - std::vector<std::string> possNeighborFilesY; - std::vector<std::string> possNeighborFilesZ; - //std::vector<std::string> possNeighborFilesX; - //std::vector<std::string> possNeighborFilesY; - //std::vector<std::string> possNeighborFilesZ; - int timeDoCheckPoint; - int timeDoRestart; - bool doCheckPoint; - bool doRestart; - int maxLevel; - std::vector<int> gridX; - std::vector<int> gridY; - std::vector<int> gridZ; - std::vector<int> distX; - std::vector<int> distY; - std::vector<int> distZ; - std::vector<bool> needInterface; - std::string mainKernel; - bool multiKernelOn; - std::vector<int> multiKernelLevel; - std::vector<std::string> multiKernelName; + ConfigDataImp(); - bool isViscosity; - bool isNumberOfDevices; - bool isDevices; - bool isOutputPath; - bool isPrefix; - bool isGridPath; - bool isPrintOutputFiles; - bool isGeometryValues; - bool isCalc2ndOrderMoments; - bool isCalc3rdOrderMoments; - bool isCalcHighOrderMoments; - bool isReadGeo; - bool isCalcMedian; - bool isCalcDragLift; - bool isCalcCp; - bool isWriteVeloASCII; - bool isCalcPlaneConc; - bool isConcFile; - bool isStreetVelocityFile; - bool isUseMeasurePoints; - bool isUseWale; - bool isUseInitNeq; - bool isSimulatePorousMedia; - bool isD3Qxx; - bool isTEnd; - bool isTOut; - bool isTStartOut; - bool isTimeCalcMedStart; - bool isTimeCalcMedEnd; - bool isPressInID; - bool isPressOutID; - bool isPressInZ; - bool isPressOutZ; - bool isDiffOn; - bool isDiffMod; - bool isDiffusivity; - bool isTemperatureInit; - bool isTemperatureBC; - //bool isViscosity; - bool isVelocity; - bool isViscosityRatio; - bool isVelocityRatio; - bool isDensityRatio; - bool isPressRatio; - bool isRealX; - bool isRealY; - bool isFactorPressBC; - bool isGeometryFileC; - bool isGeometryFileM; - bool isGeometryFileF; - bool isClockCycleForMP; - bool isTimestepForMP; - bool isForcingX; - bool isForcingY; - bool isForcingZ; - bool isQuadricLimiterP; - bool isQuadricLimiterM; - bool isQuadricLimiterD; - bool isCalcParticles; - bool isParticleBasicLevel; - bool isParticleInitLevel; - bool isNumberOfParticles; - bool isNeighborWSB; - bool isStartXHotWall; - bool isEndXHotWall; - bool isPossNeighborFilesX; - bool isPossNeighborFilesY; - bool isPossNeighborFilesZ; - bool isTimeDoCheckPoint; - bool isTimeDoRestart; - bool isDoCheckPoint; - bool isDoRestart; - bool isMaxLevel; - bool isGridX; - bool isGridY; - bool isGridZ; - bool isDistX; - bool isDistY; - bool isDistZ; - bool isNeedInterface; - bool isMainKernel; - bool isMultiKernelOn; - bool isMultiKernelLevel; - bool isMultiKernelName; + real viscosity; + uint numberOfDevices; + std::vector<uint> devices; + std::string outputPath; + std::string prefix; + std::string gridPath; + bool printOutputFiles; + bool geometryValues; + bool calc2ndOrderMoments; + bool calc3rdOrderMoments; + bool calcHighOrderMoments; + bool readGeo; + bool calcMedian; + bool calcDragLift; + bool calcCp; + bool writeVeloASCIIfiles; + bool calcPlaneConc; + bool concFile; + bool streetVelocityFile; + bool useMeasurePoints; + bool useWale; + bool useInitNeq; + bool simulatePorousMedia; + uint d3Qxx; + uint tEnd; + uint tOut; + uint tStartOut; + uint timeCalcMedStart; + uint timeCalcMedEnd; + uint pressInID; + uint pressOutID; + uint pressInZ; + uint pressOutZ; + bool diffOn; + uint diffMod; + real diffusivity; + real temperatureInit; + real temperatureBC; + // real viscosity; + real velocity; + real viscosityRatio; + real velocityRatio; + real densityRatio; + real pressRatio; + real realX; + real realY; + real factorPressBC; + std::string geometryFileC; + std::string geometryFileM; + std::string geometryFileF; + uint clockCycleForMP; + uint timestepForMP; + real forcingX; + real forcingY; + real forcingZ; + real quadricLimiterP; + real quadricLimiterM; + real quadricLimiterD; + bool calcParticles; + int particleBasicLevel; + int particleInitLevel; + int numberOfParticles; + real startXHotWall; + real endXHotWall; + std::vector<std::string> possNeighborFilesX; + std::vector<std::string> possNeighborFilesY; + std::vector<std::string> possNeighborFilesZ; + // std::vector<std::string> possNeighborFilesX; + // std::vector<std::string> possNeighborFilesY; + // std::vector<std::string> possNeighborFilesZ; + int timeDoCheckPoint; + int timeDoRestart; + bool doCheckPoint; + bool doRestart; + int maxLevel; + std::vector<int> gridX; + std::vector<int> gridY; + std::vector<int> gridZ; + std::vector<int> distX; + std::vector<int> distY; + std::vector<int> distZ; + std::vector<bool> needInterface; + std::string mainKernel; + bool multiKernelOn; + std::vector<int> multiKernelLevel; + std::vector<std::string> multiKernelName; + bool isViscosity; + bool isNumberOfDevices; + bool isDevices; + bool isOutputPath; + bool isPrefix; + bool isGridPath; + bool isPrintOutputFiles; + bool isGeometryValues; + bool isCalc2ndOrderMoments; + bool isCalc3rdOrderMoments; + bool isCalcHighOrderMoments; + bool isReadGeo; + bool isCalcMedian; + bool isCalcDragLift; + bool isCalcCp; + bool isWriteVeloASCII; + bool isCalcPlaneConc; + bool isConcFile; + bool isStreetVelocityFile; + bool isUseMeasurePoints; + bool isUseWale; + bool isUseInitNeq; + bool isSimulatePorousMedia; + bool isD3Qxx; + bool isTEnd; + bool isTOut; + bool isTStartOut; + bool isTimeCalcMedStart; + bool isTimeCalcMedEnd; + bool isPressInID; + bool isPressOutID; + bool isPressInZ; + bool isPressOutZ; + bool isDiffOn; + bool isDiffMod; + bool isDiffusivity; + bool isTemperatureInit; + bool isTemperatureBC; + // bool isViscosity; + bool isVelocity; + bool isViscosityRatio; + bool isVelocityRatio; + bool isDensityRatio; + bool isPressRatio; + bool isRealX; + bool isRealY; + bool isFactorPressBC; + bool isGeometryFileC; + bool isGeometryFileM; + bool isGeometryFileF; + bool isClockCycleForMP; + bool isTimestepForMP; + bool isForcingX; + bool isForcingY; + bool isForcingZ; + bool isQuadricLimiterP; + bool isQuadricLimiterM; + bool isQuadricLimiterD; + bool isCalcParticles; + bool isParticleBasicLevel; + bool isParticleInitLevel; + bool isNumberOfParticles; + bool isNeighborWSB; + bool isStartXHotWall; + bool isEndXHotWall; + bool isPossNeighborFilesX; + bool isPossNeighborFilesY; + bool isPossNeighborFilesZ; + bool isTimeDoCheckPoint; + bool isTimeDoRestart; + bool isDoCheckPoint; + bool isDoRestart; + bool isMaxLevel; + bool isGridX; + bool isGridY; + bool isGridZ; + bool isDistX; + bool isDistY; + bool isDistZ; + bool isNeedInterface; + bool isMainKernel; + bool isMultiKernelOn; + bool isMultiKernelLevel; + bool isMultiKernelName; }; #endif diff --git a/src/basics/Core/Input/ConfigFileReader/ConfigFileReader.cpp b/src/basics/Core/Input/ConfigFileReader/ConfigFileReader.cpp index 4bdf8669b1ed481e64d1059d1479f05cae7e164d..dce44b5551d2aedcf0c0d70a21dbcd9e8b071c8d 100644 --- a/src/basics/Core/Input/ConfigFileReader/ConfigFileReader.cpp +++ b/src/basics/Core/Input/ConfigFileReader/ConfigFileReader.cpp @@ -1,275 +1,265 @@ #include "ConfigFileReader.h" +#include "../../StringUtilities/StringUtil.h" #include "../ConfigData/ConfigDataImp.h" #include "../Input.h" -#include "../../StringUtilities/StringUtil.h" -#include <iostream> #include <fstream> - +#include <iostream> BASICS_EXPORT std::shared_ptr<ConfigFileReader> ConfigFileReader::getNewInstance() { - return std::shared_ptr<ConfigFileReader>(new ConfigFileReader()); + return std::shared_ptr<ConfigFileReader>(new ConfigFileReader()); } -ConfigFileReader::ConfigFileReader() -= default; +ConfigFileReader::ConfigFileReader() = default; -BASICS_EXPORT ConfigFileReader::~ConfigFileReader() -= default; +BASICS_EXPORT ConfigFileReader::~ConfigFileReader() = default; BASICS_EXPORT std::shared_ptr<ConfigData> ConfigFileReader::readConfigFile(const std::string &filePath) const { - std::shared_ptr<ConfigDataImp> data = ConfigDataImp::getNewInstance(); - std::ifstream stream; - stream.open(filePath.c_str(), std::ios::in); - if (stream.fail()) - throw std::runtime_error("can not open config file!"); - std::unique_ptr<input::Input> input = input::Input::makeInput(stream, "config"); - - if (input->getValue("NumberOfDevices") != "") - data->setNumberOfDevices(StringUtil::toInt(input->getValue("NumberOfDevices"))); - - if (input->getValue("Devices") != "") - data->setDevices(StringUtil::toUintVector(input->getValue("Devices"))); - - if (input->getValue("Path") != "") - data->setOutputPath(input->getValue("Path")); + std::shared_ptr<ConfigDataImp> data = ConfigDataImp::getNewInstance(); + std::ifstream stream; + stream.open(filePath.c_str(), std::ios::in); + if (stream.fail()) + throw std::runtime_error("can not open config file!"); + std::unique_ptr<input::Input> input = input::Input::makeInput(stream, "config"); - if (input->getValue("Prefix") != "") - data->setPrefix(input->getValue("Prefix")); + if (input->getValue("NumberOfDevices") != "") + data->setNumberOfDevices(StringUtil::toInt(input->getValue("NumberOfDevices"))); - if (input->getValue("GridPath") != "") - data->setGridPath(input->getValue("GridPath")); - else - { - std::cout << "GridPath has to be defined!" << std::endl; - exit(1); - } + if (input->getValue("Devices") != "") + data->setDevices(StringUtil::toUintVector(input->getValue("Devices"))); + if (input->getValue("Path") != "") + data->setOutputPath(input->getValue("Path")); - if (input->getValue("WriteGrid") != "") - data->setPrintOutputFiles(StringUtil::toBool(input->getValue("WriteGrid"))); + if (input->getValue("Prefix") != "") + data->setPrefix(input->getValue("Prefix")); - if (input->getValue("GeometryValues") != "") - data->setGeometryValues(StringUtil::toBool(input->getValue("GeometryValues"))); + if (input->getValue("GridPath") != "") + data->setGridPath(input->getValue("GridPath")); + else { + std::cout << "GridPath has to be defined!" << std::endl; + exit(1); + } - if (input->getValue("calc2ndOrderMoments") != "") - data->setCalc2ndOrderMoments(StringUtil::toBool(input->getValue("calc2ndOrderMoments"))); + if (input->getValue("WriteGrid") != "") + data->setPrintOutputFiles(StringUtil::toBool(input->getValue("WriteGrid"))); - if (input->getValue("calc3rdOrderMoments") != "") - data->setCalc3rdOrderMoments(StringUtil::toBool(input->getValue("calc3rdOrderMoments"))); + if (input->getValue("GeometryValues") != "") + data->setGeometryValues(StringUtil::toBool(input->getValue("GeometryValues"))); - if (input->getValue("calcHigherOrderMoments") != "") - data->setCalcHighOrderMoments(StringUtil::toBool(input->getValue("calcHigherOrderMoments"))); + if (input->getValue("calc2ndOrderMoments") != "") + data->setCalc2ndOrderMoments(StringUtil::toBool(input->getValue("calc2ndOrderMoments"))); - if (input->getValue("ReadGeometry") != "") - data->setReadGeo(StringUtil::toBool(input->getValue("ReadGeometry"))); + if (input->getValue("calc3rdOrderMoments") != "") + data->setCalc3rdOrderMoments(StringUtil::toBool(input->getValue("calc3rdOrderMoments"))); - if (input->getValue("calcMedian") != "") - data->setCalcMedian(StringUtil::toBool(input->getValue("calcMedian"))); + if (input->getValue("calcHigherOrderMoments") != "") + data->setCalcHighOrderMoments(StringUtil::toBool(input->getValue("calcHigherOrderMoments"))); - if (input->getValue("UseConcFile") != "") - data->setConcFile(StringUtil::toBool(input->getValue("UseConcFile"))); + if (input->getValue("ReadGeometry") != "") + data->setReadGeo(StringUtil::toBool(input->getValue("ReadGeometry"))); - if (input->getValue("UseStreetVelocityFile") != "") - data->setStreetVelocityFile(StringUtil::toBool(input->getValue("UseStreetVelocityFile"))); + if (input->getValue("calcMedian") != "") + data->setCalcMedian(StringUtil::toBool(input->getValue("calcMedian"))); - if (input->getValue("UseMeasurePoints") != "") - data->setUseMeasurePoints(StringUtil::toBool(input->getValue("UseMeasurePoints"))); + if (input->getValue("UseConcFile") != "") + data->setConcFile(StringUtil::toBool(input->getValue("UseConcFile"))); - if (input->getValue("UseWale") != "") - data->setUseWale(StringUtil::toBool(input->getValue("UseWale"))); + if (input->getValue("UseStreetVelocityFile") != "") + data->setStreetVelocityFile(StringUtil::toBool(input->getValue("UseStreetVelocityFile"))); - if (input->getValue("UseInitNeq") != "") - data->setUseInitNeq(StringUtil::toBool(input->getValue("UseInitNeq"))); + if (input->getValue("UseMeasurePoints") != "") + data->setUseMeasurePoints(StringUtil::toBool(input->getValue("UseMeasurePoints"))); - if (input->getValue("SimulatePorousMedia") != "") - data->setSimulatePorousMedia(StringUtil::toBool(input->getValue("SimulatePorousMedia"))); + if (input->getValue("UseWale") != "") + data->setUseWale(StringUtil::toBool(input->getValue("UseWale"))); - if (input->getValue("D3Qxx") != "") - data->setD3Qxx(StringUtil::toInt(input->getValue("D3Qxx"))); + if (input->getValue("UseInitNeq") != "") + data->setUseInitNeq(StringUtil::toBool(input->getValue("UseInitNeq"))); - if (input->getValue("TimeEnd") != "") - data->setTEnd(StringUtil::toInt(input->getValue("TimeEnd"))); + if (input->getValue("SimulatePorousMedia") != "") + data->setSimulatePorousMedia(StringUtil::toBool(input->getValue("SimulatePorousMedia"))); - if (input->getValue("TimeOut") != "") - data->setTOut(StringUtil::toInt(input->getValue("TimeOut"))); - - if (input->getValue("TimeStartOut") != "") - data->setTStartOut(StringUtil::toInt(input->getValue("TimeStartOut"))); + if (input->getValue("D3Qxx") != "") + data->setD3Qxx(StringUtil::toInt(input->getValue("D3Qxx"))); - if (input->getValue("TimeStartCalcMedian") != "") - data->setTimeCalcMedStart(StringUtil::toInt(input->getValue("TimeStartCalcMedian"))); + if (input->getValue("TimeEnd") != "") + data->setTEnd(StringUtil::toInt(input->getValue("TimeEnd"))); - if (input->getValue("TimeEndCalcMedian") != "") - data->setTimeCalcMedEnd(StringUtil::toInt(input->getValue("TimeEndCalcMedian"))); + if (input->getValue("TimeOut") != "") + data->setTOut(StringUtil::toInt(input->getValue("TimeOut"))); - if (input->getValue("PressInID") != "") - data->setPressInID(StringUtil::toInt(input->getValue("PressInID"))); + if (input->getValue("TimeStartOut") != "") + data->setTStartOut(StringUtil::toInt(input->getValue("TimeStartOut"))); - if (input->getValue("PressOutID") != "") - data->setPressOutID(StringUtil::toInt(input->getValue("PressOutID"))); + if (input->getValue("TimeStartCalcMedian") != "") + data->setTimeCalcMedStart(StringUtil::toInt(input->getValue("TimeStartCalcMedian"))); - if (input->getValue("PressInZ") != "") - data->setPressInZ(StringUtil::toInt(input->getValue("PressInZ"))); + if (input->getValue("TimeEndCalcMedian") != "") + data->setTimeCalcMedEnd(StringUtil::toInt(input->getValue("TimeEndCalcMedian"))); - if (input->getValue("PressOutZ") != "") - data->setPressOutZ(StringUtil::toInt(input->getValue("PressOutZ"))); - ////////////////////////////////////////////////////////////////////////// - if (input->getValue("DiffOn") != "") - data->setDiffOn(StringUtil::toBool(input->getValue("DiffOn"))); + if (input->getValue("PressInID") != "") + data->setPressInID(StringUtil::toInt(input->getValue("PressInID"))); - if (input->getValue("DiffMod") != "") - data->setDiffMod(StringUtil::toInt(input->getValue("DiffMod"))); + if (input->getValue("PressOutID") != "") + data->setPressOutID(StringUtil::toInt(input->getValue("PressOutID"))); - if (input->getValue("Diffusivity") != "") - data->setDiffusivity(StringUtil::toFloat(input->getValue("Diffusivity"))); + if (input->getValue("PressInZ") != "") + data->setPressInZ(StringUtil::toInt(input->getValue("PressInZ"))); - if (input->getValue("Temp") != "") - data->setTemperatureInit(StringUtil::toFloat(input->getValue("Temp"))); + if (input->getValue("PressOutZ") != "") + data->setPressOutZ(StringUtil::toInt(input->getValue("PressOutZ"))); + ////////////////////////////////////////////////////////////////////////// + if (input->getValue("DiffOn") != "") + data->setDiffOn(StringUtil::toBool(input->getValue("DiffOn"))); - if (input->getValue("TempBC") != "") - data->setTemperatureBC(StringUtil::toFloat(input->getValue("TempBC"))); - ////////////////////////////////////////////////////////////////////////// - if (input->getValue("Viscosity_LB") != "") - data->setViscosity(StringUtil::toFloat(input->getValue("Viscosity_LB"))); + if (input->getValue("DiffMod") != "") + data->setDiffMod(StringUtil::toInt(input->getValue("DiffMod"))); - if (input->getValue("Velocity_LB") != "") - data->setVelocity(StringUtil::toFloat(input->getValue("Velocity_LB"))); + if (input->getValue("Diffusivity") != "") + data->setDiffusivity(StringUtil::toFloat(input->getValue("Diffusivity"))); - if (input->getValue("Viscosity_Ratio_World_to_LB") != "") - data->setViscosityRatio(StringUtil::toFloat(input->getValue("Viscosity_Ratio_World_to_LB"))); + if (input->getValue("Temp") != "") + data->setTemperatureInit(StringUtil::toFloat(input->getValue("Temp"))); - if (input->getValue("Velocity_Ratio_World_to_LB") != "") - data->setVelocityRatio(StringUtil::toFloat(input->getValue("Velocity_Ratio_World_to_LB"))); + if (input->getValue("TempBC") != "") + data->setTemperatureBC(StringUtil::toFloat(input->getValue("TempBC"))); + ////////////////////////////////////////////////////////////////////////// + if (input->getValue("Viscosity_LB") != "") + data->setViscosity(StringUtil::toFloat(input->getValue("Viscosity_LB"))); - if (input->getValue("Density_Ratio_World_to_LB") != "") - data->setDensityRatio(StringUtil::toFloat(input->getValue("Density_Ratio_World_to_LB"))); + if (input->getValue("Velocity_LB") != "") + data->setVelocity(StringUtil::toFloat(input->getValue("Velocity_LB"))); - if (input->getValue("Delta_Press") != "") - data->setPressRatio(StringUtil::toFloat(input->getValue("Delta_Press"))); + if (input->getValue("Viscosity_Ratio_World_to_LB") != "") + data->setViscosityRatio(StringUtil::toFloat(input->getValue("Viscosity_Ratio_World_to_LB"))); - if (input->getValue("SliceRealX") != "") - data->setRealX(StringUtil::toFloat(input->getValue("SliceRealX"))); + if (input->getValue("Velocity_Ratio_World_to_LB") != "") + data->setVelocityRatio(StringUtil::toFloat(input->getValue("Velocity_Ratio_World_to_LB"))); - if (input->getValue("SliceRealY") != "") - data->setRealY(StringUtil::toFloat(input->getValue("SliceRealY"))); + if (input->getValue("Density_Ratio_World_to_LB") != "") + data->setDensityRatio(StringUtil::toFloat(input->getValue("Density_Ratio_World_to_LB"))); - if (input->getValue("FactorPressBC") != "") - data->setFactorPressBC(StringUtil::toFloat(input->getValue("FactorPressBC"))); + if (input->getValue("Delta_Press") != "") + data->setPressRatio(StringUtil::toFloat(input->getValue("Delta_Press"))); - if (input->getValue("GeometryC") != "") - data->setGeometryFileC(input->getValue("GeometryC")); + if (input->getValue("SliceRealX") != "") + data->setRealX(StringUtil::toFloat(input->getValue("SliceRealX"))); - if (input->getValue("GeometryM") != "") - data->setGeometryFileM(input->getValue("GeometryM")); + if (input->getValue("SliceRealY") != "") + data->setRealY(StringUtil::toFloat(input->getValue("SliceRealY"))); - if (input->getValue("GeometryF") != "") - data->setGeometryFileF(input->getValue("GeometryF")); - ////////////////////////////////////////////////////////////////////////// - if (input->getValue("measureClockCycle") != "") - data->setClockCycleForMP(StringUtil::toInt(input->getValue("measureClockCycle"))); + if (input->getValue("FactorPressBC") != "") + data->setFactorPressBC(StringUtil::toFloat(input->getValue("FactorPressBC"))); - if (input->getValue("measureTimestep") != "") - data->setTimestepForMP(StringUtil::toInt(input->getValue("measureTimestep"))); - ////////////////////////////////////////////////////////////////////////// - //Forcing - if (input->getValue("ForcingX") != "") - data->setForcingX(StringUtil::toFloat(input->getValue("ForcingX"))); - if (input->getValue("ForcingY") != "") - data->setForcingY(StringUtil::toFloat(input->getValue("ForcingY"))); - if (input->getValue("ForcingZ") != "") - data->setForcingZ(StringUtil::toFloat(input->getValue("ForcingZ"))); - ////////////////////////////////////////////////////////////////////////// - //Quadric Limiters - if (input->getValue("QuadricLimiterP") != "") - data->setQuadricLimiterP(StringUtil::toFloat(input->getValue("QuadricLimiterP"))); - if (input->getValue("QuadricLimiterM") != "") - data->setQuadricLimiterM(StringUtil::toFloat(input->getValue("QuadricLimiterM"))); - if (input->getValue("QuadricLimiterD") != "") - data->setQuadricLimiterD(StringUtil::toFloat(input->getValue("QuadricLimiterD"))); - ////////////////////////////////////////////////////////////////////////// - //Particles - if (input->getValue("calcParticles") != "") - data->setCalcParticles(StringUtil::toBool(input->getValue("calcParticles"))); + if (input->getValue("GeometryC") != "") + data->setGeometryFileC(input->getValue("GeometryC")); - if (input->getValue("baseLevel") != "") - data->setParticleBasicLevel(StringUtil::toInt(input->getValue("baseLevel"))); + if (input->getValue("GeometryM") != "") + data->setGeometryFileM(input->getValue("GeometryM")); - if (input->getValue("initLevel") != "") - data->setParticleInitLevel(StringUtil::toInt(input->getValue("initLevel"))); + if (input->getValue("GeometryF") != "") + data->setGeometryFileF(input->getValue("GeometryF")); + ////////////////////////////////////////////////////////////////////////// + if (input->getValue("measureClockCycle") != "") + data->setClockCycleForMP(StringUtil::toInt(input->getValue("measureClockCycle"))); - if (input->getValue("numberOfParticles") != "") - data->setNumberOfParticles(StringUtil::toInt(input->getValue("numberOfParticles"))); + if (input->getValue("measureTimestep") != "") + data->setTimestepForMP(StringUtil::toInt(input->getValue("measureTimestep"))); + ////////////////////////////////////////////////////////////////////////// + // Forcing + if (input->getValue("ForcingX") != "") + data->setForcingX(StringUtil::toFloat(input->getValue("ForcingX"))); + if (input->getValue("ForcingY") != "") + data->setForcingY(StringUtil::toFloat(input->getValue("ForcingY"))); + if (input->getValue("ForcingZ") != "") + data->setForcingZ(StringUtil::toFloat(input->getValue("ForcingZ"))); + ////////////////////////////////////////////////////////////////////////// + // Quadric Limiters + if (input->getValue("QuadricLimiterP") != "") + data->setQuadricLimiterP(StringUtil::toFloat(input->getValue("QuadricLimiterP"))); + if (input->getValue("QuadricLimiterM") != "") + data->setQuadricLimiterM(StringUtil::toFloat(input->getValue("QuadricLimiterM"))); + if (input->getValue("QuadricLimiterD") != "") + data->setQuadricLimiterD(StringUtil::toFloat(input->getValue("QuadricLimiterD"))); + ////////////////////////////////////////////////////////////////////////// + // Particles + if (input->getValue("calcParticles") != "") + data->setCalcParticles(StringUtil::toBool(input->getValue("calcParticles"))); - if (input->getValue("startXHotWall") != "") - data->setStartXHotWall(real(StringUtil::toDouble(input->getValue("startXHotWall")))); - - if (input->getValue("endXHotWall") != "") - data->setEndXHotWall(real(StringUtil::toDouble(input->getValue("endXHotWall")))); - //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - //Restart - if (input->getValue("TimeDoCheckPoint") != "") - data->setTimeDoCheckPoint(StringUtil::toInt(input->getValue("TimeDoCheckPoint"))); - - if (input->getValue("TimeDoRestart") != "") - data->setTimeDoRestart(StringUtil::toInt(input->getValue("TimeDoRestart"))); - - if (input->getValue("DoCheckPoint") != "") - data->setDoCheckPoint(StringUtil::toBool(input->getValue("DoCheckPoint"))); - - if (input->getValue("DoRestart") != "") - data->setDoRestart(StringUtil::toBool(input->getValue("DoRestart"))); - //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - if (input->getValue("NOGL") != "") - data->setMaxLevel(StringUtil::toInt(input->getValue("NOGL"))); - - if (input->getValue("GridX") != "") - data->setGridX(StringUtil::toIntVector(input->getValue("GridX"))); - - if (input->getValue("GridY") != "") - data->setGridY(StringUtil::toIntVector(input->getValue("GridY"))); - - if (input->getValue("GridZ") != "") - data->setGridZ(StringUtil::toIntVector(input->getValue("GridZ"))); - - if (input->getValue("DistX") != "") - data->setDistX(StringUtil::toIntVector(input->getValue("DistX"))); - - if (input->getValue("DistY") != "") - data->setDistY(StringUtil::toIntVector(input->getValue("DistY"))); - - if (input->getValue("DistZ") != "") - data->setDistZ(StringUtil::toIntVector(input->getValue("DistZ"))); - - if (input->getValue("NeedInterface") != "") - data->setNeedInterface(StringUtil::toBoolVector(input->getValue("NeedInterface"))); - //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - // Kernel - if (input->getValue("MainKernelName") != "") - data->setMainKernel(input->getValue("MainKernelName")); - - if (input->getValue("MultiKernelOn") != "") - data->setMultiKernelOn(StringUtil::toBool(input->getValue("MultiKernelOn"))); - - if (input->getValue("MultiKernelLevel") != "") - data->setMultiKernelLevel(StringUtil::toIntVector(input->getValue("MultiKernelLevel"))); - - if (input->getValue("MultiKernelName") != "") - data->setMultiKernelName(StringUtil::toStringVector(input->getValue("MultiKernelName"))); - - if (StringUtil::toStringVector(input->getValue("MultiKernelName")).size() != StringUtil::toIntVector(input->getValue("MultiKernelLevel")).size()) - { - std::cout << "MultiKernelName and MultiKernelLevel has to be of same size!" << std::endl; - exit(1); - } - //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - - return data; + if (input->getValue("baseLevel") != "") + data->setParticleBasicLevel(StringUtil::toInt(input->getValue("baseLevel"))); + if (input->getValue("initLevel") != "") + data->setParticleInitLevel(StringUtil::toInt(input->getValue("initLevel"))); + + if (input->getValue("numberOfParticles") != "") + data->setNumberOfParticles(StringUtil::toInt(input->getValue("numberOfParticles"))); + + if (input->getValue("startXHotWall") != "") + data->setStartXHotWall(real(StringUtil::toDouble(input->getValue("startXHotWall")))); + + if (input->getValue("endXHotWall") != "") + data->setEndXHotWall(real(StringUtil::toDouble(input->getValue("endXHotWall")))); + //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + // Restart + if (input->getValue("TimeDoCheckPoint") != "") + data->setTimeDoCheckPoint(StringUtil::toInt(input->getValue("TimeDoCheckPoint"))); + + if (input->getValue("TimeDoRestart") != "") + data->setTimeDoRestart(StringUtil::toInt(input->getValue("TimeDoRestart"))); + + if (input->getValue("DoCheckPoint") != "") + data->setDoCheckPoint(StringUtil::toBool(input->getValue("DoCheckPoint"))); + + if (input->getValue("DoRestart") != "") + data->setDoRestart(StringUtil::toBool(input->getValue("DoRestart"))); + //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + if (input->getValue("NOGL") != "") + data->setMaxLevel(StringUtil::toInt(input->getValue("NOGL"))); + + if (input->getValue("GridX") != "") + data->setGridX(StringUtil::toIntVector(input->getValue("GridX"))); + + if (input->getValue("GridY") != "") + data->setGridY(StringUtil::toIntVector(input->getValue("GridY"))); + + if (input->getValue("GridZ") != "") + data->setGridZ(StringUtil::toIntVector(input->getValue("GridZ"))); + + if (input->getValue("DistX") != "") + data->setDistX(StringUtil::toIntVector(input->getValue("DistX"))); + + if (input->getValue("DistY") != "") + data->setDistY(StringUtil::toIntVector(input->getValue("DistY"))); + + if (input->getValue("DistZ") != "") + data->setDistZ(StringUtil::toIntVector(input->getValue("DistZ"))); + + if (input->getValue("NeedInterface") != "") + data->setNeedInterface(StringUtil::toBoolVector(input->getValue("NeedInterface"))); + //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + // Kernel + if (input->getValue("MainKernelName") != "") + data->setMainKernel(input->getValue("MainKernelName")); + + if (input->getValue("MultiKernelOn") != "") + data->setMultiKernelOn(StringUtil::toBool(input->getValue("MultiKernelOn"))); + + if (input->getValue("MultiKernelLevel") != "") + data->setMultiKernelLevel(StringUtil::toIntVector(input->getValue("MultiKernelLevel"))); + + if (input->getValue("MultiKernelName") != "") + data->setMultiKernelName(StringUtil::toStringVector(input->getValue("MultiKernelName"))); + + if (StringUtil::toStringVector(input->getValue("MultiKernelName")).size() != + StringUtil::toIntVector(input->getValue("MultiKernelLevel")).size()) { + std::cout << "MultiKernelName and MultiKernelLevel has to be of same size!" << std::endl; + exit(1); + } + //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + + return data; } - - - - diff --git a/src/basics/Core/Input/ConfigFileReader/ConfigFileReader.h b/src/basics/Core/Input/ConfigFileReader/ConfigFileReader.h index 6dd241967652c9246640458e4fd1283766c32701..9d88dfce6a7337d8ffaa7c4ffe43a4fd63949914 100644 --- a/src/basics/Core/Input/ConfigFileReader/ConfigFileReader.h +++ b/src/basics/Core/Input/ConfigFileReader/ConfigFileReader.h @@ -7,7 +7,7 @@ class ConfigData; -class ConfigFileReader +class ConfigFileReader { public: BASICS_EXPORT static std::shared_ptr<ConfigFileReader> getNewInstance(); @@ -16,6 +16,6 @@ public: BASICS_EXPORT std::shared_ptr<ConfigData> readConfigFile(const std::string &filePath) const; private: - ConfigFileReader(); + ConfigFileReader(); }; #endif diff --git a/src/basics/Core/Input/ConfigInput/ConfigInput.cpp b/src/basics/Core/Input/ConfigInput/ConfigInput.cpp index d894bcc28bd179e0c63b0f2ddf26adc9c070de36..1fdff1e8794b5cb58f6b1a8a2e97a536531df829 100644 --- a/src/basics/Core/Input/ConfigInput/ConfigInput.cpp +++ b/src/basics/Core/Input/ConfigInput/ConfigInput.cpp @@ -1,263 +1,222 @@ #include "ConfigInput.h" -#include <cerrno> #include <algorithm> -#include <sstream> +#include <cerrno> #include <iostream> +#include <sstream> #include <string> #define COMMENT '#' namespace input { - // Trim the given characters from the beginning and end of a string. - // the default is to trim whitespace. If the string is empty or contains - // only the trim characters, an empty string is returned. - std::string trim(const std::string &instring, const std::string &trimstring = std::string(" \t\n")) - { - if (trimstring.size() == 0) - return instring; - std::string temp = ""; - std::string::size_type begpos = instring.find_first_not_of(trimstring); - if (begpos == std::string::npos) - { - return temp; - } - else - { - std::string::size_type endpos = instring.find_last_not_of(trimstring); - temp = instring.substr(begpos, endpos - begpos + 1); - } +// Trim the given characters from the beginning and end of a string. +// the default is to trim whitespace. If the string is empty or contains +// only the trim characters, an empty string is returned. +std::string trim(const std::string &instring, const std::string &trimstring = std::string(" \t\n")) +{ + if (trimstring.size() == 0) + return instring; + std::string temp = ""; + std::string::size_type begpos = instring.find_first_not_of(trimstring); + if (begpos == std::string::npos) { return temp; + } else { + std::string::size_type endpos = instring.find_last_not_of(trimstring); + temp = instring.substr(begpos, endpos - begpos + 1); } + return temp; +} - ConfigInput::ConfigInput(std::istream &stream) : stream(stream) - { - while (!stream.eof()) - this->setTokenValuePair(); - } +ConfigInput::ConfigInput(std::istream &stream) : stream(stream) +{ + while (!stream.eof()) + this->setTokenValuePair(); +} - ConfigInput::~ConfigInput() - = default; +ConfigInput::~ConfigInput() = default; - bool ConfigInput::hasValue(const std::string &key) const - { - bool valueFound = false; - std::string keyCopy = key; - this->makeLower(keyCopy); - if (configEntries.find(keyCopy.c_str()) != configEntries.end()) - valueFound = true; +bool ConfigInput::hasValue(const std::string &key) const +{ + bool valueFound = false; + std::string keyCopy = key; + this->makeLower(keyCopy); + if (configEntries.find(keyCopy.c_str()) != configEntries.end()) + valueFound = true; - return valueFound; - } + return valueFound; +} - std::string ConfigInput::getValue(const std::string &key) - { - std::string keyCopy = key; - this->makeLower(keyCopy); - if (configEntries.find(keyCopy.c_str()) != configEntries.end()) - return (*configEntries.find(keyCopy.c_str())).second; - return ""; - } +std::string ConfigInput::getValue(const std::string &key) +{ + std::string keyCopy = key; + this->makeLower(keyCopy); + if (configEntries.find(keyCopy.c_str()) != configEntries.end()) + return (*configEntries.find(keyCopy.c_str())).second; + return ""; +} - ////////////////////////////////////////////////////////////////////////// - // private methods // - ////////////////////////////////////////////////////////////////////////// +////////////////////////////////////////////////////////////////////////// +// private methods // +////////////////////////////////////////////////////////////////////////// - void ConfigInput::makeLower(std::string &value) const - { - for (size_t i = 0; i < value.size(); i++) - value[i] = tolower(value[i]); - } +void ConfigInput::makeLower(std::string &value) const +{ + for (size_t i = 0; i < value.size(); i++) + value[i] = tolower(value[i]); +} - void ConfigInput::setTokenValuePair() - { - this->eatWhiteAndComments(true); +void ConfigInput::setTokenValuePair() +{ + this->eatWhiteAndComments(true); - std::string token; - if(!this->setToken(token)) - return; + std::string token; + if (!this->setToken(token)) + return; - std::string value; - this->setValue(value); + std::string value; + this->setValue(value); - configEntries.insert(String_Pair(token, value)); - } + configEntries.insert(String_Pair(token, value)); +} - bool ConfigInput::setToken(std::string &token) - { - char tokenChar[1024]; - bool foundEqualSign = false; - int charIndex = 0; +bool ConfigInput::setToken(std::string &token) +{ + char tokenChar[1024]; + bool foundEqualSign = false; + int charIndex = 0; - this->findToken(foundEqualSign, tokenChar, charIndex); + this->findToken(foundEqualSign, tokenChar, charIndex); - if (!isToken(charIndex, foundEqualSign)) - return false; + if (!isToken(charIndex, foundEqualSign)) + return false; - this->nullTerminate(tokenChar, charIndex); - token = tokenChar; - makeLower(token); - return true; - } + this->nullTerminate(tokenChar, charIndex); + token = tokenChar; + makeLower(token); + return true; +} - void ConfigInput::findToken(bool &foundEqualSign, char *token, int &i) - { - char ch; - while (!(stream.get(ch)).fail()) - { - if ((ch != '\t')) - { - if ((ch == '=') || (ch == ' ') || (ch == '\n') || (ch == '\r') || (ch == '\t')) - { - foundEqualSign = true; - break; - } - token[i++] = ch; +void ConfigInput::findToken(bool &foundEqualSign, char *token, int &i) +{ + char ch; + while (!(stream.get(ch)).fail()) { + if ((ch != '\t')) { + if ((ch == '=') || (ch == ' ') || (ch == '\n') || (ch == '\r') || (ch == '\t')) { + foundEqualSign = true; + break; } + token[i++] = ch; } } +} - - bool ConfigInput::isToken(int charIndex, bool foundEqualSign) - { - if (charIndex == 0) - { - configEntries.insert(String_Pair("", "")); - return false; - } - - if (!foundEqualSign && !advanceToEqualSignOnLine()) - { - configEntries.insert(String_Pair("", "")); - return false; - } - return true; +bool ConfigInput::isToken(int charIndex, bool foundEqualSign) +{ + if (charIndex == 0) { + configEntries.insert(String_Pair("", "")); + return false; } - void ConfigInput::setValue(std::string &value) - { - int charIndex = 0; - char valueChar[1024]; - this->findValue(charIndex, valueChar); - - if (charIndex == 0) - value = ""; - else - { - this->nullTerminate(valueChar, charIndex); - value = valueChar; - value = trim(value); - this->stripLeadingAndTrailingQuotes(value); - } + if (!foundEqualSign && !advanceToEqualSignOnLine()) { + configEntries.insert(String_Pair("", "")); + return false; } + return true; +} +void ConfigInput::setValue(std::string &value) +{ + int charIndex = 0; + char valueChar[1024]; + this->findValue(charIndex, valueChar); + + if (charIndex == 0) + value = ""; + else { + this->nullTerminate(valueChar, charIndex); + value = valueChar; + value = trim(value); + this->stripLeadingAndTrailingQuotes(value); + } +} - int ConfigInput::findValue(int &charIndex, char * value) - { - char ch; - char c = eatWhiteAndComments(false); - if (c != '\n') - { - charIndex = 0; - while (!(stream.get(ch)).fail()) - { - if ((ch == '\t') || (ch == '\r') || (ch == '\n') || (ch == '#')) - { - while (ch != '\n') - { - if (stream.get(ch).fail()) break; - } - break; - } - else - { - value[charIndex++] = ch; +int ConfigInput::findValue(int &charIndex, char *value) +{ + char ch; + char c = eatWhiteAndComments(false); + if (c != '\n') { + charIndex = 0; + while (!(stream.get(ch)).fail()) { + if ((ch == '\t') || (ch == '\r') || (ch == '\n') || (ch == '#')) { + while (ch != '\n') { + if (stream.get(ch).fail()) + break; } + break; + } else { + value[charIndex++] = ch; } - } - return charIndex; + } } + return charIndex; +} +void ConfigInput::stripLeadingAndTrailingQuotes(std::string &m_value) +{ + if (m_value[0] == '"') + m_value = m_value.substr(1); + if (m_value[m_value.length() - 1] == '"') + m_value = m_value.substr(0, m_value.length() - 1); +} +void ConfigInput::nullTerminate(char *value, int &i) { value[i++] = '\0'; } - void ConfigInput::stripLeadingAndTrailingQuotes(std::string &m_value) - { - if (m_value[0] == '"') - m_value = m_value.substr(1); - if (m_value[m_value.length() - 1] == '"') - m_value = m_value.substr(0, m_value.length() - 1); - } - - void ConfigInput::nullTerminate(char *value, int &i) - { - value[i++] = '\0'; - } - - bool ConfigInput::advanceToEqualSignOnLine() - { - char ch; - bool foundEqual = false; - while (!(stream.get(ch)).fail()) - { - if (isNewLine(ch) || isCarriageReturn(ch)) - break; - if (isEqualSign(ch)) - { - foundEqual = true; - break; - } +bool ConfigInput::advanceToEqualSignOnLine() +{ + char ch; + bool foundEqual = false; + while (!(stream.get(ch)).fail()) { + if (isNewLine(ch) || isCarriageReturn(ch)) + break; + if (isEqualSign(ch)) { + foundEqual = true; + break; } - return foundEqual; } + return foundEqual; +} - char ConfigInput::eatWhiteAndComments(bool traverseNewlines) - { - char ch; - bool isComment = false; - - while (!(stream.get(ch)).fail()) - { - if (isCommentSign(ch)) - isComment = true; - else if (isNewLine(ch)) - { - isComment = false; - if (!traverseNewlines) - return(ch); - } - else if (isRegularChar(isComment, ch)) - { - stream.putback(ch); - return 0; - } +char ConfigInput::eatWhiteAndComments(bool traverseNewlines) +{ + char ch; + bool isComment = false; + + while (!(stream.get(ch)).fail()) { + if (isCommentSign(ch)) + isComment = true; + else if (isNewLine(ch)) { + isComment = false; + if (!traverseNewlines) + return (ch); + } else if (isRegularChar(isComment, ch)) { + stream.putback(ch); + return 0; } - return 0; - } - - bool ConfigInput::isRegularChar(bool isComment, char ch) - { - return (!isComment) && (ch != ' ') && (ch != '\t') && (ch != '\r'); } + return 0; +} - bool ConfigInput::isCommentSign(char ch) - { - return ch == COMMENT; - } +bool ConfigInput::isRegularChar(bool isComment, char ch) +{ + return (!isComment) && (ch != ' ') && (ch != '\t') && (ch != '\r'); +} - bool ConfigInput::isEqualSign(char ch) - { - return ch == '='; - } +bool ConfigInput::isCommentSign(char ch) { return ch == COMMENT; } - bool ConfigInput::isNewLine(char ch) - { - return ch == '\n'; - } +bool ConfigInput::isEqualSign(char ch) { return ch == '='; } - bool ConfigInput::isCarriageReturn(char ch) - { - return ch == '\r'; - } +bool ConfigInput::isNewLine(char ch) { return ch == '\n'; } +bool ConfigInput::isCarriageReturn(char ch) { return ch == '\r'; } -} +} // namespace input diff --git a/src/basics/Core/Input/ConfigInput/ConfigInput.h b/src/basics/Core/Input/ConfigInput/ConfigInput.h index d01e1b8128366ad5bd4287937b8f7c5577237528..aee9242ca7cb63ac259fe27869c0d4f9d5036b05 100644 --- a/src/basics/Core/Input/ConfigInput/ConfigInput.h +++ b/src/basics/Core/Input/ConfigInput/ConfigInput.h @@ -1,48 +1,48 @@ #ifndef ConfigInput_H #define ConfigInput_H -#include <string> -#include <vector> #include <istream> -#include <memory> -#include <map> #include <list> +#include <map> +#include <memory> +#include <string> +#include <vector> -#include "basics_export.h" #include "../Input.h" +#include "basics_export.h" -namespace input +namespace input +{ +class ConfigInput : public Input { - class ConfigInput : public Input - { - public: - BASICS_EXPORT ConfigInput(std::istream &stream); - BASICS_EXPORT ~ConfigInput() override; - - BASICS_EXPORT bool hasValue(const std::string &key) const override; - BASICS_EXPORT std::string getValue(const std::string &key) override; +public: + BASICS_EXPORT ConfigInput(std::istream &stream); + BASICS_EXPORT ~ConfigInput() override; + + BASICS_EXPORT bool hasValue(const std::string &key) const override; + BASICS_EXPORT std::string getValue(const std::string &key) override; - protected: - virtual void setTokenValuePair(); - void setValue(std::string &value); - bool setToken(std::string &token); - bool isToken(int charIndex, bool foundEqualSign); - int findValue(int &charIndex, char * value); - void stripLeadingAndTrailingQuotes(std::string &m_value); - void nullTerminate(char * token, int &i); - void findToken(bool &foundEqualSign, char * token, int &i); - char eatWhiteAndComments(bool traverse_newlines = true); - bool isRegularChar(bool isComment, char ch); - bool isNewLine(char ch); - bool isCommentSign(char ch); - bool advanceToEqualSignOnLine(); - bool isCarriageReturn(char ch); - bool isEqualSign(char ch); - void makeLower(std::string &instring) const; +protected: + virtual void setTokenValuePair(); + void setValue(std::string &value); + bool setToken(std::string &token); + bool isToken(int charIndex, bool foundEqualSign); + int findValue(int &charIndex, char *value); + void stripLeadingAndTrailingQuotes(std::string &m_value); + void nullTerminate(char *token, int &i); + void findToken(bool &foundEqualSign, char *token, int &i); + char eatWhiteAndComments(bool traverse_newlines = true); + bool isRegularChar(bool isComment, char ch); + bool isNewLine(char ch); + bool isCommentSign(char ch); + bool advanceToEqualSignOnLine(); + bool isCarriageReturn(char ch); + bool isEqualSign(char ch); + void makeLower(std::string &instring) const; - protected: - std::istream &stream; - using String_Pair = std::pair <std::string, std::string>; - std::map<std::string, std::string> configEntries; - }; -} +protected: + std::istream &stream; + using String_Pair = std::pair<std::string, std::string>; + std::map<std::string, std::string> configEntries; +}; +} // namespace input #endif diff --git a/src/basics/Core/Input/Input.cpp b/src/basics/Core/Input/Input.cpp index 4d2aee7de00d2e74727246f3720616a653aabc81..f971dd2260d97c28c6e84f60d9b0415eb971ea16 100644 --- a/src/basics/Core/Input/Input.cpp +++ b/src/basics/Core/Input/Input.cpp @@ -11,15 +11,14 @@ namespace input { - std::unique_ptr<input::Input> Input::makeInput(std::istream &stream, const std::string & /*inputType*/) - { +std::unique_ptr<input::Input> Input::makeInput(std::istream &stream, const std::string & /*inputType*/) +{ #ifdef BUILD_JSONCPP - if(inputType == "json") - return std::unique_ptr<Input>(new JsonInput(stream)); + if (inputType == "json") + return std::unique_ptr<Input>(new JsonInput(stream)); #endif - return std::make_unique<ConfigInput>(stream); - } - + return std::make_unique<ConfigInput>(stream); } +} // namespace input diff --git a/src/basics/Core/Input/Input.h b/src/basics/Core/Input/Input.h index 9c95e2a167139b9ba3bab2937ed5d666ba1e1022..3b07b8b32d99293c3216e1a14dc9df9fc9688bea 100644 --- a/src/basics/Core/Input/Input.h +++ b/src/basics/Core/Input/Input.h @@ -3,23 +3,22 @@ #include "basics_export.h" - -#include <string> -#include <memory> #include <istream> +#include <memory> +#include <string> namespace input { - class Input - { - public: - static BASICS_EXPORT std::unique_ptr<Input> makeInput(std::istream &stream, const std::string &inputType); +class Input +{ +public: + static BASICS_EXPORT std::unique_ptr<Input> makeInput(std::istream &stream, const std::string &inputType); - virtual ~Input() = default; + virtual ~Input() = default; - virtual bool hasValue(const std::string &key) const = 0; - virtual std::string getValue(const std::string &key) = 0; - }; -} + virtual bool hasValue(const std::string &key) const = 0; + virtual std::string getValue(const std::string &key) = 0; +}; +} // namespace input #endif diff --git a/src/basics/Core/Input/JsonInput/JsonInput.cpp b/src/basics/Core/Input/JsonInput/JsonInput.cpp index 9524e87ed3e069cac68658803ff8614b1f4ffec7..34a1d154a386d267c4d086e28b5f7e5f64c302cc 100644 --- a/src/basics/Core/Input/JsonInput/JsonInput.cpp +++ b/src/basics/Core/Input/JsonInput/JsonInput.cpp @@ -3,64 +3,65 @@ #include "JsonInput.h" #include <fstream> -#include <string> +#include <iterator> #include <sstream> +#include <string> #include <vector> -#include <iterator> namespace input { - template<typename Out> - void split(const std::string &s, char delim, Out result) { - std::stringstream ss; - ss.str(s); - std::string item; - while (std::getline(ss, item, delim)) { - *(result++) = item; - } - } - - std::vector<std::string> split(const std::string &s, char delim) { - std::vector<std::string> elems; - split(s, delim, std::back_inserter(elems)); - return elems; - } - - JsonInput::JsonInput(std::istream &stream) - { - Json::Reader reader; - reader.parse(stream, jsonValue); +template <typename Out> +void split(const std::string &s, char delim, Out result) +{ + std::stringstream ss; + ss.str(s); + std::string item; + while (std::getline(ss, item, delim)) { + *(result++) = item; } +} - bool JsonInput::hasValue(const std::string &key) const - { - auto keys = split(key, ' '); +std::vector<std::string> split(const std::string &s, char delim) +{ + std::vector<std::string> elems; + split(s, delim, std::back_inserter(elems)); + return elems; +} - if (keys.size() == 1 && !jsonValue[keys[0]].isNull()) - return true; - else if (keys.size() == 2 && !jsonValue[keys[0]][keys[1]].isNull()) - return true; - else if (keys.size() == 3 && !jsonValue[keys[0]][keys[1]][keys[2]].isNull()) - return true; - else - return false; - } +JsonInput::JsonInput(std::istream &stream) +{ + Json::Reader reader; + reader.parse(stream, jsonValue); +} - std::string JsonInput::getValue(const std::string &key) - { - auto keys = split(key, ' '); +bool JsonInput::hasValue(const std::string &key) const +{ + auto keys = split(key, ' '); - if(keys.size() == 1) - return jsonValue[keys[0]].asString(); - else if (keys.size() == 2) - return jsonValue[keys[0]][keys[1]].asString(); - else if (keys.size() == 3) - return jsonValue[keys[0]][keys[1]][keys[2]].asString(); - else - return ""; - } + if (keys.size() == 1 && !jsonValue[keys[0]].isNull()) + return true; + else if (keys.size() == 2 && !jsonValue[keys[0]][keys[1]].isNull()) + return true; + else if (keys.size() == 3 && !jsonValue[keys[0]][keys[1]][keys[2]].isNull()) + return true; + else + return false; +} +std::string JsonInput::getValue(const std::string &key) +{ + auto keys = split(key, ' '); + if (keys.size() == 1) + return jsonValue[keys[0]].asString(); + else if (keys.size() == 2) + return jsonValue[keys[0]][keys[1]].asString(); + else if (keys.size() == 3) + return jsonValue[keys[0]][keys[1]][keys[2]].asString(); + else + return ""; } +} // namespace input + #endif diff --git a/src/basics/Core/Input/JsonInput/JsonInput.h b/src/basics/Core/Input/JsonInput/JsonInput.h index 5e1d81e688db6aeb514a3950d344f5f057c17119..8a33e99bfe2904caff82349caaf2579049892b15 100644 --- a/src/basics/Core/Input/JsonInput/JsonInput.h +++ b/src/basics/Core/Input/JsonInput/JsonInput.h @@ -3,31 +3,27 @@ #ifndef JsonInput_H #define JsonInput_H - -#include <string> #include <json/json.h> - +#include <string> #include "basics_export.h" - #include "../Input.h" namespace input { - class JsonInput : public Input - { - public: - BASICS_EXPORT JsonInput(std::istream &stream); - - BASICS_EXPORT virtual bool hasValue(const std::string &key) const override; - BASICS_EXPORT virtual std::string getValue(const std::string &key) override; +class JsonInput : public Input +{ +public: + BASICS_EXPORT JsonInput(std::istream &stream); - private: - Json::Value jsonValue; + BASICS_EXPORT virtual bool hasValue(const std::string &key) const override; + BASICS_EXPORT virtual std::string getValue(const std::string &key) override; - }; -} +private: + Json::Value jsonValue; +}; +} // namespace input #endif diff --git a/src/basics/Core/LbmOrGks.h b/src/basics/Core/LbmOrGks.h index 96ef76a5a76cb029ab8aef7767574f18906c451a..ae4a17cad6488ee8ec95c19c3e3766abd408b0bf 100644 --- a/src/basics/Core/LbmOrGks.h +++ b/src/basics/Core/LbmOrGks.h @@ -1,28 +1,28 @@ //======================================================================================= -// ____ ____ __ ______ __________ __ __ __ __ -// \ \ | | | | | _ \ |___ ___| | | | | / \ | | -// \ \ | | | | | |_) | | | | | | | / \ | | -// \ \ | | | | | _ / | | | | | | / /\ \ | | -// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ -// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| -// \ \ | | ________________________________________________________________ -// \ \ | | | ______________________________________________________________| -// \ \| | | | __ __ __ __ ______ _______ -// \ | | |_____ | | | | | | | | | _ \ / _____) -// \ | | _____| | | | | | | | | | | \ \ \_______ +// ____ ____ __ ______ __________ __ __ __ __ +// \ \ | | | | | _ \ |___ ___| | | | | / \ | | +// \ \ | | | | | |_) | | | | | | | / \ | | +// \ \ | | | | | _ / | | | | | | / /\ \ | | +// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ +// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| +// \ \ | | ________________________________________________________________ +// \ \ | | | ______________________________________________________________| +// \ \| | | | __ __ __ __ ______ _______ +// \ | | |_____ | | | | | | | | | _ \ / _____) +// \ | | _____| | | | | | | | | | | \ \ \_______ // \ | | | | |_____ | \_/ | | | | |_/ / _____ | -// \ _____| |__| |________| \_______/ |__| |______/ (_______/ +// \ _____| |__| |________| \_______/ |__| |______/ (_______/ // -// This file is part of VirtualFluids. VirtualFluids is free software: you can +// This file is part of VirtualFluids. VirtualFluids is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of +// License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. -// -// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// +// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License along // with VirtualFluids (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>. // @@ -33,10 +33,6 @@ #ifndef LBMORGKS_H #define LBMORGKS_H -enum LbmOrGks -{ - LBM, - GKS -}; +enum LbmOrGks { LBM, GKS }; #endif diff --git a/src/basics/Core/Logger/Logger.cpp b/src/basics/Core/Logger/Logger.cpp index f7a9b2a1ec2ceb788840d918bbe08fff1e757795..6ee96cba58ad6a4c95e25792963027b2e53a4df7 100644 --- a/src/basics/Core/Logger/Logger.cpp +++ b/src/basics/Core/Logger/Logger.cpp @@ -1,86 +1,61 @@ #include "Logger.h" //#include "mpi.h" -#include <memory> #include <iostream> +#include <memory> #include "implementations/LoggerImp.h" +namespace logging +{ +std::shared_ptr<Logger> out = nullptr; -namespace logging { - - std::shared_ptr<Logger> out = nullptr; +logging::Logger::Level logging::Logger::globalLogLevel = logging::Logger::INFO_LOW; +logging::Logger::Level logging::Logger::localLogLevel = logging::Logger::INFO_LOW; +bool logging::Logger::printRankNumber = false; +bool logging::Logger::timeStampEnabled = false; - logging::Logger::Level logging::Logger::globalLogLevel = logging::Logger::INFO_LOW; - logging::Logger::Level logging::Logger::localLogLevel = logging::Logger::INFO_LOW; - bool logging::Logger::printRankNumber = false; - bool logging::Logger::timeStampEnabled = false; - +logging::Logger::Logger(std::ostream *stream) { streams.push_back(stream); } - logging::Logger::Logger(std::ostream* stream) - { - streams.push_back(stream); - } +logging::Logger::~Logger() = default; - logging::Logger::~Logger() - = default; - - void Logger::addStreamToList(std::ostream* stream) - { - streams.push_back(stream); - } - - void Logger::resetStreamList() - { - streams.clear(); - } +void Logger::addStreamToList(std::ostream *stream) { streams.push_back(stream); } +void Logger::resetStreamList() { streams.clear(); } //-----------static methods----------------// - void logging::Logger::resetStreams() - { - if (!out) - out = std::make_shared<LoggerImp>(&std::cout); +void logging::Logger::resetStreams() +{ + if (!out) + out = std::make_shared<LoggerImp>(&std::cout); - out->resetStreamList(); - } + out->resetStreamList(); +} - void logging::Logger::setStream(std::ostream* stream) - { - out = std::make_shared<LoggerImp>(stream); - } +void logging::Logger::setStream(std::ostream *stream) { out = std::make_shared<LoggerImp>(stream); } - void logging::Logger::addStream(std::ostream* stream) - { - if (!out) - out = std::make_shared<LoggerImp>(stream); - else - out->addStreamToList(stream); - } +void logging::Logger::addStream(std::ostream *stream) +{ + if (!out) + out = std::make_shared<LoggerImp>(stream); + else + out->addStreamToList(stream); +} - void logging::Logger::timeStamp(TimeStamp timeStamp) - { - switch(timeStamp) - { +void logging::Logger::timeStamp(TimeStamp timeStamp) +{ + switch (timeStamp) { case ENABLE: timeStampEnabled = true; break; case DISABLE: timeStampEnabled = false; break; - } } +} +void logging::Logger::setDebugLevel(const Level &level) { globalLogLevel = level; } +void logging::Logger::enablePrintedRankNumbers(bool print) { printRankNumber = print; } - void logging::Logger::setDebugLevel(const Level &level) - { - globalLogLevel = level; - } - - void logging::Logger::enablePrintedRankNumbers(bool print) - { - printRankNumber = print; - } - -} +} // namespace logging diff --git a/src/basics/Core/Logger/Logger.h b/src/basics/Core/Logger/Logger.h index fa8a00040b63a4c9c8063be91376f500e2c96ba0..d0cd91938868283ec7d13faa7439cf22d7c00729 100644 --- a/src/basics/Core/Logger/Logger.h +++ b/src/basics/Core/Logger/Logger.h @@ -3,68 +3,54 @@ #include "basics_export.h" -#include <string> #include <memory> #include <ostream> +#include <string> #include <vector> -namespace logging +namespace logging { - class BASICS_EXPORT Logger - { - protected: - Logger(std::ostream* stream); - - public: - virtual ~Logger(); - - enum Level - { - INFO_LOW = 3, - INFO_INTERMEDIATE = 2, - INFO_HIGH = 1, - WARNING = 0, - LOGGER_ERROR = -1 - }; - - enum TimeStamp - { - ENABLE, - DISABLE - }; +class BASICS_EXPORT Logger +{ +protected: + Logger(std::ostream *stream); - static void setStream(std::ostream* stream); - static void addStream(std::ostream* stream); - static void resetStreams(); +public: + virtual ~Logger(); - static void timeStamp(TimeStamp timeStamp); + enum Level { INFO_LOW = 3, INFO_INTERMEDIATE = 2, INFO_HIGH = 1, WARNING = 0, LOGGER_ERROR = -1 }; - static void setDebugLevel(const Level &level = Level::LOGGER_ERROR); - static void enablePrintedRankNumbers(bool printRankNumbers); + enum TimeStamp { ENABLE, DISABLE }; - virtual Logger& operator<<(const Level &level) = 0; - virtual Logger& operator<<(const std::string &log) = 0; - virtual Logger& operator<<(const int &log) = 0; - virtual Logger& operator<<(const unsigned int &log) = 0; - virtual Logger& operator<<(const unsigned long& log) = 0; - virtual Logger& operator<<(const float &log) = 0; - virtual Logger& operator<<(const double &log) = 0; + static void setStream(std::ostream *stream); + static void addStream(std::ostream *stream); + static void resetStreams(); - protected: - void addStreamToList(std::ostream* stream); - void resetStreamList(); + static void timeStamp(TimeStamp timeStamp); - std::vector<std::ostream*> streams; + static void setDebugLevel(const Level &level = Level::LOGGER_ERROR); + static void enablePrintedRankNumbers(bool printRankNumbers); - static Level globalLogLevel; - static Level localLogLevel; - static bool printRankNumber; - static bool timeStampEnabled; + virtual Logger &operator<<(const Level &level) = 0; + virtual Logger &operator<<(const std::string &log) = 0; + virtual Logger &operator<<(const int &log) = 0; + virtual Logger &operator<<(const unsigned int &log) = 0; + virtual Logger &operator<<(const unsigned long &log) = 0; + virtual Logger &operator<<(const float &log) = 0; + virtual Logger &operator<<(const double &log) = 0; - }; - extern BASICS_EXPORT std::shared_ptr<Logger> out; -} +protected: + void addStreamToList(std::ostream *stream); + void resetStreamList(); + std::vector<std::ostream *> streams; + static Level globalLogLevel; + static Level localLogLevel; + static bool printRankNumber; + static bool timeStampEnabled; +}; +extern BASICS_EXPORT std::shared_ptr<Logger> out; +} // namespace logging #endif diff --git a/src/basics/Core/Logger/implementations/LoggerImp.cpp b/src/basics/Core/Logger/implementations/LoggerImp.cpp index 48ad23a3082539706fa70b5d4ae895b35b0a7782..f002fdc59ee0a92bdc1be79a74aa347f0451600d 100644 --- a/src/basics/Core/Logger/implementations/LoggerImp.cpp +++ b/src/basics/Core/Logger/implementations/LoggerImp.cpp @@ -1,68 +1,52 @@ #include "LoggerImp.h" +#include <chrono> +#include <iomanip> +#include <iostream> #include <mpi.h> #include <sstream> -#include <iostream> -#include <iomanip> -#include <chrono> - -logging::LoggerImp::LoggerImp(std::ostream* stream) : logging::Logger(stream) +logging::LoggerImp::LoggerImp(std::ostream *stream) : logging::Logger(stream) { levelString[Level::WARNING] = "[WARNING] "; - levelString[Level::LOGGER_ERROR] = "[ERROR] "; + levelString[Level::LOGGER_ERROR] = "[ERROR] "; levelString[Level::INFO_LOW] = "[INFO_LOW] "; levelString[Level::INFO_INTERMEDIATE] = "[INFO_INTERMEDIATE]"; levelString[Level::INFO_HIGH] = "[INFO_HIGH] "; } -logging::LoggerImp::~LoggerImp() -= default; +logging::LoggerImp::~LoggerImp() = default; -logging::Logger& logging::LoggerImp::operator<<(const Level &level) +logging::Logger &logging::LoggerImp::operator<<(const Level &level) { localLogLevel = level; return *this; } +logging::Logger &logging::LoggerImp::operator<<(const std::string &message) { return this->log(message); } -logging::Logger& logging::LoggerImp::operator<<(const std::string &message) -{ - return this->log(message); -} - -logging::Logger& logging::LoggerImp::operator<<(const int &message) -{ - return this->log(std::to_string(message)); -} +logging::Logger &logging::LoggerImp::operator<<(const int &message) { return this->log(std::to_string(message)); } -logging::Logger& logging::LoggerImp::operator<<(const unsigned int &message) +logging::Logger &logging::LoggerImp::operator<<(const unsigned int &message) { return this->log(std::to_string(message)); } -logging::Logger& logging::LoggerImp::operator<<(const unsigned long &message) +logging::Logger &logging::LoggerImp::operator<<(const unsigned long &message) { return this->log(std::to_string(message)); } -logging::Logger& logging::LoggerImp::operator<<(const float &message) -{ - return this->log(std::to_string(message)); -} +logging::Logger &logging::LoggerImp::operator<<(const float &message) { return this->log(std::to_string(message)); } -logging::Logger& logging::LoggerImp::operator<<(const double &message) -{ - return this->log(std::to_string(message)); -} +logging::Logger &logging::LoggerImp::operator<<(const double &message) { return this->log(std::to_string(message)); } -logging::Logger& logging::LoggerImp::log(const std::string &message) +logging::Logger &logging::LoggerImp::log(const std::string &message) { - if (shouldBeLogged()) - { + if (shouldBeLogged()) { std::string modifiedMessage = message; addDebugInformation(modifiedMessage); - for(auto stream : streams) + for (auto stream : streams) *stream << modifiedMessage << std::flush; } std::size_t found = message.find(std::string("\n")); @@ -74,43 +58,37 @@ logging::Logger& logging::LoggerImp::log(const std::string &message) return *this; } -bool logging::LoggerImp::shouldBeLogged() -{ - return localLogLevel <= globalLogLevel; -} +bool logging::LoggerImp::shouldBeLogged() { return localLogLevel <= globalLogLevel; } -void logging::LoggerImp::addDebugInformation(std::string& message) +void logging::LoggerImp::addDebugInformation(std::string &message) { if (newLoggingLine) { std::stringstream os; - os << levelString[localLogLevel] << getTimeStamp() << " " << message; + os << levelString[localLogLevel] << getTimeStamp() << " " << message; message = os.str(); } } - std::string logging::LoggerImp::getTimeStamp() { if (!timeStampEnabled) return ""; const auto now = std::chrono::system_clock::now(); - time_t tt = std::chrono::system_clock::to_time_t(now); - //const tm utc_tm = *gmtime(&tt); + time_t tt = std::chrono::system_clock::to_time_t(now); + // const tm utc_tm = *gmtime(&tt); const tm local_tm = *localtime(&tt); std::stringstream os; os << " [" << std::setw(2) << std::setfill('0') << local_tm.tm_hour << ":"; - os << std::setw(2) << std::setfill('0') << local_tm.tm_min << ":"; - os << std::setw(2) << std::setfill('0') << local_tm.tm_sec << "]"; + os << std::setw(2) << std::setfill('0') << local_tm.tm_min << ":"; + os << std::setw(2) << std::setfill('0') << local_tm.tm_sec << "]"; return os.str(); } - std::string logging::LoggerImp::getRankString() { int rank; MPI_Comm_rank(MPI_COMM_WORLD, &rank); return printRankNumber ? "[" + std::to_string(rank) + "] " : ""; } - diff --git a/src/basics/Core/Logger/implementations/LoggerImp.h b/src/basics/Core/Logger/implementations/LoggerImp.h index 851f294640d887be8d4ac32d17130c6713d13eac..45b64b6dc2208991ca3c1ac67ad80af0b2ea6f22 100644 --- a/src/basics/Core/Logger/implementations/LoggerImp.h +++ b/src/basics/Core/Logger/implementations/LoggerImp.h @@ -1,7 +1,6 @@ #ifndef LoggerImp_H #define LoggerImp_H - #include "basics_export.h" #include <string> @@ -12,35 +11,33 @@ namespace logging { - class BASICS_EXPORT LoggerImp : public Logger - { - public: - LoggerImp(std::ostream* stream); - ~LoggerImp() override; - - Logger& operator<<(const Level &level) override; - Logger& operator<<(const std::string &message) override; - Logger& operator<<(const int &message) override; - Logger& operator<<(const unsigned int &message) override; - Logger& operator<<(const unsigned long& log) override; - Logger& operator<<(const float &message) override; - Logger& operator<<(const double &message) override; - - - private: - std::string getRankString(); - static bool shouldBeLogged(); - - static std::string getTimeStamp(); - void addDebugInformation(std::string& message); - logging::Logger& log(const std::string &message); - - private: - std::map<Logger::Level, std::string> levelString; - bool newLoggingLine = true; - }; - -} - +class BASICS_EXPORT LoggerImp : public Logger +{ +public: + LoggerImp(std::ostream *stream); + ~LoggerImp() override; + + Logger &operator<<(const Level &level) override; + Logger &operator<<(const std::string &message) override; + Logger &operator<<(const int &message) override; + Logger &operator<<(const unsigned int &message) override; + Logger &operator<<(const unsigned long &log) override; + Logger &operator<<(const float &message) override; + Logger &operator<<(const double &message) override; + +private: + std::string getRankString(); + static bool shouldBeLogged(); + + static std::string getTimeStamp(); + void addDebugInformation(std::string &message); + logging::Logger &log(const std::string &message); + +private: + std::map<Logger::Level, std::string> levelString; + bool newLoggingLine = true; +}; + +} // namespace logging #endif diff --git a/src/basics/Core/Logger/implementations/LoggerTest.cpp b/src/basics/Core/Logger/implementations/LoggerTest.cpp index a3b97d6975a592a1638e7c636b319f4d72789564..2c4e4e6819a19497c3061caddbfa4c2a54953054 100644 --- a/src/basics/Core/Logger/implementations/LoggerTest.cpp +++ b/src/basics/Core/Logger/implementations/LoggerTest.cpp @@ -4,7 +4,6 @@ #include "../Logger.h" - TEST(DISABLED_LoggerTest, logStringWithoutSettingLevels_WillPutTheLogMesssageIntoTheStream) { std::ostringstream stream; @@ -21,7 +20,8 @@ TEST(DISABLED_LoggerTest, logStringWithHighDebugLevel_logOnlyHighLevelMessages) logging::Logger::setStream(&stream); logging::Logger::setDebugLevel(logging::Logger::INFO_HIGH); - *logging::out << logging::Logger::INFO_LOW << "Low Debug Message\n" << logging::Logger::INFO_HIGH << "HIGH Debug Message\n"; + *logging::out << logging::Logger::INFO_LOW << "Low Debug Message\n" + << logging::Logger::INFO_HIGH << "HIGH Debug Message\n"; EXPECT_THAT(stream.str(), "[HIGH] HIGH Debug Message\n"); } @@ -35,7 +35,7 @@ TEST(DISABLED_LoggerTest, addTwoStreams_shouldWriteToBoth) logging::out->addStream(&stream2); logging::Logger::setDebugLevel(logging::Logger::INFO_LOW); - *logging::out << logging::Logger::INFO_LOW <<"Hello World\n"; + *logging::out << logging::Logger::INFO_LOW << "Hello World\n"; EXPECT_THAT(stream1.str(), "[LOW] Hello World\n"); EXPECT_THAT(stream2.str(), "[LOW] Hello World\n"); @@ -46,7 +46,8 @@ TEST(DISABLED_LoggerTest, splittetOutputShouldHaveDebugInformationOnce) std::ostringstream stream; logging::Logger::setStream(&stream); - *logging::out << logging::Logger::INFO_LOW << "Hello" << " World\n"; + *logging::out << logging::Logger::INFO_LOW << "Hello" + << " World\n"; EXPECT_THAT(stream.str(), "[LOW] Hello World\n"); } @@ -57,8 +58,8 @@ TEST(DISABLED_LoggerTest, enableTimeStampInOutput) logging::Logger::setStream(&stream); logging::Logger::timeStamp(logging::Logger::TimeStamp::ENABLE); - *logging::out << logging::Logger::INFO_LOW << "Hello" << " World\n"; - + *logging::out << logging::Logger::INFO_LOW << "Hello" + << " World\n"; + EXPECT_THAT(stream.str(), testing::StrNe("[LOW] Hello World\n")); } - diff --git a/src/basics/Core/NonCreatable.h b/src/basics/Core/NonCreatable.h index a93e4db68676cc64733feab5edbad910f88c18ff..b25fc808bf0607a047b46643b412b23fb71037b0 100644 --- a/src/basics/Core/NonCreatable.h +++ b/src/basics/Core/NonCreatable.h @@ -1,18 +1,16 @@ /* -* Author: S. Peters -* mail: peters@irmb.tu-bs.de -*/ + * Author: S. Peters + * mail: peters@irmb.tu-bs.de + */ #ifndef NON_CREATABLE_H #define NON_CREATABLE_H - class NonCreatable { private: - NonCreatable() = delete; - NonCreatable( const NonCreatable& ) = delete; - NonCreatable& operator=( const NonCreatable& ) = delete; + NonCreatable() = delete; + NonCreatable(const NonCreatable &) = delete; + NonCreatable &operator=(const NonCreatable &) = delete; }; - #endif diff --git a/src/basics/Core/RealConstants.h b/src/basics/Core/RealConstants.h index b63ff444f5d86dd67accaf83611ebeb6410f036b..d353a341c9f75d58d11ede3048f3cb0521be40b3 100644 --- a/src/basics/Core/RealConstants.h +++ b/src/basics/Core/RealConstants.h @@ -1,227 +1,223 @@ #ifndef REAL_CONSTANT_H #define REAL_CONSTANT_H - - #ifdef VF_DOUBLE_ACCURACY -#define c1o2 0.5 -#define c3o2 1.5 -#define c1o3 0.333333333333333 -#define c2o3 0.666666666666667 -#define c1o4 0.25 -#define c3o4 0.75 -#define c1o6 0.166666666666667 -#define c1o7 0.142857142857143 -#define c1o8 0.125 -#define c1o9 0.111111111111111 -#define c2o9 0.222222222222222 -#define c4o9 0.444444444444444 -#define c1o10 0.1 -#define c1o12 0.083333333333333 -#define c1o16 0.0625 -#define c3o16 0.1875 -#define c9o16 0.5625 -#define c1o18 0.055555555555556 -#define c1o20 0.05 -#define c19o20 0.95 -#define c21o20 1.05 -#define c1o24 0.041666666666667 -#define c1o27 0.037037037037037 -#define c3o32 0.09375 -#define c4o32 0.125 -#define c1o36 0.027777777777778 -#define c1o48 0.020833333333333 -#define c1o64 0.015625 -#define c3o64 0.046875 -#define c9o64 0.140625 -#define c27o64 0.421875 -#define c1o66 0.015151515151515 -#define c1o72 0.013888888888889 -#define c1o264 0.003787878787879 -#define c8o27 0.296296296296296 -#define c2o27 0.074074074074074 -#define c1o54 0.018518518518519 -#define c1o100 0.01 -#define c99o100 0.99 -#define c1o126 0.007936507936508 -#define c1o216 0.004629629629630 -#define c5o4 1.25 -#define c9o4 2.25 -#define c5o2 2.5 -#define c9o2 4.5 +#define c1o2 0.5 +#define c3o2 1.5 +#define c1o3 0.333333333333333 +#define c2o3 0.666666666666667 +#define c1o4 0.25 +#define c3o4 0.75 +#define c1o6 0.166666666666667 +#define c1o7 0.142857142857143 +#define c1o8 0.125 +#define c1o9 0.111111111111111 +#define c2o9 0.222222222222222 +#define c4o9 0.444444444444444 +#define c1o10 0.1 +#define c1o12 0.083333333333333 +#define c1o16 0.0625 +#define c3o16 0.1875 +#define c9o16 0.5625 +#define c1o18 0.055555555555556 +#define c1o20 0.05 +#define c19o20 0.95 +#define c21o20 1.05 +#define c1o24 0.041666666666667 +#define c1o27 0.037037037037037 +#define c3o32 0.09375 +#define c4o32 0.125 +#define c1o36 0.027777777777778 +#define c1o48 0.020833333333333 +#define c1o64 0.015625 +#define c3o64 0.046875 +#define c9o64 0.140625 +#define c27o64 0.421875 +#define c1o66 0.015151515151515 +#define c1o72 0.013888888888889 +#define c1o264 0.003787878787879 +#define c8o27 0.296296296296296 +#define c2o27 0.074074074074074 +#define c1o54 0.018518518518519 +#define c1o100 0.01 +#define c99o100 0.99 +#define c1o126 0.007936507936508 +#define c1o216 0.004629629629630 +#define c5o4 1.25 +#define c9o4 2.25 +#define c5o2 2.5 +#define c9o2 4.5 -#define c0o1 0. -#define c1o1 1. -#define c2o1 2. -#define c3o1 3. -#define c4o1 4. -#define c5o1 5. -#define c6o1 6. -#define c7o1 7. -#define c8o1 8. -#define c9o1 9. -#define c10o1 10. -#define c11o1 11. -#define c12o1 12. -#define c13o1 13. -#define c14o1 14. -#define c15o1 15. -#define c16o1 16. -#define c17o1 17. -#define c18o1 18. -#define c21o1 21. -#define c24o1 24. -#define c25o1 25. -#define c26o1 26. -#define c27o1 27. -#define c28o1 28. -#define c29o1 29. -#define c30o1 30. -#define c32o1 32. -#define c33o1 33. -#define c34o1 34. -#define c36o1 36. -#define c40o1 40. -#define c42o1 42. -#define c46o1 46. -#define c48o1 48. -#define c50o1 50. -#define c52o1 52. -#define c54o1 54. -#define c56o1 56. -#define c64o1 64. -#define c66o1 66. -#define c68o1 68. -#define c69o1 69. -#define c72o1 72. -#define c84o1 84. -#define c88o1 88. -#define c96o1 96. -#define c100o1 100.0 -#define c130o1 130.0 -#define c152o1 152.0 -#define c166o1 166.0 -#define c195o1 195.0 -#define c216o1 216.0 -#define c264o1 264.0 -#define c290o1 290.0 -#define c367o1 367.0 +#define c0o1 0. +#define c1o1 1. +#define c2o1 2. +#define c3o1 3. +#define c4o1 4. +#define c5o1 5. +#define c6o1 6. +#define c7o1 7. +#define c8o1 8. +#define c9o1 9. +#define c10o1 10. +#define c11o1 11. +#define c12o1 12. +#define c13o1 13. +#define c14o1 14. +#define c15o1 15. +#define c16o1 16. +#define c17o1 17. +#define c18o1 18. +#define c21o1 21. +#define c24o1 24. +#define c25o1 25. +#define c26o1 26. +#define c27o1 27. +#define c28o1 28. +#define c29o1 29. +#define c30o1 30. +#define c32o1 32. +#define c33o1 33. +#define c34o1 34. +#define c36o1 36. +#define c40o1 40. +#define c42o1 42. +#define c46o1 46. +#define c48o1 48. +#define c50o1 50. +#define c52o1 52. +#define c54o1 54. +#define c56o1 56. +#define c64o1 64. +#define c66o1 66. +#define c68o1 68. +#define c69o1 69. +#define c72o1 72. +#define c84o1 84. +#define c88o1 88. +#define c96o1 96. +#define c100o1 100.0 +#define c130o1 130.0 +#define c152o1 152.0 +#define c166o1 166.0 +#define c195o1 195.0 +#define c216o1 216.0 +#define c264o1 264.0 +#define c290o1 290.0 +#define c367o1 367.0 -#define Op0000002 0.0000002 -#define c10eM30 1e-30 -#define c10eM10 1e-10 +#define Op0000002 0.0000002 +#define c10eM30 1e-30 +#define c10eM10 1e-10 #define smallSingle 0.0000000002 - #else -#define c1o2 0.5f -#define c3o2 1.5f -#define c1o3 (1.0f/3.0f) -#define c2o3 (2.0f/3.0f) -#define c1o4 0.25f -#define c3o4 0.75f -#define c1o6 (1.0f/6.0f) -#define c1o7 (1.0f/7.0f) -#define c1o8 0.125f -#define c1o9 (1.0f/9.0f) -#define c2o9 (2.0f/9.0f) -#define c4o9 (4.0f/9.0f) -#define c1o10 0.1f -#define c1o12 (1.0f/12.0f) -#define c1o16 0.0625f -#define c3o16 0.1875f -#define c9o16 0.5625f -#define c1o18 (1.0f/18.0f) -#define c1o20 0.05f -#define c19o20 0.95f -#define c21o20 1.05f -#define c1o24 (1.0f/24.0f) -#define c1o27 (1.0f/27.0f) -#define c3o32 0.09375f -#define c4o32 0.125f -#define c1o36 (1.0f/36.0f) -#define c1o48 (1.0f/48.0f) -#define c1o64 0.015625f -#define c3o64 0.046875f -#define c9o64 0.140625f -#define c27o64 0.421875f -#define c1o66 (1.0f/66.0f) -#define c1o72 (1.0f/72.0f) -#define c1o264 (1.0f/264.0f) -#define c8o27 (8.0f/27.0f) -#define c2o27 (2.0f/27.0f) -#define c1o54 (1.0f/54.0f) -#define c1o100 0.01f -#define c99o100 0.99f -#define c1o126 (1.0f/126.0f) -#define c1o216 (1.0f/216.0f) -#define c5o4 1.25f -#define c9o4 2.25f -#define c5o2 2.5f -#define c9o2 4.5f +#define c1o2 0.5f +#define c3o2 1.5f +#define c1o3 (1.0f / 3.0f) +#define c2o3 (2.0f / 3.0f) +#define c1o4 0.25f +#define c3o4 0.75f +#define c1o6 (1.0f / 6.0f) +#define c1o7 (1.0f / 7.0f) +#define c1o8 0.125f +#define c1o9 (1.0f / 9.0f) +#define c2o9 (2.0f / 9.0f) +#define c4o9 (4.0f / 9.0f) +#define c1o10 0.1f +#define c1o12 (1.0f / 12.0f) +#define c1o16 0.0625f +#define c3o16 0.1875f +#define c9o16 0.5625f +#define c1o18 (1.0f / 18.0f) +#define c1o20 0.05f +#define c19o20 0.95f +#define c21o20 1.05f +#define c1o24 (1.0f / 24.0f) +#define c1o27 (1.0f / 27.0f) +#define c3o32 0.09375f +#define c4o32 0.125f +#define c1o36 (1.0f / 36.0f) +#define c1o48 (1.0f / 48.0f) +#define c1o64 0.015625f +#define c3o64 0.046875f +#define c9o64 0.140625f +#define c27o64 0.421875f +#define c1o66 (1.0f / 66.0f) +#define c1o72 (1.0f / 72.0f) +#define c1o264 (1.0f / 264.0f) +#define c8o27 (8.0f / 27.0f) +#define c2o27 (2.0f / 27.0f) +#define c1o54 (1.0f / 54.0f) +#define c1o100 0.01f +#define c99o100 0.99f +#define c1o126 (1.0f / 126.0f) +#define c1o216 (1.0f / 216.0f) +#define c5o4 1.25f +#define c9o4 2.25f +#define c5o2 2.5f +#define c9o2 4.5f -#define c0o1 0.f -#define c1o1 1.f -#define c2o1 2.f -#define c3o1 3.f -#define c4o1 4.f -#define c5o1 5.f -#define c6o1 6.f -#define c7o1 7.f -#define c8o1 8.f -#define c9o1 9.f -#define c10o1 10.f -#define c11o1 11.f -#define c12o1 12.f -#define c13o1 13.f -#define c14o1 14.f -#define c15o1 15.f -#define c16o1 16.f -#define c17o1 17.f -#define c18o1 18.f -#define c21o1 21.f -#define c24o1 24.f -#define c25o1 25.f -#define c26o1 26.f -#define c27o1 27.f -#define c28o1 28.f -#define c29o1 29.f -#define c30o1 30.f -#define c32o1 32.f -#define c33o1 33.f -#define c34o1 34.f -#define c36o1 36.f -#define c40o1 40.f -#define c42o1 42.f -#define c46o1 46.f -#define c48o1 48.f -#define c50o1 50.f -#define c52o1 52.f -#define c54o1 54.f -#define c56o1 56.f -#define c64o1 64.f -#define c66o1 66.f -#define c68o1 68.f -#define c69o1 69.f -#define c72o1 72.f -#define c84o1 84.f -#define c88o1 88.f -#define c96o1 96.f -#define c100o1 100.0f -#define c130o1 130.0f -#define c152o1 152.0f -#define c166o1 166.0f -#define c195o1 195.0f -#define c216o1 216.0f -#define c264o1 264.0f -#define c290o1 290.0f -#define c367o1 367.0f +#define c0o1 0.f +#define c1o1 1.f +#define c2o1 2.f +#define c3o1 3.f +#define c4o1 4.f +#define c5o1 5.f +#define c6o1 6.f +#define c7o1 7.f +#define c8o1 8.f +#define c9o1 9.f +#define c10o1 10.f +#define c11o1 11.f +#define c12o1 12.f +#define c13o1 13.f +#define c14o1 14.f +#define c15o1 15.f +#define c16o1 16.f +#define c17o1 17.f +#define c18o1 18.f +#define c21o1 21.f +#define c24o1 24.f +#define c25o1 25.f +#define c26o1 26.f +#define c27o1 27.f +#define c28o1 28.f +#define c29o1 29.f +#define c30o1 30.f +#define c32o1 32.f +#define c33o1 33.f +#define c34o1 34.f +#define c36o1 36.f +#define c40o1 40.f +#define c42o1 42.f +#define c46o1 46.f +#define c48o1 48.f +#define c50o1 50.f +#define c52o1 52.f +#define c54o1 54.f +#define c56o1 56.f +#define c64o1 64.f +#define c66o1 66.f +#define c68o1 68.f +#define c69o1 69.f +#define c72o1 72.f +#define c84o1 84.f +#define c88o1 88.f +#define c96o1 96.f +#define c100o1 100.0f +#define c130o1 130.0f +#define c152o1 152.0f +#define c166o1 166.0f +#define c195o1 195.0f +#define c216o1 216.0f +#define c264o1 264.0f +#define c290o1 290.0f +#define c367o1 367.0f -#define Op0000002 0.0000002f -#define c10eM30 1e-30 -#define c10eM10 1e-10 +#define Op0000002 0.0000002f +#define c10eM30 1e-30 +#define c10eM10 1e-10 #define smallSingle 0.0000000002f #endif - #endif \ No newline at end of file diff --git a/src/basics/Core/StringUtilities/StringUtil.cpp b/src/basics/Core/StringUtilities/StringUtil.cpp index 8fd31c718b9426086ffa3866083f7f4949b1efdc..31496beae5953159c8d9a08a25fb5e808d9efea3 100644 --- a/src/basics/Core/StringUtilities/StringUtil.cpp +++ b/src/basics/Core/StringUtilities/StringUtil.cpp @@ -3,7 +3,7 @@ #include <regex> #include <sstream> -std::string StringUtil::findAndReplace(const std::string &source, const std::string& find, const std::string& replace) +std::string StringUtil::findAndReplace(const std::string &source, const std::string &find, const std::string &replace) { std::string output = source; size_t j; @@ -12,26 +12,23 @@ std::string StringUtil::findAndReplace(const std::string &source, const std::str return output; } -std::string StringUtil::makeUpper(const std::string& instring) +std::string StringUtil::makeUpper(const std::string &instring) { std::string output = instring; transform(output.begin(), output.end(), output.begin(), ::toupper); return output; } -std::string StringUtil::makeLower(const std::string& instring) +std::string StringUtil::makeLower(const std::string &instring) { std::string output = instring; transform(output.begin(), output.end(), output.begin(), ::tolower); return output; } -bool StringUtil::contains(const std::string& source, const char *find) -{ - return (0 != strstr(source.c_str(), find)); -} +bool StringUtil::contains(const std::string &source, const char *find) { return (0 != strstr(source.c_str(), find)); } -std::string StringUtil::pad(const std::string& input, char pad, int length) +std::string StringUtil::pad(const std::string &input, char pad, int length) { std::string outstring = input; for (int i = (int)outstring.length(); i < length; ++i) @@ -43,51 +40,39 @@ std::string StringUtil::trim(const std::string &input, const std::string &trim / { if (input.size() == 0) return input; - std::string temp = ""; + std::string temp = ""; std::string::size_type begpos = input.find_first_not_of(trim); - if (begpos == std::string::npos) - { + if (begpos == std::string::npos) { return temp; - } - else - { + } else { std::string::size_type endpos = input.find_last_not_of(trim); - temp = input.substr(begpos, endpos - begpos + 1); + temp = input.substr(begpos, endpos - begpos + 1); } return temp; } -int StringUtil::toInt(const std::string &input) -{ - return std::stoi(input); -} +int StringUtil::toInt(const std::string &input) { return std::stoi(input); } -float StringUtil::toFloat(const std::string &input) -{ - return std::stof(input); -} +float StringUtil::toFloat(const std::string &input) { return std::stof(input); } -double StringUtil::toDouble(const std::string &input) -{ - return std::stod(input); -} +double StringUtil::toDouble(const std::string &input) { return std::stod(input); } bool StringUtil::toBool(const std::string &input) { - bool b {false}; + bool b{ false }; std::string trimmedInput = trim(input); if (!toBool(b, trimmedInput, std::boolalpha)) throw "StringUtils::toBool() - Not a bool: " + trimmedInput; return b; } -bool StringUtil::toBool(bool &t, const std::string &input, std::ios_base &(*f)(std::ios_base&)) +bool StringUtil::toBool(bool &t, const std::string &input, std::ios_base &(*f)(std::ios_base &)) { std::istringstream iss(input); return !(iss >> f >> t).fail(); } -std::vector<std::string> split(const std::string& str, char delim = ' ') +std::vector<std::string> split(const std::string &str, char delim = ' ') { std::stringstream ss(str); std::string token; @@ -98,91 +83,84 @@ std::vector<std::string> split(const std::string& str, char delim = ' ') return list; } -std::vector<std::string> StringUtil::split(const std::string& input, const std::string& delim/*= " "*/) +std::vector<std::string> StringUtil::split(const std::string &input, const std::string &delim /*= " "*/) { std::stringstream ss; ss << "[" << delim << "]"; std::regex re(ss.str()); - std::sregex_token_iterator first{input.begin(), input.end(), re, -1}, last; //the '-1' is what makes the regex split (-1 := what was not matched) - std::vector<std::string> tokens{first, last}; - tokens.erase(std::remove_if(tokens.begin(), tokens.end(), [](std::string& token) - { - return token.empty(); - }), tokens.end()); + std::sregex_token_iterator first{ input.begin(), input.end(), re, -1 }, + last; // the '-1' is what makes the regex split (-1 := what was not matched) + std::vector<std::string> tokens{ first, last }; + tokens.erase(std::remove_if(tokens.begin(), tokens.end(), [](std::string &token) { return token.empty(); }), + tokens.end()); return tokens; } -std::vector<int> StringUtil::toIntVector(const std::string& input) +std::vector<int> StringUtil::toIntVector(const std::string &input) { std::vector<int> v; std::vector<std::string> inputEntries; inputEntries = split(input, " \n\t"); - for(std::string entry : inputEntries) + for (std::string entry : inputEntries) if (entry != "") v.push_back(toInt(entry)); return v; } -std::vector<unsigned int> StringUtil::toUintVector(const std::string & input) +std::vector<unsigned int> StringUtil::toUintVector(const std::string &input) { - std::vector<unsigned int> v; - std::vector<std::string> inputEntries; + std::vector<unsigned int> v; + std::vector<std::string> inputEntries; inputEntries = split(input, " \n\t"); - for(std::string entry : inputEntries) - if (entry != "") - v.push_back(toInt(entry)); - return v; + for (std::string entry : inputEntries) + if (entry != "") + v.push_back(toInt(entry)); + return v; } -std::vector<bool> StringUtil::toBoolVector(const std::string & input) +std::vector<bool> StringUtil::toBoolVector(const std::string &input) { - std::vector<bool> v; - std::vector<std::string> inputEntries; + std::vector<bool> v; + std::vector<std::string> inputEntries; inputEntries = split(input, " \n\t"); - for(std::string entry : inputEntries) - { - bool b {false}; - std::string trimmedInput = trim(input); - if (toBool(b, trimmedInput, std::noboolalpha)) - v.push_back(b); - } - return v; + for (std::string entry : inputEntries) { + bool b{ false }; + std::string trimmedInput = trim(input); + if (toBool(b, trimmedInput, std::noboolalpha)) + v.push_back(b); + } + return v; } -std::vector<std::string> StringUtil::toStringVector(const std::string & input) -{ - return split(input, " \n\t"); -} +std::vector<std::string> StringUtil::toStringVector(const std::string &input) { return split(input, " \n\t"); } -BASICS_EXPORT std::vector<double> StringUtil::toDoubleVector(const std::string & input) +BASICS_EXPORT std::vector<double> StringUtil::toDoubleVector(const std::string &input) { - std::vector<double> v; - std::vector<std::string> inputEntries; + std::vector<double> v; + std::vector<std::string> inputEntries; inputEntries = split(input, " \n\t"); - for(std::string entry : inputEntries) - if (entry != "") - v.push_back(toDouble(entry)); - return v; + for (std::string entry : inputEntries) + if (entry != "") + v.push_back(toDouble(entry)); + return v; } -template<typename T> -std::string StringUtil::toString(const T& t) +template <typename T> +std::string StringUtil::toString(const T &t) { std::ostringstream stream; stream << t; return stream.str(); } -template BASICS_EXPORT std::string StringUtil::toString<int>(const int& t); - - +template BASICS_EXPORT std::string StringUtil::toString<int>(const int &t); bool StringUtil::endsWith(const std::string &input, const std::string &end) { if (input.length() >= end.length()) { - return (0 == input.compare (input.length() - end.length(), end.length(), end)); + return (0 == input.compare(input.length() - end.length(), end.length(), end)); } else { return false; } diff --git a/src/basics/Core/StringUtilities/StringUtil.h b/src/basics/Core/StringUtilities/StringUtil.h index 63ee9e965737e6fdfdb91d17bd6b158c76634453..cdf8dce290110848d5e6c50eb2fac35822dddf76 100644 --- a/src/basics/Core/StringUtilities/StringUtil.h +++ b/src/basics/Core/StringUtilities/StringUtil.h @@ -2,47 +2,49 @@ #define STRINGUTIL_H #include <algorithm> -#include <sstream> #include <iostream> +#include <sstream> #include <string> #include <vector> #include "basics_export.h" -#define SSTR( x ) static_cast< std::ostringstream & >( \ - ( std::ostringstream() << std::dec << x ) ).str() +#define SSTR(x) static_cast<std::ostringstream &>((std::ostringstream() << std::dec << x)).str() class StringUtil { public: - static BASICS_EXPORT std::string findAndReplace(const std::string &source, const std::string& find, const std::string& replace); - static BASICS_EXPORT std::string makeUpper(const std::string& instring); - static BASICS_EXPORT std::string makeLower(const std::string& instring); - static BASICS_EXPORT std::vector<std::string> split(const std::string& input, const std::string& delim = " "); - static BASICS_EXPORT bool contains(const std::string& source, const char *find); - static BASICS_EXPORT std::string pad(const std::string& input, char pad, int length); + static BASICS_EXPORT std::string findAndReplace(const std::string &source, const std::string &find, + const std::string &replace); + static BASICS_EXPORT std::string makeUpper(const std::string &instring); + static BASICS_EXPORT std::string makeLower(const std::string &instring); + static BASICS_EXPORT std::vector<std::string> split(const std::string &input, const std::string &delim = " "); + static BASICS_EXPORT bool contains(const std::string &source, const char *find); + static BASICS_EXPORT std::string pad(const std::string &input, char pad, int length); static BASICS_EXPORT std::string trim(const std::string &input, const std::string &trim = std::string(" \t\n")); static BASICS_EXPORT int toInt(const std::string &input); static BASICS_EXPORT float toFloat(const std::string &input); static BASICS_EXPORT double toDouble(const std::string &input); static BASICS_EXPORT bool toBool(const std::string &input); - static BASICS_EXPORT std::vector<int> toIntVector(const std::string& s); - static BASICS_EXPORT std::vector<unsigned int> toUintVector(const std::string& s); - static BASICS_EXPORT std::vector<bool> toBoolVector(const std::string& s); - static BASICS_EXPORT std::vector<std::string> toStringVector(const std::string& s); - static BASICS_EXPORT std::vector<double> toDoubleVector(const std::string& s); - template<typename T> - static BASICS_EXPORT std::string toString(const T& t); + static BASICS_EXPORT std::vector<int> toIntVector(const std::string &s); + static BASICS_EXPORT std::vector<unsigned int> toUintVector(const std::string &s); + static BASICS_EXPORT std::vector<bool> toBoolVector(const std::string &s); + static BASICS_EXPORT std::vector<std::string> toStringVector(const std::string &s); + static BASICS_EXPORT std::vector<double> toDoubleVector(const std::string &s); + template <typename T> + static BASICS_EXPORT std::string toString(const T &t); static BASICS_EXPORT bool endsWith(const std::string &input, const std::string &end); private: - StringUtil() = default;; - StringUtil(const StringUtil&) = default;; - virtual ~StringUtil() = default;; - - static bool toBool(bool &t, const std::string &input, std::ios_base &(*f)(std::ios_base&)); + StringUtil() = default; + ; + StringUtil(const StringUtil &) = default; + ; + virtual ~StringUtil() = default; + ; + + static bool toBool(bool &t, const std::string &input, std::ios_base &(*f)(std::ios_base &)); }; #endif - diff --git a/src/basics/Core/StringUtilities/StringUtilTest.cpp b/src/basics/Core/StringUtilities/StringUtilTest.cpp index e87e15423ec74258f3be9a565c118954355aff38..52f9511b3774a03f6d6f1e19536839825eff1394 100644 --- a/src/basics/Core/StringUtilities/StringUtilTest.cpp +++ b/src/basics/Core/StringUtilities/StringUtilTest.cpp @@ -15,47 +15,47 @@ int main(int argc, char *argv[]) TEST(StringUtilTest, endsWith_shouldReturnTrue) { - const std::string input {"input_string"}; - const std::string ends_with {"string"}; + const std::string input{ "input_string" }; + const std::string ends_with{ "string" }; ASSERT_TRUE(StringUtil::endsWith(input, ends_with)); } TEST(StringUtilTest, endsWith_shouldReturnFalse) { - const std::string input {"input_string"}; - const std::string ends_with {"string_"}; + const std::string input{ "input_string" }; + const std::string ends_with{ "string_" }; ASSERT_FALSE(StringUtil::endsWith(input, ends_with)); } TEST(StringUtilTest, toIntVector) { - const std::string input {"1 2\n3 4"}; - std::vector<int> expected_result {1, 2, 3, 4}; + const std::string input{ "1 2\n3 4" }; + std::vector<int> expected_result{ 1, 2, 3, 4 }; auto result = StringUtil::toIntVector(input); - ASSERT_THAT(result,testing::Eq(expected_result)); + ASSERT_THAT(result, testing::Eq(expected_result)); } TEST(StringUtilTest, splitIntoStringsWithDelimeter) { - const std::string input {"1 2\n3 4\t5"}; - const std::string delimeter {" \n\t"}; - std::vector<std::string> expected_result {"1", "2", "3", "4", "5"}; + const std::string input{ "1 2\n3 4\t5" }; + const std::string delimeter{ " \n\t" }; + std::vector<std::string> expected_result{ "1", "2", "3", "4", "5" }; auto result = StringUtil::split(input, delimeter); - ASSERT_THAT(result,testing::Eq(expected_result)); + ASSERT_THAT(result, testing::Eq(expected_result)); } TEST(StringUtilTest, toStringVector) { - const std::string input {"1 2\n3 4\t5"}; - std::vector<std::string> expected_result {"1", "2", "3", "4", "5"}; + const std::string input{ "1 2\n3 4\t5" }; + std::vector<std::string> expected_result{ "1", "2", "3", "4", "5" }; auto result = StringUtil::toStringVector(input); - ASSERT_THAT(result,testing::Eq(expected_result)); + ASSERT_THAT(result, testing::Eq(expected_result)); } \ No newline at end of file diff --git a/src/basics/Core/Timer/Timer.h b/src/basics/Core/Timer/Timer.h index 702cfafb4b2eaef7cf779136d58ce7c37bc1b1e5..e8a97000fb8cc3967490e60edca1c564cc8431c7 100644 --- a/src/basics/Core/Timer/Timer.h +++ b/src/basics/Core/Timer/Timer.h @@ -13,11 +13,10 @@ public: static SPtr<Timer> makeStart(); virtual void start() = 0; - virtual void end() = 0; + virtual void end() = 0; - virtual real getTimeInSeconds() const = 0; + virtual real getTimeInSeconds() const = 0; virtual real getCurrentRuntimeInSeconds() const = 0; }; #endif - diff --git a/src/basics/Core/Timer/TimerImp.cpp b/src/basics/Core/Timer/TimerImp.cpp index 7942f970a8b2f3e1047ef93dbf484fbd019611ea..7aef3e999c0d5466fb69b08eafa32fa95370383b 100644 --- a/src/basics/Core/Timer/TimerImp.cpp +++ b/src/basics/Core/Timer/TimerImp.cpp @@ -1,22 +1,18 @@ #include "TimerImp.h" +void TimerImp::start() { this->startTime = std::chrono::high_resolution_clock::now(); } -void TimerImp::start() -{ - this->startTime = std::chrono::high_resolution_clock::now(); -} - -void TimerImp::end() -{ - this->endTime = std::chrono::high_resolution_clock::now(); -} +void TimerImp::end() { this->endTime = std::chrono::high_resolution_clock::now(); } real TimerImp::getTimeInSeconds() const { - return real(std::chrono::duration_cast<std::chrono::microseconds>( endTime - startTime ).count() / 1000000.0); + return real(std::chrono::duration_cast<std::chrono::microseconds>(endTime - startTime).count() / 1000000.0); } real TimerImp::getCurrentRuntimeInSeconds() const { - return real(std::chrono::duration_cast<std::chrono::microseconds>( std::chrono::high_resolution_clock::now() - startTime ).count() / 1000000.0); + return real( + std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::high_resolution_clock::now() - startTime) + .count() / + 1000000.0); } diff --git a/src/basics/Core/Timer/TimerImp.h b/src/basics/Core/Timer/TimerImp.h index 9759b9daac566fe23c04235105357ea9770457a7..bcc078db9a4f00eb23abe93a9a1e16509c948820 100644 --- a/src/basics/Core/Timer/TimerImp.h +++ b/src/basics/Core/Timer/TimerImp.h @@ -5,10 +5,8 @@ #include <chrono> - #include "DataTypes.h" - class BASICS_EXPORT TimerImp : public Timer { public: @@ -26,4 +24,3 @@ private: }; #endif - diff --git a/src/basics/Core/VectorTypes.cpp b/src/basics/Core/VectorTypes.cpp index 59c3d80c8cbfae3f177484a8378edf50bfdbb86e..dab2675093415ec103d1bf7ffd3666d57b0977f5 100644 --- a/src/basics/Core/VectorTypes.cpp +++ b/src/basics/Core/VectorTypes.cpp @@ -1,20 +1,8 @@ #include "VectorTypes.h" -//Vec3 Vec3::operator+( Vec3& left, Vec3& right ){ -Vec3 Vec3::operator+( Vec3& right ){ - return { this->x + right.x, - this->y + right.y, - this->z + right.z }; -} +// Vec3 Vec3::operator+( Vec3& left, Vec3& right ){ +Vec3 Vec3::operator+(Vec3 &right) { return { this->x + right.x, this->y + right.y, this->z + right.z }; } -Vec3 Vec3::operator-( Vec3& right ){ - return { this->x - right.x, - this->y - right.y, - this->z - right.z }; -} +Vec3 Vec3::operator-(Vec3 &right) { return { this->x - right.x, this->y - right.y, this->z - right.z }; } -Vec3 operator*( real scalar, Vec3& vec ){ - return { scalar * vec.x, - scalar * vec.y, - scalar * vec.z }; -} +Vec3 operator*(real scalar, Vec3 &vec) { return { scalar * vec.x, scalar * vec.y, scalar * vec.z }; } diff --git a/src/basics/Core/VectorTypes.h b/src/basics/Core/VectorTypes.h index d59771bf9934d59431ed3c3f408defc7950c02cd..0256a960ddf53a6d4fb8efee8b54e5d4679987f1 100644 --- a/src/basics/Core/VectorTypes.h +++ b/src/basics/Core/VectorTypes.h @@ -16,21 +16,19 @@ #include "RealConstants.h" struct BASICS_EXPORT Vec3 { - real x{c0o1}, y{c0o1}, z{c0o1}; + real x{ c0o1 }, y{ c0o1 }, z{ c0o1 }; __host__ __device__ Vec3(real x, real y, real z) : x(x), y(y), z(z) {} - __host__ __device__ Vec3() = default; + __host__ __device__ Vec3() = default; - __host__ __device__ real length() { - return std::sqrt( x*x + y*y + z*z ); - } + __host__ __device__ real length() { return std::sqrt(x * x + y * y + z * z); } - Vec3 operator+( Vec3& right ); - Vec3 operator-( Vec3& right ); + Vec3 operator+(Vec3 &right); + Vec3 operator-(Vec3 &right); }; -//BASICS_EXPORT Vec3 operator+( Vec3& left, Vec3& right ); -//BASICS_EXPORT Vec3 operator-( Vec3& left, Vec3& right ); -BASICS_EXPORT Vec3 operator*( real scalar, Vec3& vec ); +// BASICS_EXPORT Vec3 operator+( Vec3& left, Vec3& right ); +// BASICS_EXPORT Vec3 operator-( Vec3& left, Vec3& right ); +BASICS_EXPORT Vec3 operator*(real scalar, Vec3 &vec); #endif diff --git a/src/basics/Core/buildInfo.h b/src/basics/Core/buildInfo.h index b9ba18ec0ff31f6bee344fbd7901a0d1ffd0ee49..a5499518c7a13ea52d470895b702ca0aab1294e0 100644 --- a/src/basics/Core/buildInfo.h +++ b/src/basics/Core/buildInfo.h @@ -1,26 +1,23 @@ #ifndef buildInfo_H #define buildInfo_H - namespace buildInfo { - const char * gitCommitHash(); - const char * gitBranch(); - const char * buildType(); - const char * compilerFlags(); - const char * buildMachine(); - const char * projectDir(); - const char * binaryDir(); -} - -#define GIT_COMMIT_HASH buildinfo::gitCommitHash() -#define GIT_BRANCH buildinfo::gitBranch() -#define BUILD_MACHINE buildinfo::buildMachine() -#define PROJECT_DIR buildinfo::projectDir() -#define BINARY_DIR buildinfo::binaryDir() -#define COMPILER_FLAGS buildinfo::compilerFlags() -#define BUILD_TYPE buildinfo::buildType() - +const char *gitCommitHash(); +const char *gitBranch(); +const char *buildType(); +const char *compilerFlags(); +const char *buildMachine(); +const char *projectDir(); +const char *binaryDir(); +} // namespace buildInfo +#define GIT_COMMIT_HASH buildinfo::gitCommitHash() +#define GIT_BRANCH buildinfo::gitBranch() +#define BUILD_MACHINE buildinfo::buildMachine() +#define PROJECT_DIR buildinfo::projectDir() +#define BINARY_DIR buildinfo::binaryDir() +#define COMPILER_FLAGS buildinfo::compilerFlags() +#define BUILD_TYPE buildinfo::buildType() #endif diff --git a/src/basics/Core/buildInfo.in.cpp b/src/basics/Core/buildInfo.in.cpp index 2cd55e8654c5a021d95ed584a8fb6d5def2014ee..56f302208256ba86d7f814bfa6711f704aea3479 100644 --- a/src/basics/Core/buildInfo.in.cpp +++ b/src/basics/Core/buildInfo.in.cpp @@ -2,14 +2,13 @@ #include "basics_export.h" - namespace buildInfo { - BASICS_EXPORT const char *gitCommitHash() { return "@git_commit_hash@"; } - BASICS_EXPORT const char *gitBranch() { return "@git_branch@"; } - BASICS_EXPORT const char *buildType() { return "@CMAKE_BUILD_TYPE@"; } - BASICS_EXPORT const char *compilerFlags() { return "@COMPILER_FLAGS@"; } - BASICS_EXPORT const char *buildMachine() { return "@BUILD_computerName@";} - BASICS_EXPORT const char *projectDir() { return "@CMAKE_SOURCE_DIR@"; } - BASICS_EXPORT const char *binaryDir() { return "@CMAKE_BINARY_DIR@"; } -} +BASICS_EXPORT const char *gitCommitHash() { return "@git_commit_hash@"; } +BASICS_EXPORT const char *gitBranch() { return "@git_branch@"; } +BASICS_EXPORT const char *buildType() { return "@CMAKE_BUILD_TYPE@"; } +BASICS_EXPORT const char *compilerFlags() { return "@COMPILER_FLAGS@"; } +BASICS_EXPORT const char *buildMachine() { return "@BUILD_computerName@"; } +BASICS_EXPORT const char *projectDir() { return "@CMAKE_SOURCE_DIR@"; } +BASICS_EXPORT const char *binaryDir() { return "@CMAKE_BINARY_DIR@"; } +} // namespace buildInfo diff --git a/src/basics/PointerDefinitions.h b/src/basics/PointerDefinitions.h index 07462b89eca7f3248ee311a849ba185261597204..4b8657025cc5100c6623b5172cbab3484bc2f8a1 100644 --- a/src/basics/PointerDefinitions.h +++ b/src/basics/PointerDefinitions.h @@ -1,13 +1,12 @@ /* -* Author: S. Peters -* mail: peters@irmb.tu-bs.de -*/ + * Author: S. Peters + * mail: peters@irmb.tu-bs.de + */ #ifndef SHARED_POINTER_H #define SHARED_POINTER_H #include <memory> - template <class T> using SPtr = std::shared_ptr<T>; @@ -18,7 +17,7 @@ template <class T> using UPtr = std::unique_ptr<T>; template <class T> -using RPtr = T*; +using RPtr = T *; template <class T> using enableSharedFromThis = std::enable_shared_from_this<T>; diff --git a/src/basics/basics/container/CbArray2D.h b/src/basics/basics/container/CbArray2D.h index 107bc386f964b2276ccb0ece2bf022d139b757c6..79e8a9c3ac21ae050938f3c420eeafd51d0074cd 100644 --- a/src/basics/basics/container/CbArray2D.h +++ b/src/basics/basics/container/CbArray2D.h @@ -1,28 +1,28 @@ //======================================================================================= -// ____ ____ __ ______ __________ __ __ __ __ -// \ \ | | | | | _ \ |___ ___| | | | | / \ | | -// \ \ | | | | | |_) | | | | | | | / \ | | -// \ \ | | | | | _ / | | | | | | / /\ \ | | -// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ -// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| -// \ \ | | ________________________________________________________________ -// \ \ | | | ______________________________________________________________| -// \ \| | | | __ __ __ __ ______ _______ -// \ | | |_____ | | | | | | | | | _ \ / _____) -// \ | | _____| | | | | | | | | | | \ \ \_______ +// ____ ____ __ ______ __________ __ __ __ __ +// \ \ | | | | | _ \ |___ ___| | | | | / \ | | +// \ \ | | | | | |_) | | | | | | | / \ | | +// \ \ | | | | | _ / | | | | | | / /\ \ | | +// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ +// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| +// \ \ | | ________________________________________________________________ +// \ \ | | | ______________________________________________________________| +// \ \| | | | __ __ __ __ ______ _______ +// \ | | |_____ | | | | | | | | | _ \ / _____) +// \ | | _____| | | | | | | | | | | \ \ \_______ // \ | | | | |_____ | \_/ | | | | |_/ / _____ | -// \ _____| |__| |________| \_______/ |__| |______/ (_______/ +// \ _____| |__| |________| \_______/ |__| |______/ (_______/ // -// This file is part of VirtualFluids. VirtualFluids is free software: you can +// This file is part of VirtualFluids. VirtualFluids is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of +// License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. -// -// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// +// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License along // with VirtualFluids (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>. // @@ -35,58 +35,63 @@ #include <iomanip> -#include <basics/utilities/UbException.h> -#include <basics/utilities/UbEqual.h> #include <algorithm> +#include <basics/utilities/UbEqual.h> +#include <basics/utilities/UbException.h> #include <typeinfo> ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// // IndexClasses -//IndexerX2X1: +// IndexerX2X1: // 4 5 6 // Array 1 2 3 --> vector 1 2 3 4 5 6 -//optimaler schleifendurchlauf -//for(alle X2) +// optimaler schleifendurchlauf +// for(alle X2) // for(alle X1) class IndexerX2X1 { public: - using size_type = int; + using size_type = int; + public: - inline std::size_t getIndex(const size_type& x1, const size_type& x2, const size_type& nx1, const size_type& /*nx2*/) const - { - return nx1* x2 + x1; - } - inline std::size_t getStartIndexOfSortedArray(const size_type& /*x1*/, const size_type& x2, const size_type& nx1, const size_type& /*nx2*/) const - { - return nx1* x2; - } + inline std::size_t getIndex(const size_type &x1, const size_type &x2, const size_type &nx1, + const size_type & /*nx2*/) const + { + return nx1 * x2 + x1; + } + inline std::size_t getStartIndexOfSortedArray(const size_type & /*x1*/, const size_type &x2, const size_type &nx1, + const size_type & /*nx2*/) const + { + return nx1 * x2; + } }; -//IndexerX1X2: +// IndexerX1X2: // 4 5 6 // Array 1 2 3 --> vector 1 4 2 5 3 6 -//optimaler schleifendurchlauf -//for(alle X1) +// optimaler schleifendurchlauf +// for(alle X1) // for(alle X2) class IndexerX1X2 { public: - using size_type = int; + using size_type = int; + public: - inline std::size_t getIndex(const size_type& x1, const size_type& x2, const size_type& /*nx1*/,const size_type& nx2) const - { - return nx2* x1+ x2; - } - inline std::size_t getStartIndexOfSortedArray(const size_type& x1, const size_type& /*x2*/, const size_type& /*nx1*/, const size_type& nx2) const - { - return nx2* x1; - } + inline std::size_t getIndex(const size_type &x1, const size_type &x2, const size_type & /*nx1*/, + const size_type &nx2) const + { + return nx2 * x1 + x2; + } + inline std::size_t getStartIndexOfSortedArray(const size_type &x1, const size_type & /*x2*/, + const size_type & /*nx1*/, const size_type &nx2) const + { + return nx2 * x1; + } }; - ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// // CbArray2D @@ -100,311 +105,284 @@ public: //! //! -release: not defined "NO_CB_RANGECHECK" && defined "CB_RANGECHECK" ////////////////////////////////////////////////////////////////////////// -template<typename T, typename IndexClass = IndexerX2X1> +template <typename T, typename IndexClass = IndexerX2X1> class CbArray2D { public: - using value_type = T; - using indexer_type = IndexClass; - using size_type = typename IndexClass::size_type; - using reference = typename std::vector<value_type>::reference; - using const_reference = typename std::vector<value_type>::const_reference; - using pointer = typename std::vector<value_type>::pointer; - using const_pointer = typename std::vector<value_type>::const_pointer; + using value_type = T; + using indexer_type = IndexClass; + using size_type = typename IndexClass::size_type; + using reference = typename std::vector<value_type>::reference; + using const_reference = typename std::vector<value_type>::const_reference; + using pointer = typename std::vector<value_type>::pointer; + using const_pointer = typename std::vector<value_type>::const_pointer; private: - template< typename value_type2, typename IndexClass2 > friend class CbArray2D; + template <typename value_type2, typename IndexClass2> + friend class CbArray2D; public: - /*=======================================================================*/ - CbArray2D() - { - this->resize(0,0); - } - /*=======================================================================*/ - CbArray2D(const size_type& nx2, const size_type& nx1) - { - this->resize(nx2,nx1); - } - /*=======================================================================*/ - CbArray2D(const size_type& nx2, const size_type& nx1, const value_type& val) - { - this->resize(nx2,nx1,val); - } - /*=======================================================================*/ - CbArray2D(const size_type& uniformDimensionSize /*nx1==nx2*/) - { - this->resize(uniformDimensionSize,uniformDimensionSize); - } - /*=======================================================================*/ - //ssbernimmt vector als daten vector! (erstellt KEINE kopie!!!, vec ist anschlieueend leer, da swap verwendet wird) - CbArray2D(std::vector<value_type>& vec, const size_type& nx1,const size_type& nx2) - { - assert( (nx1*nx2)==vec.size() ); - this->data.swap(vec); - this->resize(nx1,nx2); - } - /*=======================================================================*/ - CbArray2D(const CbArray2D& src) - : nx1(src.nx1) - , nx2(src.nx2) - , data(src.data) - { - } - /*=======================================================================*/ - template< typename value_type2 > - CbArray2D(const CbArray2D< value_type2 >& src) - : nx1(src.nx1) - , nx2(src.nx2) - { - //Sourcedaten kopieren - this->data.resize( src.data.size() ); - for(std::size_t i=0; i<data.size(); ++i) - this->data[i] = src.data[i]; - } - /*=======================================================================*/ - virtual ~CbArray2D() = default; - /*=======================================================================*/ - CbArray2D& operator= (const CbArray2D& rhs) - { - if(this == &rhs) return *this; + /*=======================================================================*/ + CbArray2D() { this->resize(0, 0); } + /*=======================================================================*/ + CbArray2D(const size_type &nx2, const size_type &nx1) { this->resize(nx2, nx1); } + /*=======================================================================*/ + CbArray2D(const size_type &nx2, const size_type &nx1, const value_type &val) { this->resize(nx2, nx1, val); } + /*=======================================================================*/ + CbArray2D(const size_type &uniformDimensionSize /*nx1==nx2*/) + { + this->resize(uniformDimensionSize, uniformDimensionSize); + } + /*=======================================================================*/ + // ssbernimmt vector als daten vector! (erstellt KEINE kopie!!!, vec ist anschlieueend leer, da swap verwendet wird) + CbArray2D(std::vector<value_type> &vec, const size_type &nx1, const size_type &nx2) + { + assert((nx1 * nx2) == vec.size()); + this->data.swap(vec); + this->resize(nx1, nx2); + } + /*=======================================================================*/ + CbArray2D(const CbArray2D &src) : nx1(src.nx1), nx2(src.nx2), data(src.data) {} + /*=======================================================================*/ + template <typename value_type2> + CbArray2D(const CbArray2D<value_type2> &src) : nx1(src.nx1), nx2(src.nx2) + { + // Sourcedaten kopieren + this->data.resize(src.data.size()); + for (std::size_t i = 0; i < data.size(); ++i) + this->data[i] = src.data[i]; + } + /*=======================================================================*/ + virtual ~CbArray2D() = default; + /*=======================================================================*/ + CbArray2D &operator=(const CbArray2D &rhs) + { + if (this == &rhs) + return *this; - this->nx1 = rhs.nx1; - this->nx2 = rhs.nx2; + this->nx1 = rhs.nx1; + this->nx2 = rhs.nx2; - //Laenge anpassen - this->data.resize(rhs.data.size()); - //gespeicherte Datenelemente loeschen - this->data.clear(); + // Laenge anpassen + this->data.resize(rhs.data.size()); + // gespeicherte Datenelemente loeschen + this->data.clear(); - //Sourcedaten kopieren - this->data = rhs.data; + // Sourcedaten kopieren + this->data = rhs.data; - return *this; - } - /*=======================================================================*/ - //durch value_type2 kann man z.B. ein float array einem double array zuweisen! - template< typename value_type2, typename IndexClass2 > - CbArray2D& operator= (const CbArray2D< value_type2, IndexClass2 >& rhs) - { - this->nx1 = rhs.nx1; - this->nx2 = rhs.nx2; + return *this; + } + /*=======================================================================*/ + // durch value_type2 kann man z.B. ein float array einem double array zuweisen! + template <typename value_type2, typename IndexClass2> + CbArray2D &operator=(const CbArray2D<value_type2, IndexClass2> &rhs) + { + this->nx1 = rhs.nx1; + this->nx2 = rhs.nx2; - //gespeicherte Datenelemente loeschen - this->data.clear(); - //Laenge anpassen - this->data.resize(rhs.data.size()); + // gespeicherte Datenelemente loeschen + this->data.clear(); + // Laenge anpassen + this->data.resize(rhs.data.size()); - //Sourcedaten kopieren (!! koennte anderen Indexer besitzen!!! -> operator() benutzen) - //ACHTUNG: fuer diese Konvertierung muss bei Klassen der demenstrechende operator - // implementiert sein, e.g.: class value_type2 {public: inline operator value_type2() const { return value_type2(); } - for(int x1=0; x1<this->nx1; x1++) - for(int x2=0; x2<this->nx2; x2++) - this->operator()(x1,x2) = static_cast< value_type >( rhs.operator()(x1,x2) ); + // Sourcedaten kopieren (!! koennte anderen Indexer besitzen!!! -> operator() benutzen) + // ACHTUNG: fuer diese Konvertierung muss bei Klassen der demenstrechende operator + // implementiert sein, e.g.: class value_type2 {public: inline operator value_type2() const { return + // value_type2(); } + for (int x1 = 0; x1 < this->nx1; x1++) + for (int x2 = 0; x2 < this->nx2; x2++) + this->operator()(x1, x2) = static_cast<value_type>(rhs.operator()(x1, x2)); - return *this; - } - /*=======================================================================*/ - bool operator== (const CbArray2D& rhs) const - { - if( this == &rhs ) return true; + return *this; + } + /*=======================================================================*/ + bool operator==(const CbArray2D &rhs) const + { + if (this == &rhs) + return true; - if( this->nx1!=rhs.nx1 - || this->nx2!=rhs.nx2 - || this->data.size() != rhs.data.size() ) - { - return false; - } + if (this->nx1 != rhs.nx1 || this->nx2 != rhs.nx2 || this->data.size() != rhs.data.size()) { + return false; + } - return std::equal( this->data.begin(), this->data.end(), rhs.data.begin(), UbEqual<value_type, value_type >() ); - } - /*=======================================================================*/ - template< typename value_type2, typename IndexClass2 > - bool operator== (const CbArray2D< value_type2, IndexClass2 >& rhs) const - { - if( this->data.size() != rhs.data.size() ) return false; + return std::equal(this->data.begin(), this->data.end(), rhs.data.begin(), UbEqual<value_type, value_type>()); + } + /*=======================================================================*/ + template <typename value_type2, typename IndexClass2> + bool operator==(const CbArray2D<value_type2, IndexClass2> &rhs) const + { + if (this->data.size() != rhs.data.size()) + return false; - //Sourcedaten einzeln checken (!! koennte anderen Indexer besitzen!!! -> operator() benutzen) - for(int x1=0; x1<this->nx1; x1++) - for(int x2=0; x2<this->nx2; x2++) - if( !isUbEqual(this->operator()(x1,x2), rhs.operator()(x1,x2)) ) - return false; + // Sourcedaten einzeln checken (!! koennte anderen Indexer besitzen!!! -> operator() benutzen) + for (int x1 = 0; x1 < this->nx1; x1++) + for (int x2 = 0; x2 < this->nx2; x2++) + if (!isUbEqual(this->operator()(x1, x2), rhs.operator()(x1, x2))) + return false; - return true; - } - /*=======================================================================*/ - bool operator!= (const CbArray2D& rhs) const - { - return !(*this==rhs); - } - /*=======================================================================*/ - template< typename value_type2, typename IndexClass2 > - bool operator!= (const CbArray2D< value_type2, IndexClass2 >& rhs) const - { - return !(*this==rhs); - } - /*=======================================================================*/ - reference operator() (const size_type& x1,const size_type& x2) - { - #if !defined(NO_CB_RANGECHECK) && ( defined(_DEBUG) || defined(CB_RANGECHECK) ) - if( !this->indicesInRange(x1,x2) ) - UB_THROW( UbException(UB_EXARGS,getExceptionErrorString(x1,x2)) ); - #endif + return true; + } + /*=======================================================================*/ + bool operator!=(const CbArray2D &rhs) const { return !(*this == rhs); } + /*=======================================================================*/ + template <typename value_type2, typename IndexClass2> + bool operator!=(const CbArray2D<value_type2, IndexClass2> &rhs) const + { + return !(*this == rhs); + } + /*=======================================================================*/ + reference operator()(const size_type &x1, const size_type &x2) + { +#if !defined(NO_CB_RANGECHECK) && (defined(_DEBUG) || defined(CB_RANGECHECK)) + if (!this->indicesInRange(x1, x2)) + UB_THROW(UbException(UB_EXARGS, getExceptionErrorString(x1, x2))); +#endif - return this->data[indexer.getIndex(x1,x2,nx1,nx2)]; - } - /*=======================================================================*/ - const_reference operator() (const size_type& x1,const size_type& x2) const - { - #if !defined(NO_CB_RANGECHECK) && ( defined(_DEBUG) || defined(CB_RANGECHECK) ) - if( !this->indicesInRange(x1,x2) ) - UB_THROW( UbException(UB_EXARGS,getExceptionErrorString(x1,x2)) ); - #endif + return this->data[indexer.getIndex(x1, x2, nx1, nx2)]; + } + /*=======================================================================*/ + const_reference operator()(const size_type &x1, const size_type &x2) const + { +#if !defined(NO_CB_RANGECHECK) && (defined(_DEBUG) || defined(CB_RANGECHECK)) + if (!this->indicesInRange(x1, x2)) + UB_THROW(UbException(UB_EXARGS, getExceptionErrorString(x1, x2))); +#endif - return this->data[indexer.getIndex(x1,x2,nx1,nx2)]; - } - /*=======================================================================*/ - pointer getStartAdressOfSortedArray(const size_type& x1, const size_type& x2) - { - #if !defined(NO_CB_RANGECHECK) && ( defined(_DEBUG) || defined(CB_RANGECHECK) ) - if( !this->indicesInRange(x1,x2) ) - UB_THROW( UbException(UB_EXARGS,getExceptionErrorString(x1,x2)) ); - #endif - return &this->data[indexer.getStartIndexOfSortedArray(x1,x2,nx1,nx2)]; - } - /*=======================================================================*/ - const_pointer getStartAdressOfSortedArray(const size_type& x1, const size_type& x2) const - { - #if !defined(NO_CB_RANGECHECK) && ( defined(_DEBUG) || defined(CB_RANGECHECK) ) - if( !this->indicesInRange(x1,x2) ) - UB_THROW( UbException(UB_EXARGS,getExceptionErrorString(x1,x2)) ); - #endif - return &this->data[indexer.getStartIndexOfSortedArray(x1,x2,nx1,nx2)]; - } - /*=======================================================================*/ - void setObject(const size_type& x1,const size_type& x2,const value_type& value) - { - #if !defined(NO_CB_RANGECHECK) && ( defined(_DEBUG) || defined(CB_RANGECHECK) ) - if( !this->indicesInRange(x1,x2) ) - UB_THROW( UbException(UB_EXARGS,getExceptionErrorString(x1,x2)) ); - #endif - this->data[indexer.getIndex(x1,x2,nx1,nx2)] = value; - } - /*=======================================================================*/ - reference getObject(const size_type& x1, const size_type& x2) - { - #if !defined(NO_CB_RANGECHECK) && ( defined(_DEBUG) || defined(CB_RANGECHECK) ) - if( !this->indicesInRange(x1,x2) ) - UB_THROW( UbException(UB_EXARGS,getExceptionErrorString(x1,x2)) ); - #endif - return this->data[indexer.getIndex(x1,x2,nx1,nx2)] ; - } - /*=======================================================================*/ - typename std::vector<value_type>::const_reference getObject(const size_type& x1, const size_type& x2) const - { - return this->operator()(x1,x2); - } - /*=======================================================================*/ - bool isEmpty() const { return data.empty(); } - size_type getNX1() const { return this->nx1; } - size_type getNX2() const { return this->nx2; } - /*=======================================================================*/ - void reset(const T& val) - { - std::fill( this->data.begin(), this->data.end(), val ); - } - /*=======================================================================*/ - std::string toString() const - { - std::stringstream text; - for(size_type x2=0; x2<this->nx2; x2++) - { - for(size_type x1=0; x1<this->nx1; x1++) - { - //hier kommts zum Konflikt ab und an ... - text<<this->getObject(x1,x2)<<", "; - } - text<<"\n"; - } + return this->data[indexer.getIndex(x1, x2, nx1, nx2)]; + } + /*=======================================================================*/ + pointer getStartAdressOfSortedArray(const size_type &x1, const size_type &x2) + { +#if !defined(NO_CB_RANGECHECK) && (defined(_DEBUG) || defined(CB_RANGECHECK)) + if (!this->indicesInRange(x1, x2)) + UB_THROW(UbException(UB_EXARGS, getExceptionErrorString(x1, x2))); +#endif + return &this->data[indexer.getStartIndexOfSortedArray(x1, x2, nx1, nx2)]; + } + /*=======================================================================*/ + const_pointer getStartAdressOfSortedArray(const size_type &x1, const size_type &x2) const + { +#if !defined(NO_CB_RANGECHECK) && (defined(_DEBUG) || defined(CB_RANGECHECK)) + if (!this->indicesInRange(x1, x2)) + UB_THROW(UbException(UB_EXARGS, getExceptionErrorString(x1, x2))); +#endif + return &this->data[indexer.getStartIndexOfSortedArray(x1, x2, nx1, nx2)]; + } + /*=======================================================================*/ + void setObject(const size_type &x1, const size_type &x2, const value_type &value) + { +#if !defined(NO_CB_RANGECHECK) && (defined(_DEBUG) || defined(CB_RANGECHECK)) + if (!this->indicesInRange(x1, x2)) + UB_THROW(UbException(UB_EXARGS, getExceptionErrorString(x1, x2))); +#endif + this->data[indexer.getIndex(x1, x2, nx1, nx2)] = value; + } + /*=======================================================================*/ + reference getObject(const size_type &x1, const size_type &x2) + { +#if !defined(NO_CB_RANGECHECK) && (defined(_DEBUG) || defined(CB_RANGECHECK)) + if (!this->indicesInRange(x1, x2)) + UB_THROW(UbException(UB_EXARGS, getExceptionErrorString(x1, x2))); +#endif + return this->data[indexer.getIndex(x1, x2, nx1, nx2)]; + } + /*=======================================================================*/ + typename std::vector<value_type>::const_reference getObject(const size_type &x1, const size_type &x2) const + { + return this->operator()(x1, x2); + } + /*=======================================================================*/ + bool isEmpty() const { return data.empty(); } + size_type getNX1() const { return this->nx1; } + size_type getNX2() const { return this->nx2; } + /*=======================================================================*/ + void reset(const T &val) { std::fill(this->data.begin(), this->data.end(), val); } + /*=======================================================================*/ + std::string toString() const + { + std::stringstream text; + for (size_type x2 = 0; x2 < this->nx2; x2++) { + for (size_type x1 = 0; x1 < this->nx1; x1++) { + // hier kommts zum Konflikt ab und an ... + text << this->getObject(x1, x2) << ", "; + } + text << "\n"; + } - return text.str(); - } - /*=======================================================================*/ - std::string getInfo() const - { - std::stringstream text; - text<<"CbArray2D< storageType="<<typeid(T).name()<<", indexer="<<typeid(IndexClass).name()<<" >"; - text<<"( nx1="<<this->nx1<<", nx2="<<this->nx2<<")"; - return text.str(); - } - /*=======================================================================*/ - void resize(const size_type& uniformDimensionSize) - { - this->resize(uniformDimensionSize,uniformDimensionSize); - } - /*=======================================================================*/ - void resize(const size_type& nx1,const size_type& nx2) - { - this->nx1 = nx1; - this->nx2 = nx2; - this->data.resize(nx1*nx2); - } - /*=======================================================================*/ - void resize(const size_type& nx1, const size_type& nx2, const value_type& initVal ) - { - this->nx1 = nx1; - this->nx2 = nx2; - this->data.resize(nx1*nx2,initVal); - } - /*=======================================================================*/ - void clear() - { - this->nx1 = 0; - this->nx2 = 0; - this->data.clear(); - } - /*=======================================================================*/ - std::vector< value_type >& getDataVector() { return this->data; } - /*=======================================================================*/ - const std::vector< value_type >& getDataVector() const { return this->data; } - /*=======================================================================*/ - inline size_type getDataVectorIndex(const size_type& x1, const size_type& x2) const - { - #if !defined(NO_CB_RANGECHECK) && ( defined(_DEBUG) || defined(CB_RANGECHECK) ) - if( !this->indicesInRange(x1,x2) ) - UB_THROW( UbException(UB_EXARGS,getExceptionErrorString(x1,x2)) ); - #endif + return text.str(); + } + /*=======================================================================*/ + std::string getInfo() const + { + std::stringstream text; + text << "CbArray2D< storageType=" << typeid(T).name() << ", indexer=" << typeid(IndexClass).name() << " >"; + text << "( nx1=" << this->nx1 << ", nx2=" << this->nx2 << ")"; + return text.str(); + } + /*=======================================================================*/ + void resize(const size_type &uniformDimensionSize) { this->resize(uniformDimensionSize, uniformDimensionSize); } + /*=======================================================================*/ + void resize(const size_type &nx1, const size_type &nx2) + { + this->nx1 = nx1; + this->nx2 = nx2; + this->data.resize(nx1 * nx2); + } + /*=======================================================================*/ + void resize(const size_type &nx1, const size_type &nx2, const value_type &initVal) + { + this->nx1 = nx1; + this->nx2 = nx2; + this->data.resize(nx1 * nx2, initVal); + } + /*=======================================================================*/ + void clear() + { + this->nx1 = 0; + this->nx2 = 0; + this->data.clear(); + } + /*=======================================================================*/ + std::vector<value_type> &getDataVector() { return this->data; } + /*=======================================================================*/ + const std::vector<value_type> &getDataVector() const { return this->data; } + /*=======================================================================*/ + inline size_type getDataVectorIndex(const size_type &x1, const size_type &x2) const + { +#if !defined(NO_CB_RANGECHECK) && (defined(_DEBUG) || defined(CB_RANGECHECK)) + if (!this->indicesInRange(x1, x2)) + UB_THROW(UbException(UB_EXARGS, getExceptionErrorString(x1, x2))); +#endif - return indexer.getIndex(x1,x2,nx1,nx2); - } + return indexer.getIndex(x1, x2, nx1, nx2); + } protected: - /*=======================================================================*/ - //success -> true - //else -> false - inline bool indicesInRange(const size_type& x1, const size_type& x2) const - { - if( x1 < 0 || x1 >= this->nx1 - || x2 < 0 || x2 >= this->nx2 ) - { - return false; - } - return true; - } - /*=======================================================================*/ - std::string getExceptionErrorString(const size_type& x1, const size_type& x2) const - { - std::stringstream out("index out of range - "); - out<<"("<<x1<<","<<x2<<") not in ("<<nx1<<","<<nx2<<")"; - return out.str(); - } - /*=======================================================================*/ + /*=======================================================================*/ + // success -> true + // else -> false + inline bool indicesInRange(const size_type &x1, const size_type &x2) const + { + if (x1 < 0 || x1 >= this->nx1 || x2 < 0 || x2 >= this->nx2) { + return false; + } + return true; + } + /*=======================================================================*/ + std::string getExceptionErrorString(const size_type &x1, const size_type &x2) const + { + std::stringstream out("index out of range - "); + out << "(" << x1 << "," << x2 << ") not in (" << nx1 << "," << nx2 << ")"; + return out.str(); + } + /*=======================================================================*/ protected: - size_type nx1; - size_type nx2; - indexer_type indexer; - std::vector< value_type > data; + size_type nx1; + size_type nx2; + indexer_type indexer; + std::vector<value_type> data; }; -#endif //CBARRAY2D_H +#endif // CBARRAY2D_H diff --git a/src/basics/basics/container/CbArray3D.h b/src/basics/basics/container/CbArray3D.h index 103cc6110574328bfc673843d78c02563fdd5b66..f7fb495f78ca45a9fee431ed8b2a67783fc01f8f 100644 --- a/src/basics/basics/container/CbArray3D.h +++ b/src/basics/basics/container/CbArray3D.h @@ -1,28 +1,28 @@ //======================================================================================= -// ____ ____ __ ______ __________ __ __ __ __ -// \ \ | | | | | _ \ |___ ___| | | | | / \ | | -// \ \ | | | | | |_) | | | | | | | / \ | | -// \ \ | | | | | _ / | | | | | | / /\ \ | | -// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ -// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| -// \ \ | | ________________________________________________________________ -// \ \ | | | ______________________________________________________________| -// \ \| | | | __ __ __ __ ______ _______ -// \ | | |_____ | | | | | | | | | _ \ / _____) -// \ | | _____| | | | | | | | | | | \ \ \_______ +// ____ ____ __ ______ __________ __ __ __ __ +// \ \ | | | | | _ \ |___ ___| | | | | / \ | | +// \ \ | | | | | |_) | | | | | | | / \ | | +// \ \ | | | | | _ / | | | | | | / /\ \ | | +// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ +// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| +// \ \ | | ________________________________________________________________ +// \ \ | | | ______________________________________________________________| +// \ \| | | | __ __ __ __ ______ _______ +// \ | | |_____ | | | | | | | | | _ \ / _____) +// \ | | _____| | | | | | | | | | | \ \ \_______ // \ | | | | |_____ | \_/ | | | | |_/ / _____ | -// \ _____| |__| |________| \_______/ |__| |______/ (_______/ +// \ _____| |__| |________| \_______/ |__| |______/ (_______/ // -// This file is part of VirtualFluids. VirtualFluids is free software: you can +// This file is part of VirtualFluids. VirtualFluids is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of +// License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. -// -// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// +// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License along // with VirtualFluids (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>. // @@ -35,90 +35,97 @@ #include <iomanip> -#include <basics/utilities/UbException.h> -#include <basics/utilities/UbEqual.h> +#include "PointerDefinitions.h" #include <algorithm> +#include <basics/utilities/UbEqual.h> +#include <basics/utilities/UbException.h> #include <typeinfo> -#include "PointerDefinitions.h" ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// // IndexClasses -//IndexerX3X2X1: +// IndexerX3X2X1: // 4 5 6 10 11 12 // Array ebene A 1 2 3 ebene B 7 8 9 --> vector 1 2 3 4 5 6 7 8 9 10 11 12 -//x1-reihen "liegen am stueck" im speicher -//optimaler schleifendurchlauf -//for(alle X3) +// x1-reihen "liegen am stueck" im speicher +// optimaler schleifendurchlauf +// for(alle X3) // for(alle X2) // for(alle X1) -class IndexerX3X2X1// FunctorX1SortedForX1X2Plane +class IndexerX3X2X1 // FunctorX1SortedForX1X2Plane { public: - using size_type = size_t; + using size_type = size_t; + public: - inline std::size_t getIndex( const size_type& x1 , const size_type& x2 , const size_type& x3 - , const size_type& nx1, const size_type& nx2, const size_type& /*nx3*/ ) const - { - return nx1 * ( nx2 * x3 + x2) + x1 ; - } - inline std::size_t getStartIndexOfSortedArray( const size_type& /*x1*/ , const size_type& x2 , const size_type& x3 - , const size_type& nx1, const size_type& nx2, const size_type& /*nx3*/ ) const - { - return nx1 * ( nx2 * x3 + x2); - } + inline std::size_t getIndex(const size_type &x1, const size_type &x2, const size_type &x3, const size_type &nx1, + const size_type &nx2, const size_type & /*nx3*/) const + { + return nx1 * (nx2 * x3 + x2) + x1; + } + inline std::size_t getStartIndexOfSortedArray(const size_type & /*x1*/, const size_type &x2, const size_type &x3, + const size_type &nx1, const size_type &nx2, + const size_type & /*nx3*/) const + { + return nx1 * (nx2 * x3 + x2); + } }; -//IndexerX1X2X3: +// IndexerX1X2X3: // 4 5 6 10 11 12 // Array ebene A 1 2 3 ebene B 7 8 9 --> -//optimaler schleifendurchlauf -//for(alle X1) +// optimaler schleifendurchlauf +// for(alle X1) // for(alle X2) // for(alle X3) -class IndexerX1X2X3 //FunctorX3SortedForX3X2Plane +class IndexerX1X2X3 // FunctorX3SortedForX3X2Plane { public: - using size_type = size_t; + using size_type = size_t; + public: - inline std::size_t getIndex( const size_type& x1 , const size_type& x2 , const size_type& x3 - , const size_type& /*nx1*/, const size_type& nx2, const size_type& nx3 ) const - { - return nx3 * ( nx2 * x1 + x2) + x3 ; - } - inline std::size_t getStartIndexOfSortedArray( const size_type& x1 , const size_type& x2 , const size_type& /*x3*/ - , const size_type& /*nx1*/, const size_type& nx2, const size_type& nx3 ) const - { - return nx3 * ( nx2 * x1 + x2); - } + inline std::size_t getIndex(const size_type &x1, const size_type &x2, const size_type &x3, + const size_type & /*nx1*/, const size_type &nx2, const size_type &nx3) const + { + return nx3 * (nx2 * x1 + x2) + x3; + } + inline std::size_t getStartIndexOfSortedArray(const size_type &x1, const size_type &x2, const size_type & /*x3*/ + , + const size_type & /*nx1*/, const size_type &nx2, + const size_type &nx3) const + { + return nx3 * (nx2 * x1 + x2); + } }; -//IndexerX2X1X3: +// IndexerX2X1X3: // 4 5 6 10 11 12 // Array ebene A 1 2 3 ebene B 7 8 9 --> vector 1 7 2 8 3 9 4 10 5 11 6 12 -//optimaler schleifendurchlauf -//for(alle X2) +// optimaler schleifendurchlauf +// for(alle X2) // for(alle X1) // for(alle X3) class IndexerX2X1X3 { public: - using size_type = size_t; + using size_type = size_t; + public: - inline std::size_t getIndex( const size_type& x1 , const size_type& x2 , const size_type& x3 - , const size_type& nx1, const size_type& /*nx2*/, const size_type& nx3 ) const - { - return nx3* ( nx1 * x2 + x1) + x3 ; - } - inline std::size_t getStartIndexOfSortedArray( const size_type& x1 , const size_type& x2 , const size_type& /*x3*/ - , const size_type& nx1, const size_type& /*nx2*/, const size_type& nx3 ) const - { - return nx3* ( nx1 * x2 + x1); - } + inline std::size_t getIndex(const size_type &x1, const size_type &x2, const size_type &x3, const size_type &nx1, + const size_type & /*nx2*/, const size_type &nx3) const + { + return nx3 * (nx1 * x2 + x1) + x3; + } + inline std::size_t getStartIndexOfSortedArray(const size_type &x1, const size_type &x2, const size_type & /*x3*/ + , + const size_type &nx1, const size_type & /*nx2*/, + const size_type &nx3) const + { + return nx3 * (nx1 * x2 + x1); + } }; - ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// // CbArray3D @@ -132,334 +139,307 @@ public: //! //! -release: not defined "NO_CB_RANGECHECK" && defined "CB_RANGECHECK" ////////////////////////////////////////////////////////////////////////// -template<typename T, typename IndexClass = IndexerX3X2X1> +template <typename T, typename IndexClass = IndexerX3X2X1> class CbArray3D { public: - using CbArray3DPtr = SPtr<CbArray3D<T, IndexClass> >; + using CbArray3DPtr = SPtr<CbArray3D<T, IndexClass>>; - using value_type = T; - using indexer_type = IndexClass; - using size_type = typename IndexClass::size_type; - using reference = typename std::vector<value_type>::reference; - using const_reference = typename std::vector<value_type>::const_reference; - using pointer = typename std::vector<value_type>::pointer; - using const_pointer = typename std::vector<value_type>::const_pointer; + using value_type = T; + using indexer_type = IndexClass; + using size_type = typename IndexClass::size_type; + using reference = typename std::vector<value_type>::reference; + using const_reference = typename std::vector<value_type>::const_reference; + using pointer = typename std::vector<value_type>::pointer; + using const_pointer = typename std::vector<value_type>::const_pointer; private: - template< typename value_type2, typename IndexClass2 > friend class CbArray3D; + template <typename value_type2, typename IndexClass2> + friend class CbArray3D; public: - /*=======================================================================*/ - CbArray3D() - { - this->resize(0,0,0); - } - /*=======================================================================*/ - CbArray3D(const size_type& nx1,const size_type& nx2, const size_type& nx3, const value_type& val) - { - this->resize(nx1,nx2,nx3,val); - } - /*=======================================================================*/ - CbArray3D(const size_type& nx1,const size_type& nx2, const size_type& nx3) + /*=======================================================================*/ + CbArray3D() { this->resize(0, 0, 0); } + /*=======================================================================*/ + CbArray3D(const size_type &nx1, const size_type &nx2, const size_type &nx3, const value_type &val) { - this->resize(nx1,nx2,nx3); + this->resize(nx1, nx2, nx3, val); + } + /*=======================================================================*/ + CbArray3D(const size_type &nx1, const size_type &nx2, const size_type &nx3) { this->resize(nx1, nx2, nx3); } + /*=======================================================================*/ + CbArray3D(const size_type &uniformDimensionSize /*nx1==nx2==nx3*/) + { + this->resize(uniformDimensionSize, uniformDimensionSize, uniformDimensionSize); + } + /*=======================================================================*/ + // ssbernimmt vector als daten vector! (erstellt KEINE kopie!!!, vec ist anschliessend leer, da swap verwendet wird) + CbArray3D(std::vector<value_type> &vec, const size_type &nx1, const size_type &nx2, const size_type &nx3) + { + assert((nx1 * nx2 * nx3) == vec.size()); + this->data.swap(vec); + this->resize(nx1, nx2, nx3); + } + /*=======================================================================*/ + CbArray3D(const CbArray3D &src) : nx1(src.nx1), nx2(src.nx2), nx3(src.nx3), data(src.data) {} + /*=======================================================================*/ + template <typename value_type2> + CbArray3D(const CbArray3D<value_type2> &src) : nx1(src.nx1), nx2(src.nx2), nx3(src.nx3) + { + // Sourcedaten kopieren + this->data.resize(src.data.size()); + for (std::size_t i = 0; i < data.size(); ++i) + this->data[i] = src.data[i]; + } + /*=======================================================================*/ + virtual ~CbArray3D() = default; + /*=======================================================================*/ + CbArray3D &operator=(const CbArray3D &rhs) + { + if (this == &rhs) + return *this; + + this->nx1 = rhs.nx1; + this->nx2 = rhs.nx2; + this->nx3 = rhs.nx3; + + // gespeicherte Datenelemente loeschen + // Laenge anpassen + this->data.resize(rhs.data.size()); + // gespeicherte Datenelemente loeschen + this->data.clear(); + + // Sourcedaten kopieren + this->data = rhs.data; + + return *this; + } + /*=======================================================================*/ + // durch value_type2 kann man z.B. ein float array einer double array zuweisen! + template <typename value_type2, typename IndexClass2> + CbArray3D &operator=(const CbArray3D<value_type2, IndexClass2> &rhs) + { + this->nx1 = rhs.nx1; + this->nx2 = rhs.nx2; + this->nx3 = rhs.nx3; + + // gespeicherte Datenelemente loeschen + this->data.clear(); + // Laenge anpassen + this->data.resize(rhs.data.size()); + + // Sourcedaten kopieren (!! koennte anderen Indexer besitzen!!! -> operator() benutzen) + for (int x3 = 0; x3 < this->nx3; x3++) + for (int x2 = 0; x2 < this->nx2; x2++) + for (int x1 = 0; x1 < this->nx1; x1++) + this->operator()(x1, x2, x3) = static_cast<value_type>(rhs.operator()(x1, x2, x3)); + + return *this; + } + /*=======================================================================*/ + bool operator==(const CbArray3D &rhs) const + { + if (this == &rhs) + return true; + + if (this->nx1 != rhs.nx1 || this->nx2 != rhs.nx2 || this->nx3 != rhs.nx3 || + this->data.size() != rhs.data.size()) { + return false; + } + + return std::equal(this->data.begin(), this->data.end(), rhs.data.begin(), UbEqual<value_type, value_type>()); + } + /*=======================================================================*/ + template <typename value_type2, typename IndexClass2> + bool operator==(const CbArray3D<value_type2, IndexClass2> &rhs) const + { + if (this->data.size() != rhs.data.size()) + return false; + + // Sourcedaten einzeln checken (!! koennte anderen Indexer besitzen!!! -> operator() benutzen) + for (int x3 = 0; x3 < this->nx3; x3++) + for (int x2 = 0; x2 < this->nx2; x2++) + for (int x1 = 0; x1 < this->nx1; x1++) + if (!isUbEqual(this->operator()(x1, x2, x3), rhs.operator()(x1, x2, x3))) + return false; + + return true; + } + /*=======================================================================*/ + bool operator!=(const CbArray3D &src) const { return !(*this == src); } + /*=======================================================================*/ + template <typename value_type2, typename IndexClass2> + bool operator!=(const CbArray3D<value_type2, IndexClass2> &rhs) const + { + return !(*this == rhs); + } + /*=======================================================================*/ + reference operator()(const size_type &x1, const size_type &x2, const size_type &x3) + { +#if !defined(NO_CB_RANGECHECK) && (defined(_DEBUG) || defined(CB_RANGECHECK)) + if (!this->indicesInRange(x1, x2, x3)) + UB_THROW(UbException(UB_EXARGS, getExceptionErrorString(x1, x2, x3))); +#endif + + return this->data[indexer.getIndex(x1, x2, x3, nx1, nx2, nx3)]; + } + /*=======================================================================*/ + const_reference operator()(const size_type &x1, const size_type &x2, const size_type &x3) const + { +#if !defined(NO_CB_RANGECHECK) && (defined(_DEBUG) || defined(CB_RANGECHECK)) + if (!this->indicesInRange(x1, x2, x3)) + UB_THROW(UbException(UB_EXARGS, getExceptionErrorString(x1, x2, x3))); +#endif + + return this->data[indexer.getIndex(x1, x2, x3, nx1, nx2, nx3)]; + } + /*=======================================================================*/ + pointer getStartAdressOfSortedArray(const size_type &x1, const size_type &x2, const size_type &x3) + { +#if !defined(NO_CB_RANGECHECK) && (defined(_DEBUG) || defined(CB_RANGECHECK)) + if (!this->indicesInRange(x1, x2, x3)) + UB_THROW(UbException(UB_EXARGS, getExceptionErrorString(x1, x2, x3))); +#endif + + return &this->data[indexer.getStartIndexOfSortedArray(x1, x2, x3, nx1, nx2, nx3)]; + } + /*=======================================================================*/ + const_pointer getStartAdressOfSortedArray(const size_type &x1, const size_type &x2, const size_type &x3) const + { +#if !defined(NO_CB_RANGECHECK) && (defined(_DEBUG) || defined(CB_RANGECHECK)) + if (!this->indicesInRange(x1, x2, x3)) + UB_THROW(UbException(UB_EXARGS, getExceptionErrorString(x1, x2, x3))); +#endif + + return &this->data[indexer.getStartIndexOfSortedArray(x1, x2, x3, nx1, nx2, nx3)]; + } + /*=======================================================================*/ + void setObject(const size_type &x1, const size_type &x2, const size_type &x3, const value_type &value) + { +#if !defined(NO_CB_RANGECHECK) && (defined(_DEBUG) || defined(CB_RANGECHECK)) + if (!this->indicesInRange(x1, x2, x3)) + UB_THROW(UbException(UB_EXARGS, getExceptionErrorString(x1, x2, x3))); +#endif + + this->data[indexer.getIndex(x1, x2, x3, nx1, nx2, nx3)] = value; + } + /*=======================================================================*/ + reference getObject(const size_type &x1, const size_type &x2, const size_type &x3) + { +#if !defined(NO_CB_RANGECHECK) && (defined(_DEBUG) || defined(CB_RANGECHECK)) + if (!this->indicesInRange(x1, x2, x3)) + UB_THROW(UbException(UB_EXARGS, getExceptionErrorString(x1, x2, x3))); +#endif + + return this->data[indexer.getIndex(x1, x2, x3, nx1, nx2, nx3)]; + } + /*=======================================================================*/ + const_reference getObject(const size_type &x1, const size_type &x2, const size_type &x3) const + { + return (*this)(x1, x2, x3); + } + /*=======================================================================*/ + bool isEmpty() const { return data.empty(); } + size_type getNX1() const { return this->nx1; } + size_type getNX2() const { return this->nx2; } + size_type getNX3() const { return this->nx3; } + /*=======================================================================*/ + void reset(const value_type &val) { std::fill(this->data.begin(), this->data.end(), val); } + /*=======================================================================*/ + std::string toString() const + { + std::stringstream text; + for (size_type x1 = 0; x1 < this->nx1; x1++) { + for (size_type x2 = 0; x2 < this->nx2; x2++) { + for (size_type x3 = 0; x3 < this->nx3; x3++) { + text << (*this)(x1, x2, x3) << ", "; + } + text << std::endl; + } + text << std::endl << std::endl; + } + + return text.str(); + } + /*=======================================================================*/ + std::string getInfo() const + { + std::stringstream text; + text << "CbArray3D< storageType=" << typeid(T).name() << ", indexer=" << typeid(IndexClass).name() << " >"; + text << "( nx1=" << this->nx1 << ", nx2=" << this->nx2 << ", nx3=" << this->nx3 << ")"; + return text.str(); + } + /*=======================================================================*/ + void resize(const int &uniformDimensionSize) + { + this->resize(uniformDimensionSize, uniformDimensionSize, uniformDimensionSize); + } + /*=======================================================================*/ + void resize(const size_type &nx1, const size_type &nx2, const size_type &nx3) + { + this->nx1 = nx1; + this->nx2 = nx2; + this->nx3 = nx3; + this->data.resize(nx1 * nx2 * nx3); + } + /*=======================================================================*/ + void resize(const size_type &nx1, const size_type &nx2, const size_type &nx3, const value_type &val) + { + this->nx1 = nx1; + this->nx2 = nx2; + this->nx3 = nx3; + this->data.resize(nx1 * nx2 * nx3, val); + } + /*=======================================================================*/ + void clear() + { + this->nx1 = 0; + this->nx2 = 0; + this->nx3 = 0; + this->data.clear(); + } + /*=======================================================================*/ + std::vector<value_type> &getDataVector() { return this->data; } + /*=======================================================================*/ + const std::vector<value_type> &getDataVector() const { return this->data; } + /*=======================================================================*/ + inline std::size_t getDataVectorIndex(const size_type &x1, const size_type &x2, const size_type &x3) const + { +#if !defined(NO_CB_RANGECHECK) && (defined(_DEBUG) || defined(CB_RANGECHECK)) + if (!this->indicesInRange(x1, x2, x3)) + UB_THROW(UbException(UB_EXARGS, getExceptionErrorString(x1, x2, x3))); +#endif + + return indexer.getIndex(x1, x2, x3, nx1, nx2, nx3); + } + + /*=======================================================================*/ + // success -> true + // else -> false + inline bool indicesInRange(const size_type &x1, const size_type &x2, const size_type &x3) const + { + if (x1 < 0 || x1 >= this->nx1 || x2 < 0 || x2 >= this->nx2 || x3 < 0 || x3 >= this->nx3) { + return false; + } + return true; } - /*=======================================================================*/ - CbArray3D(const size_type& uniformDimensionSize /*nx1==nx2==nx3*/) - { - this->resize(uniformDimensionSize,uniformDimensionSize,uniformDimensionSize); - } - /*=======================================================================*/ - //ssbernimmt vector als daten vector! (erstellt KEINE kopie!!!, vec ist anschliessend leer, da swap verwendet wird) - CbArray3D(std::vector<value_type>& vec, const size_type& nx1,const size_type& nx2, const size_type& nx3) - { - assert( (nx1*nx2*nx3)==vec.size() ); - this->data.swap(vec); - this->resize(nx1,nx2,nx3); - } - /*=======================================================================*/ - CbArray3D(const CbArray3D& src) - : nx1(src.nx1) - , nx2(src.nx2) - , nx3(src.nx3) - , data(src.data) - { - } - /*=======================================================================*/ - template< typename value_type2 > - CbArray3D(const CbArray3D< value_type2 >& src) - : nx1(src.nx1) - , nx2(src.nx2) - , nx3(src.nx3) - { - //Sourcedaten kopieren - this->data.resize( src.data.size() ); - for(std::size_t i=0; i<data.size(); ++i) - this->data[i] = src.data[i]; - } - /*=======================================================================*/ - virtual ~CbArray3D() = default; - /*=======================================================================*/ - CbArray3D& operator= (const CbArray3D& rhs) - { - if(this == &rhs) return *this; - - this->nx1 = rhs.nx1; - this->nx2 = rhs.nx2; - this->nx3 = rhs.nx3; - - //gespeicherte Datenelemente loeschen - //Laenge anpassen - this->data.resize(rhs.data.size()); - //gespeicherte Datenelemente loeschen - this->data.clear(); - - //Sourcedaten kopieren - this->data = rhs.data; - - return *this; - } - /*=======================================================================*/ - //durch value_type2 kann man z.B. ein float array einer double array zuweisen! - template< typename value_type2, typename IndexClass2 > - CbArray3D& operator= (const CbArray3D< value_type2, IndexClass2 >& rhs) - { - this->nx1 = rhs.nx1; - this->nx2 = rhs.nx2; - this->nx3 = rhs.nx3; - - //gespeicherte Datenelemente loeschen - this->data.clear(); - //Laenge anpassen - this->data.resize(rhs.data.size()); - - //Sourcedaten kopieren (!! koennte anderen Indexer besitzen!!! -> operator() benutzen) - for(int x3=0; x3<this->nx3; x3++) - for(int x2=0; x2<this->nx2; x2++) - for(int x1=0; x1<this->nx1; x1++) - this->operator()(x1,x2,x3) = static_cast< value_type >( rhs.operator()(x1,x2,x3) ); - - return *this; - } - /*=======================================================================*/ - bool operator== (const CbArray3D& rhs) const - { - if(this == &rhs) return true; - - if( this->nx1!=rhs.nx1 - || this->nx2!=rhs.nx2 - || this->nx3!=rhs.nx3 - || this->data.size() != rhs.data.size() ) - { - return false; - } - - return std::equal( this->data.begin(), this->data.end(), rhs.data.begin(), UbEqual<value_type, value_type >() ); - } - /*=======================================================================*/ - template< typename value_type2, typename IndexClass2 > - bool operator== (const CbArray3D< value_type2, IndexClass2 >& rhs) const - { - if( this->data.size() != rhs.data.size() ) return false; - - //Sourcedaten einzeln checken (!! koennte anderen Indexer besitzen!!! -> operator() benutzen) - for(int x3=0; x3<this->nx3; x3++) - for(int x2=0; x2<this->nx2; x2++) - for(int x1=0; x1<this->nx1; x1++) - if( !isUbEqual(this->operator()(x1,x2,x3), rhs.operator()(x1,x2,x3)) ) - return false; - - return true; - } - /*=======================================================================*/ - bool operator!= (const CbArray3D& src) const - { - return !(*this==src); - } - /*=======================================================================*/ - template< typename value_type2, typename IndexClass2 > - bool operator!= (const CbArray3D< value_type2, IndexClass2 >& rhs) const - { - return !(*this==rhs); - } - /*=======================================================================*/ - reference operator() (const size_type& x1, const size_type& x2, const size_type& x3) - { - #if !defined(NO_CB_RANGECHECK) && ( defined(_DEBUG) || defined(CB_RANGECHECK) ) - if( !this->indicesInRange(x1,x2,x3) ) - UB_THROW( UbException(UB_EXARGS,getExceptionErrorString(x1,x2,x3)) ); - #endif - - return this->data[ indexer.getIndex(x1,x2,x3,nx1,nx2,nx3) ]; - } - /*=======================================================================*/ - const_reference operator() (const size_type& x1, const size_type& x2, const size_type& x3) const - { - #if !defined(NO_CB_RANGECHECK) && ( defined(_DEBUG) || defined(CB_RANGECHECK) ) - if( !this->indicesInRange(x1,x2,x3) ) - UB_THROW( UbException(UB_EXARGS,getExceptionErrorString(x1,x2,x3)) ); - #endif - - return this->data[ indexer.getIndex(x1,x2,x3,nx1,nx2,nx3) ]; - } - /*=======================================================================*/ - pointer getStartAdressOfSortedArray(const size_type& x1, const size_type& x2, const size_type& x3) - { - #if !defined(NO_CB_RANGECHECK) && ( defined(_DEBUG) || defined(CB_RANGECHECK) ) - if( !this->indicesInRange(x1,x2,x3) ) - UB_THROW( UbException(UB_EXARGS,getExceptionErrorString(x1,x2,x3)) ); - #endif - - return &this->data[indexer.getStartIndexOfSortedArray(x1,x2,x3,nx1,nx2,nx3)]; - } - /*=======================================================================*/ - const_pointer getStartAdressOfSortedArray(const size_type& x1, const size_type& x2, const size_type& x3) const - { - #if !defined(NO_CB_RANGECHECK) && ( defined(_DEBUG) || defined(CB_RANGECHECK) ) - if( !this->indicesInRange(x1,x2,x3) ) - UB_THROW( UbException(UB_EXARGS,getExceptionErrorString(x1,x2,x3)) ); - #endif - - return &this->data[indexer.getStartIndexOfSortedArray(x1,x2,x3,nx1,nx2,nx3)]; - } - /*=======================================================================*/ - void setObject(const size_type& x1, const size_type& x2, const size_type& x3, const value_type& value) - { - #if !defined(NO_CB_RANGECHECK) && ( defined(_DEBUG) || defined(CB_RANGECHECK) ) - if( !this->indicesInRange(x1,x2,x3) ) - UB_THROW( UbException(UB_EXARGS,getExceptionErrorString(x1,x2,x3)) ); - #endif - - this->data[ indexer.getIndex(x1,x2,x3,nx1,nx2,nx3) ] = value; - } - /*=======================================================================*/ - reference getObject(const size_type& x1, const size_type& x2, const size_type& x3) - { - #if !defined(NO_CB_RANGECHECK) && ( defined(_DEBUG) || defined(CB_RANGECHECK) ) - if( !this->indicesInRange(x1,x2,x3) ) - UB_THROW( UbException(UB_EXARGS,getExceptionErrorString(x1,x2,x3)) ); - #endif - - return this->data[ indexer.getIndex(x1,x2,x3,nx1,nx2,nx3) ] ; - } - /*=======================================================================*/ - const_reference getObject(const size_type& x1, const size_type& x2, const size_type& x3) const - { - return (*this)(x1,x2,x3); - } - /*=======================================================================*/ - bool isEmpty() const { return data.empty(); } - size_type getNX1() const { return this->nx1; } - size_type getNX2() const { return this->nx2; } - size_type getNX3() const { return this->nx3; } - /*=======================================================================*/ - void reset(const value_type& val) - { - std::fill( this->data.begin(), this->data.end(), val ); - } - /*=======================================================================*/ - std::string toString() const - { - std::stringstream text; - for(size_type x1=0; x1<this->nx1; x1++) - { - for(size_type x2=0; x2<this->nx2; x2++) - { - for(size_type x3=0; x3<this->nx3; x3++) - { - text<<(*this)(x1,x2,x3)<<", "; - } - text<<std::endl; - } - text<<std::endl<<std::endl; - } - - return text.str(); - } - /*=======================================================================*/ - std::string getInfo() const - { - std::stringstream text; - text<<"CbArray3D< storageType="<<typeid(T).name()<<", indexer="<<typeid(IndexClass).name()<<" >"; - text<<"( nx1="<<this->nx1<<", nx2="<<this->nx2<<", nx3="<<this->nx3<<")"; - return text.str(); - } - /*=======================================================================*/ - void resize(const int& uniformDimensionSize) - { - this->resize(uniformDimensionSize,uniformDimensionSize,uniformDimensionSize); - } - /*=======================================================================*/ - void resize(const size_type& nx1,const size_type& nx2, const size_type& nx3) - { - this->nx1 = nx1; - this->nx2 = nx2; - this->nx3 = nx3; - this->data.resize(nx1*nx2*nx3); - } - /*=======================================================================*/ - void resize(const size_type& nx1,const size_type& nx2, const size_type& nx3,const value_type& val) - { - this->nx1 = nx1; - this->nx2 = nx2; - this->nx3 = nx3; - this->data.resize(nx1*nx2*nx3,val); - } - /*=======================================================================*/ - void clear() - { - this->nx1 = 0; - this->nx2 = 0; - this->nx3 = 0; - this->data.clear(); - } - /*=======================================================================*/ - std::vector< value_type >& getDataVector() { return this->data; } - /*=======================================================================*/ - const std::vector< value_type >& getDataVector() const { return this->data; } - /*=======================================================================*/ - inline std::size_t getDataVectorIndex(const size_type& x1, const size_type& x2, const size_type& x3) const - { - #if !defined(NO_CB_RANGECHECK) && ( defined(_DEBUG) || defined(CB_RANGECHECK) ) - if( !this->indicesInRange(x1,x2,x3) ) - UB_THROW( UbException(UB_EXARGS,getExceptionErrorString(x1,x2,x3)) ); - #endif - - return indexer.getIndex(x1,x2,x3,nx1,nx2,nx3); - } - - - /*=======================================================================*/ - //success -> true - //else -> false - inline bool indicesInRange(const size_type& x1, const size_type& x2, const size_type& x3) const - { - if( x1 < 0 || x1 >= this->nx1 - || x2 < 0 || x2 >= this->nx2 - || x3 < 0 || x3 >= this->nx3 ) - { - return false; - } - return true; - } -protected: - /*=======================================================================*/ - std::string getExceptionErrorString(const size_type& x1, const size_type& x2, const size_type& x3) const - { - std::stringstream out("index out of range - "); - out<<"("<<x1<<","<<x2<<","<<x3<<") not in ("<<nx1<<","<<nx2<<","<<nx3<<")"; - return out.str(); - } - /*=======================================================================*/ protected: - size_type nx1; - size_type nx2; - size_type nx3; - indexer_type indexer; - std::vector< value_type > data; + /*=======================================================================*/ + std::string getExceptionErrorString(const size_type &x1, const size_type &x2, const size_type &x3) const + { + std::stringstream out("index out of range - "); + out << "(" << x1 << "," << x2 << "," << x3 << ") not in (" << nx1 << "," << nx2 << "," << nx3 << ")"; + return out.str(); + } + /*=======================================================================*/ +protected: + size_type nx1; + size_type nx2; + size_type nx3; + indexer_type indexer; + std::vector<value_type> data; }; -#endif //CBARRAY3D_H +#endif // CBARRAY3D_H diff --git a/src/basics/basics/container/CbArray4D.h b/src/basics/basics/container/CbArray4D.h index 16c5542323de11ab72c3598e5b6fa03ed475e18e..31238e1b8c1d4acd875737b8f45803f20d78c7fc 100644 --- a/src/basics/basics/container/CbArray4D.h +++ b/src/basics/basics/container/CbArray4D.h @@ -1,28 +1,28 @@ //======================================================================================= -// ____ ____ __ ______ __________ __ __ __ __ -// \ \ | | | | | _ \ |___ ___| | | | | / \ | | -// \ \ | | | | | |_) | | | | | | | / \ | | -// \ \ | | | | | _ / | | | | | | / /\ \ | | -// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ -// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| -// \ \ | | ________________________________________________________________ -// \ \ | | | ______________________________________________________________| -// \ \| | | | __ __ __ __ ______ _______ -// \ | | |_____ | | | | | | | | | _ \ / _____) -// \ | | _____| | | | | | | | | | | \ \ \_______ +// ____ ____ __ ______ __________ __ __ __ __ +// \ \ | | | | | _ \ |___ ___| | | | | / \ | | +// \ \ | | | | | |_) | | | | | | | / \ | | +// \ \ | | | | | _ / | | | | | | / /\ \ | | +// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ +// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| +// \ \ | | ________________________________________________________________ +// \ \ | | | ______________________________________________________________| +// \ \| | | | __ __ __ __ ______ _______ +// \ | | |_____ | | | | | | | | | _ \ / _____) +// \ | | _____| | | | | | | | | | | \ \ \_______ // \ | | | | |_____ | \_/ | | | | |_/ / _____ | -// \ _____| |__| |________| \_______/ |__| |______/ (_______/ +// \ _____| |__| |________| \_______/ |__| |______/ (_______/ // -// This file is part of VirtualFluids. VirtualFluids is free software: you can +// This file is part of VirtualFluids. VirtualFluids is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of +// License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. -// -// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// +// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License along // with VirtualFluids (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>. // @@ -33,67 +33,73 @@ #ifndef CBARRAY4D_H #define CBARRAY4D_H - - -#include <iomanip> -#include <basics/utilities/UbException.h> -#include <basics/utilities/UbEqual.h> +#include "PointerDefinitions.h" #include <algorithm> +#include <basics/utilities/UbEqual.h> +#include <basics/utilities/UbException.h> +#include <iomanip> #include <typeinfo> -#include "PointerDefinitions.h" ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// // IndexClasses -//IndexerX1X2X3X4: -//x4-reihen "liegen am stueck" im speicher -//optimaler schleifendurchlauf -//for(alle X1) +// IndexerX1X2X3X4: +// x4-reihen "liegen am stueck" im speicher +// optimaler schleifendurchlauf +// for(alle X1) // for(alle X2) // for(alle X3) // for(alle X4) class IndexerX1X2X3X4 { public: - using size_type = int; + using size_type = int; + public: - inline std::size_t getIndex( const size_type& x1 , const size_type& x2 , const size_type& x3 , const size_type& x4 - , const size_type& /*nx1*/, const size_type& nx2, const size_type& nx3, const size_type& nx4 ) const - { - return nx4*(nx3*(nx2*x1+ x2)+x3)+x4 ; - } - inline std::size_t getStartIndexOfSortedArray( const size_type& x1 , const size_type& x2 , const size_type& x3 , const size_type& /*x4*/ - , const size_type& /*nx1*/, const size_type& nx2, const size_type& nx3, const size_type& nx4 ) const - { - return nx4*(nx3*(nx2*x1+ x2)+x3); - } + inline std::size_t getIndex(const size_type &x1, const size_type &x2, const size_type &x3, const size_type &x4, + const size_type & /*nx1*/, const size_type &nx2, const size_type &nx3, + const size_type &nx4) const + { + return nx4 * (nx3 * (nx2 * x1 + x2) + x3) + x4; + } + inline std::size_t getStartIndexOfSortedArray(const size_type &x1, const size_type &x2, const size_type &x3, + const size_type & /*x4*/ + , + const size_type & /*nx1*/, const size_type &nx2, const size_type &nx3, + const size_type &nx4) const + { + return nx4 * (nx3 * (nx2 * x1 + x2) + x3); + } }; ////////////////////////////////////////////////////////////////////////// // IndexClasses -//IndexerX4X3X2X1: -//x1-reihen "liegen am stueck" im speicher -//optimaler schleifendurchlauf -//for(alle X4) +// IndexerX4X3X2X1: +// x1-reihen "liegen am stueck" im speicher +// optimaler schleifendurchlauf +// for(alle X4) // for(alle X3) // for(alle X2) // for(alle X1) class IndexerX4X3X2X1 { public: - using size_type = size_t; + using size_type = size_t; + public: - inline std::size_t getIndex( const size_type& x1 , const size_type& x2 , const size_type& x3 , const size_type& x4 - , const size_type& nx1, const size_type& nx2, const size_type& nx3, const size_type& /*nx4*/ ) const - { - return nx1*(nx2*(nx3*x4+ x3)+x2)+x1; - } - inline std::size_t getStartIndexOfSortedArray( const size_type& /*x1*/ , const size_type& x2 , const size_type& x3 , const size_type& x4 - , const size_type& nx1, const size_type& nx2, const size_type& nx3, const size_type& /*nx4*/ ) const - { - return nx1*(nx2*(nx3*x4+ x3)+x2); - } + inline std::size_t getIndex(const size_type &x1, const size_type &x2, const size_type &x3, const size_type &x4, + const size_type &nx1, const size_type &nx2, const size_type &nx3, + const size_type & /*nx4*/) const + { + return nx1 * (nx2 * (nx3 * x4 + x3) + x2) + x1; + } + inline std::size_t getStartIndexOfSortedArray(const size_type & /*x1*/, const size_type &x2, const size_type &x3, + const size_type &x4, const size_type &nx1, const size_type &nx2, + const size_type &nx3, const size_type & /*nx4*/) const + { + return nx1 * (nx2 * (nx3 * x4 + x3) + x2); + } }; ////////////////////////////////////////////////////////////////////////// // CbArray4D @@ -106,343 +112,327 @@ public: //! //! -release: not defined "NO_CB_RANGECHECK" && defined "CB_RANGECHECK" ////////////////////////////////////////////////////////////////////////// -template<typename T, typename IndexClass = IndexerX4X3X2X1> +template <typename T, typename IndexClass = IndexerX4X3X2X1> class CbArray4D { public: - using CbArray4DPtr = SPtr<CbArray4D<T, IndexClass> >; + using CbArray4DPtr = SPtr<CbArray4D<T, IndexClass>>; - using value_type = T; - using indexer_type = IndexClass; - using size_type = typename IndexClass::size_type; - using reference = typename std::vector<value_type>::reference; - using const_reference = typename std::vector<value_type>::const_reference; - using pointer = typename std::vector<value_type>::pointer; - using const_pointer = typename std::vector<value_type>::const_pointer; + using value_type = T; + using indexer_type = IndexClass; + using size_type = typename IndexClass::size_type; + using reference = typename std::vector<value_type>::reference; + using const_reference = typename std::vector<value_type>::const_reference; + using pointer = typename std::vector<value_type>::pointer; + using const_pointer = typename std::vector<value_type>::const_pointer; private: - template< typename value_type2, typename IndexClass2 > friend class CbArray4D; + template <typename value_type2, typename IndexClass2> + friend class CbArray4D; public: - /*=======================================================================*/ - CbArray4D() - { - this->resize(0,0,0,0); - } - /*=======================================================================*/ - CbArray4D(const size_type& nx1,const size_type& nx2, const size_type& nx3, const size_type& nx4) - { - this->resize(nx1,nx2,nx3,nx4); - } - /*=======================================================================*/ - CbArray4D(const size_type& nx1,const size_type& nx2, const size_type& nx3, const size_type& nx4, const value_type& val) - { - this->resize(nx1,nx2,nx3,nx4,val); - } - /*=======================================================================*/ - CbArray4D(const size_type& uniformDimensionSize /*nx1=nx2=nx3=nx4*/) - { - this->resize(uniformDimensionSize,uniformDimensionSize,uniformDimensionSize,uniformDimensionSize); - } - /*=======================================================================*/ - //ubernimmt vector als daten vector! (erstellt KEINE kopie!!!, vec ist anschliessend leer, da swap verwendet wird) - CbArray4D(std::vector<value_type>& vec, const size_type& nx1,const size_type& nx2, const size_type& nx3, const size_type& nx4) - { - assert( (nx1*nx2*nx3*nx4)==vec.size() ); - this->data.swap(vec); - this->resize(nx1,nx2,nx3,nx4); - } - /*=======================================================================*/ - CbArray4D(const CbArray4D& src) - : nx1(src.nx1) - , nx2(src.nx2) - , nx3(src.nx3) - , nx4(src.nx4) - , data(src.data) - { - } - /*=======================================================================*/ - template< typename value_type2 > - CbArray4D(const CbArray4D< value_type2 >& src) - : nx1(src.nx1) - , nx2(src.nx2) - , nx3(src.nx3) - , nx4(src.nx4) - { - //Sourcedaten kopieren - this->data.resize( src.data.size() ); - for(std::size_t i=0; i<data.size(); ++i) - this->data[i] = src.data[i]; - } - /*=======================================================================*/ - virtual ~CbArray4D()= default; - /*=======================================================================*/ - CbArray4D& operator= (const CbArray4D& rhs) - { - if(this == &rhs) return *this; - - this->nx1 = rhs.nx1; - this->nx2 = rhs.nx2; - this->nx3 = rhs.nx3; - this->nx4 = rhs.nx4; - - //gespeicherte Datenelemente loeschen - //Laenge anpassen - this->data.resize(rhs.data.size()); - //gespeicherte Datenelemente loeschen - this->data.clear(); - - //Sourcedaten kopieren - this->data = rhs.data; - - return *this; - } - /*=======================================================================*/ - //durch value_type2 kann man z.B. ein float Array einem double Array zuweisen! - template< typename value_type2, typename IndexClass2 > - CbArray4D& operator= (const CbArray4D< value_type2, IndexClass2 >& rhs) - { - this->nx1 = rhs.nx1; - this->nx2 = rhs.nx2; - this->nx3 = rhs.nx3; - this->nx4 = rhs.nx4; - - //gespeicherte Datenelemente loeschen - this->data.clear(); - //Laenge anpassen - this->data.resize(rhs.data.size()); - - //Sourcedaten kopieren (!! koennte anderen Indexer besitzen!!! -> operator() benutzen) - for(int x1=0; x1<this->nx1; x1++) - for(int x2=0; x2<this->nx2; x2++) - for(int x3=0; x3<this->nx3; x3++) - for(int x4=0; x4<this->nx4; x4++) - this->operator()(x1,x2,x3,x4) = static_cast< value_type >( rhs.operator()(x1,x2,x3,x4)); - - return *this; - } - /*=======================================================================*/ - bool operator== (const CbArray4D& rhs) const - { - if( this == &rhs ) return true; - - if( this->nx1!=rhs.nx1 - || this->nx2!=rhs.nx2 - || this->nx3!=rhs.nx3 - || this->nx4!=rhs.nx4 - || this->data.size() != rhs.data.size() ) - { - return false; - } - - return std::equal( this->data.begin(), this->data.end(), rhs.data.begin(), UbEqual<value_type, value_type >() ); - } - /*=======================================================================*/ - template< typename value_type2, typename IndexClass2 > - bool operator== (const CbArray4D< value_type2, IndexClass2 >& rhs) const - { - if( this->data.size() != rhs.data.size() ) return false; - - //Sourcedaten einzeln checken (!! koennte anderen Indexer besitzen!!! -> operator() benutzen) - for(int x4=0; x4<this->nx4; x4++) - for(int x3=0; x3<this->nx3; x3++) - for(int x2=0; x2<this->nx2; x2++) - for(int x1=0; x1<this->nx1; x1++) - if( !isUbEqual(this->operator()(x1,x2,x3,x4), rhs.operator()(x1,x2,x3,x4)) ) - return false; - - return true; - } - /*=======================================================================*/ - bool operator!= (const CbArray4D& rhs) const - { - return !(*this==rhs); - } - /*=======================================================================*/ - template< typename value_type2, typename IndexClass2 > - bool operator!= (const CbArray4D< value_type2, IndexClass2 >& rhs) const - { - return !(*this==rhs); - } - /*=======================================================================*/ - reference operator() (const size_type& x1, const size_type& x2, const size_type& x3, const size_type& x4) - { - #if !defined(NO_CB_RANGECHECK) && ( defined(_DEBUG) || defined(CB_RANGECHECK) ) - if( !this->indicesInRange(x1,x2,x3,x4) ) - UB_THROW( UbException(UB_EXARGS,getExceptionErrorString(x1,x2,x3,x4)) ); - #endif - - return this->data[indexer.getIndex(x1,x2,x3,x4,nx1,nx2,nx3,nx4)]; - } - /*=======================================================================*/ - const_reference operator() (const size_type& x1, const size_type& x2, const size_type& x3, const size_type& x4) const - { - #ifdef CbArray4D_RANGECHECKING - if( !this->indicesInRange(x1,x2,x3,x4) ) - UB_THROW( UbException(UB_EXARGS,getExceptionErrorString(x1,x2,x3,x4)) ); - #endif - - return this->data[indexer.getIndex(x1,x2,x3,x4,nx1,nx2,nx3,nx4)]; - } - /*=======================================================================*/ - pointer getStartAdressOfSortedArray(const size_type& x1, const size_type& x2, const size_type& x3, const size_type& x4) - { - #if !defined(NO_CB_RANGECHECK) && ( defined(_DEBUG) || defined(CB_RANGECHECK) ) - if( !this->indicesInRange(x1,x2,x3,x4) ) - UB_THROW( UbException(UB_EXARGS,getExceptionErrorString(x1,x2,x3,x4)) ); - #endif - - return &this->data[indexer.getStartIndexOfSortedArray(x1,x2,x3,x4,nx1,nx2,nx3,nx4)]; - } - /*=======================================================================*/ - const_pointer getStartAdressOfSortedArray(const size_type& x1, const size_type& x2, const size_type& x3, const size_type& x4) const - { - #if !defined(NO_CB_RANGECHECK) && ( defined(_DEBUG) || defined(CB_RANGECHECK) ) - if( !this->indicesInRange(x1,x2,x3,x4) ) - UB_THROW( UbException(UB_EXARGS,getExceptionErrorString(x1,x2,x3,x4)) ); - #endif - - return &this->data[indexer.getStartIndexOfSortedArray(x1,x2,x3,x4,nx1,nx2,nx3,nx4)]; - } - /*=======================================================================*/ - void setObject(const size_type& x1, const size_type& x2, const size_type& x3, const size_type& x4, const value_type& value) - { - #if !defined(NO_CB_RANGECHECK) && ( defined(_DEBUG) || defined(CB_RANGECHECK) ) - if( !this->indicesInRange(x1,x2,x3,x4) ) - UB_THROW( UbException(UB_EXARGS,getExceptionErrorString(x1,x2,x3,x4)) ); - #endif - - this->data[indexer.getIndex(x1,x2,x3,x4,nx1,nx2,nx3,nx4)] = value; - } - /*=======================================================================*/ - reference getObject(const size_type& x1, const size_type& x2, const size_type& x3, const size_type& x4) - { - #if !defined(NO_CB_RANGECHECK) && ( defined(_DEBUG) || defined(CB_RANGECHECK) ) - if( !this->indicesInRange(x1,x2,x3,x4) ) - UB_THROW( UbException(UB_EXARGS,getExceptionErrorString(x1,x2,x3,x4)) ); - #endif - - return this->data[indexer.getIndex(x1,x2,x3,x4,nx1,nx2,nx3,nx4)]; - } - /*=======================================================================*/ - const_reference getObject(const size_type& x1, const size_type& x2, const size_type& x3, const size_type& x4) const - { - #if !defined(NO_CB_RANGECHECK) && ( defined(_DEBUG) || defined(CB_RANGECHECK) ) - if( !this->indicesInRange(x1,x2,x3,x4) ) - UB_THROW( UbException(UB_EXARGS,getExceptionErrorString(x1,x2,x3,x4)) ); - #endif - return (*this)(x1,x2,x3,x4,nx1,nx2,nx3,nx4); - } - /*=======================================================================*/ - bool isEmpty() const { return data.empty(); } - size_type getNX1() const { return this->nx1; } - size_type getNX2() const { return this->nx2; } - size_type getNX3() const { return this->nx3; } - size_type getNX4() const { return this->nx4; } - /*=======================================================================*/ - void reset(const value_type& val) - { - std::fill( this->data.begin(), this->data.end(), val ); - } - /*=======================================================================*/ - std::string toString() const - { - std::stringstream text; - text<<std::setprecision(19); - for(size_type x1=0; x1<this->nx1; x1++) - { - for(size_type x2=0; x2<this->nx2; x2++) - { - for(size_type x3=0; x3<this->nx3; x3++) - { - for(size_type x4=0; x4<this->nx4; x4++) - { - text<<(*this)(x1,x2,x3,x4)<<", "; - } - text<<std::endl; - } - text<<std::endl; - } - text<<std::endl<<std::endl; - } - - return text.str(); - } - /*=======================================================================*/ - std::string getInfo() const - { - std::stringstream text; - text<<"CbArray4D< storageType="<<typeid(T).name()<<", indexer="<<typeid(IndexClass).name()<<" >"; - text<<"( nx1="<<this->nx1<<", nx2="<<this->nx2<<", nx3="<<this->nx3<<", nx4="<<this->nx4<<")"; - return text.str(); - } - /*=======================================================================*/ - void resize(const size_type& uniformDimensionSize) { this->resize(uniformDimensionSize,uniformDimensionSize,uniformDimensionSize); } - /*=======================================================================*/ - void resize(const size_type& nx1, const size_type& nx2, const size_type& nx3, const size_type& nx4) - { - this->nx1 = nx1; - this->nx2 = nx2; - this->nx3 = nx3; - this->nx4 = nx4; - this->data.resize(nx1*nx2*nx3*nx4); - } - /*=======================================================================*/ - void resize(const size_type& nx1, const size_type& nx2, const size_type& nx3, const size_type& nx4, const value_type& val) - { - this->nx1 = nx1; - this->nx2 = nx2; - this->nx3 = nx3; - this->nx4 = nx4; - this->data.resize(nx1*nx2*nx3*nx4,val); - } - /*=======================================================================*/ - std::vector< value_type >& getDataVector() { return this->data; } - /*=======================================================================*/ - const std::vector< value_type >& getDataVector() const { return this->data; } - /*=======================================================================*/ - inline std::size_t getDataVectorIndex(const size_type& x1, const size_type& x2, const size_type& x3, const size_type& x4) const - { - #if !defined(NO_CB_RANGECHECK) && ( defined(_DEBUG) || defined(CB_RANGECHECK) ) - if( !this->indicesInRange(x1,x2,x3,x4) ) - UB_THROW( UbException(UB_EXARGS,getExceptionErrorString(x1,x2,x3,x4)) ); - #endif - - return indexer.getIndex(x1,x2,x3,x4,nx1,nx2,nx3,nx4); - } + /*=======================================================================*/ + CbArray4D() { this->resize(0, 0, 0, 0); } + /*=======================================================================*/ + CbArray4D(const size_type &nx1, const size_type &nx2, const size_type &nx3, const size_type &nx4) + { + this->resize(nx1, nx2, nx3, nx4); + } + /*=======================================================================*/ + CbArray4D(const size_type &nx1, const size_type &nx2, const size_type &nx3, const size_type &nx4, + const value_type &val) + { + this->resize(nx1, nx2, nx3, nx4, val); + } + /*=======================================================================*/ + CbArray4D(const size_type &uniformDimensionSize /*nx1=nx2=nx3=nx4*/) + { + this->resize(uniformDimensionSize, uniformDimensionSize, uniformDimensionSize, uniformDimensionSize); + } + /*=======================================================================*/ + // ubernimmt vector als daten vector! (erstellt KEINE kopie!!!, vec ist anschliessend leer, da swap verwendet wird) + CbArray4D(std::vector<value_type> &vec, const size_type &nx1, const size_type &nx2, const size_type &nx3, + const size_type &nx4) + { + assert((nx1 * nx2 * nx3 * nx4) == vec.size()); + this->data.swap(vec); + this->resize(nx1, nx2, nx3, nx4); + } + /*=======================================================================*/ + CbArray4D(const CbArray4D &src) : nx1(src.nx1), nx2(src.nx2), nx3(src.nx3), nx4(src.nx4), data(src.data) {} + /*=======================================================================*/ + template <typename value_type2> + CbArray4D(const CbArray4D<value_type2> &src) : nx1(src.nx1), nx2(src.nx2), nx3(src.nx3), nx4(src.nx4) + { + // Sourcedaten kopieren + this->data.resize(src.data.size()); + for (std::size_t i = 0; i < data.size(); ++i) + this->data[i] = src.data[i]; + } + /*=======================================================================*/ + virtual ~CbArray4D() = default; + /*=======================================================================*/ + CbArray4D &operator=(const CbArray4D &rhs) + { + if (this == &rhs) + return *this; + + this->nx1 = rhs.nx1; + this->nx2 = rhs.nx2; + this->nx3 = rhs.nx3; + this->nx4 = rhs.nx4; + + // gespeicherte Datenelemente loeschen + // Laenge anpassen + this->data.resize(rhs.data.size()); + // gespeicherte Datenelemente loeschen + this->data.clear(); + + // Sourcedaten kopieren + this->data = rhs.data; + + return *this; + } + /*=======================================================================*/ + // durch value_type2 kann man z.B. ein float Array einem double Array zuweisen! + template <typename value_type2, typename IndexClass2> + CbArray4D &operator=(const CbArray4D<value_type2, IndexClass2> &rhs) + { + this->nx1 = rhs.nx1; + this->nx2 = rhs.nx2; + this->nx3 = rhs.nx3; + this->nx4 = rhs.nx4; + + // gespeicherte Datenelemente loeschen + this->data.clear(); + // Laenge anpassen + this->data.resize(rhs.data.size()); + + // Sourcedaten kopieren (!! koennte anderen Indexer besitzen!!! -> operator() benutzen) + for (int x1 = 0; x1 < this->nx1; x1++) + for (int x2 = 0; x2 < this->nx2; x2++) + for (int x3 = 0; x3 < this->nx3; x3++) + for (int x4 = 0; x4 < this->nx4; x4++) + this->operator()(x1, x2, x3, x4) = static_cast<value_type>(rhs.operator()(x1, x2, x3, x4)); + + return *this; + } + /*=======================================================================*/ + bool operator==(const CbArray4D &rhs) const + { + if (this == &rhs) + return true; + + if (this->nx1 != rhs.nx1 || this->nx2 != rhs.nx2 || this->nx3 != rhs.nx3 || this->nx4 != rhs.nx4 || + this->data.size() != rhs.data.size()) { + return false; + } + + return std::equal(this->data.begin(), this->data.end(), rhs.data.begin(), UbEqual<value_type, value_type>()); + } + /*=======================================================================*/ + template <typename value_type2, typename IndexClass2> + bool operator==(const CbArray4D<value_type2, IndexClass2> &rhs) const + { + if (this->data.size() != rhs.data.size()) + return false; + + // Sourcedaten einzeln checken (!! koennte anderen Indexer besitzen!!! -> operator() benutzen) + for (int x4 = 0; x4 < this->nx4; x4++) + for (int x3 = 0; x3 < this->nx3; x3++) + for (int x2 = 0; x2 < this->nx2; x2++) + for (int x1 = 0; x1 < this->nx1; x1++) + if (!isUbEqual(this->operator()(x1, x2, x3, x4), rhs.operator()(x1, x2, x3, x4))) + return false; + + return true; + } + /*=======================================================================*/ + bool operator!=(const CbArray4D &rhs) const { return !(*this == rhs); } + /*=======================================================================*/ + template <typename value_type2, typename IndexClass2> + bool operator!=(const CbArray4D<value_type2, IndexClass2> &rhs) const + { + return !(*this == rhs); + } + /*=======================================================================*/ + reference operator()(const size_type &x1, const size_type &x2, const size_type &x3, const size_type &x4) + { +#if !defined(NO_CB_RANGECHECK) && (defined(_DEBUG) || defined(CB_RANGECHECK)) + if (!this->indicesInRange(x1, x2, x3, x4)) + UB_THROW(UbException(UB_EXARGS, getExceptionErrorString(x1, x2, x3, x4))); +#endif + + return this->data[indexer.getIndex(x1, x2, x3, x4, nx1, nx2, nx3, nx4)]; + } + /*=======================================================================*/ + const_reference operator()(const size_type &x1, const size_type &x2, const size_type &x3, const size_type &x4) const + { +#ifdef CbArray4D_RANGECHECKING + if (!this->indicesInRange(x1, x2, x3, x4)) + UB_THROW(UbException(UB_EXARGS, getExceptionErrorString(x1, x2, x3, x4))); +#endif + + return this->data[indexer.getIndex(x1, x2, x3, x4, nx1, nx2, nx3, nx4)]; + } + /*=======================================================================*/ + pointer getStartAdressOfSortedArray(const size_type &x1, const size_type &x2, const size_type &x3, + const size_type &x4) + { +#if !defined(NO_CB_RANGECHECK) && (defined(_DEBUG) || defined(CB_RANGECHECK)) + if (!this->indicesInRange(x1, x2, x3, x4)) + UB_THROW(UbException(UB_EXARGS, getExceptionErrorString(x1, x2, x3, x4))); +#endif + + return &this->data[indexer.getStartIndexOfSortedArray(x1, x2, x3, x4, nx1, nx2, nx3, nx4)]; + } + /*=======================================================================*/ + const_pointer getStartAdressOfSortedArray(const size_type &x1, const size_type &x2, const size_type &x3, + const size_type &x4) const + { +#if !defined(NO_CB_RANGECHECK) && (defined(_DEBUG) || defined(CB_RANGECHECK)) + if (!this->indicesInRange(x1, x2, x3, x4)) + UB_THROW(UbException(UB_EXARGS, getExceptionErrorString(x1, x2, x3, x4))); +#endif + + return &this->data[indexer.getStartIndexOfSortedArray(x1, x2, x3, x4, nx1, nx2, nx3, nx4)]; + } + /*=======================================================================*/ + void setObject(const size_type &x1, const size_type &x2, const size_type &x3, const size_type &x4, + const value_type &value) + { +#if !defined(NO_CB_RANGECHECK) && (defined(_DEBUG) || defined(CB_RANGECHECK)) + if (!this->indicesInRange(x1, x2, x3, x4)) + UB_THROW(UbException(UB_EXARGS, getExceptionErrorString(x1, x2, x3, x4))); +#endif + + this->data[indexer.getIndex(x1, x2, x3, x4, nx1, nx2, nx3, nx4)] = value; + } + /*=======================================================================*/ + reference getObject(const size_type &x1, const size_type &x2, const size_type &x3, const size_type &x4) + { +#if !defined(NO_CB_RANGECHECK) && (defined(_DEBUG) || defined(CB_RANGECHECK)) + if (!this->indicesInRange(x1, x2, x3, x4)) + UB_THROW(UbException(UB_EXARGS, getExceptionErrorString(x1, x2, x3, x4))); +#endif + + return this->data[indexer.getIndex(x1, x2, x3, x4, nx1, nx2, nx3, nx4)]; + } + /*=======================================================================*/ + const_reference getObject(const size_type &x1, const size_type &x2, const size_type &x3, const size_type &x4) const + { +#if !defined(NO_CB_RANGECHECK) && (defined(_DEBUG) || defined(CB_RANGECHECK)) + if (!this->indicesInRange(x1, x2, x3, x4)) + UB_THROW(UbException(UB_EXARGS, getExceptionErrorString(x1, x2, x3, x4))); +#endif + return (*this)(x1, x2, x3, x4, nx1, nx2, nx3, nx4); + } + /*=======================================================================*/ + bool isEmpty() const { return data.empty(); } + size_type getNX1() const { return this->nx1; } + size_type getNX2() const { return this->nx2; } + size_type getNX3() const { return this->nx3; } + size_type getNX4() const { return this->nx4; } + /*=======================================================================*/ + void reset(const value_type &val) { std::fill(this->data.begin(), this->data.end(), val); } + /*=======================================================================*/ + std::string toString() const + { + std::stringstream text; + text << std::setprecision(19); + for (size_type x1 = 0; x1 < this->nx1; x1++) { + for (size_type x2 = 0; x2 < this->nx2; x2++) { + for (size_type x3 = 0; x3 < this->nx3; x3++) { + for (size_type x4 = 0; x4 < this->nx4; x4++) { + text << (*this)(x1, x2, x3, x4) << ", "; + } + text << std::endl; + } + text << std::endl; + } + text << std::endl << std::endl; + } + + return text.str(); + } + /*=======================================================================*/ + std::string getInfo() const + { + std::stringstream text; + text << "CbArray4D< storageType=" << typeid(T).name() << ", indexer=" << typeid(IndexClass).name() << " >"; + text << "( nx1=" << this->nx1 << ", nx2=" << this->nx2 << ", nx3=" << this->nx3 << ", nx4=" << this->nx4 << ")"; + return text.str(); + } + /*=======================================================================*/ + void resize(const size_type &uniformDimensionSize) + { + this->resize(uniformDimensionSize, uniformDimensionSize, uniformDimensionSize); + } + /*=======================================================================*/ + void resize(const size_type &nx1, const size_type &nx2, const size_type &nx3, const size_type &nx4) + { + this->nx1 = nx1; + this->nx2 = nx2; + this->nx3 = nx3; + this->nx4 = nx4; + this->data.resize(nx1 * nx2 * nx3 * nx4); + } + /*=======================================================================*/ + void resize(const size_type &nx1, const size_type &nx2, const size_type &nx3, const size_type &nx4, + const value_type &val) + { + this->nx1 = nx1; + this->nx2 = nx2; + this->nx3 = nx3; + this->nx4 = nx4; + this->data.resize(nx1 * nx2 * nx3 * nx4, val); + } + /*=======================================================================*/ + std::vector<value_type> &getDataVector() { return this->data; } + /*=======================================================================*/ + const std::vector<value_type> &getDataVector() const { return this->data; } + /*=======================================================================*/ + inline std::size_t getDataVectorIndex(const size_type &x1, const size_type &x2, const size_type &x3, + const size_type &x4) const + { +#if !defined(NO_CB_RANGECHECK) && (defined(_DEBUG) || defined(CB_RANGECHECK)) + if (!this->indicesInRange(x1, x2, x3, x4)) + UB_THROW(UbException(UB_EXARGS, getExceptionErrorString(x1, x2, x3, x4))); +#endif + + return indexer.getIndex(x1, x2, x3, x4, nx1, nx2, nx3, nx4); + } protected: - /*=======================================================================*/ - //success -> true - //else -> false - inline bool indicesInRange(const size_type& x1, const size_type& x2, const size_type& x3, const size_type& x4) const - { - if( x1 < 0 || x1 >= this->nx1 - || x2 < 0 || x2 >= this->nx2 - || x3 < 0 || x3 >= this->nx3 - || x4 < 0 || x4 >= this->nx4 ) - { - return false; - } - return true; - } - /*=======================================================================*/ - std::string getExceptionErrorString(const size_type& x1, const size_type& x2, const size_type& x3, const size_type& x4) const - { - std::stringstream out("index out of range - "); - out<<"("<<x1<<","<<x2<<","<<x3<<","<<x4<<") not in ("<<nx1<<","<<nx2<<","<<nx3<<","<<nx4<<")"; - return out.str(); - } - /*=======================================================================*/ + /*=======================================================================*/ + // success -> true + // else -> false + inline bool indicesInRange(const size_type &x1, const size_type &x2, const size_type &x3, const size_type &x4) const + { + if (x1 < 0 || x1 >= this->nx1 || x2 < 0 || x2 >= this->nx2 || x3 < 0 || x3 >= this->nx3 || x4 < 0 || + x4 >= this->nx4) { + return false; + } + return true; + } + /*=======================================================================*/ + std::string getExceptionErrorString(const size_type &x1, const size_type &x2, const size_type &x3, + const size_type &x4) const + { + std::stringstream out("index out of range - "); + out << "(" << x1 << "," << x2 << "," << x3 << "," << x4 << ") not in (" << nx1 << "," << nx2 << "," << nx3 + << "," << nx4 << ")"; + return out.str(); + } + /*=======================================================================*/ protected: - size_type nx1; - size_type nx2; - size_type nx3; - size_type nx4; - indexer_type indexer; - std::vector< value_type > data; - + size_type nx1; + size_type nx2; + size_type nx3; + size_type nx4; + indexer_type indexer; + std::vector<value_type> data; }; -#endif //CBARRAY4D_H +#endif // CBARRAY4D_H diff --git a/src/basics/basics/container/CbVector.h b/src/basics/basics/container/CbVector.h index 49ccfcfacbd25d47bcfafa1c52f10cfe6a0c139c..3cf88151ee15efb7eee52a5d1092b9956b8003fe 100644 --- a/src/basics/basics/container/CbVector.h +++ b/src/basics/basics/container/CbVector.h @@ -1,28 +1,28 @@ //======================================================================================= -// ____ ____ __ ______ __________ __ __ __ __ -// \ \ | | | | | _ \ |___ ___| | | | | / \ | | -// \ \ | | | | | |_) | | | | | | | / \ | | -// \ \ | | | | | _ / | | | | | | / /\ \ | | -// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ -// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| -// \ \ | | ________________________________________________________________ -// \ \ | | | ______________________________________________________________| -// \ \| | | | __ __ __ __ ______ _______ -// \ | | |_____ | | | | | | | | | _ \ / _____) -// \ | | _____| | | | | | | | | | | \ \ \_______ +// ____ ____ __ ______ __________ __ __ __ __ +// \ \ | | | | | _ \ |___ ___| | | | | / \ | | +// \ \ | | | | | |_) | | | | | | | / \ | | +// \ \ | | | | | _ / | | | | | | / /\ \ | | +// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ +// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| +// \ \ | | ________________________________________________________________ +// \ \ | | | ______________________________________________________________| +// \ \| | | | __ __ __ __ ______ _______ +// \ | | |_____ | | | | | | | | | _ \ / _____) +// \ | | _____| | | | | | | | | | | \ \ \_______ // \ | | | | |_____ | \_/ | | | | |_/ / _____ | -// \ _____| |__| |________| \_______/ |__| |______/ (_______/ +// \ _____| |__| |________| \_______/ |__| |______/ (_______/ // -// This file is part of VirtualFluids. VirtualFluids is free software: you can +// This file is part of VirtualFluids. VirtualFluids is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of +// License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. -// -// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// +// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License along // with VirtualFluids (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>. // @@ -33,22 +33,24 @@ #ifndef CBVECTOR_H #define CBVECTOR_H +#include <PointerDefinitions.h> //for memcopy +#include <algorithm> //for std::swap +#include <typeinfo> //for typeid #include <vector> -#include <algorithm> //for std::swap -#include <typeinfo> //for typeid -#include <PointerDefinitions.h> //for memcopy -#include <basics/utilities/UbSystem.h> #include <basics/utilities/UbEqual.h> +#include <basics/utilities/UbSystem.h> -template< typename T > class CbVectorAllocator; -template< typename T > class CbVectorAllocatorStd; +template <typename T> +class CbVectorAllocator; +template <typename T> +class CbVectorAllocatorStd; //========================================================================= //! \brief A class implements a container like a vector //! \details //! For this class it was required to ave only the type as template argument. -//! Hence, the allocator must be an abstract class. With out this requirement, +//! Hence, the allocator must be an abstract class. With out this requirement, //! an allocator as second template argument would have been possible, as in the //! STL vector. This would lead to the compiler generating two different classes //! for the same data type with different allocators during compile time. Here it @@ -59,250 +61,250 @@ template< typename T > class CbVectorAllocatorStd; //! -release: not defined "NO_CB_RANGECHECK" && defined "CB_RANGECHECK" //========================================================================= ////////////////////////////////////////////////////////////////////////// -template< typename T > +template <typename T> class CbVector { public: - using value_type = T; - using pointer = value_type *; - using size_type = std::size_t; + using value_type = T; + using pointer = value_type *; + using size_type = std::size_t; - friend class CbVectorAllocator<value_type>; //um auf ptrData und dataSize zugreifen zu koennen! + friend class CbVectorAllocator<value_type>; // um auf ptrData und dataSize zugreifen zu koennen! + + CbVector<value_type>(const CbVector<value_type> &src) = delete; - CbVector<value_type>(const CbVector<value_type>& src) = delete; public: - /*==========================================================*/ - CbVector( CbVectorAllocator<value_type>* const& allocator = new CbVectorAllocatorStd<value_type> ) - : ptrData(NULL) - , - allocator(allocator) - { - this->allocator->alloc(*this,0,value_type()); - } - /*==========================================================*/ - CbVector( const size_type size, CbVectorAllocator<value_type>* const& allocator = new CbVectorAllocatorStd<value_type>, const value_type& value=value_type() ) - : ptrData(NULL) - , - allocator(allocator) - { - this->allocator->alloc(*this,size,value); - } - /*==========================================================*/ - virtual ~CbVector() - { - if(allocator) - { - this->allocator->dealloc(*this); - delete allocator; - allocator=NULL; - } - } - /*=======================================================================*/ - CbVector& operator= (const CbVector& src) - { - if(this == &src) - return *this; + /*==========================================================*/ + CbVector(CbVectorAllocator<value_type> *const &allocator = new CbVectorAllocatorStd<value_type>) + : ptrData(NULL), allocator(allocator) + { + this->allocator->alloc(*this, 0, value_type()); + } + /*==========================================================*/ + CbVector(const size_type size, + CbVectorAllocator<value_type> *const &allocator = new CbVectorAllocatorStd<value_type>, + const value_type &value = value_type()) + : ptrData(NULL), allocator(allocator) + { + this->allocator->alloc(*this, size, value); + } + /*==========================================================*/ + virtual ~CbVector() + { + if (allocator) { + this->allocator->dealloc(*this); + delete allocator; + allocator = NULL; + } + } + /*=======================================================================*/ + CbVector &operator=(const CbVector &src) + { + if (this == &src) + return *this; - //gespeicherte Datenelemente loeschen - //Laenge anpassen - this->allocator->resize(*this, src.size()); + // gespeicherte Datenelemente loeschen + // Laenge anpassen + this->allocator->resize(*this, src.size()); - //gespeicherte Datenelemente kopieren - if( !src.empty() ) - { - memcpy( (char*)ptrData, (char*)&src[0], src.size()*sizeof(value_type) ); - //for(size_type i=0; i<src.size(); i++) - // (*this)[i] = src[i]; - } + // gespeicherte Datenelemente kopieren + if (!src.empty()) { + memcpy((char *)ptrData, (char *)&src[0], src.size() * sizeof(value_type)); + // for(size_type i=0; i<src.size(); i++) + // (*this)[i] = src[i]; + } - return *this; - } - /*=======================================================================*/ - CbVector& operator= (const std::vector< value_type >& src) - { - //gespeicherte Datenelemente loeschen - //Laenge anpassen - this->allocator->resize(*this, src.size()); + return *this; + } + /*=======================================================================*/ + CbVector &operator=(const std::vector<value_type> &src) + { + // gespeicherte Datenelemente loeschen + // Laenge anpassen + this->allocator->resize(*this, src.size()); - //gespeicherte Datenelemente kopieren - if( !src.empty() ) - { - memcpy( (char*)ptrData, (char*)&src[0], src.size()*sizeof(value_type) ); - //for(size_type i=0; i<src.size(); i++) - // (*this)[i] = src[i]; - } - - return *this; - } - /*=======================================================================*/ - bool operator== (const CbVector& rhs) const - { - if( this == &rhs ) return true; - if( this->dataSize != rhs.dataSize ) return false; + // gespeicherte Datenelemente kopieren + if (!src.empty()) { + memcpy((char *)ptrData, (char *)&src[0], src.size() * sizeof(value_type)); + // for(size_type i=0; i<src.size(); i++) + // (*this)[i] = src[i]; + } - for(size_type i=0; i<rhs.size(); i++) - if( !isUbEqual( this->operator[](i), rhs.operator[](i) ) ) + return *this; + } + /*=======================================================================*/ + bool operator==(const CbVector &rhs) const + { + if (this == &rhs) + return true; + if (this->dataSize != rhs.dataSize) return false; - return true; - } - /*==========================================================*/ - void setAllocator( CbVectorAllocator<value_type>* const& allocator ) - { - if(this->allocator) - { - if(this->allocator==allocator) return; - this->allocator->dealloc(*this); - delete this->allocator; - } - this->allocator = allocator; - this->allocator->alloc(*this,0); - } - /*==========================================================*/ - size_type size() const { return dataSize; } - /*==========================================================*/ - bool empty() const { return dataSize==0; } - /*==========================================================*/ - bool resize(const size_type& dataSize) - { - return allocator->resize(*this, dataSize); - } - /*==========================================================*/ - bool resize(const size_type& dataSize, const value_type& value) - { - return allocator->resize(*this, dataSize, value); - } - /*==========================================================*/ - void swap(CbVector& rhs) - { - if( this == &rhs ) return; + for (size_type i = 0; i < rhs.size(); i++) + if (!isUbEqual(this->operator[](i), rhs.operator[](i))) + return false; + + return true; + } + /*==========================================================*/ + void setAllocator(CbVectorAllocator<value_type> *const &allocator) + { + if (this->allocator) { + if (this->allocator == allocator) + return; + this->allocator->dealloc(*this); + delete this->allocator; + } + this->allocator = allocator; + this->allocator->alloc(*this, 0); + } + /*==========================================================*/ + size_type size() const { return dataSize; } + /*==========================================================*/ + bool empty() const { return dataSize == 0; } + /*==========================================================*/ + bool resize(const size_type &dataSize) { return allocator->resize(*this, dataSize); } + /*==========================================================*/ + bool resize(const size_type &dataSize, const value_type &value) + { + return allocator->resize(*this, dataSize, value); + } + /*==========================================================*/ + void swap(CbVector &rhs) + { + if (this == &rhs) + return; - std::swap( this->ptrData , rhs.ptrData ); - std::swap( this->dataSize , rhs.dataSize ); - std::swap( this->allocator, rhs.allocator ); - } - /*==========================================================*/ - value_type& operator[](const size_type& i) - { - #if !defined(NO_CB_RANGECHECK) && ( defined(_DEBUG) || defined(CB_RANGECHECK) ) - if(i>=dataSize) - UB_THROW( UbException(UB_EXARGS,"T="+(std::string)typeid(*this).name()+UbSystem::toString(i)+" out of range (size="+UbSystem::toString(dataSize)+")") ); - #endif // _DEBUG + std::swap(this->ptrData, rhs.ptrData); + std::swap(this->dataSize, rhs.dataSize); + std::swap(this->allocator, rhs.allocator); + } + /*==========================================================*/ + value_type &operator[](const size_type &i) + { +#if !defined(NO_CB_RANGECHECK) && (defined(_DEBUG) || defined(CB_RANGECHECK)) + if (i >= dataSize) + UB_THROW(UbException(UB_EXARGS, "T=" + (std::string) typeid(*this).name() + UbSystem::toString(i) + + " out of range (size=" + UbSystem::toString(dataSize) + ")")); +#endif // _DEBUG - return ptrData[i]; - } - /*==========================================================*/ - const value_type& operator[](const size_type& i) const - { - #if !defined(NO_CB_RANGECHECK) && ( defined(_DEBUG) || defined(CB_RANGECHECK) ) - if(i>=dataSize) - UB_THROW( UbException(UB_EXARGS,"T="+(std::string)typeid(*this).name()+UbSystem::toString(i)+" out of range (size="+UbSystem::toString(dataSize)+")") ); - #endif // _DEBUG + return ptrData[i]; + } + /*==========================================================*/ + const value_type &operator[](const size_type &i) const + { +#if !defined(NO_CB_RANGECHECK) && (defined(_DEBUG) || defined(CB_RANGECHECK)) + if (i >= dataSize) + UB_THROW(UbException(UB_EXARGS, "T=" + (std::string) typeid(*this).name() + UbSystem::toString(i) + + " out of range (size=" + UbSystem::toString(dataSize) + ")")); +#endif // _DEBUG - return ptrData[i]; - } - /*==========================================================*/ - CbVectorAllocator<value_type>* getAllocator() const { return allocator; } - /*==========================================================*/ + return ptrData[i]; + } + /*==========================================================*/ + CbVectorAllocator<value_type> *getAllocator() const { return allocator; } + /*==========================================================*/ private: - value_type* ptrData; - size_type dataSize{0}; - CbVectorAllocator<value_type>* allocator; - //CbVector<value_type>& operator=(const CbVector<value_type>& src); + value_type *ptrData; + size_type dataSize{ 0 }; + CbVectorAllocator<value_type> *allocator; + // CbVector<value_type>& operator=(const CbVector<value_type>& src); }; ////////////////////////////////////////////////////////////////////////// // CbVectorAllocator-Interface ////////////////////////////////////////////////////////////////////////// -template< typename T > +template <typename T> class CbVectorAllocator { public: - using value_type = typename CbVector<T>::value_type; - using size_type = typename CbVector<value_type>::size_type; + using value_type = typename CbVector<T>::value_type; + using size_type = typename CbVector<value_type>::size_type; public: - CbVectorAllocator() = default; - virtual ~CbVectorAllocator() = default; + CbVectorAllocator() = default; + virtual ~CbVectorAllocator() = default; - virtual bool alloc(CbVector< value_type >& vec, const size_type& dataSize, const value_type& value=value_type()) = 0; - virtual bool resize(CbVector< value_type >& vec, const size_type& dataSize, const value_type& value=value_type()) = 0; - virtual bool dealloc(CbVector< value_type >& vec) = 0; + virtual bool alloc(CbVector<value_type> &vec, const size_type &dataSize, + const value_type &value = value_type()) = 0; + virtual bool resize(CbVector<value_type> &vec, const size_type &dataSize, + const value_type &value = value_type()) = 0; + virtual bool dealloc(CbVector<value_type> &vec) = 0; protected: - //folgende Methoden ersparen eine friend Deklaierung aller moeglichen Allocatoren - //denn durch diese beiden Methoden haben sie exklusive Zugriffsrechte! - //**********************************************************************************// - inline value_type*& ptrDataOf( CbVector< value_type >& vec ) - { - if( vec.getAllocator()!=this ) UB_THROW( UbException(UB_EXARGS,"allocator is not member of vec!") ); - return vec.ptrData; - } - //**********************************************************************************// - inline size_type& dataSizeOf( CbVector< value_type >& vec ) - { - if( vec.getAllocator()!=this ) UB_THROW( UbException(UB_EXARGS,"allocator is not member of vec!") ); - return vec.dataSize; - } + // folgende Methoden ersparen eine friend Deklaierung aller moeglichen Allocatoren + // denn durch diese beiden Methoden haben sie exklusive Zugriffsrechte! + //**********************************************************************************// + inline value_type *&ptrDataOf(CbVector<value_type> &vec) + { + if (vec.getAllocator() != this) + UB_THROW(UbException(UB_EXARGS, "allocator is not member of vec!")); + return vec.ptrData; + } + //**********************************************************************************// + inline size_type &dataSizeOf(CbVector<value_type> &vec) + { + if (vec.getAllocator() != this) + UB_THROW(UbException(UB_EXARGS, "allocator is not member of vec!")); + return vec.dataSize; + } }; ////////////////////////////////////////////////////////////////////////// // CbVectorAllocatorStd ////////////////////////////////////////////////////////////////////////// -template< typename T > +template <typename T> class CbVectorAllocatorStd : public CbVectorAllocator<T> { public: - //typedefs wiederholen, da Basisklasse = template -> "Dependent-Base"-Problem - using value_type = typename CbVector<T>::value_type; - using size_type = typename CbVector<value_type>::size_type; + // typedefs wiederholen, da Basisklasse = template -> "Dependent-Base"-Problem + using value_type = typename CbVector<T>::value_type; + using size_type = typename CbVector<value_type>::size_type; public: - CbVectorAllocatorStd() : CbVectorAllocator<value_type>() - { - - } - /*==========================================================*/ - bool alloc(CbVector< value_type >& src, const size_type& dataSize, const value_type& value=value_type()) override - { - return this->resize(src,dataSize,value); - } - /*==========================================================*/ - bool resize(CbVector< value_type >& vec, const size_type& dataSize, const value_type& value=value_type()) override - { - if( CbVectorAllocatorStd< value_type >::dataSizeOf(vec) == dataSize) return false; + CbVectorAllocatorStd() : CbVectorAllocator<value_type>() {} + /*==========================================================*/ + bool alloc(CbVector<value_type> &src, const size_type &dataSize, const value_type &value = value_type()) override + { + return this->resize(src, dataSize, value); + } + /*==========================================================*/ + bool resize(CbVector<value_type> &vec, const size_type &dataSize, const value_type &value = value_type()) override + { + if (CbVectorAllocatorStd<value_type>::dataSizeOf(vec) == dataSize) + return false; - //new array - value_type* new_data = new value_type[dataSize]; - //copy existing data to array - if( this->ptrDataOf(vec) ) - { - for(size_type i=0; (i<vec.size() && i<dataSize); ++i) new_data[i] = CbVectorAllocatorStd< value_type >::ptrDataOf(vec)[i]; - delete[] this->ptrDataOf(vec); - } - this->ptrDataOf(vec) = new_data; - //new value for new items - for(size_type i=this->dataSizeOf(vec); i<dataSize; ++i) this->ptrDataOf(vec)[i] = value; - //assign new dataSize - this->dataSizeOf(vec) = dataSize; + // new array + value_type *new_data = new value_type[dataSize]; + // copy existing data to array + if (this->ptrDataOf(vec)) { + for (size_type i = 0; (i < vec.size() && i < dataSize); ++i) + new_data[i] = CbVectorAllocatorStd<value_type>::ptrDataOf(vec)[i]; + delete[] this->ptrDataOf(vec); + } + this->ptrDataOf(vec) = new_data; + // new value for new items + for (size_type i = this->dataSizeOf(vec); i < dataSize; ++i) + this->ptrDataOf(vec)[i] = value; + // assign new dataSize + this->dataSizeOf(vec) = dataSize; - return true; - } - /*==========================================================*/ - bool dealloc(CbVector< value_type >& vec) override - { - if( this->ptrDataOf(vec) ) - { - delete[] this->ptrDataOf(vec); - this->ptrDataOf(vec) = NULL; - } - this->dataSizeOf(vec) = 0; - return true; - } - /*==========================================================*/ + return true; + } + /*==========================================================*/ + bool dealloc(CbVector<value_type> &vec) override + { + if (this->ptrDataOf(vec)) { + delete[] this->ptrDataOf(vec); + this->ptrDataOf(vec) = NULL; + } + this->dataSizeOf(vec) = 0; + return true; + } + /*==========================================================*/ private: }; -#endif //CBVECTOR_H +#endif // CBVECTOR_H diff --git a/src/basics/basics/container/CbVectorPool.h b/src/basics/basics/container/CbVectorPool.h index a025016672bd7999de7fc4060804b52620da4ced..85ce16ab652bd65dd5856913cd866bce7eccf400 100644 --- a/src/basics/basics/container/CbVectorPool.h +++ b/src/basics/basics/container/CbVectorPool.h @@ -8,16 +8,16 @@ #define CBVECTORPOOL_H #include <iostream> -#include <sstream> -#include <vector> -#include <map> #include <limits> +#include <map> +#include <sstream> #include <typeinfo> +#include <vector> +#include <basics/container/CbVector.h> #include <basics/utilities/UbException.h> -#include <basics/utilities/UbTuple.h> #include <basics/utilities/UbLogger.h> -#include <basics/container/CbVector.h> +#include <basics/utilities/UbTuple.h> //#include "MPICommunicator.h" // @@ -58,409 +58,417 @@ hier ganz normal der Datenspeicher wieder freigegen und der Poolvektor verk�rz ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// - -template<typename T> class CbVectorAllocatorPool; +template <typename T> +class CbVectorAllocatorPool; /*==================================================================*/ -template<typename T> +template <typename T> class CbVectorPool { public: - using value_type = typename CbVector<T>::value_type; - using size_type = typename CbVector<T>::size_type; - using Pool = std::vector<value_type>; + using value_type = typename CbVector<T>::value_type; + using size_type = typename CbVector<T>::size_type; + using Pool = std::vector<value_type>; - using CbVectorKey = std::string; - using CbVectorMap = std::map<CbVectorKey, CbVector<value_type> *>; - using CbVectorMapIter = typename CbVectorMap::iterator; + using CbVectorKey = std::string; + using CbVectorMap = std::map<CbVectorKey, CbVector<value_type> *>; + using CbVectorMapIter = typename CbVectorMap::iterator; public: - ////////////////////////////////////////////////////////////////////////// - CbVectorPool( const size_type& startPoolSize = 20000) //startPoolSize*sizeof(T)/1024/1024 [MB] - : poolStartAdress(NULL) - , nextCbVectorStartIndexInPool(0) - , nextCbVectorKey() - { - pool.reserve(startPoolSize); - } - /*==================================================================*/ - virtual ~CbVectorPool() - { - //hier werden lediglich ihre datenvektoren "resetet" - for(CbVectorMapIter it=cbVectorMap.begin(); it!=cbVectorMap.end(); ++it) - { - CbVector< value_type >& vec = *it->second; - CbVectorAllocatorPool< value_type >& allocator = dynamic_cast< CbVectorAllocatorPool< value_type >& >(*vec.getAllocator() ); - //FIXME: //if(allocator.ptrVectorPool != this) UB_THROW( UbException(UB_EXARGS,"CbVectorAllocator is part of different Pool") ); - - //allocator daten reseten - allocator.ptrVectorPool = NULL; - allocator.key = CbVectorKey(); - allocator.startIndexInPool = 0; - - //Datenzeiger/-groessen reseten - allocator.ptrDataOf(vec) = NULL; - allocator.dataSizeOf(vec) = 0; - } - } - /*==========================================================*/ - CbVectorKey getNextCbVectorKey() const - { - return this->nextCbVectorKey; - } - /*==================================================================*/ - bool allocVectorData(CbVector<value_type>& vec, const size_type& dataSize, const value_type& value=value_type() ) - { - //pool-allocator holen - CbVectorAllocatorPool< value_type >& allocator = dynamic_cast< CbVectorAllocatorPool< value_type >& >(*vec.getAllocator() ); - if(allocator.ptrVectorPool != this) UB_THROW( UbException(UB_EXARGS,"CbVectorAllocator is part of different Pool") ); - - //alloc nur wenn cbVector noch kein Element von Pool! - if( cbVectorMap.find(allocator.key)==cbVectorMap.end() ) - { - return this->allocData(allocator, vec, dataSize, value ); - } - - UB_THROW( UbException(UB_EXARGS,"vector-key="+UbSystem::toString(allocator.key)+" bereits vergeben!") ); - } - /*==================================================================*/ - bool resizeVectorData(CbVector<value_type>& vec, const size_type& dataSize, const value_type& value=value_type() ) - { - CbVectorAllocatorPool< value_type >& allocator = dynamic_cast< CbVectorAllocatorPool< value_type >& >(*vec.getAllocator() ); - if(allocator.ptrVectorPool != this) UB_THROW( UbException(UB_EXARGS,"CbVectorAllocator is part of different Pool") ); - - //cbVector noch nicht in map? - CbVectorMapIter pos = cbVectorMap.find(allocator.key); - - if( pos!=cbVectorMap.end() ) //cbVector vorhanden - { - //wenn bei alloc keine Laenge zugewiesen wurde, so erfolgt das nun - if( allocator.startIndexInPool==0 && allocator.ptrDataOf(vec)==NULL ) - return this->allocData(allocator, vec, dataSize, value ) ; - else - return this->resizeData(allocator, vec, dataSize, value ); - } - - UB_THROW( UbException(UB_EXARGS,"vector gehoert laut allocator zum pool aber den key gibt s nicht... wie kann das sein?") ); - } - /*==================================================================*/ - bool deallocVectorData(CbVector<value_type>& vec) - { - CbVectorAllocatorPool< value_type >& allocator = dynamic_cast< CbVectorAllocatorPool< value_type >& >(*vec.getAllocator() ); - if(allocator.ptrVectorPool != this) UB_THROW( UbException(UB_EXARGS,"CbVectorAllocator is part of different Pool") ); - - //nur wenn vector auch teil des - if( cbVectorMap.erase(allocator.key) > 0 ) - { - if( this->resizeData(allocator,vec,0,0) ) - { + ////////////////////////////////////////////////////////////////////////// + CbVectorPool(const size_type &startPoolSize = 20000) // startPoolSize*sizeof(T)/1024/1024 [MB] + : poolStartAdress(NULL), nextCbVectorStartIndexInPool(0), nextCbVectorKey() + { + pool.reserve(startPoolSize); + } + /*==================================================================*/ + virtual ~CbVectorPool() + { + // hier werden lediglich ihre datenvektoren "resetet" + for (CbVectorMapIter it = cbVectorMap.begin(); it != cbVectorMap.end(); ++it) { + CbVector<value_type> &vec = *it->second; + CbVectorAllocatorPool<value_type> &allocator = + dynamic_cast<CbVectorAllocatorPool<value_type> &>(*vec.getAllocator()); + // FIXME: //if(allocator.ptrVectorPool != this) UB_THROW( UbException(UB_EXARGS,"CbVectorAllocator is part + // of different Pool") ); + + // allocator daten reseten allocator.ptrVectorPool = NULL; allocator.key = CbVectorKey(); allocator.startIndexInPool = 0; - //das Datenzeiger/-groessen reseten wird bereits in resize durchgefuehrt - return true; - } - else UB_THROW( UbException(UB_EXARGS,"unknown error") ); - } - - - //SPtr<Communicator> comm = MPICommunicator::getInstance(); - //int myid = comm->getProcessID(); - -// // Get the name of the processor -// char machinename[MPI_MAX_PROCESSOR_NAME]; -// int name_len; -// MPI_Get_processor_name(machinename, &name_len); -// UBLOG(logINFO, "PID = " << myid << " host name: " << machinename); -// -// int j, nptrs; -//#define SIZE 100 -// void *buffer[100]; -// char **strings; -// -// nptrs = backtrace(buffer, SIZE); -// printf("backtrace() returned %d addresses\n", nptrs); -// -// /* The call backtrace_symbols_fd(buffer, nptrs, STDOUT_FILENO) -// would produce similar output to the following: */ -// -// strings = backtrace_symbols(buffer, nptrs); -// if (strings == NULL) -// { -// perror("backtrace_symbols"); -// exit(EXIT_FAILURE); -// } -// -// for (j = 0; j < nptrs; j++) -// printf("%s\n", strings[j]); -// -// free(strings); - - UB_THROW(UbException(UB_EXARGS, "vector gehoert laut allocator zum pool aber den key gibt s nicht... wie kann das sein?")); - } - /*==================================================================*/ - friend std::ostream& operator<<(std::ostream& os, const CbVectorPool& cbPool) - { - os<<"map"<<std::endl; - for(CbVectorMapIter pos=cbPool.cbVectorMap.begin(); pos!=cbPool.cbVectorMap.end(); ++pos) - { - CbVectorAllocatorPool< value_type >& tmpAllocator = dynamic_cast< CbVectorAllocatorPool<value_type>& >(*pos->second->getAllocator()); - os<<"vector-size="<<pos->second->size()<<"vector-Adress="<<tmpAllocator->ptrDataOf(*pos->second)<<", allocator(key="<<tmpAllocator.key<<", startIndex="<<tmpAllocator.startIndexInPool<<")"<<std::endl; - for(size_type i=0; i<pos->second->size(); i++) os<<(*pos->second)[i]<<","; - os<<std::endl; - } - os<<"pool"<<std::endl; - for(size_type i=0; i<cbPool.pool.size(); i++) { - os<<cbPool.pool[i]<<","; - os<<std::endl; - } - - return os; - } - /*==================================================================*/ - typename CbVectorMap::size_type getNofStoredVectors() const - { - return this->cbVectorMap.size(); - } - /*==================================================================*/ - typename Pool::size_type getPoolSize() const - { - return this->pool.size(); - } - /*==================================================================*/ - // checks if all vectors have one to one pool-entries - bool consistencyCheck() - { - std::vector<int> pool2(pool.size(),0); - for(CbVectorMapIter it=cbVectorMap.begin(); it!=cbVectorMap.end(); ++it) - { - CbVector< value_type >& tmpVec = *it->second; - CbVectorAllocatorPool< value_type >& tmpAllocator = dynamic_cast< CbVectorAllocatorPool<value_type>& >(*tmpVec.getAllocator()); - for(size_type i=tmpAllocator.startIndexInPool; i<tmpAllocator.startIndexInPool+tmpVec.size(); ++i) - { - pool2.at(i)++; - } - } - for( size_type i=0; i<pool2.size(); ++i ) - { - if(pool2.at(i) > 1 ) { UBLOG(logERROR,UB_FUNCTION<<" - test failed typo 1"); return false; } - if(pool2.at(i) < 1 ) { UBLOG(logERROR,UB_FUNCTION<<" - test failed typo 2"); return false; } - } - return true; - } + // Datenzeiger/-groessen reseten + allocator.ptrDataOf(vec) = NULL; + allocator.dataSizeOf(vec) = 0; + } + } + /*==========================================================*/ + CbVectorKey getNextCbVectorKey() const { return this->nextCbVectorKey; } + /*==================================================================*/ + bool allocVectorData(CbVector<value_type> &vec, const size_type &dataSize, const value_type &value = value_type()) + { + // pool-allocator holen + CbVectorAllocatorPool<value_type> &allocator = + dynamic_cast<CbVectorAllocatorPool<value_type> &>(*vec.getAllocator()); + if (allocator.ptrVectorPool != this) + UB_THROW(UbException(UB_EXARGS, "CbVectorAllocator is part of different Pool")); + + // alloc nur wenn cbVector noch kein Element von Pool! + if (cbVectorMap.find(allocator.key) == cbVectorMap.end()) { + return this->allocData(allocator, vec, dataSize, value); + } + + UB_THROW(UbException(UB_EXARGS, "vector-key=" + UbSystem::toString(allocator.key) + " bereits vergeben!")); + } + /*==================================================================*/ + bool resizeVectorData(CbVector<value_type> &vec, const size_type &dataSize, const value_type &value = value_type()) + { + CbVectorAllocatorPool<value_type> &allocator = + dynamic_cast<CbVectorAllocatorPool<value_type> &>(*vec.getAllocator()); + if (allocator.ptrVectorPool != this) + UB_THROW(UbException(UB_EXARGS, "CbVectorAllocator is part of different Pool")); + + // cbVector noch nicht in map? + CbVectorMapIter pos = cbVectorMap.find(allocator.key); + + if (pos != cbVectorMap.end()) // cbVector vorhanden + { + // wenn bei alloc keine Laenge zugewiesen wurde, so erfolgt das nun + if (allocator.startIndexInPool == 0 && allocator.ptrDataOf(vec) == NULL) + return this->allocData(allocator, vec, dataSize, value); + else + return this->resizeData(allocator, vec, dataSize, value); + } + + UB_THROW(UbException(UB_EXARGS, + "vector gehoert laut allocator zum pool aber den key gibt s nicht... wie kann das sein?")); + } + /*==================================================================*/ + bool deallocVectorData(CbVector<value_type> &vec) + { + CbVectorAllocatorPool<value_type> &allocator = + dynamic_cast<CbVectorAllocatorPool<value_type> &>(*vec.getAllocator()); + if (allocator.ptrVectorPool != this) + UB_THROW(UbException(UB_EXARGS, "CbVectorAllocator is part of different Pool")); + + // nur wenn vector auch teil des + if (cbVectorMap.erase(allocator.key) > 0) { + if (this->resizeData(allocator, vec, 0, 0)) { + allocator.ptrVectorPool = NULL; + allocator.key = CbVectorKey(); + allocator.startIndexInPool = 0; + + // das Datenzeiger/-groessen reseten wird bereits in resize durchgefuehrt + return true; + } else + UB_THROW(UbException(UB_EXARGS, "unknown error")); + } + + // SPtr<Communicator> comm = MPICommunicator::getInstance(); + // int myid = comm->getProcessID(); + + // // Get the name of the processor + // char machinename[MPI_MAX_PROCESSOR_NAME]; + // int name_len; + // MPI_Get_processor_name(machinename, &name_len); + // UBLOG(logINFO, "PID = " << myid << " host name: " << machinename); + // + // int j, nptrs; + //#define SIZE 100 + // void *buffer[100]; + // char **strings; + // + // nptrs = backtrace(buffer, SIZE); + // printf("backtrace() returned %d addresses\n", nptrs); + // + // /* The call backtrace_symbols_fd(buffer, nptrs, STDOUT_FILENO) + // would produce similar output to the following: */ + // + // strings = backtrace_symbols(buffer, nptrs); + // if (strings == NULL) + // { + // perror("backtrace_symbols"); + // exit(EXIT_FAILURE); + // } + // + // for (j = 0; j < nptrs; j++) + // printf("%s\n", strings[j]); + // + // free(strings); + + UB_THROW(UbException(UB_EXARGS, + "vector gehoert laut allocator zum pool aber den key gibt s nicht... wie kann das sein?")); + } + /*==================================================================*/ + friend std::ostream &operator<<(std::ostream &os, const CbVectorPool &cbPool) + { + os << "map" << std::endl; + for (CbVectorMapIter pos = cbPool.cbVectorMap.begin(); pos != cbPool.cbVectorMap.end(); ++pos) { + CbVectorAllocatorPool<value_type> &tmpAllocator = + dynamic_cast<CbVectorAllocatorPool<value_type> &>(*pos->second->getAllocator()); + os << "vector-size=" << pos->second->size() << "vector-Adress=" << tmpAllocator->ptrDataOf(*pos->second) + << ", allocator(key=" << tmpAllocator.key << ", startIndex=" << tmpAllocator.startIndexInPool << ")" + << std::endl; + for (size_type i = 0; i < pos->second->size(); i++) + os << (*pos->second)[i] << ","; + os << std::endl; + } + os << "pool" << std::endl; + for (size_type i = 0; i < cbPool.pool.size(); i++) { + os << cbPool.pool[i] << ","; + os << std::endl; + } + + return os; + } + /*==================================================================*/ + typename CbVectorMap::size_type getNofStoredVectors() const { return this->cbVectorMap.size(); } + /*==================================================================*/ + typename Pool::size_type getPoolSize() const { return this->pool.size(); } + /*==================================================================*/ + // checks if all vectors have one to one pool-entries + bool consistencyCheck() + { + std::vector<int> pool2(pool.size(), 0); + for (CbVectorMapIter it = cbVectorMap.begin(); it != cbVectorMap.end(); ++it) { + CbVector<value_type> &tmpVec = *it->second; + CbVectorAllocatorPool<value_type> &tmpAllocator = + dynamic_cast<CbVectorAllocatorPool<value_type> &>(*tmpVec.getAllocator()); + for (size_type i = tmpAllocator.startIndexInPool; i < tmpAllocator.startIndexInPool + tmpVec.size(); ++i) { + pool2.at(i)++; + } + } + for (size_type i = 0; i < pool2.size(); ++i) { + if (pool2.at(i) > 1) { + UBLOG(logERROR, UB_FUNCTION << " - test failed typo 1"); + return false; + } + if (pool2.at(i) < 1) { + UBLOG(logERROR, UB_FUNCTION << " - test failed typo 2"); + return false; + } + } + return true; + } + protected: - /*==================================================================*/ - inline bool allocData(CbVectorAllocatorPool< value_type >& allocator, CbVector< value_type >& vec, const size_type& dataSize, const value_type& value ) - { - //safety checks - if( allocator.startIndexInPool!=0 - || allocator.ptrDataOf(vec)!=NULL - || allocator.dataSizeOf(vec)!=0 ) - { - UB_THROW( UbException(UB_EXARGS,"zu allokierender vector ist nicht ganz sauber!!") ); - } - - //poolVector vergroessern - if( dataSize>0 ) - { - pool.resize( pool.size() + dataSize, value ); - - //Zeiger der vorhandenen CbVectoren neu setzen, wenn Pool im Speicher verschoben wurde - if( poolStartAdress != &pool.front() ) - { + /*==================================================================*/ + inline bool allocData(CbVectorAllocatorPool<value_type> &allocator, CbVector<value_type> &vec, + const size_type &dataSize, const value_type &value) + { + // safety checks + if (allocator.startIndexInPool != 0 || allocator.ptrDataOf(vec) != NULL || allocator.dataSizeOf(vec) != 0) { + UB_THROW(UbException(UB_EXARGS, "zu allokierender vector ist nicht ganz sauber!!")); + } + + // poolVector vergroessern + if (dataSize > 0) { + pool.resize(pool.size() + dataSize, value); + + // Zeiger der vorhandenen CbVectoren neu setzen, wenn Pool im Speicher verschoben wurde + if (poolStartAdress != &pool.front()) { + poolStartAdress = &pool.front(); + for (CbVectorMapIter it = cbVectorMap.begin(); it != cbVectorMap.end(); ++it) { + CbVector<value_type> &tmpVec = *it->second; + CbVectorAllocatorPool<value_type> &tmpAllocator = + dynamic_cast<CbVectorAllocatorPool<value_type> &>(*tmpVec.getAllocator()); + + if (!tmpAllocator.ptrDataOf(tmpVec)) + continue; // Fall: CbVector hat noch keinen Datenbereich (data zeigt auf NULL) + tmpAllocator.ptrDataOf(tmpVec) = &pool[tmpAllocator.startIndexInPool]; + } + // std::cout<<"CbVectorPoolMpi::allocVectorData vector wurde im speicher verschoben - adressen + // angepasst!!!"<<std::endl; + } + + // aktuellem element adresse zuweisen (wurde evtl schon inder schleife zuvor gemacht) + allocator.ptrDataOf(vec) = &pool.at(nextCbVectorStartIndexInPool); + allocator.startIndexInPool = nextCbVectorStartIndexInPool; + + // neuen StartIndex fuer naechstes Element berechnen + nextCbVectorStartIndexInPool += dataSize; + if (nextCbVectorStartIndexInPool != pool.size()) + UB_THROW(UbException(UB_EXARGS, "index Problem... Annahme falsch?")); + } + + // vector zu map hinzuf�gen (speicher wird dann anschliessend zugwiesen) + cbVectorMap.insert( + std::make_pair(allocator.key, &vec)); // ist angeblich performanter als cbVectorMap[ allocator.key ] = + // cbVector; //aus Effective STL von Scott Meyer + allocator.dataSizeOf(vec) = dataSize; + + // dummDoof nextKey-Generung... + if (allocator.key >= this->nextCbVectorKey) + this->nextCbVectorKey = allocator.key + "1"; + + return true; + } + /*==========================================================*/ + bool resizeData(CbVectorAllocatorPool<value_type> &allocator, CbVector<value_type> &vec, const size_type &dataSize, + const value_type &value) + { + // datenvector verlaengern/-kuerzen + typename Pool::iterator startPos = + pool.begin() + allocator.startIndexInPool; // startPosition der cbVector-Daten im Pool + if (vec.size() > dataSize) + pool.erase(startPos + dataSize, startPos + vec.size()); + else + pool.insert(startPos + vec.size(), dataSize - vec.size(), value); + + ////////////////////////////////////////////////////////////////////////// + // adressen und laengen der einzelnen vectoren anpassen + if (!pool.empty()) { + bool poolMoved = (poolStartAdress != &pool.front()); poolStartAdress = &pool.front(); - for(CbVectorMapIter it=cbVectorMap.begin(); it!=cbVectorMap.end(); ++it) - { - CbVector< value_type >& tmpVec = *it->second; - CbVectorAllocatorPool< value_type >& tmpAllocator = dynamic_cast< CbVectorAllocatorPool< value_type >& >(*tmpVec.getAllocator()); - if( !tmpAllocator.ptrDataOf(tmpVec) ) continue; //Fall: CbVector hat noch keinen Datenbereich (data zeigt auf NULL) - tmpAllocator.ptrDataOf(tmpVec) = &pool[ tmpAllocator.startIndexInPool]; + for (CbVectorMapIter it = cbVectorMap.begin(); it != cbVectorMap.end(); ++it) { + CbVector<value_type> &tmpVec = *it->second; + + if (tmpVec.size() > 0) { + CbVectorAllocatorPool<value_type> &tmpAllocator = + dynamic_cast<CbVectorAllocatorPool<value_type> &>(*tmpVec.getAllocator()); + // liegt CbVector VOR ver�ndertem CbVector? + if (tmpAllocator.startIndexInPool <= + allocator.startIndexInPool) // ja: anpassung NUR wenn pool verschoben wurde! + { + if (poolMoved && tmpVec.size() > 0) + tmpAllocator.ptrDataOf(tmpVec) = &pool[tmpAllocator.startIndexInPool]; + } else // nein: -> Adresse + Index MUSS immer angepasst werden + { + tmpAllocator.startIndexInPool += dataSize - vec.size(); + tmpAllocator.ptrDataOf(tmpVec) = &pool[tmpAllocator.startIndexInPool]; + } + } } - //std::cout<<"CbVectorPoolMpi::allocVectorData vector wurde im speicher verschoben - adressen angepasst!!!"<<std::endl; - } - - //aktuellem element adresse zuweisen (wurde evtl schon inder schleife zuvor gemacht) - allocator.ptrDataOf(vec) = &pool.at(nextCbVectorStartIndexInPool); - allocator.startIndexInPool = nextCbVectorStartIndexInPool; - - //neuen StartIndex fuer naechstes Element berechnen - nextCbVectorStartIndexInPool += dataSize; - if(nextCbVectorStartIndexInPool!=pool.size()) - UB_THROW( UbException(UB_EXARGS,"index Problem... Annahme falsch?") ); - } - - //vector zu map hinzuf�gen (speicher wird dann anschliessend zugwiesen) - cbVectorMap.insert( std::make_pair( allocator.key, &vec ) ); // ist angeblich performanter als cbVectorMap[ allocator.key ] = cbVector; //aus Effective STL von Scott Meyer - allocator.dataSizeOf(vec) = dataSize; - - //dummDoof nextKey-Generung... - if( allocator.key >= this->nextCbVectorKey ) this->nextCbVectorKey = allocator.key + "1"; - - return true; - } - /*==========================================================*/ - bool resizeData(CbVectorAllocatorPool< value_type >& allocator, CbVector<value_type>& vec, const size_type& dataSize, const value_type& value ) - { - //datenvector verlaengern/-kuerzen - typename Pool::iterator startPos = pool.begin()+allocator.startIndexInPool; //startPosition der cbVector-Daten im Pool - if( vec.size() > dataSize ) pool.erase( startPos+dataSize, startPos+vec.size()); - else pool.insert( startPos+vec.size(), dataSize-vec.size(), value ); - - ////////////////////////////////////////////////////////////////////////// - //adressen und laengen der einzelnen vectoren anpassen - if( !pool.empty() ) - { - bool poolMoved = ( poolStartAdress != &pool.front() ); - poolStartAdress = &pool.front(); - - for(CbVectorMapIter it=cbVectorMap.begin(); it!=cbVectorMap.end(); ++it) - { - CbVector< value_type >& tmpVec = *it->second; - - if( tmpVec.size()>0 ) - { - CbVectorAllocatorPool< value_type >& tmpAllocator = dynamic_cast< CbVectorAllocatorPool<value_type>& >(*tmpVec.getAllocator()); - //liegt CbVector VOR ver�ndertem CbVector? - if( tmpAllocator.startIndexInPool <= allocator.startIndexInPool ) //ja: anpassung NUR wenn pool verschoben wurde! - { - if(poolMoved && tmpVec.size()>0 ) tmpAllocator.ptrDataOf(tmpVec) = &pool[ tmpAllocator.startIndexInPool]; - } - else //nein: -> Adresse + Index MUSS immer angepasst werden - { - tmpAllocator.startIndexInPool += dataSize-vec.size(); - tmpAllocator.ptrDataOf(tmpVec) = &pool[ tmpAllocator.startIndexInPool ]; - } + } else // Sonderfall: alle Elemente haben Laenge 0 -> kein pool -> alle Feld-Adressen auf NULL setzen! + { + poolStartAdress = NULL; + for (CbVectorMapIter it = cbVectorMap.begin(); it != cbVectorMap.end(); ++it) { + CbVector<value_type> &tmpVec = *it->second; + CbVectorAllocatorPool<value_type> &tmpAllocator = + dynamic_cast<CbVectorAllocatorPool<value_type> &>(*tmpVec.getAllocator()); + tmpAllocator.startIndexInPool = 0; } - } - } - else //Sonderfall: alle Elemente haben Laenge 0 -> kein pool -> alle Feld-Adressen auf NULL setzen! - { - poolStartAdress = NULL; - for(CbVectorMapIter it=cbVectorMap.begin(); it!=cbVectorMap.end(); ++it) - { - CbVector< value_type >& tmpVec = *it->second; - CbVectorAllocatorPool< value_type >& tmpAllocator = dynamic_cast< CbVectorAllocatorPool<value_type>& >(*tmpVec.getAllocator()); - tmpAllocator.startIndexInPool = 0; - } - - } - - //restliche Daten von cbVector + allocator aktualisieren - allocator.dataSizeOf(vec) = dataSize; - if(dataSize==0) - { - allocator.ptrDataOf(vec) = NULL; - allocator.startIndexInPool = 0; - } - - nextCbVectorStartIndexInPool = pool.size(); - - return true; - } + } + + // restliche Daten von cbVector + allocator aktualisieren + allocator.dataSizeOf(vec) = dataSize; + if (dataSize == 0) { + allocator.ptrDataOf(vec) = NULL; + allocator.startIndexInPool = 0; + } + + nextCbVectorStartIndexInPool = pool.size(); + + return true; + } protected: - /*==================================================================*/ - void getCbVectorData(const CbVector< value_type >& vec, CbVectorKey& vectorKey, size_type& startIndexInPool, size_type& dataSize ) - { - CbVectorAllocatorPool< value_type >& allocator = dynamic_cast< CbVectorAllocatorPool< value_type >& >(*vec.getAllocator() ); - - startIndexInPool = allocator.startIndexInPool; - vectorKey = allocator.key; - dataSize = vec.size(); - } - /*==================================================================*/ - void setCbVectorData(CbVector< value_type >& vec, const CbVectorKey& vectorKey, const size_type& startIndexInPool, const size_type& dataSize ) - { - CbVectorAllocatorPool< value_type >& allocator = dynamic_cast< CbVectorAllocatorPool< value_type >& >(*vec.getAllocator() ); - - allocator.startIndexInPool = startIndexInPool; - allocator.key = vectorKey; - allocator.dataSizeOf(vec) = dataSize; - allocator.ptrDataOf(vec) = &this->pool[ startIndexInPool ]; - } - /*==================================================================*/ - - CbVectorMap cbVectorMap; //informationsmap fuer MPIData und zugewiesener vector - - Pool pool; //globaler Datenvector - typename Pool::pointer poolStartAdress; //StartAdresse des aktuellen Datenvektors - typename Pool::size_type nextCbVectorStartIndexInPool; //StartIndex fuer den naechsten CbVector - - //key - erstmal dummdoof - CbVectorKey nextCbVectorKey; + /*==================================================================*/ + void getCbVectorData(const CbVector<value_type> &vec, CbVectorKey &vectorKey, size_type &startIndexInPool, + size_type &dataSize) + { + CbVectorAllocatorPool<value_type> &allocator = + dynamic_cast<CbVectorAllocatorPool<value_type> &>(*vec.getAllocator()); + + startIndexInPool = allocator.startIndexInPool; + vectorKey = allocator.key; + dataSize = vec.size(); + } + /*==================================================================*/ + void setCbVectorData(CbVector<value_type> &vec, const CbVectorKey &vectorKey, const size_type &startIndexInPool, + const size_type &dataSize) + { + CbVectorAllocatorPool<value_type> &allocator = + dynamic_cast<CbVectorAllocatorPool<value_type> &>(*vec.getAllocator()); + + allocator.startIndexInPool = startIndexInPool; + allocator.key = vectorKey; + allocator.dataSizeOf(vec) = dataSize; + allocator.ptrDataOf(vec) = &this->pool[startIndexInPool]; + } + /*==================================================================*/ + + CbVectorMap cbVectorMap; // informationsmap fuer MPIData und zugewiesener vector + + Pool pool; // globaler Datenvector + typename Pool::pointer poolStartAdress; // StartAdresse des aktuellen Datenvektors + typename Pool::size_type nextCbVectorStartIndexInPool; // StartIndex fuer den naechsten CbVector + + // key - erstmal dummdoof + CbVectorKey nextCbVectorKey; }; - ////////////////////////////////////////////////////////////////////////// // CbVectorAllocatorPool ////////////////////////////////////////////////////////////////////////// -template< typename T > +template <typename T> class CbVectorAllocatorPool : public CbVectorAllocator<T> { public: - //typedefs wiederholen, da Basisklasse = template -> "Dependent-Base"-Problem - using value_type = typename CbVector<T>::value_type; - using size_type = typename CbVector<value_type>::size_type; + // typedefs wiederholen, da Basisklasse = template -> "Dependent-Base"-Problem + using value_type = typename CbVector<T>::value_type; + using size_type = typename CbVector<value_type>::size_type; + + friend class CbVectorPool<value_type>; - friend class CbVectorPool< value_type >; + CbVectorAllocatorPool(const CbVectorAllocatorPool &) = delete; + const CbVectorAllocatorPool &operator=(const CbVectorAllocatorPool &) = delete; - CbVectorAllocatorPool( const CbVectorAllocatorPool& ) = delete; - const CbVectorAllocatorPool& operator=( const CbVectorAllocatorPool& ) = delete; public: - /*==========================================================*/ - CbVectorAllocatorPool(const typename CbVectorPool< value_type >::CbVectorKey& key, CbVectorPool<value_type>* const& ptrVectorPool) - : CbVectorAllocator<value_type>() - , key(key) - , startIndexInPool(0) - , ptrVectorPool(ptrVectorPool) - { - if(!ptrVectorPool) UB_THROW( UbException(UB_EXARGS,"ptrVectorPool==NULL") ); - } - /*==========================================================*/ - //hier wird der key automatisch erzeugt! - CbVectorAllocatorPool(CbVectorPool<value_type>* const& ptrVectorPool) - : CbVectorAllocator<value_type>() - , startIndexInPool(0) - , ptrVectorPool(ptrVectorPool) - { - if(!ptrVectorPool) UB_THROW( UbException(UB_EXARGS,"ptrVectorPool==NULL") ); - key = ptrVectorPool->getNextCbVectorKey(); - } - /*==========================================================*/ - bool alloc(CbVector< value_type >& vec, const size_type& dataSize, const value_type& value=value_type()) override - { - if(!ptrVectorPool) UB_THROW( UbException(UB_EXARGS,"vectorPool seems to be destroyed, ptrVectorPool==NULL") ); - return ptrVectorPool->allocVectorData(vec, dataSize, value); - } - /*==========================================================*/ - bool resize(CbVector< value_type >& vec, const size_type& dataSize, const value_type& value=value_type()) override - { - if(!ptrVectorPool) UB_THROW( UbException(UB_EXARGS,"vectorPool seems to be destroyed, ptrVectorPool==NULL") ); - return ptrVectorPool->resizeVectorData(vec, dataSize, value); - } - /*==========================================================*/ - bool dealloc(CbVector< value_type >& vec) override - { - if(ptrVectorPool) return this->ptrVectorPool->deallocVectorData(vec); - //wenn kein ptrVectorPool -> wurde bereits deallokiert - return true; - } - /*==========================================================*/ - const CbVectorPool< value_type >& getCbVectorPool() - { - if(!ptrVectorPool) UB_THROW( UbException(UB_EXARGS,"vectorPool seems to be destroyed, ptrVectorPool==NULL") ); - return *ptrVectorPool; - } - /*==========================================================*/ + /*==========================================================*/ + CbVectorAllocatorPool(const typename CbVectorPool<value_type>::CbVectorKey &key, + CbVectorPool<value_type> *const &ptrVectorPool) + : CbVectorAllocator<value_type>(), key(key), startIndexInPool(0), ptrVectorPool(ptrVectorPool) + { + if (!ptrVectorPool) + UB_THROW(UbException(UB_EXARGS, "ptrVectorPool==NULL")); + } + /*==========================================================*/ + // hier wird der key automatisch erzeugt! + CbVectorAllocatorPool(CbVectorPool<value_type> *const &ptrVectorPool) + : CbVectorAllocator<value_type>(), startIndexInPool(0), ptrVectorPool(ptrVectorPool) + { + if (!ptrVectorPool) + UB_THROW(UbException(UB_EXARGS, "ptrVectorPool==NULL")); + key = ptrVectorPool->getNextCbVectorKey(); + } + /*==========================================================*/ + bool alloc(CbVector<value_type> &vec, const size_type &dataSize, const value_type &value = value_type()) override + { + if (!ptrVectorPool) + UB_THROW(UbException(UB_EXARGS, "vectorPool seems to be destroyed, ptrVectorPool==NULL")); + return ptrVectorPool->allocVectorData(vec, dataSize, value); + } + /*==========================================================*/ + bool resize(CbVector<value_type> &vec, const size_type &dataSize, const value_type &value = value_type()) override + { + if (!ptrVectorPool) + UB_THROW(UbException(UB_EXARGS, "vectorPool seems to be destroyed, ptrVectorPool==NULL")); + return ptrVectorPool->resizeVectorData(vec, dataSize, value); + } + /*==========================================================*/ + bool dealloc(CbVector<value_type> &vec) override + { + if (ptrVectorPool) + return this->ptrVectorPool->deallocVectorData(vec); + // wenn kein ptrVectorPool -> wurde bereits deallokiert + return true; + } + /*==========================================================*/ + const CbVectorPool<value_type> &getCbVectorPool() + { + if (!ptrVectorPool) + UB_THROW(UbException(UB_EXARGS, "vectorPool seems to be destroyed, ptrVectorPool==NULL")); + return *ptrVectorPool; + } + /*==========================================================*/ private: - typename CbVectorPool< value_type >::CbVectorKey key; - typename CbVectorPool< value_type >::Pool::size_type startIndexInPool; + typename CbVectorPool<value_type>::CbVectorKey key; + typename CbVectorPool<value_type>::Pool::size_type startIndexInPool; - CbVectorPool< value_type >* ptrVectorPool; + CbVectorPool<value_type> *ptrVectorPool; }; - -#endif //CBVECTORPOOL_H +#endif // CBVECTORPOOL_H diff --git a/src/basics/basics/memory/MbSmartPtr.h b/src/basics/basics/memory/MbSmartPtr.h index 54d154f148d99afb22d61e15d46304dff6099dbf..1ddced8c061708af5b04e005d7c7224900f64d3c 100644 --- a/src/basics/basics/memory/MbSmartPtr.h +++ b/src/basics/basics/memory/MbSmartPtr.h @@ -13,15 +13,14 @@ #pragma clang system_header #endif - //===================================================== // Globale Funktion, um das Loeschen des referenzierten // Objektes flexibler zu gestalten. // -template<class ObjType> -void deleteRefPtr(ObjType* ptr) +template <class ObjType> +void deleteRefPtr(ObjType *ptr) { - delete ptr; + delete ptr; } //====================================================== @@ -34,95 +33,76 @@ void deleteRefPtr(ObjType* ptr) // ueber die globale Template-Funktion deleteRefPtr(), die bei Bedarf ueberschrieben werden kann. // Der Reference-Pointer verfuegt also sozusagen ueber eine automatische Garbage Collection -template<class ObjType> -class MbSmartPtr : public MbSmartPtrBase +template <class ObjType> +class MbSmartPtr : public MbSmartPtrBase { public: - // Konstruktoren //bei explicit geht der implizite cast nicht mehr, aber um keinen stress zu verursachen - /*explicit*/ MbSmartPtr<ObjType>(const ObjType* pPtr=NULL) - : MbSmartPtrBase(), mpPtr(NULL) - { - init(pPtr); - } - template<class ParamType> - MbSmartPtr<ObjType>(const MbSmartPtr<ParamType>& ptr) - : MbSmartPtrBase(), mpPtr(NULL) - { - init(ptr.get()); - } - // Destruktor - ~MbSmartPtr<ObjType>() override - { - init(NULL); - } - //--------------------------------------------------- - // Kopierkonstruktor - MbSmartPtr<ObjType>(const MbSmartPtr<ObjType>& ptr) - : MbSmartPtrBase(), mpPtr(NULL) - { - init(ptr.get()); - } - //--------------------------------------------------- - // Zuweisungsoperatoren - template<class ParamType> - const MbSmartPtr<ObjType>& operator =(const MbSmartPtr<ParamType>& ptr) - { - init(ptr.get()); - return *this; - } - const MbSmartPtr<ObjType>& operator =(const MbSmartPtr<ObjType>& ptr) - { - init(ptr.get()); - return *this; - } + // Konstruktoren //bei explicit geht der implizite cast nicht mehr, aber um keinen stress zu verursachen + /*explicit*/ MbSmartPtr<ObjType>(const ObjType *pPtr = NULL) : MbSmartPtrBase(), mpPtr(NULL) { init(pPtr); } + template <class ParamType> + MbSmartPtr<ObjType>(const MbSmartPtr<ParamType> &ptr) : MbSmartPtrBase(), mpPtr(NULL) + { + init(ptr.get()); + } + // Destruktor + ~MbSmartPtr<ObjType>() override { init(NULL); } + //--------------------------------------------------- + // Kopierkonstruktor + MbSmartPtr<ObjType>(const MbSmartPtr<ObjType> &ptr) : MbSmartPtrBase(), mpPtr(NULL) { init(ptr.get()); } + //--------------------------------------------------- + // Zuweisungsoperatoren + template <class ParamType> + const MbSmartPtr<ObjType> &operator=(const MbSmartPtr<ParamType> &ptr) + { + init(ptr.get()); + return *this; + } + const MbSmartPtr<ObjType> &operator=(const MbSmartPtr<ObjType> &ptr) + { + init(ptr.get()); + return *this; + } + + const MbSmartPtr<ObjType> &operator=(const ObjType *pPtr) + { + init(pPtr); + return *this; + } + //--------------------------------------------------- + // Dereferenzierung-Operatoren + ObjType &operator*() const { return *mpPtr; } + ObjType *operator->() const { return mpPtr; } + bool operator!() const { return !mpPtr; } + operator ObjType *() const { return mpPtr; } + //--------------------------------------------------- + // Methoden + ObjType *get() const { return mpPtr; } + //--------------------------------------------------- + int ref_count() const { return MbSmartPtrBase::ref_count(mpPtr); } + //--------------------------------------------------- + bool release() const { return MbSmartPtrBase::removeFromGC(mpPtr); } - const MbSmartPtr<ObjType>& operator =(const ObjType *pPtr) - { - init(pPtr); - return *this; - } - //--------------------------------------------------- - // Dereferenzierung-Operatoren - ObjType& operator *() const { return *mpPtr; } - ObjType* operator ->() const { return mpPtr; } - bool operator !() const { return !mpPtr; } - operator ObjType *() const { return mpPtr; } - //--------------------------------------------------- - // Methoden - ObjType* get() const - { - return mpPtr; - } - //--------------------------------------------------- - int ref_count() const - { - return MbSmartPtrBase::ref_count(mpPtr); - } - //--------------------------------------------------- - bool release() const - { - return MbSmartPtrBase::removeFromGC(mpPtr); - } private: - void init(const ObjType* pPtr) - { - // Nur was tun, wenn wirklich noetig - if(pPtr==mpPtr) return; + void init(const ObjType *pPtr) + { + // Nur was tun, wenn wirklich noetig + if (pPtr == mpPtr) + return; - // Aktuell referenziertes Objekt freigeben, dabei ueberpruefen, ob letztes Release - if(mpPtr && releaseRef(mpPtr)) - { - // referenziertes Objekt loeschen - deleteRefPtr(mpPtr); - } + // Aktuell referenziertes Objekt freigeben, dabei ueberpruefen, ob letztes Release + if (mpPtr && releaseRef(mpPtr)) { + // referenziertes Objekt loeschen + deleteRefPtr(mpPtr); + } - // Wenn pPtr ein neues Objekt ist, Zugriffszaehler auf neues Objekt erhoehen - mpPtr=const_cast<ObjType*>(pPtr); - if(mpPtr) addRef(mpPtr); - } + // Wenn pPtr ein neues Objekt ist, Zugriffszaehler auf neues Objekt erhoehen + mpPtr = const_cast<ObjType *>(pPtr); + if (mpPtr) + addRef(mpPtr); + } private: - ObjType* mpPtr; + ObjType *mpPtr; }; -#endif //MBSMARTPTR_H +#endif // MBSMARTPTR_H diff --git a/src/basics/basics/memory/MbSmartPtrBase.cpp b/src/basics/basics/memory/MbSmartPtrBase.cpp index d0e07fa9503fe01f94128543d84927804505b97a..a0651b0290f6628d50442658d26912e4337d0cd6 100644 --- a/src/basics/basics/memory/MbSmartPtrBase.cpp +++ b/src/basics/basics/memory/MbSmartPtrBase.cpp @@ -2,43 +2,42 @@ using namespace std; -bool MbSmartPtrBase::addRef(void* ptr) +bool MbSmartPtrBase::addRef(void *ptr) { - MbSmartPtrBaseMap::getInstance()->getMap()[ptr]++; - return true; + MbSmartPtrBaseMap::getInstance()->getMap()[ptr]++; + return true; } //------------------------------------------------- -bool MbSmartPtrBase::releaseRef(void* ptr) +bool MbSmartPtrBase::releaseRef(void *ptr) { - map<void*,int>& ptrMap = MbSmartPtrBaseMap::getInstance()->getMap(); - map<void*,int>::iterator pos=ptrMap.find(ptr); - - if( pos!=ptrMap.end() ) - { - pos->second--; - - if(pos->second==0) - { - ptrMap.erase(pos); - return true; - } - } - return false; + map<void *, int> &ptrMap = MbSmartPtrBaseMap::getInstance()->getMap(); + map<void *, int>::iterator pos = ptrMap.find(ptr); + + if (pos != ptrMap.end()) { + pos->second--; + + if (pos->second == 0) { + ptrMap.erase(pos); + return true; + } + } + return false; } //------------------------------------------------- -bool MbSmartPtrBase::removeFromGC(void* ptr) const +bool MbSmartPtrBase::removeFromGC(void *ptr) const { - if( MbSmartPtrBaseMap::getInstance()->getMap().erase(ptr) ) return true; - return false; + if (MbSmartPtrBaseMap::getInstance()->getMap().erase(ptr)) + return true; + return false; } //------------------------------------------------- -int MbSmartPtrBase::ref_count(void* ptr) const +int MbSmartPtrBase::ref_count(void *ptr) const { - map<void*,int>& ptrMap = MbSmartPtrBaseMap::getInstance()->getMap(); - map<void*,int>::iterator pos=ptrMap.find(ptr); + map<void *, int> &ptrMap = MbSmartPtrBaseMap::getInstance()->getMap(); + map<void *, int>::iterator pos = ptrMap.find(ptr); - if( pos!=ptrMap.end() ) return pos->second; - else return 0; + if (pos != ptrMap.end()) + return pos->second; + else + return 0; } - - diff --git a/src/basics/basics/memory/MbSmartPtrBase.h b/src/basics/basics/memory/MbSmartPtrBase.h index 7c531902b4279f842daa99b0126eee9984154d54..1abdcac81c1454694d846d5d4a396df2dca095da 100644 --- a/src/basics/basics/memory/MbSmartPtrBase.h +++ b/src/basics/basics/memory/MbSmartPtrBase.h @@ -18,34 +18,39 @@ // class MbSmartPtrBase { - //Ursprung: - // mpCntrMap ist ein Pointer, weil sichergestellt sein muss, dass die - // Map existiert, wenn das erste mal darauf zugegriffen wird. - // Ein Zugriff zwischen zwei statischen Objekten kann zum Fehler fuehren, da - // die Reihenfolge der Konstruktorenaufrufe dann vom Linker bestimmt wird. - - //Anpassung a la UbWriter mit SingletonMap - class MbSmartPtrBaseMap - { - private: - MbSmartPtrBaseMap() = default; - - std::map<void*,int> mpCntrMap; - public: - MbSmartPtrBaseMap( const MbSmartPtrBaseMap& ) = delete; - const MbSmartPtrBaseMap& operator=( const MbSmartPtrBaseMap& ) = delete; - - static MbSmartPtrBaseMap* getInstance() { static MbSmartPtrBaseMap instance; return &instance; } - std::map<void*,int>& getMap() { return mpCntrMap; } - }; + // Ursprung: + // mpCntrMap ist ein Pointer, weil sichergestellt sein muss, dass die + // Map existiert, wenn das erste mal darauf zugegriffen wird. + // Ein Zugriff zwischen zwei statischen Objekten kann zum Fehler fuehren, da + // die Reihenfolge der Konstruktorenaufrufe dann vom Linker bestimmt wird. + + // Anpassung a la UbWriter mit SingletonMap + class MbSmartPtrBaseMap + { + private: + MbSmartPtrBaseMap() = default; + + std::map<void *, int> mpCntrMap; + + public: + MbSmartPtrBaseMap(const MbSmartPtrBaseMap &) = delete; + const MbSmartPtrBaseMap &operator=(const MbSmartPtrBaseMap &) = delete; + + static MbSmartPtrBaseMap *getInstance() + { + static MbSmartPtrBaseMap instance; + return &instance; + } + std::map<void *, int> &getMap() { return mpCntrMap; } + }; protected: - MbSmartPtrBase() = default; - virtual ~MbSmartPtrBase() = default; - bool addRef(void* p); - bool releaseRef(void* p); - bool removeFromGC(void* ptr) const; - int ref_count(void* ptr) const; + MbSmartPtrBase() = default; + virtual ~MbSmartPtrBase() = default; + bool addRef(void *p); + bool releaseRef(void *p); + bool removeFromGC(void *ptr) const; + int ref_count(void *ptr) const; }; -#endif //MBSMARTPTRBASE_H +#endif // MBSMARTPTRBASE_H diff --git a/src/basics/basics/objects/ObObject.h b/src/basics/basics/objects/ObObject.h index 0b543dc18c2a260a7146a168155f33966d619638..6d40d8af49979947e941dc9eb92b47d6f2b78b3d 100644 --- a/src/basics/basics/objects/ObObject.h +++ b/src/basics/basics/objects/ObObject.h @@ -1,28 +1,28 @@ //======================================================================================= -// ____ ____ __ ______ __________ __ __ __ __ -// \ \ | | | | | _ \ |___ ___| | | | | / \ | | -// \ \ | | | | | |_) | | | | | | | / \ | | -// \ \ | | | | | _ / | | | | | | / /\ \ | | -// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ -// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| -// \ \ | | ________________________________________________________________ -// \ \ | | | ______________________________________________________________| -// \ \| | | | __ __ __ __ ______ _______ -// \ | | |_____ | | | | | | | | | _ \ / _____) -// \ | | _____| | | | | | | | | | | \ \ \_______ +// ____ ____ __ ______ __________ __ __ __ __ +// \ \ | | | | | _ \ |___ ___| | | | | / \ | | +// \ \ | | | | | |_) | | | | | | | / \ | | +// \ \ | | | | | _ / | | | | | | / /\ \ | | +// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ +// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| +// \ \ | | ________________________________________________________________ +// \ \ | | | ______________________________________________________________| +// \ \| | | | __ __ __ __ ______ _______ +// \ | | |_____ | | | | | | | | | _ \ / _____) +// \ | | _____| | | | | | | | | | | \ \ \_______ // \ | | | | |_____ | \_/ | | | | |_/ / _____ | -// \ _____| |__| |________| \_______/ |__| |______/ (_______/ +// \ _____| |__| |________| \_______/ |__| |______/ (_______/ // -// This file is part of VirtualFluids. VirtualFluids is free software: you can +// This file is part of VirtualFluids. VirtualFluids is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of +// License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. -// -// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// +// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License along // with VirtualFluids (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>. // @@ -41,21 +41,19 @@ class ObObject : public UbObservable { public: ObObject() = default; - ObObject(const std::string& name) : name(name) { } + ObObject(const std::string &name) : name(name) {} - ~ObObject() override = default; + ~ObObject() override = default; - virtual ObObject* clone() = 0; + virtual ObObject *clone() = 0; - virtual std::string getName() { return name; } - void setName(std::string name) { this->name = name; } - - std::string toString() override = 0; + virtual std::string getName() { return name; } + void setName(std::string name) { this->name = name; } + std::string toString() override = 0; private: - std::string name; + std::string name; }; - #endif diff --git a/src/basics/basics/parallel/PbMpi.h b/src/basics/basics/parallel/PbMpi.h index d3954e363a77bc77d2c9fe97c48b1a352c571d57..63470c2d82d35ccc22599fc3623e6e1d93354a1a 100644 --- a/src/basics/basics/parallel/PbMpi.h +++ b/src/basics/basics/parallel/PbMpi.h @@ -7,11 +7,11 @@ #ifndef PbMpi_H #define PbMpi_H -#include <vector> #include <sstream> +#include <vector> #ifndef VF_MPI -# error VF_MPI has to be defined +#error VF_MPI has to be defined #endif // As we doing a lot of const-cast here we define PbMpi.h to system_header to mute clang-tidy @@ -27,433 +27,451 @@ #include <basics/utilities/UbException.h> #ifdef USE_MPI_CXX_SYNTAX - #define PbMpi_COMM_WORLD MPI::COMM_WORLD - #define PbMpi_INT MPI::INT - #define PbMpi_CHAR MPI::CHAR - #define PbMpi_SHORT MPI::SHORT - #define PbMpi_FLOAT MPI::FLOAT - #define PbMpi_DOUBLE MPI::DOUBLE - #define PbMpi_COMM_NULL MPI::COMM_NULL - +#define PbMpi_COMM_WORLD MPI::COMM_WORLD +#define PbMpi_INT MPI::INT +#define PbMpi_CHAR MPI::CHAR +#define PbMpi_SHORT MPI::SHORT +#define PbMpi_FLOAT MPI::FLOAT +#define PbMpi_DOUBLE MPI::DOUBLE +#define PbMpi_COMM_NULL MPI::COMM_NULL namespace PbMpi { - typedef MPI::Intracomm Comm; - typedef MPI::Group Group; - typedef MPI::Request Request; - typedef MPI::Status Status; - - inline void Init( ) - { - MPI::Init(); - MPI::COMM_WORLD.Set_errhandler(MPI::ERRORS_THROW_EXCEPTIONS); - } - inline void Init(int& argc, char** argv ) - { - MPI::Init(argc, argv); - MPI::COMM_WORLD.Set_errhandler(MPI::ERRORS_THROW_EXCEPTIONS); - } - inline void Finalize() { MPI::Finalize(); } - - inline int GetCommSize( const Comm& comm ) { return comm.Get_size(); } - inline int GetCommRank( const Comm& comm ) { return comm.Get_rank(); } - inline void Barrier( const Comm& comm ) { comm.Barrier(); } - - inline double Wtime() { return MPI::Wtime(); } - inline double Wtick() { return MPI::Wtick(); } - - inline void Wait( Request& request, Status* outStatus=NULL) - { - if(outStatus) request.Wait(*outStatus); - else request.Wait(); - } - - inline Group GetCommGroup(Comm& comm) { return comm.Get_group(); } - inline Group GetGroupIncl( Group& group, const int& n, int* ranks ) { return group.Incl(n, ranks); } - inline Comm CommCreateComm( Comm& comm, Group& group ) { return comm.Create(group); } - - inline void Alltoall( Comm& comm, void* sendBuffer, const int& sn, const MPI_Datatype& sdatatype, void* recvBuffer, const int& rn, const MPI_Datatype& rdatatype) - { - comm.Alltoall(sendBuffer, sn, sdatatype, recvBuffer, rn, rdatatype); - } - inline void Bcast(Comm& comm, void* data, const int& n, const MPI_Datatype& datatype , const int& srcRank ) - { - comm.Bcast(data, n, datatype, srcRank); - } - inline void Send(Comm& comm, const void* data, const int& length, const MPI_Datatype& dataType, const int& destRank, const int& tag) - { - try - { - comm.Send(data, length, dataType, destRank, tag); - } - catch(MPI::Exception& e) - { - std::stringstream ss; - ss<<"MPI::Exception error_string="<<e.Get_error_string()<<std::endl; - throw UbException(UB_EXARGS,"MPI:Exception catched\n"+ss.str()); - } - catch(...) - { - throw UbException(UB_EXARGS,"unknown exception"); - } - } - inline void Recv(Comm& comm, const void* data, const int& length, const MPI_Datatype& dataType, const int& srcRank, const int& tag) - { - try - { - comm.Recv(const_cast<void*>(data), length, dataType, srcRank, tag); - } - catch(MPI::Exception& e) - { - std::stringstream ss; - ss<<"MPI::Exception error_string="<<e.Get_error_string()<<std::endl; - throw UbException(UB_EXARGS,"MPI:Exception catched \n"+ss.str()); - } - catch(...) - { - throw UbException(UB_EXARGS,"unknown exception"); - } - } - - inline void Irecv(Comm comm, const void* data, const int& length, const MPI_Datatype& dataType, const int& srcRank, const int& tag, Request& outRequest) - { - outRequest = comm.Irecv(const_cast<void*>(data), length, dataType, srcRank, tag); - } - inline void Ssend(Comm& comm, const void* data, const int& length, const MPI_Datatype& dataType, const int& destRank, const int& tag) - { - try - { - comm.Ssend(data, length, dataType, destRank, tag); - } - catch(MPI::Exception& e) - { - std::stringstream ss; - ss<<"MPI::Exception error_string="<<e.Get_error_string()<<std::endl; - throw UbException(UB_EXARGS,"MPI:Exception catched\n"+ss.str()); - } - catch(...) - { - throw UbException(UB_EXARGS,"unknown exception"); - } - } +typedef MPI::Intracomm Comm; +typedef MPI::Group Group; +typedef MPI::Request Request; +typedef MPI::Status Status; + +inline void Init() +{ + MPI::Init(); + MPI::COMM_WORLD.Set_errhandler(MPI::ERRORS_THROW_EXCEPTIONS); +} +inline void Init(int &argc, char **argv) +{ + MPI::Init(argc, argv); + MPI::COMM_WORLD.Set_errhandler(MPI::ERRORS_THROW_EXCEPTIONS); +} +inline void Finalize() { MPI::Finalize(); } + +inline int GetCommSize(const Comm &comm) { return comm.Get_size(); } +inline int GetCommRank(const Comm &comm) { return comm.Get_rank(); } +inline void Barrier(const Comm &comm) { comm.Barrier(); } + +inline double Wtime() { return MPI::Wtime(); } +inline double Wtick() { return MPI::Wtick(); } + +inline void Wait(Request &request, Status *outStatus = NULL) +{ + if (outStatus) + request.Wait(*outStatus); + else + request.Wait(); +} + +inline Group GetCommGroup(Comm &comm) { return comm.Get_group(); } +inline Group GetGroupIncl(Group &group, const int &n, int *ranks) { return group.Incl(n, ranks); } +inline Comm CommCreateComm(Comm &comm, Group &group) { return comm.Create(group); } + +inline void Alltoall(Comm &comm, void *sendBuffer, const int &sn, const MPI_Datatype &sdatatype, void *recvBuffer, + const int &rn, const MPI_Datatype &rdatatype) +{ + comm.Alltoall(sendBuffer, sn, sdatatype, recvBuffer, rn, rdatatype); +} +inline void Bcast(Comm &comm, void *data, const int &n, const MPI_Datatype &datatype, const int &srcRank) +{ + comm.Bcast(data, n, datatype, srcRank); +} +inline void Send(Comm &comm, const void *data, const int &length, const MPI_Datatype &dataType, const int &destRank, + const int &tag) +{ + try { + comm.Send(data, length, dataType, destRank, tag); + } catch (MPI::Exception &e) { + std::stringstream ss; + ss << "MPI::Exception error_string=" << e.Get_error_string() << std::endl; + throw UbException(UB_EXARGS, "MPI:Exception catched\n" + ss.str()); + } catch (...) { + throw UbException(UB_EXARGS, "unknown exception"); + } +} +inline void Recv(Comm &comm, const void *data, const int &length, const MPI_Datatype &dataType, const int &srcRank, + const int &tag) +{ + try { + comm.Recv(const_cast<void *>(data), length, dataType, srcRank, tag); + } catch (MPI::Exception &e) { + std::stringstream ss; + ss << "MPI::Exception error_string=" << e.Get_error_string() << std::endl; + throw UbException(UB_EXARGS, "MPI:Exception catched \n" + ss.str()); + } catch (...) { + throw UbException(UB_EXARGS, "unknown exception"); + } +} +inline void Irecv(Comm comm, const void *data, const int &length, const MPI_Datatype &dataType, const int &srcRank, + const int &tag, Request &outRequest) +{ + outRequest = comm.Irecv(const_cast<void *>(data), length, dataType, srcRank, tag); +} +inline void Ssend(Comm &comm, const void *data, const int &length, const MPI_Datatype &dataType, const int &destRank, + const int &tag) +{ + try { + comm.Ssend(data, length, dataType, destRank, tag); + } catch (MPI::Exception &e) { + std::stringstream ss; + ss << "MPI::Exception error_string=" << e.Get_error_string() << std::endl; + throw UbException(UB_EXARGS, "MPI:Exception catched\n" + ss.str()); + } catch (...) { + throw UbException(UB_EXARGS, "unknown exception"); + } } + +} // namespace PbMpi #else ////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////// - // C-Syntax - ////////////////////////////////////////////////////////////////////////// - namespace PbMpi - { - using Comm = MPI_Comm; - using Group = MPI_Group; - using Request = MPI_Request; - using Status = MPI_Status; - } - - #define PbMpi_COMM_WORLD ((PbMpi::Comm)MPI_COMM_WORLD) - #define PbMpi_INT MPI_INT - #define PbMpi_CHAR MPI_CHAR - #define PbMpi_SHORT MPI_SHORT - #define PbMpi_FLOAT MPI_FLOAT - #define PbMpi_DOUBLE MPI_DOUBLE - #define PbMpi_COMM_NULL MPI_COMM_NULL +////////////////////////////////////////////////////////////////////////// +// C-Syntax +////////////////////////////////////////////////////////////////////////// +namespace PbMpi +{ +using Comm = MPI_Comm; +using Group = MPI_Group; +using Request = MPI_Request; +using Status = MPI_Status; +} // namespace PbMpi + +#define PbMpi_COMM_WORLD ((PbMpi::Comm)MPI_COMM_WORLD) +#define PbMpi_INT MPI_INT +#define PbMpi_CHAR MPI_CHAR +#define PbMpi_SHORT MPI_SHORT +#define PbMpi_FLOAT MPI_FLOAT +#define PbMpi_DOUBLE MPI_DOUBLE +#define PbMpi_COMM_NULL MPI_COMM_NULL namespace PbMpi { - inline void Init( ) - { - int argc = 1; - char** argv = new char*[1]; - argv[0] = new char[1]; - argv[0][0] = 'n'; - MPI_Init(&argc, &argv); - } - inline void Init(int& argc, char** argv ) { MPI_Init(&argc, &argv); } - inline void Finalize( ) { MPI_Finalize(); } - inline int GetCommSize( Comm comm ) { int tmp; MPI_Comm_size(comm, &tmp); return tmp; } - inline int GetCommRank( Comm comm ) { int tmp; MPI_Comm_rank(comm, &tmp); return tmp; } - inline void Barrier( Comm comm ) { MPI_Barrier( comm ); } - inline double Wtime() { return MPI_Wtime(); } - inline double Wtick() { return MPI_Wtick(); } - inline void Wait( Request& request, Status* outStatus=NULL) { MPI_Wait( &request, outStatus); } - - inline Group GetCommGroup(Comm comm) { Group out; MPI_Comm_group(comm, &out); return out; } - inline Group GetGroupIncl( Group group, const int& n, int* ranks ) { Group out; MPI_Group_incl(group, n, ranks, &out); return out; } - inline Comm CommCreateComm( Comm comm, Group& group ) { Comm out; MPI_Comm_create(comm, group, &out); return out; } - - inline void Alltoall( Comm comm, void* sendBuffer, const int& sn, const MPI_Datatype& sdatatype, void* recvBuffer, const int& rn, const MPI_Datatype& rdatatype) - { - MPI_Alltoall(sendBuffer, sn, sdatatype, recvBuffer, rn, rdatatype, comm); - } - inline void Bcast(Comm comm, void* data, const int& n, const MPI_Datatype& datatype , const int& srcRank ) - { - MPI_Bcast(data, n, datatype, srcRank, comm); - } - inline void Send(Comm comm, const void* data, const int& length, const MPI_Datatype& dataType, const int& destRank, const int& tag) - { - MPI_Send(const_cast<void*>(data), length, dataType, destRank, tag, comm); - } - inline void Recv(Comm comm, const void* data, const int& length, const MPI_Datatype& dataType, const int& srcRank, const int& tag) - { - MPI_Recv(const_cast<void*>(data), length, dataType, srcRank, tag, comm, MPI_STATUS_IGNORE); - } - inline void Ssend(Comm comm, const void* data, const int& length, const MPI_Datatype& dataType, const int& destRank, const int& tag) - { - MPI_Ssend(const_cast<void*>(data), length, dataType, destRank, tag, comm); - } - inline void Irecv(Comm comm, const void* data, const int& length, const MPI_Datatype& dataType, const int& srcRank, const int& tag, Request& outRequest) - { - MPI_Irecv(const_cast<void*>(data), length, dataType, srcRank, tag, comm, &outRequest); - } +inline void Init() +{ + int argc = 1; + char **argv = new char *[1]; + argv[0] = new char[1]; + argv[0][0] = 'n'; + MPI_Init(&argc, &argv); +} +inline void Init(int &argc, char **argv) { MPI_Init(&argc, &argv); } +inline void Finalize() { MPI_Finalize(); } +inline int GetCommSize(Comm comm) +{ + int tmp; + MPI_Comm_size(comm, &tmp); + return tmp; +} +inline int GetCommRank(Comm comm) +{ + int tmp; + MPI_Comm_rank(comm, &tmp); + return tmp; +} +inline void Barrier(Comm comm) { MPI_Barrier(comm); } +inline double Wtime() { return MPI_Wtime(); } +inline double Wtick() { return MPI_Wtick(); } +inline void Wait(Request &request, Status *outStatus = NULL) { MPI_Wait(&request, outStatus); } +inline Group GetCommGroup(Comm comm) +{ + Group out; + MPI_Comm_group(comm, &out); + return out; +} +inline Group GetGroupIncl(Group group, const int &n, int *ranks) +{ + Group out; + MPI_Group_incl(group, n, ranks, &out); + return out; +} +inline Comm CommCreateComm(Comm comm, Group &group) +{ + Comm out; + MPI_Comm_create(comm, group, &out); + return out; +} + +inline void Alltoall(Comm comm, void *sendBuffer, const int &sn, const MPI_Datatype &sdatatype, void *recvBuffer, + const int &rn, const MPI_Datatype &rdatatype) +{ + MPI_Alltoall(sendBuffer, sn, sdatatype, recvBuffer, rn, rdatatype, comm); +} +inline void Bcast(Comm comm, void *data, const int &n, const MPI_Datatype &datatype, const int &srcRank) +{ + MPI_Bcast(data, n, datatype, srcRank, comm); +} +inline void Send(Comm comm, const void *data, const int &length, const MPI_Datatype &dataType, const int &destRank, + const int &tag) +{ + MPI_Send(const_cast<void *>(data), length, dataType, destRank, tag, comm); +} +inline void Recv(Comm comm, const void *data, const int &length, const MPI_Datatype &dataType, const int &srcRank, + const int &tag) +{ + MPI_Recv(const_cast<void *>(data), length, dataType, srcRank, tag, comm, MPI_STATUS_IGNORE); +} +inline void Ssend(Comm comm, const void *data, const int &length, const MPI_Datatype &dataType, const int &destRank, + const int &tag) +{ + MPI_Ssend(const_cast<void *>(data), length, dataType, destRank, tag, comm); +} +inline void Irecv(Comm comm, const void *data, const int &length, const MPI_Datatype &dataType, const int &srcRank, + const int &tag, Request &outRequest) +{ + MPI_Irecv(const_cast<void *>(data), length, dataType, srcRank, tag, comm, &outRequest); } + +} // namespace PbMpi #endif namespace PbMpi { - /*======================================================================*/ - // send a single value "value" of MPI_Datatype - template <class T> - inline void sendSingleValue(const T& value, MPI_Datatype datatype, int dest, int tag, PbMpi::Comm comm); - - /*======================================================================*/ - // receives a single value "value" of MPI_Datatype - template <class T> - inline void receiveSingleValue(T& value, MPI_Datatype datatype, int source, int tag, PbMpi::Comm comm); - - /*======================================================================*/ - // receives and returns a single value of MPI_Datatype - // expample: int value = PbMpi::receiveSingleValue<int>(MPI::INT,0,10,comm); - template <class T> - inline T receiveSingleValue(MPI_Datatype datatype, int source, int tag, PbMpi::Comm comm); - - /*======================================================================*/ - // sends bool value (doesn't work with template, why ever... stupid MPI) - inline void sendBoolValue(const bool& value,int dest, int tag, PbMpi::Comm comm); - - /*======================================================================*/ - // receives bool value (doesn't work with template, why ever... stupid MPI) - inline bool receiveBoolValue(int source, int tag, PbMpi::Comm comm); - - /*======================================================================*/ - // sends bool value (doesn't work with template, why ever... stupid MPI) - inline void sendStringValue(const std::string& value,int dest, int tag, PbMpi::Comm comm); - - /*======================================================================*/ - // receives bool value (doesn't work with template, why ever... stupid MPI) - inline std::string receiveStringValue(int source, int tag, PbMpi::Comm comm); - - /*======================================================================*/ - // send a vector of MPI_Datatype - template <class T> - inline void sendVector(const std::vector<T>& v, MPI_Datatype datatype, int dest, int tag, PbMpi::Comm comm); - - /*======================================================================*/ - // receive a std::vector of MPI_Datatype - template <class T> - inline void receiveVector(std::vector<T>& v, MPI_Datatype datatype, int source, int tag, PbMpi::Comm comm); - - /*======================================================================*/ - // receive a vector of MPI_Datatype and adds this vector to existing vector - // ans returns number of received elements - template <class T> - inline int receiveVectorAndAddToVector(std::vector<T>& v, MPI_Datatype datatype, int source, int tag, PbMpi::Comm comm); - - /*======================================================================*/ - // send a std::vector of strings - inline void sendStringVector(const std::vector<std::string>& v, int dest, int tag, PbMpi::Comm comm); - - /*======================================================================*/ - // send a vector of strings - inline void receiveStringVector(std::vector<std::string>& v, int dest, int tag, PbMpi::Comm comm); -}; - -/*======================================================================*/ +/*======================================================================*/ +// send a single value "value" of MPI_Datatype +template <class T> +inline void sendSingleValue(const T &value, MPI_Datatype datatype, int dest, int tag, PbMpi::Comm comm); + +/*======================================================================*/ +// receives a single value "value" of MPI_Datatype +template <class T> +inline void receiveSingleValue(T &value, MPI_Datatype datatype, int source, int tag, PbMpi::Comm comm); + +/*======================================================================*/ +// receives and returns a single value of MPI_Datatype +// expample: int value = PbMpi::receiveSingleValue<int>(MPI::INT,0,10,comm); +template <class T> +inline T receiveSingleValue(MPI_Datatype datatype, int source, int tag, PbMpi::Comm comm); + +/*======================================================================*/ +// sends bool value (doesn't work with template, why ever... stupid MPI) +inline void sendBoolValue(const bool &value, int dest, int tag, PbMpi::Comm comm); + +/*======================================================================*/ +// receives bool value (doesn't work with template, why ever... stupid MPI) +inline bool receiveBoolValue(int source, int tag, PbMpi::Comm comm); + +/*======================================================================*/ +// sends bool value (doesn't work with template, why ever... stupid MPI) +inline void sendStringValue(const std::string &value, int dest, int tag, PbMpi::Comm comm); + +/*======================================================================*/ +// receives bool value (doesn't work with template, why ever... stupid MPI) +inline std::string receiveStringValue(int source, int tag, PbMpi::Comm comm); + +/*======================================================================*/ +// send a vector of MPI_Datatype +template <class T> +inline void sendVector(const std::vector<T> &v, MPI_Datatype datatype, int dest, int tag, PbMpi::Comm comm); + +/*======================================================================*/ +// receive a std::vector of MPI_Datatype +template <class T> +inline void receiveVector(std::vector<T> &v, MPI_Datatype datatype, int source, int tag, PbMpi::Comm comm); + +/*======================================================================*/ +// receive a vector of MPI_Datatype and adds this vector to existing vector +// ans returns number of received elements +template <class T> +inline int receiveVectorAndAddToVector(std::vector<T> &v, MPI_Datatype datatype, int source, int tag, PbMpi::Comm comm); + +/*======================================================================*/ +// send a std::vector of strings +inline void sendStringVector(const std::vector<std::string> &v, int dest, int tag, PbMpi::Comm comm); + +/*======================================================================*/ +// send a vector of strings +inline void receiveStringVector(std::vector<std::string> &v, int dest, int tag, PbMpi::Comm comm); +}; // namespace PbMpi + +/*======================================================================*/ // send a single value of MPI_Datatype template <class T> -void PbMpi::sendSingleValue(const T& value, MPI_Datatype datatype, int dest, int tag, PbMpi::Comm comm) +void PbMpi::sendSingleValue(const T &value, MPI_Datatype datatype, int dest, int tag, PbMpi::Comm comm) { - PbMpi::Send(comm, &value, 1, datatype, dest, tag); - //comm.Send(&value, 1, datatype, dest, tag); + PbMpi::Send(comm, &value, 1, datatype, dest, tag); + // comm.Send(&value, 1, datatype, dest, tag); } -/*======================================================================*/ +/*======================================================================*/ template <class T> -void PbMpi::receiveSingleValue(T& value, MPI_Datatype datatype, int source, int tag, PbMpi::Comm comm) +void PbMpi::receiveSingleValue(T &value, MPI_Datatype datatype, int source, int tag, PbMpi::Comm comm) { - PbMpi::Recv(comm, &value, 1, datatype, source, tag); - //comm.Recv(&value, 1, datatype, source, tag); + PbMpi::Recv(comm, &value, 1, datatype, source, tag); + // comm.Recv(&value, 1, datatype, source, tag); } -/*======================================================================*/ +/*======================================================================*/ template <class T> -T PbMpi::receiveSingleValue(MPI_Datatype datatype, int source, int tag, PbMpi::Comm comm) +T PbMpi::receiveSingleValue(MPI_Datatype datatype, int source, int tag, PbMpi::Comm comm) { - T value; - PbMpi::Recv(comm, &value, 1, datatype, source, tag); - //comm.Recv(&value, 1, datatype, source, tag); + T value; + PbMpi::Recv(comm, &value, 1, datatype, source, tag); + // comm.Recv(&value, 1, datatype, source, tag); - return value; + return value; } -/*======================================================================*/ +/*======================================================================*/ // send a bool value (bool doesn't work with template, why ever) -void PbMpi::sendBoolValue(const bool& value,int dest, int tag, PbMpi::Comm comm) +void PbMpi::sendBoolValue(const bool &value, int dest, int tag, PbMpi::Comm comm) { - short dummy; - if(value) dummy=1; - else dummy=0; - - PbMpi::Send(comm, &dummy, 1, PbMpi_SHORT, dest, tag); - //comm.Send(&dummy, 1, MPI::SHORT, dest, tag); + short dummy; + if (value) + dummy = 1; + else + dummy = 0; + + PbMpi::Send(comm, &dummy, 1, PbMpi_SHORT, dest, tag); + // comm.Send(&dummy, 1, MPI::SHORT, dest, tag); } -/*======================================================================*/ -bool PbMpi::receiveBoolValue(int source, int tag, PbMpi::Comm comm) +/*======================================================================*/ +bool PbMpi::receiveBoolValue(int source, int tag, PbMpi::Comm comm) { - short dummy {0}; - PbMpi::Recv(comm, &dummy, 1, PbMpi_SHORT, source, tag); - //comm.Recv(&dummy, 1, MPI::SHORT, source, tag); - - return (dummy==1); + short dummy{ 0 }; + PbMpi::Recv(comm, &dummy, 1, PbMpi_SHORT, source, tag); + // comm.Recv(&dummy, 1, MPI::SHORT, source, tag); + + return (dummy == 1); } -/*======================================================================*/ +/*======================================================================*/ // sends bool value (doesn't work with template, why ever... stupid MPI) -void PbMpi::sendStringValue(const std::string& value,int dest, int tag, PbMpi::Comm comm) +void PbMpi::sendStringValue(const std::string &value, int dest, int tag, PbMpi::Comm comm) { - std::vector<char> vec; - for(char i : value) - vec.push_back(i); - - PbMpi::sendVector(vec,PbMpi_CHAR,dest,tag,comm); + std::vector<char> vec; + for (char i : value) + vec.push_back(i); + + PbMpi::sendVector(vec, PbMpi_CHAR, dest, tag, comm); } -/*======================================================================*/ +/*======================================================================*/ // receives bool value (doesn't work with template, why ever... stupid MPI) std::string PbMpi::receiveStringValue(int source, int tag, PbMpi::Comm comm) { - std::vector<char> vec; - PbMpi::receiveVector(vec,PbMpi_CHAR,source,tag,comm); - - std::string str; - for(char i : vec) - str+=i; + std::vector<char> vec; + PbMpi::receiveVector(vec, PbMpi_CHAR, source, tag, comm); + + std::string str; + for (char i : vec) + str += i; - return str; + return str; } -/*======================================================================*/ +/*======================================================================*/ // send a vector of MPI_Datatype template <class T> -void PbMpi::sendVector(const std::vector<T>& v, MPI_Datatype datatype, int dest, int tag, PbMpi::Comm comm) -{ - // send size - int size = (int)v.size(); - - PbMpi::Send(comm, &size, 1, PbMpi_INT, dest, tag); - //comm.Send(&size, 1, MPI::INT, dest, tag); - - if(size>0) - { - PbMpi::Send(comm, &v[0], size, datatype, dest, tag); - //comm.Send(&v[0], size, datatype, dest, tag); - } -} -/*======================================================================*/ +void PbMpi::sendVector(const std::vector<T> &v, MPI_Datatype datatype, int dest, int tag, PbMpi::Comm comm) +{ + // send size + int size = (int)v.size(); + + PbMpi::Send(comm, &size, 1, PbMpi_INT, dest, tag); + // comm.Send(&size, 1, MPI::INT, dest, tag); + + if (size > 0) { + PbMpi::Send(comm, &v[0], size, datatype, dest, tag); + // comm.Send(&v[0], size, datatype, dest, tag); + } +} +/*======================================================================*/ // receive a vector of MPI_Datatype template <class T> -void PbMpi::receiveVector(std::vector<T>& v, MPI_Datatype datatype, int source, int tag, PbMpi::Comm comm) +void PbMpi::receiveVector(std::vector<T> &v, MPI_Datatype datatype, int source, int tag, PbMpi::Comm comm) { - int size {0}; + int size{ 0 }; - PbMpi::Recv(comm, &size, 1, PbMpi_INT, source, tag); - //comm.Recv(&size, 1, MPI::INT, source, tag); + PbMpi::Recv(comm, &size, 1, PbMpi_INT, source, tag); + // comm.Recv(&size, 1, MPI::INT, source, tag); - v.resize(size); + v.resize(size); - if( size>0 ) - { - PbMpi::Recv(comm, &v[0], size, datatype, source, tag); - //comm.Recv(&v[0], size, datatype, source, tag); - } + if (size > 0) { + PbMpi::Recv(comm, &v[0], size, datatype, source, tag); + // comm.Recv(&v[0], size, datatype, source, tag); + } } -/*======================================================================*/ +/*======================================================================*/ // receive a vector of MPI_Datatype and adds this vector to existing vector // return value is size of received elements template <class T> -int PbMpi::receiveVectorAndAddToVector(std::vector<T>& v, MPI_Datatype datatype, int source, int tag, PbMpi::Comm comm) +int PbMpi::receiveVectorAndAddToVector(std::vector<T> &v, MPI_Datatype datatype, int source, int tag, PbMpi::Comm comm) { - int incommingSize; + int incommingSize; - PbMpi::Recv(comm, &incommingSize, 1, PbMpi_INT, source, tag); - //comm.Recv(&incommingSize, 1, MPI::INT, source, tag); + PbMpi::Recv(comm, &incommingSize, 1, PbMpi_INT, source, tag); + // comm.Recv(&incommingSize, 1, MPI::INT, source, tag); - int oldSize = (int)v.size(); - v.resize(oldSize+incommingSize); + int oldSize = (int)v.size(); + v.resize(oldSize + incommingSize); - if( incommingSize>0 ) - { - PbMpi::Recv(comm, &v[oldSize], incommingSize, datatype, source, tag); - //comm.Recv(&v[oldSize], incommingSize, datatype, source, tag); - } + if (incommingSize > 0) { + PbMpi::Recv(comm, &v[oldSize], incommingSize, datatype, source, tag); + // comm.Recv(&v[oldSize], incommingSize, datatype, source, tag); + } - return incommingSize; + return incommingSize; } -/*======================================================================*/ +/*======================================================================*/ // send a vector of strings -void PbMpi::sendStringVector(const std::vector<std::string>& v, int dest, int tag, PbMpi::Comm comm) +void PbMpi::sendStringVector(const std::vector<std::string> &v, int dest, int tag, PbMpi::Comm comm) { - // send size - int stringVectorSize = (int)v.size(); - - PbMpi::Send(comm, &stringVectorSize, 1, PbMpi_INT, dest, tag); - //comm.Send(&stringVectorSize, 1, MPI::INT, dest, tag); - - if(stringVectorSize>0) - { - std::vector<int> singleStringSizes(stringVectorSize+1); - int nofChars = 0; - for(int i=0; i<stringVectorSize; i++) - nofChars += singleStringSizes[i] = (int)v[i].length(); - singleStringSizes[stringVectorSize] = nofChars; - - PbMpi::Send(comm, &singleStringSizes[0], stringVectorSize+1, PbMpi_INT, dest, tag); - - std::vector<char> charVector(nofChars); - int pos = 0; - for(int i=0; i<stringVectorSize; i++) - for(int j=0; j<singleStringSizes[i]; j++) - charVector[pos++] = v[i][j]; - - PbMpi::Send(comm, &charVector[0], nofChars, PbMpi_CHAR, dest, tag); - //comm.Send(&charVector[0], nofChars, MPI::CHAR, dest, tag); - } + // send size + int stringVectorSize = (int)v.size(); + + PbMpi::Send(comm, &stringVectorSize, 1, PbMpi_INT, dest, tag); + // comm.Send(&stringVectorSize, 1, MPI::INT, dest, tag); + + if (stringVectorSize > 0) { + std::vector<int> singleStringSizes(stringVectorSize + 1); + int nofChars = 0; + for (int i = 0; i < stringVectorSize; i++) + nofChars += singleStringSizes[i] = (int)v[i].length(); + singleStringSizes[stringVectorSize] = nofChars; + + PbMpi::Send(comm, &singleStringSizes[0], stringVectorSize + 1, PbMpi_INT, dest, tag); + + std::vector<char> charVector(nofChars); + int pos = 0; + for (int i = 0; i < stringVectorSize; i++) + for (int j = 0; j < singleStringSizes[i]; j++) + charVector[pos++] = v[i][j]; + + PbMpi::Send(comm, &charVector[0], nofChars, PbMpi_CHAR, dest, tag); + // comm.Send(&charVector[0], nofChars, MPI::CHAR, dest, tag); + } } -/*======================================================================*/ +/*======================================================================*/ // send a vector of strings -void PbMpi::receiveStringVector(std::vector<std::string>& v, int source, int tag, PbMpi::Comm comm) +void PbMpi::receiveStringVector(std::vector<std::string> &v, int source, int tag, PbMpi::Comm comm) { - // send size - int stringVectorSize {0}; - PbMpi::Recv(comm, &stringVectorSize, 1, PbMpi_INT, source, tag); - //comm.Recv(&stringVectorSize, 1, MPI::INT, source, tag); + // send size + int stringVectorSize{ 0 }; + PbMpi::Recv(comm, &stringVectorSize, 1, PbMpi_INT, source, tag); + // comm.Recv(&stringVectorSize, 1, MPI::INT, source, tag); - v.clear(); - v.resize(stringVectorSize); + v.clear(); + v.resize(stringVectorSize); - if(stringVectorSize>0) - { - std::vector<int> singleStringSizes(stringVectorSize+1); + if (stringVectorSize > 0) { + std::vector<int> singleStringSizes(stringVectorSize + 1); - PbMpi::Recv(comm, &singleStringSizes[0], stringVectorSize+1, PbMpi_INT, source, tag); - //comm.Recv(&singleStringSizes[0], stringVectorSize+1, MPI::INT, source, tag); + PbMpi::Recv(comm, &singleStringSizes[0], stringVectorSize + 1, PbMpi_INT, source, tag); + // comm.Recv(&singleStringSizes[0], stringVectorSize+1, MPI::INT, source, tag); - int nofChars = singleStringSizes[stringVectorSize]; - std::vector<char> charVector(nofChars); + int nofChars = singleStringSizes[stringVectorSize]; + std::vector<char> charVector(nofChars); - PbMpi::Recv(comm, &charVector[0], nofChars, PbMpi_CHAR, source, tag); - //comm.Recv(&charVector[0], nofChars, MPI::CHAR, source, tag); + PbMpi::Recv(comm, &charVector[0], nofChars, PbMpi_CHAR, source, tag); + // comm.Recv(&charVector[0], nofChars, MPI::CHAR, source, tag); - int pos=0; - for(int i=0; i<stringVectorSize; i++) - for(int j=0; j<singleStringSizes[i]; j++) - v[i].push_back(charVector[pos++]); - } + int pos = 0; + for (int i = 0; i < stringVectorSize; i++) + for (int j = 0; j < singleStringSizes[i]; j++) + v[i].push_back(charVector[pos++]); + } } -#endif //PbMpi_H +#endif // PbMpi_H diff --git a/src/basics/basics/transmitter/TbTransmitter.h b/src/basics/basics/transmitter/TbTransmitter.h index 61874360faa73689d435068baafdf9ece8f9ac44..4d5e5195d9840ea54b3a4f62b0063626e60e4c5b 100644 --- a/src/basics/basics/transmitter/TbTransmitter.h +++ b/src/basics/basics/transmitter/TbTransmitter.h @@ -17,52 +17,52 @@ This Class provides the base for sending and receiving of data. <BR><BR> @author <A HREF="mailto:muffmolch@gmx.de">S. Freudiger</A> @version 1.0 - 08.11.07 -*/ +*/ /* usage: ... */ ////////////////////////////////////////////////////////////////////////// -// Transmitter +// Transmitter // macht nichts ausser daten senden und empfangen -template<typename T> +template <typename T> class TbTransmitter { public: - using value_type = T; + using value_type = T; public: - TbTransmitter() = default; - virtual ~TbTransmitter() = default; + TbTransmitter() = default; + virtual ~TbTransmitter() = default; + + virtual bool isLocalTransmitter() const = 0; + virtual bool isRemoteTransmitter() const = 0; - virtual bool isLocalTransmitter() const = 0; - virtual bool isRemoteTransmitter() const = 0; + // preprocess (e.g. synchronizing send-/receive-buffer) + virtual void sendDataSize() = 0; + virtual void receiveDataSize() = 0; - //preprocess (e.g. synchronizing send-/receive-buffer) - virtual void sendDataSize() = 0; - virtual void receiveDataSize()= 0; - - //calculation - virtual void prepareForSend() {} - virtual void sendData()=0; - virtual void prepareForReceive() {} - virtual value_type& receiveData()=0; + // calculation + virtual void prepareForSend() {} + virtual void sendData() = 0; + virtual void prepareForReceive() {} + virtual value_type &receiveData() = 0; - //data-access - inline value_type& getData() { return this->data; } - inline const value_type& getData() const { return this->data; } + // data-access + inline value_type &getData() { return this->data; } + inline const value_type &getData() const { return this->data; } - //info-section (usable for remote transmitter) - virtual int getSendToRank() const { return -1; } - virtual int getSendToTag() const { return -1; } - virtual int getRecvFromRank() const { return -1; } - virtual int getRecvFromTag() const { return -1; } + // info-section (usable for remote transmitter) + virtual int getSendToRank() const { return -1; } + virtual int getSendToTag() const { return -1; } + virtual int getRecvFromRank() const { return -1; } + virtual int getRecvFromTag() const { return -1; } - virtual std::string toString() const = 0; + virtual std::string toString() const = 0; protected: - value_type data; + value_type data; }; -#endif //TBTRANSMITTER_H +#endif // TBTRANSMITTER_H diff --git a/src/basics/basics/transmitter/TbTransmitterLocal.h b/src/basics/basics/transmitter/TbTransmitterLocal.h index abc127a0a9f01d8b7a83954b0351ede87b0813c3..f0a6c30df18a28dd61bfc25af48610d931ba270f 100644 --- a/src/basics/basics/transmitter/TbTransmitterLocal.h +++ b/src/basics/basics/transmitter/TbTransmitterLocal.h @@ -7,9 +7,9 @@ #ifndef TOTRANSMITTERLOCAL_H #define TOTRANSMITTERLOCAL_H -#include <basics/utilities/UbException.h> -#include <basics/transmitter/TbTransmitter.h> #include <PointerDefinitions.h> +#include <basics/transmitter/TbTransmitter.h> +#include <basics/utilities/UbException.h> /*================================================================================*/ /* TbLocalTransmitter, TbVectorSenderLocal, TbVectorReceiverLocal */ @@ -19,7 +19,7 @@ This Class provides the base for exception handling. <BR><BR> @author <A HREF="mailto:muffmolch@gmx.de">S. Freudiger</A> @version 1.0 - 08.11.07 -*/ +*/ /* usage: ... @@ -28,102 +28,95 @@ usage: ... ////////////////////////////////////////////////////////////////////////// // LocalTransmitter lokalen Datenaustausch // data = send- und zugleich receive-buffer -template<typename T> +template <typename T> class TbLocalTransmitter : public TbTransmitter<T> { public: - using TbLocalTransmitterPtr = SPtr<TbLocalTransmitter<T> >; + using TbLocalTransmitterPtr = SPtr<TbLocalTransmitter<T>>; - using value_type = T; + using value_type = T; public: - TbLocalTransmitter() : TbTransmitter<T>() - { + TbLocalTransmitter() : TbTransmitter<T>() {} - } - - bool isLocalTransmitter() const override { return true; } - bool isRemoteTransmitter() const override { return !this->isLocalTransmitter(); } + bool isLocalTransmitter() const override { return true; } + bool isRemoteTransmitter() const override { return !this->isLocalTransmitter(); } - //send buffer wird autom resized - void sendDataSize() override { } - //reiceive braucht nichts machen, da send==receive buffer ;-) - void receiveDataSize() override { } + // send buffer wird autom resized + void sendDataSize() override {} + // reiceive braucht nichts machen, da send==receive buffer ;-) + void receiveDataSize() override {} - void sendData() override { } - value_type& receiveData() override { return this->data; } + void sendData() override {} + value_type &receiveData() override { return this->data; } - std::string toString() const override { return "TbLocalTransmitter"+(std::string)typeid(T).name(); } + std::string toString() const override { return "TbLocalTransmitter" + (std::string) typeid(T).name(); } }; ////////////////////////////////////////////////////////////////////////// // TbVectorSender/ReceiverLocal lokalen Datenaustausch ueber ZWEI vektoren -template<typename T> +template <typename T> class TbVectorReceiverLocal : public TbTransmitter<T> { public: - using value_type = T; + using value_type = T; public: - TbVectorReceiverLocal() : TbTransmitter<value_type>() - { - - } - //virtual ~TbVectorReceiverLocal() { std::cout<<typeid(*this).name()<<" tot"<<std::endl; } + TbVectorReceiverLocal() : TbTransmitter<value_type>() {} + // virtual ~TbVectorReceiverLocal() { std::cout<<typeid(*this).name()<<" tot"<<std::endl; } - bool isLocalTransmitter() const { return true; } - bool isRemoteTransmitter() const { return !this->isLocalTransmitter(); } + bool isLocalTransmitter() const { return true; } + bool isRemoteTransmitter() const { return !this->isLocalTransmitter(); } - //send buffer wird autom resized - void sendDataSize() { UB_THROW( UbException(UB_EXARGS,"empfaengt nur") ); } - //reiceive braucht nichts machen, das macht der sender :-) - void receiveDataSize() { } + // send buffer wird autom resized + void sendDataSize() { UB_THROW(UbException(UB_EXARGS, "empfaengt nur")); } + // reiceive braucht nichts machen, das macht der sender :-) + void receiveDataSize() {} - void sendData() { UB_THROW( UbException(UB_EXARGS,"empfaengt nur") ); } - value_type& receiveData() { return this->data; } + void sendData() { UB_THROW(UbException(UB_EXARGS, "empfaengt nur")); } + value_type &receiveData() { return this->data; } - std::string toString() const { return "TbVectorReceiverLocal<"+(std::string)typeid(T).name()+">"; } + std::string toString() const { return "TbVectorReceiverLocal<" + (std::string) typeid(T).name() + ">"; } }; -template<typename T> +template <typename T> class TbVectorSenderLocal : public TbTransmitter<T> { public: - using value_type = T; + using value_type = T; public: - TbVectorSenderLocal(SPtr< TbVectorReceiverLocal< value_type > > receiver) - : TbTransmitter< value_type >(), receiver(receiver) - { - - } - //virtual ~TbVectorSenderLocal() { std::cout<<typeid(*this).name()<<" tot"<<std::endl; } - - bool isLocalTransmitter() const { return true; } - bool isRemoteTransmitter() const { return !this->isLocalTransmitter(); } - - //send buffer wird autom resized - void sendDataSize() - { - assert(receiver!=NULL); - receiver->getData().resize( this->data.size() ); - } - //reiceive braucht nichts machen, da send==receive buffer ;-) - void receiveDataSize() { UB_THROW( UbException(UB_EXARGS,"sendet nur") ); } - - void sendData() - { - assert( this->data.size() == receiver->getData().size() ); - receiver->getData() = this->data; -// for(int i=(int)this->data.size()-1; i>=0; --i) -// receiver->getData()[i]= this->data[i]; - } - value_type& receiveData() { UB_THROW( UbException(UB_EXARGS,"sendet nur") ); } - - std::string toString() const { return "TbVectorSenderLocal<"+(std::string)typeid(T).name()+">"; } + TbVectorSenderLocal(SPtr<TbVectorReceiverLocal<value_type>> receiver) + : TbTransmitter<value_type>(), receiver(receiver) + { + } + // virtual ~TbVectorSenderLocal() { std::cout<<typeid(*this).name()<<" tot"<<std::endl; } + + bool isLocalTransmitter() const { return true; } + bool isRemoteTransmitter() const { return !this->isLocalTransmitter(); } + + // send buffer wird autom resized + void sendDataSize() + { + assert(receiver != NULL); + receiver->getData().resize(this->data.size()); + } + // reiceive braucht nichts machen, da send==receive buffer ;-) + void receiveDataSize() { UB_THROW(UbException(UB_EXARGS, "sendet nur")); } + + void sendData() + { + assert(this->data.size() == receiver->getData().size()); + receiver->getData() = this->data; + // for(int i=(int)this->data.size()-1; i>=0; --i) + // receiver->getData()[i]= this->data[i]; + } + value_type &receiveData() { UB_THROW(UbException(UB_EXARGS, "sendet nur")); } + + std::string toString() const { return "TbVectorSenderLocal<" + (std::string) typeid(T).name() + ">"; } protected: - SPtr< TbVectorReceiverLocal< value_type > > receiver; + SPtr<TbVectorReceiverLocal<value_type>> receiver; }; - -#endif //TOTRANSMITTERLOCAL_H + +#endif // TOTRANSMITTERLOCAL_H diff --git a/src/basics/basics/transmitter/TbTransmitterMpiPool.h b/src/basics/basics/transmitter/TbTransmitterMpiPool.h index aa5a9c16704e8491052abb63520a686bd8336a45..ff170e18e31f6f14beef00e245e724a259a9e753 100644 --- a/src/basics/basics/transmitter/TbTransmitterMpiPool.h +++ b/src/basics/basics/transmitter/TbTransmitterMpiPool.h @@ -9,528 +9,540 @@ #ifdef VF_MPI +#include <iomanip> #include <iostream> +#include <map> #include <sstream> -#include <iomanip> #include <vector> -#include <map> #include <mpi.h> -#include <basics/transmitter/TbTransmitter.h> #include <basics/container/CbVector.h> #include <basics/container/CbVectorPool.h> +#include <basics/transmitter/TbTransmitter.h> #include <PointerDefinitions.h> ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// -//TbCbVectorMpiPoolSender/Receiver -//diese verschicken immer einen VectorPool. Letztlich einen langen vector, -//der eigentlich aus vielen kleinen besteht -//jeder MpiPoolVector hat einen pointer auf die startadresse in diesem vector -//die informationen werden im TbMpiVectorPool verwaltet -//MpiPoolVector verhaelt sich nach aussen hin mit einschraenkungen wie ein std::vector -//und kann somit bei den vector connector verwendet werden -//man kann die klassen theoretisch verallgemeinern. - -template<typename T> class TbCbVectorSenderMpiPool; -template<typename T> class TbCbVectorReceiverMpiPool; +// TbCbVectorMpiPoolSender/Receiver +// diese verschicken immer einen VectorPool. Letztlich einen langen vector, +// der eigentlich aus vielen kleinen besteht +// jeder MpiPoolVector hat einen pointer auf die startadresse in diesem vector +// die informationen werden im TbMpiVectorPool verwaltet +// MpiPoolVector verhaelt sich nach aussen hin mit einschraenkungen wie ein std::vector +// und kann somit bei den vector connector verwendet werden +// man kann die klassen theoretisch verallgemeinern. + +template <typename T> +class TbCbVectorSenderMpiPool; +template <typename T> +class TbCbVectorReceiverMpiPool; /*==================================================================*/ -template<typename T> +template <typename T> class TbCbVectorMpiPool : public CbVectorPool<T> { public: - using MpiPoolPtr = SPtr< TbCbVectorMpiPool< T > >; + using MpiPoolPtr = SPtr<TbCbVectorMpiPool<T>>; - ////////////////////////////////////////////////////////////////////////// - using MpiPoolPtrMap = std::map<std::string, MpiPoolPtr>; - using MpiPoolPtrMapIter = typename MpiPoolPtrMap::iterator; + ////////////////////////////////////////////////////////////////////////// + using MpiPoolPtrMap = std::map<std::string, MpiPoolPtr>; + using MpiPoolPtrMapIter = typename MpiPoolPtrMap::iterator; - //da BasisKlasse templateKlasse ist MUSS man hier die typedefs nochmal wiederholen! - using value_type = typename CbVector<T>::value_type; - using size_type = typename CbVector<T>::size_type; - using Pool = std::vector<value_type>; + // da BasisKlasse templateKlasse ist MUSS man hier die typedefs nochmal wiederholen! + using value_type = typename CbVector<T>::value_type; + using size_type = typename CbVector<T>::size_type; + using Pool = std::vector<value_type>; - using CbVectorKey = std::string; - using CbVectorMap = std::map<CbVectorKey, CbVector<value_type> *>; - using CbVectorMapIter = typename CbVectorMap::iterator; + using CbVectorKey = std::string; + using CbVectorMap = std::map<CbVectorKey, CbVector<value_type> *>; + using CbVectorMapIter = typename CbVectorMap::iterator; - ////////////////////////////////////////////////////////////////////////// - friend class TbCbVectorSenderMpiPool< T >; - friend class TbCbVectorReceiverMpiPool< T >; + ////////////////////////////////////////////////////////////////////////// + friend class TbCbVectorSenderMpiPool<T>; + friend class TbCbVectorReceiverMpiPool<T>; protected: - ////////////////////////////////////////////////////////////////////////// - static MpiPoolPtrMap poolMap; + ////////////////////////////////////////////////////////////////////////// + static MpiPoolPtrMap poolMap; + public: - ////////////////////////////////////////////////////////////////////////// - //STATIC MEMBERS - ////////////////////////////////////////////////////////////////////////// - //createTbCbVectorMpiPool: - // poolKey : Schluessel fuer eindeutige Indizierung in Map - // mpiRemoteRank: mpi-rank des Empfaengers/Senders - // mpiTag : mpi-tag mit dem empfangen/gesendet wird - static MpiPoolPtr createTbCbVectorMpiPool(CbVectorKey poolKey, int mpiRemoteRank, int mpiTag, MPI_Comm comm, size_type startPoolSize = 20000 ) //startPoolSize*sizeof(T)/1024/1024 [MB] - - { - if( poolMap.find(poolKey)!=poolMap.end() ) - { - throw UbException(UB_EXARGS,"es ist bereits ein Pool mit dem key vorhanden!!!"); - } - - //pool erstellen - MpiPoolPtr mpiPool(new TbCbVectorMpiPool<T>(poolKey, mpiRemoteRank, mpiTag, comm, startPoolSize) ); - - //pool "speichern" - TbCbVectorMpiPool< value_type >::poolMap[poolKey] = mpiPool; - - return mpiPool; - } - static void deleteTbCbVectorMpiPool(CbVectorKey poolKey) - { - MpiPoolPtrMapIter it = TbCbVectorMpiPool< value_type >::poolMap.find(poolKey); - if( it==poolMap.end() ) - { - throw UbException(UB_EXARGS,"kein Pool mit dem key vorhanden"); - } - TbCbVectorMpiPool< value_type >::poolMap.erase(it); - } - /*==================================================================*/ - static MpiPoolPtr getTbCbVectorMpiPool(CbVectorKey poolKey) - { - MpiPoolPtrMapIter it; - if( (it=TbCbVectorMpiPool< T >::poolMap.find(poolKey))!=TbCbVectorMpiPool< T >::poolMap.end() ) - { - return it->second; - } - return MpiPoolPtr(); - } - /*==================================================================*/ - static std::string getInfoString() - { - std::stringstream out; - out<<"TbCbVectorMpiPool<"<< typeid( T ).name() << ") - Info:"<<std::endl; - for(MpiPoolPtrMapIter it=poolMap.begin(); it!=poolMap.end(); ++it) - out<<"pool with key(" <<std::setw(15)<<it->first<<") " - <<"stores " <<std::setw(12)<<it->second->getNofStoredVectors() <<" vectors " - <<", elements to transfer = "<<std::setw(15)<<it->second->getPoolSize() - <<" ( "<< it->second->getPoolSize()*sizeof( T ) / ( 1024.0 * 1024.0 ) << " MB )" <<std::endl; - return out.str(); - } - /*==================================================================*/ - // checks if all vectors have one to one pool-entries - static bool consistencyCheck() - { - for(MpiPoolPtrMapIter it=poolMap.begin(); it!=poolMap.end(); ++it) - { - if( !it->second-> CbVectorPool<T>::consistencyCheck() ) - { - return false; - } - } - - return true; - } - ////////////////////////////////////////////////////////////////////////// - static void eraseMap() - { - poolMap.clear(); - } + ////////////////////////////////////////////////////////////////////////// + // STATIC MEMBERS + ////////////////////////////////////////////////////////////////////////// + // createTbCbVectorMpiPool: + // poolKey : Schluessel fuer eindeutige Indizierung in Map + // mpiRemoteRank: mpi-rank des Empfaengers/Senders + // mpiTag : mpi-tag mit dem empfangen/gesendet wird + static MpiPoolPtr createTbCbVectorMpiPool(CbVectorKey poolKey, int mpiRemoteRank, int mpiTag, MPI_Comm comm, + size_type startPoolSize = 20000) // startPoolSize*sizeof(T)/1024/1024 [MB] + + { + if (poolMap.find(poolKey) != poolMap.end()) { + throw UbException(UB_EXARGS, "es ist bereits ein Pool mit dem key vorhanden!!!"); + } + + // pool erstellen + MpiPoolPtr mpiPool(new TbCbVectorMpiPool<T>(poolKey, mpiRemoteRank, mpiTag, comm, startPoolSize)); + + // pool "speichern" + TbCbVectorMpiPool<value_type>::poolMap[poolKey] = mpiPool; + + return mpiPool; + } + static void deleteTbCbVectorMpiPool(CbVectorKey poolKey) + { + MpiPoolPtrMapIter it = TbCbVectorMpiPool<value_type>::poolMap.find(poolKey); + if (it == poolMap.end()) { + throw UbException(UB_EXARGS, "kein Pool mit dem key vorhanden"); + } + TbCbVectorMpiPool<value_type>::poolMap.erase(it); + } + /*==================================================================*/ + static MpiPoolPtr getTbCbVectorMpiPool(CbVectorKey poolKey) + { + MpiPoolPtrMapIter it; + if ((it = TbCbVectorMpiPool<T>::poolMap.find(poolKey)) != TbCbVectorMpiPool<T>::poolMap.end()) { + return it->second; + } + return MpiPoolPtr(); + } + /*==================================================================*/ + static std::string getInfoString() + { + std::stringstream out; + out << "TbCbVectorMpiPool<" << typeid(T).name() << ") - Info:" << std::endl; + for (MpiPoolPtrMapIter it = poolMap.begin(); it != poolMap.end(); ++it) + out << "pool with key(" << std::setw(15) << it->first << ") " + << "stores " << std::setw(12) << it->second->getNofStoredVectors() << " vectors " + << ", elements to transfer = " << std::setw(15) << it->second->getPoolSize() << " ( " + << it->second->getPoolSize() * sizeof(T) / (1024.0 * 1024.0) << " MB )" << std::endl; + return out.str(); + } + /*==================================================================*/ + // checks if all vectors have one to one pool-entries + static bool consistencyCheck() + { + for (MpiPoolPtrMapIter it = poolMap.begin(); it != poolMap.end(); ++it) { + if (!it->second->CbVectorPool<T>::consistencyCheck()) { + return false; + } + } + + return true; + } + ////////////////////////////////////////////////////////////////////////// + static void eraseMap() { poolMap.clear(); } + protected: - ////////////////////////////////////////////////////////////////////////// - TbCbVectorMpiPool(CbVectorKey poolKey, int mpiRemoteRank, int mpiTag, MPI_Comm comm, size_type startPoolSize ) - : CbVectorPool< value_type >( startPoolSize ) - , poolKey(poolKey) - , nofStoredVectors(0) //=Anzahl an Vectoren im Pool, wird bei send/receiveDataOrder gesetzt - , counterPrepareReceiveDataOrder(0) - , counterSendDataOrder(0) - , counterReceiveDataOrder(0) - , counterPrepareForReceive(0) - , counterReceive(0) - , counterPrepareForSend(0) - , counterSend(0) - , comm(comm) - , receiveRequest(MPI_REQUEST_NULL) - //, sendRequest(MPI_REQUEST_NULL) - , mpiRemoteRank(mpiRemoteRank) - , mpiTag(mpiTag) - { - if ( (std::string)typeid(value_type).name()==(std::string)typeid(double).name() ) mpiDataType = MPI_DOUBLE; - else if( (std::string)typeid(value_type).name()==(std::string)typeid(float).name() ) mpiDataType = MPI_FLOAT; - else if( (std::string)typeid(value_type).name()==(std::string)typeid(int).name() ) mpiDataType = MPI_INT; - else throw UbException(UB_EXARGS,"no MpiDataType for T"+(std::string)typeid(T).name()); - - for (int i = 0; i < 3; i++) - { - sendRequest[i] = MPI_REQUEST_NULL; - } - } + ////////////////////////////////////////////////////////////////////////// + TbCbVectorMpiPool(CbVectorKey poolKey, int mpiRemoteRank, int mpiTag, MPI_Comm comm, size_type startPoolSize) + : CbVectorPool<value_type>(startPoolSize), poolKey(poolKey), + nofStoredVectors(0) //=Anzahl an Vectoren im Pool, wird bei send/receiveDataOrder gesetzt + , + counterPrepareReceiveDataOrder(0), counterSendDataOrder(0), counterReceiveDataOrder(0), + counterPrepareForReceive(0), counterReceive(0), counterPrepareForSend(0), counterSend(0), comm(comm), + receiveRequest(MPI_REQUEST_NULL) + //, sendRequest(MPI_REQUEST_NULL) + , + mpiRemoteRank(mpiRemoteRank), mpiTag(mpiTag) + { + if ((std::string) typeid(value_type).name() == (std::string) typeid(double).name()) + mpiDataType = MPI_DOUBLE; + else if ((std::string) typeid(value_type).name() == (std::string) typeid(float).name()) + mpiDataType = MPI_FLOAT; + else if ((std::string) typeid(value_type).name() == (std::string) typeid(int).name()) + mpiDataType = MPI_INT; + else + throw UbException(UB_EXARGS, "no MpiDataType for T" + (std::string) typeid(T).name()); + + for (int i = 0; i < 3; i++) { + sendRequest[i] = MPI_REQUEST_NULL; + } + } public: - /*==================================================================*/ - //returns key of Pool in MpiPoolMap - CbVectorKey getPoolKey() const { return this->poolKey; } - /*==================================================================*/ - //returns rank of process pool data will be send to/received from - int getRemoteRank() const { return this->mpiRemoteRank; } - /*==================================================================*/ - //returns tag of process pool data will be send to/received from - int getRemoteTag() const { return this->mpiTag; } + /*==================================================================*/ + // returns key of Pool in MpiPoolMap + CbVectorKey getPoolKey() const { return this->poolKey; } + /*==================================================================*/ + // returns rank of process pool data will be send to/received from + int getRemoteRank() const { return this->mpiRemoteRank; } + /*==================================================================*/ + // returns tag of process pool data will be send to/received from + int getRemoteTag() const { return this->mpiTag; } protected: - /*==================================================================*/ - void sendDataOrder() - { - counterSendDataOrder++; - if(counterSendDataOrder==this->cbVectorMap.size()) - { - //allg.: bei MPI muss man darauf achten, dass bei unblocked operationen die puffer (aus dem oder in den - //geschrieben wird auch noch vorhanden sind!!! wuerde man hier z.B. einen lokalen vector mit Isend() los- - //schicken, dann wurde der scope verlassen werden und der vector evtl geloescht werden, bevor mpi den - //vorgang abgeschlossen hat!!! -> tmpOrderVec ist class-member!!! - unsigned nofElements = (unsigned)this->cbVectorMap.size()*3+1; - tmpSendOrderVec.resize(nofElements);//std::vector< unsigned > vec(nofElements); - unsigned index = 0; - tmpSendOrderVec[index++] = (unsigned)this->pool.size(); //= laenge des vectors - if(this->nextCbVectorStartIndexInPool != this->pool.size()) throw UbException(UB_EXARGS,"an dieser Stelle sollten nextStartIndex und pool.size() identisch sein!!!"); - for(CbVectorMapIter it = this->cbVectorMap.begin(); it!=this->cbVectorMap.end(); ++it) - { - CbVectorKey vectorKey; - size_type dataSize=0, startIndexInPool=0; - this->getCbVectorData(*it->second/*vec*/, vectorKey, startIndexInPool, dataSize ); - if(it->first != vectorKey) throw UbException(UB_EXARGS,"key mismatch!"); - - tmpSendOrderKeyVec += vectorKey; //vectorKey == allocator.getAllocatorKey() - tmpSendOrderVec[index++] = (unsigned)vectorKey.length(); - tmpSendOrderVec[index++] = (unsigned)startIndexInPool; //startIndex in poolVector - tmpSendOrderVec[index++] = (unsigned)dataSize; //dataSize - } - - MPI_Isend(&tmpSendOrderVec[0],(int)tmpSendOrderVec.size(), MPI_UNSIGNED, mpiRemoteRank, mpiTag, comm, &sendRequest[0]); - - tmpSendOrderKeyVecLength = (unsigned)tmpSendOrderKeyVec.length(); - MPI_Isend(&tmpSendOrderKeyVecLength,1, MPI_UNSIGNED, mpiRemoteRank, mpiTag, comm, &sendRequest[1]); - MPI_Isend((char *)tmpSendOrderKeyVec.c_str(),tmpSendOrderKeyVecLength, MPI_CHAR, mpiRemoteRank, mpiTag, comm, &sendRequest[2]); - - - counterSendDataOrder=0; - - nofStoredVectors = this->cbVectorMap.size(); - - UBLOG(logDEBUG5, "TbCbVectorMpiPool::sendDataOrder()"<<" mpiRemoteRank="<<mpiRemoteRank<<" mpiTag="<<mpiTag); + /*==================================================================*/ + void sendDataOrder() + { + counterSendDataOrder++; + if (counterSendDataOrder == this->cbVectorMap.size()) { + // allg.: bei MPI muss man darauf achten, dass bei unblocked operationen die puffer (aus dem oder in den + // geschrieben wird auch noch vorhanden sind!!! wuerde man hier z.B. einen lokalen vector mit Isend() los- + // schicken, dann wurde der scope verlassen werden und der vector evtl geloescht werden, bevor mpi den + // vorgang abgeschlossen hat!!! -> tmpOrderVec ist class-member!!! + unsigned nofElements = (unsigned)this->cbVectorMap.size() * 3 + 1; + tmpSendOrderVec.resize(nofElements); // std::vector< unsigned > vec(nofElements); + unsigned index = 0; + tmpSendOrderVec[index++] = (unsigned)this->pool.size(); //= laenge des vectors + if (this->nextCbVectorStartIndexInPool != this->pool.size()) + throw UbException(UB_EXARGS, + "an dieser Stelle sollten nextStartIndex und pool.size() identisch sein!!!"); + for (CbVectorMapIter it = this->cbVectorMap.begin(); it != this->cbVectorMap.end(); ++it) { + CbVectorKey vectorKey; + size_type dataSize = 0, startIndexInPool = 0; + this->getCbVectorData(*it->second /*vec*/, vectorKey, startIndexInPool, dataSize); + if (it->first != vectorKey) + throw UbException(UB_EXARGS, "key mismatch!"); + + tmpSendOrderKeyVec += vectorKey; // vectorKey == allocator.getAllocatorKey() + tmpSendOrderVec[index++] = (unsigned)vectorKey.length(); + tmpSendOrderVec[index++] = (unsigned)startIndexInPool; // startIndex in poolVector + tmpSendOrderVec[index++] = (unsigned)dataSize; // dataSize + } + + MPI_Isend(&tmpSendOrderVec[0], (int)tmpSendOrderVec.size(), MPI_UNSIGNED, mpiRemoteRank, mpiTag, comm, + &sendRequest[0]); + + tmpSendOrderKeyVecLength = (unsigned)tmpSendOrderKeyVec.length(); + MPI_Isend(&tmpSendOrderKeyVecLength, 1, MPI_UNSIGNED, mpiRemoteRank, mpiTag, comm, &sendRequest[1]); + MPI_Isend((char *)tmpSendOrderKeyVec.c_str(), tmpSendOrderKeyVecLength, MPI_CHAR, mpiRemoteRank, mpiTag, + comm, &sendRequest[2]); + + counterSendDataOrder = 0; + + nofStoredVectors = this->cbVectorMap.size(); + + UBLOG(logDEBUG5, "TbCbVectorMpiPool::sendDataOrder()" + << " mpiRemoteRank=" << mpiRemoteRank << " mpiTag=" << mpiTag); #ifdef _DEBUG - orgPoolVectorStartPointer = &this->pool[0]; + orgPoolVectorStartPointer = &this->pool[0]; #endif - } - } - /*==================================================================*/ - void receiveDataOrder() - { - counterReceiveDataOrder++; - if(counterReceiveDataOrder==this->cbVectorMap.size()) - { - //receiveRequest.Wait(); - unsigned nofElements = (unsigned)this->cbVectorMap.size()*3+1; //map MUSS auf beiden seiten gleich gross sein, sonst hat man ein grundsaetzliches problem ;-) - - UBLOG(logDEBUG5, "TbCbVectorMpiPool::receiveDataOrder()"<<" mpiRemoteRank="<<mpiRemoteRank<<" mpiTag="<<mpiTag); - - std::vector< unsigned > tmpRecvOrderVec; - tmpRecvOrderVec.resize(nofElements); - - std::vector<char> tmpRecvOrderKeyVec; - - //MPI_Status status; - MPI_Recv(&tmpRecvOrderVec[0], nofElements, MPI_UNSIGNED, mpiRemoteRank, mpiTag, comm, MPI_STATUS_IGNORE); - - unsigned rcount; - MPI_Recv(&rcount, 1, MPI_UNSIGNED, mpiRemoteRank, mpiTag, comm, MPI_STATUS_IGNORE); - tmpRecvOrderKeyVec.resize(rcount); - MPI_Recv(&tmpRecvOrderKeyVec[0], rcount, MPI_CHAR, mpiRemoteRank, mpiTag, comm, MPI_STATUS_IGNORE); - - if(nofElements!=(unsigned)tmpRecvOrderVec.size()) - throw UbException(UB_EXARGS,"error... vec size stimmt nicht"); - - unsigned index = 0; - size_type index2 = 0; - this->nextCbVectorStartIndexInPool = tmpRecvOrderVec[index++]; //= laenge des vectors - this->pool.resize(this->nextCbVectorStartIndexInPool); - CbVectorMapIter it = this->cbVectorMap.begin(); - for(/*index*/; index<nofElements; index+=3, ++it) - { - size_type vectorKeyLength = (size_type)tmpRecvOrderVec.at(index ); - size_type startIndexInPool = (size_type)tmpRecvOrderVec.at(index+1); - size_type dataSize = (size_type)tmpRecvOrderVec.at(index+2); - CbVectorKey vectorKey = CbVectorKey(&tmpRecvOrderKeyVec[index2], vectorKeyLength); - index2 += vectorKeyLength; - - //if(it==this->cbVectorMap.end() || it->first != vectorKey ) - //throw UbException(UB_EXARGS, "entweder hat map nicht die gleiche reihenfolge oder vectorKey = "+UbSystem::toString(vectorKey)+" nicht vorhanden"); - if (it==this->cbVectorMap.end()) - throw UbException(UB_EXARGS,"map ist leer"); - else if (it->first != vectorKey) - throw UbException(UB_EXARGS, "vectorKey = "+UbSystem::toString(vectorKey)+" nicht vorhanden it->first =" + UbSystem::toString(it->first)); - - this->setCbVectorData(*it->second/*vec*/, vectorKey, startIndexInPool, dataSize ); - - } - if(it!=this->cbVectorMap.end()) - throw UbException(UB_EXARGS,"error... in der map sind scheinbar noch weiter elemente vorhanden, die es auf der send seite nicht gibt..."); - - counterReceiveDataOrder = 0; - nofStoredVectors = this->cbVectorMap.size(); + } + } + /*==================================================================*/ + void receiveDataOrder() + { + counterReceiveDataOrder++; + if (counterReceiveDataOrder == this->cbVectorMap.size()) { + // receiveRequest.Wait(); + unsigned nofElements = + (unsigned)this->cbVectorMap.size() * 3 + + 1; // map MUSS auf beiden seiten gleich gross sein, sonst hat man ein grundsaetzliches problem ;-) + + UBLOG(logDEBUG5, "TbCbVectorMpiPool::receiveDataOrder()" + << " mpiRemoteRank=" << mpiRemoteRank << " mpiTag=" << mpiTag); + + std::vector<unsigned> tmpRecvOrderVec; + tmpRecvOrderVec.resize(nofElements); + + std::vector<char> tmpRecvOrderKeyVec; + + // MPI_Status status; + MPI_Recv(&tmpRecvOrderVec[0], nofElements, MPI_UNSIGNED, mpiRemoteRank, mpiTag, comm, MPI_STATUS_IGNORE); + + unsigned rcount; + MPI_Recv(&rcount, 1, MPI_UNSIGNED, mpiRemoteRank, mpiTag, comm, MPI_STATUS_IGNORE); + tmpRecvOrderKeyVec.resize(rcount); + MPI_Recv(&tmpRecvOrderKeyVec[0], rcount, MPI_CHAR, mpiRemoteRank, mpiTag, comm, MPI_STATUS_IGNORE); + + if (nofElements != (unsigned)tmpRecvOrderVec.size()) + throw UbException(UB_EXARGS, "error... vec size stimmt nicht"); + + unsigned index = 0; + size_type index2 = 0; + this->nextCbVectorStartIndexInPool = tmpRecvOrderVec[index++]; //= laenge des vectors + this->pool.resize(this->nextCbVectorStartIndexInPool); + CbVectorMapIter it = this->cbVectorMap.begin(); + for (/*index*/; index < nofElements; index += 3, ++it) { + size_type vectorKeyLength = (size_type)tmpRecvOrderVec.at(index); + size_type startIndexInPool = (size_type)tmpRecvOrderVec.at(index + 1); + size_type dataSize = (size_type)tmpRecvOrderVec.at(index + 2); + CbVectorKey vectorKey = CbVectorKey(&tmpRecvOrderKeyVec[index2], vectorKeyLength); + index2 += vectorKeyLength; + + // if(it==this->cbVectorMap.end() || it->first != vectorKey ) + // throw UbException(UB_EXARGS, "entweder hat map nicht die gleiche reihenfolge oder vectorKey = + // "+UbSystem::toString(vectorKey)+" nicht vorhanden"); + if (it == this->cbVectorMap.end()) + throw UbException(UB_EXARGS, "map ist leer"); + else if (it->first != vectorKey) + throw UbException(UB_EXARGS, "vectorKey = " + UbSystem::toString(vectorKey) + + " nicht vorhanden it->first =" + UbSystem::toString(it->first)); + + this->setCbVectorData(*it->second /*vec*/, vectorKey, startIndexInPool, dataSize); + } + if (it != this->cbVectorMap.end()) + throw UbException(UB_EXARGS, "error... in der map sind scheinbar noch weiter elemente vorhanden, die " + "es auf der send seite nicht gibt..."); + + counterReceiveDataOrder = 0; + nofStoredVectors = this->cbVectorMap.size(); #ifdef _DEBUG - orgPoolVectorStartPointer = &this->pool[0]; + orgPoolVectorStartPointer = &this->pool[0]; #endif - } - } - /*==================================================================*/ - void prepareForSendData() - { - //da sendDataOrder einen request verwendet muss man hier immer abfragen - if(counterPrepareForSend==0) - { - UBLOG(logDEBUG5, "TbCbVectorMpiPool::prepareForSendData():start"<<" mpiRemoteRank="<<mpiRemoteRank<<" mpiTag="<<mpiTag); - //if(sendRequest != MPI_REQUEST_NULL) MPI_Wait(&sendRequest, MPI_STATUS_IGNORE); - if(sendRequest[2] != MPI_REQUEST_NULL) MPI_Waitall(3, sendRequest, MPI_STATUS_IGNORE); - UBLOG(logDEBUG5, "TbCbVectorMpiPool::prepareForSendData():end"<<" mpiRemoteRank="<<mpiRemoteRank<<" mpiTag="<<mpiTag); - } - - counterPrepareForSend++; - - if(counterPrepareForSend==nofStoredVectors) - { - counterPrepareForSend=0; - } - - - //A - non blocking - ////der ERSTE is entscheidend - ////Grund: wenn man - //// for(all trans) { trans->prepare(); trans->fillBuffer(); } - //// aufruft, dann wuerde u.U. der Buffer neu beschrieben werden obwohl noch nicht versendet wurde!!! - //counterPrepareForSend++; - //if(counterPrepareForSend==1) - //{ - // if(sendRequest != MPI::REQUEST_NULL) sendRequest.Wait(); - //} - // - //if(counterPrepareForSend==nofStoredVectors) - // counterPrepareForSend=0; - } - /*==================================================================*/ - void sendData() - { - //A - non blocking - //der LETZTE is entscheidend - //counterSend++; - //if(counterSend==nofStoredVectors) - //{ - // //std::cout<<"Isend von "<<(int)nextStartIndex<<"elementen von "<<mpiRemoteRank<<" mit tag="<<mpiTag<<std::endl; - // sendRequest = comm.Isend(&pool[0],(int)nextCbVectorStartIndexInPool, mpiDataType, mpiRemoteRank, mpiTag); - // counterSend=0; - //} - //B - blocking - //der LETZTE is entscheidend - counterSend++; - if(counterSend==nofStoredVectors) - { - //std::cout<<"Isend von "<<(int)nextStartIndex<<"elementen von "<<mpiRemoteRank<<" mit tag="<<mpiTag<<std::endl; - UBLOG(logDEBUG5, "TbCbVectorMpiPool::sendData():start"<<" mpiRemoteRank="<<mpiRemoteRank<<" mpiTag="<<mpiTag); - - //synchronous send - //comm.Ssend(&this->pool[0],(int)this->nextCbVectorStartIndexInPool, mpiDataType, mpiRemoteRank, mpiTag); + } + } + /*==================================================================*/ + void prepareForSendData() + { + // da sendDataOrder einen request verwendet muss man hier immer abfragen + if (counterPrepareForSend == 0) { + UBLOG(logDEBUG5, "TbCbVectorMpiPool::prepareForSendData():start" + << " mpiRemoteRank=" << mpiRemoteRank << " mpiTag=" << mpiTag); + // if(sendRequest != MPI_REQUEST_NULL) MPI_Wait(&sendRequest, MPI_STATUS_IGNORE); + if (sendRequest[2] != MPI_REQUEST_NULL) + MPI_Waitall(3, sendRequest, MPI_STATUS_IGNORE); + UBLOG(logDEBUG5, "TbCbVectorMpiPool::prepareForSendData():end" + << " mpiRemoteRank=" << mpiRemoteRank << " mpiTag=" << mpiTag); + } + + counterPrepareForSend++; + + if (counterPrepareForSend == nofStoredVectors) { + counterPrepareForSend = 0; + } + + // A - non blocking + ////der ERSTE is entscheidend + ////Grund: wenn man + //// for(all trans) { trans->prepare(); trans->fillBuffer(); } + //// aufruft, dann wuerde u.U. der Buffer neu beschrieben werden obwohl noch nicht versendet wurde!!! + // counterPrepareForSend++; + // if(counterPrepareForSend==1) + //{ + // if(sendRequest != MPI::REQUEST_NULL) sendRequest.Wait(); + //} + // + // if(counterPrepareForSend==nofStoredVectors) + // counterPrepareForSend=0; + } + /*==================================================================*/ + void sendData() + { + // A - non blocking + // der LETZTE is entscheidend + // counterSend++; + // if(counterSend==nofStoredVectors) + //{ + // //std::cout<<"Isend von "<<(int)nextStartIndex<<"elementen von "<<mpiRemoteRank<<" mit + // tag="<<mpiTag<<std::endl; sendRequest = comm.Isend(&pool[0],(int)nextCbVectorStartIndexInPool, mpiDataType, + // mpiRemoteRank, mpiTag); counterSend=0; + //} + // B - blocking + // der LETZTE is entscheidend + counterSend++; + if (counterSend == nofStoredVectors) { + // std::cout<<"Isend von "<<(int)nextStartIndex<<"elementen von "<<mpiRemoteRank<<" mit + // tag="<<mpiTag<<std::endl; + UBLOG(logDEBUG5, "TbCbVectorMpiPool::sendData():start" + << " mpiRemoteRank=" << mpiRemoteRank << " mpiTag=" << mpiTag); + + // synchronous send + // comm.Ssend(&this->pool[0],(int)this->nextCbVectorStartIndexInPool, mpiDataType, mpiRemoteRank, mpiTag); #ifdef _DEBUG - if(this->orgPoolVectorStartPointer != &this->pool[0] ) throw UbException(UB_EXARGS, "ups, pool array adress changed - unknown behavoir"); + if (this->orgPoolVectorStartPointer != &this->pool[0]) + throw UbException(UB_EXARGS, "ups, pool array adress changed - unknown behavoir"); #endif - //standard send - MPI_Send(&this->pool[0],(int)this->nextCbVectorStartIndexInPool, mpiDataType, mpiRemoteRank, mpiTag, comm); - UBLOG(logDEBUG5, "TbCbVectorMpiPool::sendData():end"<<" mpiRemoteRank="<<mpiRemoteRank<<" mpiTag="<<mpiTag); -//////////////////////////////////////////////////////////////////////////////////////////// -//DEBUG/////////////////////////////////////// - //int irank; - //MPI_Comm_rank(MPI_COMM_WORLD, &irank); - //std::cout << "MPI_Send: " << irank << " " << mpiRemoteRank << " " <<mpiTag<<std::endl; -/////////////////////////////////////////////////// - counterSend=0; - } - } - /*==================================================================*/ - void prepareForReceiveData() - { - //A - non blocking - //sobald der Letzte kann man den den request holen. - //andernfalls kann nicht gewaehrleistet werden, dass evtl noch mit dem buffer gearbeitet wird!!! - counterPrepareForReceive++; - if(counterPrepareForReceive==this->nofStoredVectors) - { - UBLOG(logDEBUG5, "TbCbVectorMpiPool::prepareForReceiveData():start"<<" mpiRemoteRank="<<mpiRemoteRank<<" mpiTag="<<mpiTag); + // standard send + MPI_Send(&this->pool[0], (int)this->nextCbVectorStartIndexInPool, mpiDataType, mpiRemoteRank, mpiTag, comm); + UBLOG(logDEBUG5, "TbCbVectorMpiPool::sendData():end" + << " mpiRemoteRank=" << mpiRemoteRank << " mpiTag=" << mpiTag); + //////////////////////////////////////////////////////////////////////////////////////////// + // DEBUG/////////////////////////////////////// + // int irank; + // MPI_Comm_rank(MPI_COMM_WORLD, &irank); + // std::cout << "MPI_Send: " << irank << " " << mpiRemoteRank << " " <<mpiTag<<std::endl; + /////////////////////////////////////////////////// + counterSend = 0; + } + } + /*==================================================================*/ + void prepareForReceiveData() + { + // A - non blocking + // sobald der Letzte kann man den den request holen. + // andernfalls kann nicht gewaehrleistet werden, dass evtl noch mit dem buffer gearbeitet wird!!! + counterPrepareForReceive++; + if (counterPrepareForReceive == this->nofStoredVectors) { + UBLOG(logDEBUG5, "TbCbVectorMpiPool::prepareForReceiveData():start" + << " mpiRemoteRank=" << mpiRemoteRank << " mpiTag=" << mpiTag); #ifdef _DEBUG - if(this->orgPoolVectorStartPointer != &this->pool[0] ) throw UbException(UB_EXARGS, "ups, pool array adress changed - unknown behavoir"); + if (this->orgPoolVectorStartPointer != &this->pool[0]) + throw UbException(UB_EXARGS, "ups, pool array adress changed - unknown behavoir"); #endif - MPI_Irecv(&this->pool[0],(int)this->nextCbVectorStartIndexInPool, mpiDataType, mpiRemoteRank, mpiTag, comm, &receiveRequest); - UBLOG(logDEBUG5, "TbCbVectorMpiPool::prepareForReceiveData():end"<<" mpiRemoteRank="<<mpiRemoteRank<<" mpiTag="<<mpiTag); - counterPrepareForReceive=0; - } - } - /*==================================================================*/ - void receiveData() - { - //A - non blocking - //sobald der ERSTE reinkommt muss man warten, bis received wurde!!! - //denn erst anschliessend stehen die empfangenen daten zur verfuegung - if(counterReceive==0) - { - UBLOG(logDEBUG5, "TbCbVectorMpiPool::receiveData():start"<<" mpiRemoteRank="<<mpiRemoteRank<<" mpiTag="<<mpiTag); - MPI_Wait(&receiveRequest, MPI_STATUS_IGNORE); - UBLOG(logDEBUG5, "TbCbVectorMpiPool::receiveData():end"<<" mpiRemoteRank="<<mpiRemoteRank<<" mpiTag="<<mpiTag); - } - counterReceive++; - if(counterReceive==this->nofStoredVectors) //alle receiver waren hier - { - counterReceive=0; - } - - ////B - blocking - ////sobald der ERSTE reinkommt muss man warten, bis received wurde!!! - ////denn erst anschliessend stehen die empfangenen daten zur verfuegung - //if(counterReceive==0) - //{ - // comm.Recv(&this->pool[0],(int)this->nextCbVectorStartIndexInPool, mpiDataType, mpiRemoteRank, mpiTag); - //} - //counterReceive++; - //if(counterReceive==this->nofStoredVectors) //alle receiver waren hier - // counterReceive=0; - } + MPI_Irecv(&this->pool[0], (int)this->nextCbVectorStartIndexInPool, mpiDataType, mpiRemoteRank, mpiTag, comm, + &receiveRequest); + UBLOG(logDEBUG5, "TbCbVectorMpiPool::prepareForReceiveData():end" + << " mpiRemoteRank=" << mpiRemoteRank << " mpiTag=" << mpiTag); + counterPrepareForReceive = 0; + } + } + /*==================================================================*/ + void receiveData() + { + // A - non blocking + // sobald der ERSTE reinkommt muss man warten, bis received wurde!!! + // denn erst anschliessend stehen die empfangenen daten zur verfuegung + if (counterReceive == 0) { + UBLOG(logDEBUG5, "TbCbVectorMpiPool::receiveData():start" + << " mpiRemoteRank=" << mpiRemoteRank << " mpiTag=" << mpiTag); + MPI_Wait(&receiveRequest, MPI_STATUS_IGNORE); + UBLOG(logDEBUG5, "TbCbVectorMpiPool::receiveData():end" + << " mpiRemoteRank=" << mpiRemoteRank << " mpiTag=" << mpiTag); + } + counterReceive++; + if (counterReceive == this->nofStoredVectors) // alle receiver waren hier + { + counterReceive = 0; + } + + ////B - blocking + ////sobald der ERSTE reinkommt muss man warten, bis received wurde!!! + ////denn erst anschliessend stehen die empfangenen daten zur verfuegung + // if(counterReceive==0) + //{ + // comm.Recv(&this->pool[0],(int)this->nextCbVectorStartIndexInPool, mpiDataType, mpiRemoteRank, mpiTag); + //} + // counterReceive++; + // if(counterReceive==this->nofStoredVectors) //alle receiver waren hier + // counterReceive=0; + } protected: - CbVectorKey poolKey; //eindeutiger schluessel fuer pool - size_type nofStoredVectors; - - size_type counterPrepareReceiveDataOrder; - size_type counterSendDataOrder; - size_type counterReceiveDataOrder; - size_type counterPrepareForReceive; - size_type counterReceive; - size_type counterPrepareForSend; - size_type counterSend; - - std::vector< unsigned > tmpSendOrderVec; //wird zur temp speicherung der anordnung benoetigt - std::string tmpSendOrderKeyVec; - unsigned tmpSendOrderKeyVecLength; - - MPI_Comm comm; - MPI_Request receiveRequest; - //MPI_Request sendRequest; - MPI_Request sendRequest[3]; - //MPI_Status sendStatus; - //MPI_Status receiveStatus; - MPI_Datatype mpiDataType; - - int mpiRemoteRank, mpiTag; + CbVectorKey poolKey; // eindeutiger schluessel fuer pool + size_type nofStoredVectors; + + size_type counterPrepareReceiveDataOrder; + size_type counterSendDataOrder; + size_type counterReceiveDataOrder; + size_type counterPrepareForReceive; + size_type counterReceive; + size_type counterPrepareForSend; + size_type counterSend; + + std::vector<unsigned> tmpSendOrderVec; // wird zur temp speicherung der anordnung benoetigt + std::string tmpSendOrderKeyVec; + unsigned tmpSendOrderKeyVecLength; + + MPI_Comm comm; + MPI_Request receiveRequest; + // MPI_Request sendRequest; + MPI_Request sendRequest[3]; + // MPI_Status sendStatus; + // MPI_Status receiveStatus; + MPI_Datatype mpiDataType; + + int mpiRemoteRank, mpiTag; #ifdef _DEBUG - T* orgPoolVectorStartPointer; + T *orgPoolVectorStartPointer; #endif }; -template<typename T> +template <typename T> typename TbCbVectorMpiPool<T>::MpiPoolPtrMap TbCbVectorMpiPool<T>::poolMap; ////////////////////////////////////////////////////////////////////////// // TbSenderMpiPool ////////////////////////////////////////////////////////////////////////// -template<typename T> -class TbCbVectorSenderMpiPool : public TbTransmitter< CbVector< T > > +template <typename T> +class TbCbVectorSenderMpiPool : public TbTransmitter<CbVector<T>> { public: - using value_type = CbVector<T>; + using value_type = CbVector<T>; public: - TbCbVectorSenderMpiPool(std::string cbVectorKey, TbCbVectorMpiPool< T >* mpiVectorPool) - : mpiVectorPool(mpiVectorPool) - { - this->getData().setAllocator( new CbVectorAllocatorPool<T>(cbVectorKey,this->mpiVectorPool) ); - } - ~TbCbVectorSenderMpiPool() override - { - if( this->mpiVectorPool->getNofStoredVectors()==1 ) //last entry! - { - TbCbVectorMpiPool< T >::deleteTbCbVectorMpiPool(this->mpiVectorPool->getPoolKey()); - } - } - - bool isLocalTransmitter() const override { return false; } - bool isRemoteTransmitter() const override { return !this->isLocalTransmitter(); } - - void sendDataSize() override { this->mpiVectorPool->sendDataOrder(); } - void receiveDataSize() override { throw UbException(UB_EXARGS,"TbMpiPoolSender sends only"); } - CbVector< T >& receiveData() override { throw UbException(UB_EXARGS,"TbMpiPoolSender sends only"); } - void prepareForSend() override { this->mpiVectorPool->prepareForSendData(); } - void sendData() override { this->mpiVectorPool->sendData(); } - - //info-section (usable for remote transmitter) - int getSendTbRank() const { return this->mpiVectorPool->getRemoteRank(); } - int getSendTbTag() const { return this->mpiVectorPool->getRemoteTag(); } - int getRecvFromRank() const override { throw UbException(UB_EXARGS,"TbCbVectorSenderMpiPool sends only"); } - int getRecvFromTag() const override { throw UbException(UB_EXARGS,"TbCbVectorSenderMpiPool sends only"); } - - std::string toString() const override { return "TbCbVectorSenderMpiPool<"+(std::string)typeid(T).name()+" to rank (tag)"+UbSystem::toString(getSendTbRank())+"("+UbSystem::toString(getSendTbTag())+")"; } + TbCbVectorSenderMpiPool(std::string cbVectorKey, TbCbVectorMpiPool<T> *mpiVectorPool) : mpiVectorPool(mpiVectorPool) + { + this->getData().setAllocator(new CbVectorAllocatorPool<T>(cbVectorKey, this->mpiVectorPool)); + } + ~TbCbVectorSenderMpiPool() override + { + if (this->mpiVectorPool->getNofStoredVectors() == 1) // last entry! + { + TbCbVectorMpiPool<T>::deleteTbCbVectorMpiPool(this->mpiVectorPool->getPoolKey()); + } + } + + bool isLocalTransmitter() const override { return false; } + bool isRemoteTransmitter() const override { return !this->isLocalTransmitter(); } + + void sendDataSize() override { this->mpiVectorPool->sendDataOrder(); } + void receiveDataSize() override { throw UbException(UB_EXARGS, "TbMpiPoolSender sends only"); } + CbVector<T> &receiveData() override { throw UbException(UB_EXARGS, "TbMpiPoolSender sends only"); } + void prepareForSend() override { this->mpiVectorPool->prepareForSendData(); } + void sendData() override { this->mpiVectorPool->sendData(); } + + // info-section (usable for remote transmitter) + int getSendTbRank() const { return this->mpiVectorPool->getRemoteRank(); } + int getSendTbTag() const { return this->mpiVectorPool->getRemoteTag(); } + int getRecvFromRank() const override { throw UbException(UB_EXARGS, "TbCbVectorSenderMpiPool sends only"); } + int getRecvFromTag() const override { throw UbException(UB_EXARGS, "TbCbVectorSenderMpiPool sends only"); } + + std::string toString() const override + { + return "TbCbVectorSenderMpiPool<" + (std::string) typeid(T).name() + " to rank (tag)" + + UbSystem::toString(getSendTbRank()) + "(" + UbSystem::toString(getSendTbTag()) + ")"; + } protected: - TbCbVectorMpiPool<T>* mpiVectorPool; + TbCbVectorMpiPool<T> *mpiVectorPool; }; - /*==================================================================*/ -template<typename T> -class TbCbVectorReceiverMpiPool : public TbTransmitter< CbVector< T > > +template <typename T> +class TbCbVectorReceiverMpiPool : public TbTransmitter<CbVector<T>> { public: - using value_type = CbVector<T>; + using value_type = CbVector<T>; public: - TbCbVectorReceiverMpiPool(std::string cbVectorKey, TbCbVectorMpiPool< T >* mpiVectorPool) - : mpiVectorPool(mpiVectorPool) - { - this->getData().setAllocator( new CbVectorAllocatorPool<T>(cbVectorKey, this->mpiVectorPool) ); - } - ~TbCbVectorReceiverMpiPool() override - { - if( this->mpiVectorPool->getNofStoredVectors()==1 ) //last entry! - { - TbCbVectorMpiPool< T >::deleteTbCbVectorMpiPool(this->mpiVectorPool->getPoolKey()); - } - } - bool isLocalTransmitter() const override { return false; } - bool isRemoteTransmitter() const override { return !this->isLocalTransmitter(); } - - void sendDataSize() override { throw UbException(UB_EXARGS,"TbCbVectorReceiverMpiPool receives only"); } - void receiveDataSize() override { this->mpiVectorPool->receiveDataOrder(); } - void sendData() override { throw UbException(UB_EXARGS,"TbCbVectorReceiverMpiPool receives only"); } - void prepareForReceive() override { this->mpiVectorPool->prepareForReceiveData(); } - CbVector< T >& receiveData() override - { - this->mpiVectorPool->receiveData(); - return this->getData(); - } - - //info-section (usable for remote transmitter) - int getSendTbRank() const { throw UbException(UB_EXARGS,"TbCbVectorReceiverMpiPool receives only"); } - int getSendTbTag() const { throw UbException(UB_EXARGS,"TbCbVectorReceiverMpiPool receives only"); } - int getRecvFromRank() const override { return this->mpiVectorPool->getRemoteRank(); } - int getRecvFromTag() const override { return this->mpiVectorPool->getRemoteTag(); } - - std::string toString() const override { return "TbCbVectorReceiverMpiPool<"+(std::string)typeid(T).name()+" to rank (tag)"+UbSystem::toString(getRecvFromRank())+"("+UbSystem::toString(getRecvFromTag())+")"; } + TbCbVectorReceiverMpiPool(std::string cbVectorKey, TbCbVectorMpiPool<T> *mpiVectorPool) + : mpiVectorPool(mpiVectorPool) + { + this->getData().setAllocator(new CbVectorAllocatorPool<T>(cbVectorKey, this->mpiVectorPool)); + } + ~TbCbVectorReceiverMpiPool() override + { + if (this->mpiVectorPool->getNofStoredVectors() == 1) // last entry! + { + TbCbVectorMpiPool<T>::deleteTbCbVectorMpiPool(this->mpiVectorPool->getPoolKey()); + } + } + bool isLocalTransmitter() const override { return false; } + bool isRemoteTransmitter() const override { return !this->isLocalTransmitter(); } + + void sendDataSize() override { throw UbException(UB_EXARGS, "TbCbVectorReceiverMpiPool receives only"); } + void receiveDataSize() override { this->mpiVectorPool->receiveDataOrder(); } + void sendData() override { throw UbException(UB_EXARGS, "TbCbVectorReceiverMpiPool receives only"); } + void prepareForReceive() override { this->mpiVectorPool->prepareForReceiveData(); } + CbVector<T> &receiveData() override + { + this->mpiVectorPool->receiveData(); + return this->getData(); + } + + // info-section (usable for remote transmitter) + int getSendTbRank() const { throw UbException(UB_EXARGS, "TbCbVectorReceiverMpiPool receives only"); } + int getSendTbTag() const { throw UbException(UB_EXARGS, "TbCbVectorReceiverMpiPool receives only"); } + int getRecvFromRank() const override { return this->mpiVectorPool->getRemoteRank(); } + int getRecvFromTag() const override { return this->mpiVectorPool->getRemoteTag(); } + + std::string toString() const override + { + return "TbCbVectorReceiverMpiPool<" + (std::string) typeid(T).name() + " to rank (tag)" + + UbSystem::toString(getRecvFromRank()) + "(" + UbSystem::toString(getRecvFromTag()) + ")"; + } protected: - TbCbVectorMpiPool<T>* mpiVectorPool; + TbCbVectorMpiPool<T> *mpiVectorPool; }; -#endif //VF_MPI +#endif // VF_MPI -#endif //TBTRANSMITTERMPIPOOL_H - +#endif // TBTRANSMITTERMPIPOOL_H diff --git a/src/basics/basics/utilities/UbComparators.h b/src/basics/basics/utilities/UbComparators.h index 0e7d2cbeda4334e34630611f9bafa90d4e5ab7c0..bc507e456b9603d85d42f8597fe4748a135e51d2 100644 --- a/src/basics/basics/utilities/UbComparators.h +++ b/src/basics/basics/utilities/UbComparators.h @@ -1,28 +1,28 @@ //======================================================================================= -// ____ ____ __ ______ __________ __ __ __ __ -// \ \ | | | | | _ \ |___ ___| | | | | / \ | | -// \ \ | | | | | |_) | | | | | | | / \ | | -// \ \ | | | | | _ / | | | | | | / /\ \ | | -// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ -// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| -// \ \ | | ________________________________________________________________ -// \ \ | | | ______________________________________________________________| -// \ \| | | | __ __ __ __ ______ _______ -// \ | | |_____ | | | | | | | | | _ \ / _____) -// \ | | _____| | | | | | | | | | | \ \ \_______ +// ____ ____ __ ______ __________ __ __ __ __ +// \ \ | | | | | _ \ |___ ___| | | | | / \ | | +// \ \ | | | | | |_) | | | | | | | / \ | | +// \ \ | | | | | _ / | | | | | | / /\ \ | | +// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ +// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| +// \ \ | | ________________________________________________________________ +// \ \ | | | ______________________________________________________________| +// \ \| | | | __ __ __ __ ______ _______ +// \ | | |_____ | | | | | | | | | _ \ / _____) +// \ | | _____| | | | | | | | | | | \ \ \_______ // \ | | | | |_____ | \_/ | | | | |_/ / _____ | -// \ _____| |__| |________| \_______/ |__| |______/ (_______/ +// \ _____| |__| |________| \_______/ |__| |______/ (_______/ // -// This file is part of VirtualFluids. VirtualFluids is free software: you can +// This file is part of VirtualFluids. VirtualFluids is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of +// License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. -// -// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// +// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License along // with VirtualFluids (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>. // @@ -30,202 +30,200 @@ //! \ingroup utilities //! \author Soeren Freudiger, Sebastian Geller //======================================================================================= -#ifndef UBCOMPARATORS_H +#ifndef UBCOMPARATORS_H #define UBCOMPARATORS_H -#include <functional> +#include <functional> namespace UbComparators { - //type_traits - template <typename T> struct MemberInfo; //not defined for correct compiler errors! - - // specialization for MemberFunctionsPtr - // C - class with return T method - template <typename T, typename C> - struct MemberInfo<T C::*> - { - using type = T; - using class_type = C; - - static T& apply( C& c, T C::* ptr ) { return c.*ptr; } - static const T& apply( const C& c, T C::* ptr ) { return c.*ptr; } - }; - //specialization for MemberFunctionsPtr - //C - class with return T method - template <typename T, typename C> - struct MemberInfo<T (C::*)()> - { - using type = T; - using class_type = C; - - static T apply( C& c, T (C::*ptr)() ) { return (c.*ptr)(); } - }; - //specialization for const MemberFunctionsPtr - //C - class with return T method - template <typename T, typename C> - struct MemberInfo<T (C::*)() const> - { - using type = T; - using class_type = C; - - static T apply( const C& c, T (C::*ptr)() const ) { return (c.*ptr)(); } - }; - - //MemberComparative-Class - template <typename Ptr, typename Comp = std::less<typename MemberInfo<Ptr>::type> > - class MemComp - : private Comp // -> usage of Empty Base Class Optimization (EBCO) - { - using C = typename MemberInfo<Ptr>::class_type; - - public: - MemComp( Ptr ptr, Comp c = Comp() ) - : Comp(c), mp_(ptr) - {} - - bool operator()(C& lhs, C& rhs) - { - return Comp::operator()( MemberInfo<Ptr>::apply(lhs, mp_), MemberInfo<Ptr>::apply(rhs, mp_) ); - } - bool operator()(C& lhs, C& rhs) const - { - return Comp::operator()( MemberInfo<Ptr>::apply(lhs, mp_), MemberInfo<Ptr>::apply(rhs, mp_) ); - } - bool operator()(const C& lhs, const C& rhs) - { - return Comp::operator()( MemberInfo<Ptr>::apply(lhs, mp_), MemberInfo<Ptr>::apply(rhs, mp_) ); - } - bool operator()(const C& lhs, const C& rhs) const - { - return Comp::operator()( MemberInfo<Ptr>::apply(lhs, mp_), MemberInfo<Ptr>::apply(rhs, mp_) ); - } - - private: - Ptr mp_; - }; - - // Factoryfunktionen - template <typename Ptr> - MemComp<Ptr> membercomp(Ptr p) - { - return MemComp<Ptr>(p); - } - - template<typename Comp, typename Ptr> - MemComp<Ptr, Comp> membercomp(Ptr p, Comp c = Comp()) - { - return MemComp<Ptr, Comp>(p, c); - } - - template<template<typename> class Comp, typename Ptr> - MemComp<Ptr, Comp<typename MemberInfo<Ptr>::type> > - membercomp(Ptr p, Comp<typename MemberInfo<Ptr>::type> c = Comp<typename MemberInfo<Ptr>::type>()) - { - return MemComp<Ptr, Comp<typename MemberInfo<Ptr>::type> >(p, c); - } - - - ////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////// - //andere Variante (alerdings ist hier keine Deduction moeglich!!!) - ////////////////////////////////////////////////////////////////////////// - //Vergleichs-Templates: - //Funktor zum "non-const" Methodenvergleich: liste.sort( compareMethods<Klasse, int, &Klasse::getVal1 ); - template<typename K/*Klasse*/, typename M /*MethodenRueckgabeTyp*/, M (K::*fct)() /*MethodenPointer*/> // Allgemeiner Fall - struct compareMethods - { - bool operator()(K& r, K& l) const // da fct nicht const ist, kann auch K nicht const sein. das const hinter der deklaration besagt dass compareMethods const sein kann - { return (r.*fct)() < (l.*fct)(); } - }; - ////////////////////////////////////////////////////////////////////////// - //Funktor zum "const" Methodenvergleich: liste.sort( compareMethods<Klasse, int, &Klasse::getVal1 ); - template<typename K/*Klasse*/, typename M /*MethodenRueckgabeTyp*/, M (K::*fct)() const /*MethodenPointer*/> // <- hier const - struct compareConstMethods - { - bool operator()(const K& r, const K& l) const //hier koennen die K's auch const sein, muessen sie aber nicht (const hinzufuegen geht ja problemlos) - { return (r.*fct)() < (l.*fct)(); } - }; - ////////////////////////////////////////////////////////////////////////// - //Funktor zum Membervergleich: lise.sort( compareMember<Klasse, int, &Klasse::member>() ); - template<typename K/*Klasse*/, typename M /*MemberTyp*/, M (K::*Member) /*MemberPointer*/> // <- hier const - struct compareMember - { - bool operator()(const K& r,const K& l) const - { return r.*Member < l.*Member; } - }; - //Bsp: - //class Klasse{ - //public: - // Klasse(double val1, double val2 ) : val1(val1),val2(val2) {} - // double getVal1() { return val1; } - // double getVal2() const { return val2; } // <- hier const - // double val1, val2; - //}; - //int main(int argc, char** argv){ - // std::list<Klasse> l; - // l.push_back( Klasse(10,10) ); - // l.push_back( Klasse(1,5) ); - // l.sort( compareMember<Klasse, double, &Klasse::val1 >() ); - // l.sort( compareMethods<Klasse, double, &Klasse::getVal1 >() ); - // l.sort( compareConstMethods<Klasse, double, &Klasse::getVal1 >() ); - //} +// type_traits +template <typename T> +struct MemberInfo; // not defined for correct compiler errors! + +// specialization for MemberFunctionsPtr +// C - class with return T method +template <typename T, typename C> +struct MemberInfo<T C::*> { + using type = T; + using class_type = C; + + static T &apply(C &c, T C::*ptr) { return c.*ptr; } + static const T &apply(const C &c, T C::*ptr) { return c.*ptr; } +}; +// specialization for MemberFunctionsPtr +// C - class with return T method +template <typename T, typename C> +struct MemberInfo<T (C::*)()> { + using type = T; + using class_type = C; + + static T apply(C &c, T (C::*ptr)()) { return (c.*ptr)(); } +}; +// specialization for const MemberFunctionsPtr +// C - class with return T method +template <typename T, typename C> +struct MemberInfo<T (C::*)() const> { + using type = T; + using class_type = C; + + static T apply(const C &c, T (C::*ptr)() const) { return (c.*ptr)(); } +}; +// MemberComparative-Class +template <typename Ptr, typename Comp = std::less<typename MemberInfo<Ptr>::type>> +class MemComp : private Comp // -> usage of Empty Base Class Optimization (EBCO) +{ + using C = typename MemberInfo<Ptr>::class_type; + +public: + MemComp(Ptr ptr, Comp c = Comp()) : Comp(c), mp_(ptr) {} + + bool operator()(C &lhs, C &rhs) + { + return Comp::operator()(MemberInfo<Ptr>::apply(lhs, mp_), MemberInfo<Ptr>::apply(rhs, mp_)); + } + bool operator()(C &lhs, C &rhs) const + { + return Comp::operator()(MemberInfo<Ptr>::apply(lhs, mp_), MemberInfo<Ptr>::apply(rhs, mp_)); + } + bool operator()(const C &lhs, const C &rhs) + { + return Comp::operator()(MemberInfo<Ptr>::apply(lhs, mp_), MemberInfo<Ptr>::apply(rhs, mp_)); + } + bool operator()(const C &lhs, const C &rhs) const + { + return Comp::operator()(MemberInfo<Ptr>::apply(lhs, mp_), MemberInfo<Ptr>::apply(rhs, mp_)); + } + +private: + Ptr mp_; }; -#endif //UBCOMPARATOR_H - -//example -// #include <basics/utilities/UbComparators.h" -// #include <list> -// using namespace std; -// using namespace UbComparators; -// -// struct S { -// S(int i) :x(i) {} -// int x; -// float f() {return x;}; -// double g() const {return x;} -// }; -// -// struct intComp { -// bool operator()(int l, int r) const -// { return l > r; } -// }; -// -// struct dblComp { -// bool operator()(double l, double r) const -// { return l > r; } -// }; -// -// template <typename T> -// struct genComp { +// Factoryfunktionen +template <typename Ptr> +MemComp<Ptr> membercomp(Ptr p) +{ + return MemComp<Ptr>(p); +} + +template <typename Comp, typename Ptr> +MemComp<Ptr, Comp> membercomp(Ptr p, Comp c = Comp()) +{ + return MemComp<Ptr, Comp>(p, c); +} + +template <template <typename> class Comp, typename Ptr> +MemComp<Ptr, Comp<typename MemberInfo<Ptr>::type>> +membercomp(Ptr p, Comp<typename MemberInfo<Ptr>::type> c = Comp<typename MemberInfo<Ptr>::type>()) +{ + return MemComp<Ptr, Comp<typename MemberInfo<Ptr>::type>>(p, c); +} + +////////////////////////////////////////////////////////////////////////// +////////////////////////////////////////////////////////////////////////// +////////////////////////////////////////////////////////////////////////// +// andere Variante (alerdings ist hier keine Deduction moeglich!!!) +////////////////////////////////////////////////////////////////////////// +// Vergleichs-Templates: +// Funktor zum "non-const" Methodenvergleich: liste.sort( compareMethods<Klasse, int, &Klasse::getVal1 ); +template <typename K /*Klasse*/, typename M /*MethodenRueckgabeTyp*/, + M (K::*fct)() /*MethodenPointer*/> // Allgemeiner Fall +struct compareMethods { + bool operator()(K &r, K &l) const // da fct nicht const ist, kann auch K nicht const sein. das const hinter der + // deklaration besagt dass compareMethods const sein kann + { + return (r.*fct)() < (l.*fct)(); + } +}; +////////////////////////////////////////////////////////////////////////// +// Funktor zum "const" Methodenvergleich: liste.sort( compareMethods<Klasse, int, &Klasse::getVal1 ); +template <typename K /*Klasse*/, typename M /*MethodenRueckgabeTyp*/, + M (K::*fct)() const /*MethodenPointer*/> // <- hier const +struct compareConstMethods { + bool operator()(const K &r, const K &l) + const // hier koennen die K's auch const sein, muessen sie aber nicht (const hinzufuegen geht ja problemlos) + { + return (r.*fct)() < (l.*fct)(); + } +}; +////////////////////////////////////////////////////////////////////////// +// Funktor zum Membervergleich: lise.sort( compareMember<Klasse, int, &Klasse::member>() ); +template <typename K /*Klasse*/, typename M /*MemberTyp*/, M(K::*Member) /*MemberPointer*/> // <- hier const +struct compareMember { + bool operator()(const K &r, const K &l) const { return r.*Member < l.*Member; } +}; +// Bsp: +// class Klasse{ +// public: +// Klasse(double val1, double val2 ) : val1(val1),val2(val2) {} +// double getVal1() { return val1; } +// double getVal2() const { return val2; } // <- hier const +// double val1, val2; +//}; +// int main(int argc, char** argv){ +// std::list<Klasse> l; +// l.push_back( Klasse(10,10) ); +// l.push_back( Klasse(1,5) ); +// l.sort( compareMember<Klasse, double, &Klasse::val1 >() ); +// l.sort( compareMethods<Klasse, double, &Klasse::getVal1 >() ); +// l.sort( compareConstMethods<Klasse, double, &Klasse::getVal1 >() ); +//} + +}; // namespace UbComparators + +#endif // UBCOMPARATOR_H + +// example +// #include <basics/utilities/UbComparators.h" +// #include <list> +// using namespace std; +// using namespace UbComparators; +// +// struct S { +// S(int i) :x(i) {} +// int x; +// float f() {return x;}; +// double g() const {return x;} +// }; +// +// struct intComp { +// bool operator()(int l, int r) const +// { return l > r; } +// }; +// +// struct dblComp { +// bool operator()(double l, double r) const +// { return l > r; } +// }; +// +// template <typename T> +// struct genComp { // bool operator()(const T& l, const T& r) const -// { return l > r; } -// }; -// -// -// int main() -// { -// S a(1); -// S b(2); -// list<S> sList; -// sList.push_back(a); -// sList.push_back(b); -// sList.sort(UbComparators::membercomp(&S::x,intComp())); //calls overload (1) -// sList.sort(UbComparators::membercomp<intComp>(&S::x)); //same -// sList.sort(UbComparators::membercomp(&S::x)); //calls overload (5) -// sList.sort(UbComparators::membercomp<genComp>(&S::x)); //calls overload(3) -// sList.sort(UbComparators::membercomp(&S::x, genComp<int>())); //calls overload(1) -// //same for nonconst function -// sList.sort(UbComparators::membercomp(&S::f, dblComp())); //overload(2) -// sList.sort(UbComparators::membercomp<dblComp>(&S::f)); //same -// sList.sort(UbComparators::membercomp(&S::f)); //overload(6) -// sList.sort(UbComparators::membercomp<genComp>(&S::f)); //overload(4) -// //same for const function -// sList.sort(UbComparators::membercomp(&S::g, dblComp())); //overload(2) -// sList.sort(UbComparators::membercomp<dblComp>(&S::g)); //same -// sList.sort(UbComparators::membercomp(&S::g)); //overload(6) -// sList.sort(UbComparators::membercomp<genComp>(&S::g)); //overload(4) -// } +// { return l > r; } +// }; +// +// +// int main() +// { +// S a(1); +// S b(2); +// list<S> sList; +// sList.push_back(a); +// sList.push_back(b); +// sList.sort(UbComparators::membercomp(&S::x,intComp())); //calls overload (1) +// sList.sort(UbComparators::membercomp<intComp>(&S::x)); //same +// sList.sort(UbComparators::membercomp(&S::x)); //calls overload (5) +// sList.sort(UbComparators::membercomp<genComp>(&S::x)); //calls overload(3) +// sList.sort(UbComparators::membercomp(&S::x, genComp<int>())); //calls overload(1) +// //same for nonconst function +// sList.sort(UbComparators::membercomp(&S::f, dblComp())); //overload(2) +// sList.sort(UbComparators::membercomp<dblComp>(&S::f)); //same +// sList.sort(UbComparators::membercomp(&S::f)); //overload(6) +// sList.sort(UbComparators::membercomp<genComp>(&S::f)); //overload(4) +// //same for const function +// sList.sort(UbComparators::membercomp(&S::g, dblComp())); //overload(2) +// sList.sort(UbComparators::membercomp<dblComp>(&S::g)); //same +// sList.sort(UbComparators::membercomp(&S::g)); //overload(6) +// sList.sort(UbComparators::membercomp<genComp>(&S::g)); //overload(4) +// } diff --git a/src/basics/basics/utilities/UbEqual.h b/src/basics/basics/utilities/UbEqual.h index c605c36efd8b793ba4585aad27fc9eb083185e26..b3ca9102d585faeac0b2a4e413434d4d0d759282 100644 --- a/src/basics/basics/utilities/UbEqual.h +++ b/src/basics/basics/utilities/UbEqual.h @@ -1,28 +1,28 @@ //======================================================================================= -// ____ ____ __ ______ __________ __ __ __ __ -// \ \ | | | | | _ \ |___ ___| | | | | / \ | | -// \ \ | | | | | |_) | | | | | | | / \ | | -// \ \ | | | | | _ / | | | | | | / /\ \ | | -// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ -// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| -// \ \ | | ________________________________________________________________ -// \ \ | | | ______________________________________________________________| -// \ \| | | | __ __ __ __ ______ _______ -// \ | | |_____ | | | | | | | | | _ \ / _____) -// \ | | _____| | | | | | | | | | | \ \ \_______ +// ____ ____ __ ______ __________ __ __ __ __ +// \ \ | | | | | _ \ |___ ___| | | | | / \ | | +// \ \ | | | | | |_) | | | | | | | / \ | | +// \ \ | | | | | _ / | | | | | | / /\ \ | | +// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ +// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| +// \ \ | | ________________________________________________________________ +// \ \ | | | ______________________________________________________________| +// \ \| | | | __ __ __ __ ______ _______ +// \ | | |_____ | | | | | | | | | _ \ / _____) +// \ | | _____| | | | | | | | | | | \ \ \_______ // \ | | | | |_____ | \_/ | | | | |_/ / _____ | -// \ _____| |__| |________| \_______/ |__| |______/ (_______/ +// \ _____| |__| |________| \_______/ |__| |______/ (_______/ // -// This file is part of VirtualFluids. VirtualFluids is free software: you can +// This file is part of VirtualFluids. VirtualFluids is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of +// License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. -// -// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// +// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License along // with VirtualFluids (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>. // @@ -33,7 +33,7 @@ #ifndef UBEQUAL_H #define UBEQUAL_H -#include<cmath> +#include <cmath> ////////////////////////////////////////////////////////////////////////// // @@ -52,94 +52,220 @@ // ////////////////////////////////////////////////////////////////////////// -//std-trait, fuer alle nicht spezifischen typen: -template < typename T1, typename T2 > -struct UbEqualTrait -{ - using High = T1; - using Low = T1; +// std-trait, fuer alle nicht spezifischen typen: +template <typename T1, typename T2> +struct UbEqualTrait { + using High = T1; + using Low = T1; }; -//std-trait, fuer gleiche T -template < typename T > -struct UbEqualTrait< T, T > -{ - using High = T; - using Low = T; -}; - -//spezialisierung fuer diverse Typen-Tuples -template<> struct UbEqualTrait< short, int > { using High = int; using Low = short; }; -template<> struct UbEqualTrait< short, long > { using High = long; using Low = short; }; -template<> struct UbEqualTrait< short, float > { using High = float; using Low = short; }; -template<> struct UbEqualTrait< short, double > { using High = double; using Low = short; }; -template<> struct UbEqualTrait< short, long double > { using High = long double; using Low = short; }; - -template<> struct UbEqualTrait< int, short > { using High = int; using Low = short; }; -template<> struct UbEqualTrait< int, long > { using High = long; using Low = int; }; -template<> struct UbEqualTrait< int, float > { using High = float; using Low = int; }; -template<> struct UbEqualTrait< int, double > { using High = double; using Low = int; }; -template<> struct UbEqualTrait< int, long double > { using High = long double; using Low = int; }; - -template<> struct UbEqualTrait< long, short > { using High = long; using Low = short; }; -template<> struct UbEqualTrait< long, int > { using High = long; using Low = int; }; -template<> struct UbEqualTrait< long, float > { using High = float; using Low = long; }; -template<> struct UbEqualTrait< long, double > { using High = double; using Low = long; }; -template<> struct UbEqualTrait< long, long double > { using High = long double; using Low = long; }; - -template<> struct UbEqualTrait< float, short > { using High = float; using Low = short; }; -template<> struct UbEqualTrait< float, int > { using High = float; using Low = int; }; -template<> struct UbEqualTrait< float, long > { using High = float; using Low = long; }; -template<> struct UbEqualTrait< float, double > { using High = double; using Low = float; }; -template<> struct UbEqualTrait< float, long double > { using High = long double; using Low = float; }; - -template<> struct UbEqualTrait< double, short > { using High = double; using Low = short; }; -template<> struct UbEqualTrait< double, int > { using High = double; using Low = int; }; -template<> struct UbEqualTrait< double, long > { using High = double; using Low = long; }; -template<> struct UbEqualTrait< double, float > { using High = double; using Low = float; }; -template<> struct UbEqualTrait< double, long double > { using High = long double; using Low = double; }; - -template<> struct UbEqualTrait< long double, short > { using High = long double; using Low = short; }; -template<> struct UbEqualTrait< long double, int > { using High = long double; using Low = int; }; -template<> struct UbEqualTrait< long double, long > { using High = long double; using Low = long; }; -template<> struct UbEqualTrait< long double, float > { using High = long double; using Low = float; }; -template<> struct UbEqualTrait< long double, double > { using High = long double; using Low = double; }; +// std-trait, fuer gleiche T +template <typename T> +struct UbEqualTrait<T, T> { + using High = T; + using Low = T; +}; + +// spezialisierung fuer diverse Typen-Tuples +template <> +struct UbEqualTrait<short, int> { + using High = int; + using Low = short; +}; +template <> +struct UbEqualTrait<short, long> { + using High = long; + using Low = short; +}; +template <> +struct UbEqualTrait<short, float> { + using High = float; + using Low = short; +}; +template <> +struct UbEqualTrait<short, double> { + using High = double; + using Low = short; +}; +template <> +struct UbEqualTrait<short, long double> { + using High = long double; + using Low = short; +}; + +template <> +struct UbEqualTrait<int, short> { + using High = int; + using Low = short; +}; +template <> +struct UbEqualTrait<int, long> { + using High = long; + using Low = int; +}; +template <> +struct UbEqualTrait<int, float> { + using High = float; + using Low = int; +}; +template <> +struct UbEqualTrait<int, double> { + using High = double; + using Low = int; +}; +template <> +struct UbEqualTrait<int, long double> { + using High = long double; + using Low = int; +}; + +template <> +struct UbEqualTrait<long, short> { + using High = long; + using Low = short; +}; +template <> +struct UbEqualTrait<long, int> { + using High = long; + using Low = int; +}; +template <> +struct UbEqualTrait<long, float> { + using High = float; + using Low = long; +}; +template <> +struct UbEqualTrait<long, double> { + using High = double; + using Low = long; +}; +template <> +struct UbEqualTrait<long, long double> { + using High = long double; + using Low = long; +}; + +template <> +struct UbEqualTrait<float, short> { + using High = float; + using Low = short; +}; +template <> +struct UbEqualTrait<float, int> { + using High = float; + using Low = int; +}; +template <> +struct UbEqualTrait<float, long> { + using High = float; + using Low = long; +}; +template <> +struct UbEqualTrait<float, double> { + using High = double; + using Low = float; +}; +template <> +struct UbEqualTrait<float, long double> { + using High = long double; + using Low = float; +}; + +template <> +struct UbEqualTrait<double, short> { + using High = double; + using Low = short; +}; +template <> +struct UbEqualTrait<double, int> { + using High = double; + using Low = int; +}; +template <> +struct UbEqualTrait<double, long> { + using High = double; + using Low = long; +}; +template <> +struct UbEqualTrait<double, float> { + using High = double; + using Low = float; +}; +template <> +struct UbEqualTrait<double, long double> { + using High = long double; + using Low = double; +}; + +template <> +struct UbEqualTrait<long double, short> { + using High = long double; + using Low = short; +}; +template <> +struct UbEqualTrait<long double, int> { + using High = long double; + using Low = int; +}; +template <> +struct UbEqualTrait<long double, long> { + using High = long double; + using Low = long; +}; +template <> +struct UbEqualTrait<long double, float> { + using High = long double; + using Low = float; +}; +template <> +struct UbEqualTrait<long double, double> { + using High = long double; + using Low = double; +}; ////////////////////////////////////////////////////////////////////////// -//fuer Allgmeine-Typen ( operator== ): -template< typename T1, typename T2 > -inline bool specific_equal(const T1& a, const T2& b) { return a==b; } +// fuer Allgmeine-Typen ( operator== ): +template <typename T1, typename T2> +inline bool specific_equal(const T1 &a, const T2 &b) +{ + return a == b; +} ////////////////////////////////////////////////////////////////////////// -//fuer floating point build-in-type -//float.float -template< /*float,float*/> -inline bool specific_equal< float, float >(const float& a, const float& b) { return std::fabs( a - b ) < 1E-8; } +// fuer floating point build-in-type +// float.float +template </*float,float*/> +inline bool specific_equal<float, float>(const float &a, const float &b) +{ + return std::fabs(a - b) < 1E-8; +} -template</*double,double*/> -inline bool specific_equal< double, double >(const double& a, const double& b) { return std::fabs( a - b ) < 1E-13; } +template </*double,double*/> +inline bool specific_equal<double, double>(const double &a, const double &b) +{ + return std::fabs(a - b) < 1E-13; +} -template</*long double,long double*/> -inline bool specific_equal< long double, long double >(const long double& a, const long double& b) { return std::fabs( a - b ) < 1E-16; } +template </*long double,long double*/> +inline bool specific_equal<long double, long double>(const long double &a, const long double &b) +{ + return std::fabs(a - b) < 1E-16; +} ////////////////////////////////////////////////////////////////////////// -//globale isUbEqual - Funktion -template< typename T1, typename T2 > -inline bool isUbEqual(const T1& a, const T2& b) +// globale isUbEqual - Funktion +template <typename T1, typename T2> +inline bool isUbEqual(const T1 &a, const T2 &b) { - using Low = typename UbEqualTrait<T1, T2>::Low; - return specific_equal< Low, Low >(static_cast< Low >( a ),static_cast< Low >( b )); + using Low = typename UbEqualTrait<T1, T2>::Low; + return specific_equal<Low, Low>(static_cast<Low>(a), static_cast<Low>(b)); }; ////////////////////////////////////////////////////////////////////////// -//UbEqual-Functor -template< typename T1, typename T2 > -struct UbEqual -{ - bool operator()(const T1& a, const T2& b) - { - return isUbEqual(a,b); - } +// UbEqual-Functor +template <typename T1, typename T2> +struct UbEqual { + bool operator()(const T1 &a, const T2 &b) { return isUbEqual(a, b); } }; -#endif //UBEQUAL_H +#endif // UBEQUAL_H diff --git a/src/basics/basics/utilities/UbException.h b/src/basics/basics/utilities/UbException.h index 7c625c33f73fb92ae4d3aa1a7a20c822276f16a0..9a458980688145c199bf7193000131aeb5fb5e30 100644 --- a/src/basics/basics/utilities/UbException.h +++ b/src/basics/basics/utilities/UbException.h @@ -1,28 +1,28 @@ //======================================================================================= -// ____ ____ __ ______ __________ __ __ __ __ -// \ \ | | | | | _ \ |___ ___| | | | | / \ | | -// \ \ | | | | | |_) | | | | | | | / \ | | -// \ \ | | | | | _ / | | | | | | / /\ \ | | -// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ -// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| -// \ \ | | ________________________________________________________________ -// \ \ | | | ______________________________________________________________| -// \ \| | | | __ __ __ __ ______ _______ -// \ | | |_____ | | | | | | | | | _ \ / _____) -// \ | | _____| | | | | | | | | | | \ \ \_______ +// ____ ____ __ ______ __________ __ __ __ __ +// \ \ | | | | | _ \ |___ ___| | | | | / \ | | +// \ \ | | | | | |_) | | | | | | | / \ | | +// \ \ | | | | | _ / | | | | | | / /\ \ | | +// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ +// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| +// \ \ | | ________________________________________________________________ +// \ \ | | | ______________________________________________________________| +// \ \| | | | __ __ __ __ ______ _______ +// \ | | |_____ | | | | | | | | | _ \ / _____) +// \ | | _____| | | | | | | | | | | \ \ \_______ // \ | | | | |_____ | \_/ | | | | |_/ / _____ | -// \ _____| |__| |________| \_______/ |__| |______/ (_______/ +// \ _____| |__| |________| \_______/ |__| |______/ (_______/ // -// This file is part of VirtualFluids. VirtualFluids is free software: you can +// This file is part of VirtualFluids. VirtualFluids is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of +// License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. -// -// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// +// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License along // with VirtualFluids (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>. // @@ -33,11 +33,11 @@ #ifndef UBEXCEPTION_H #define UBEXCEPTION_H -#include <vector> #include <iostream> -#include <string> #include <sstream> #include <stdexcept> +#include <string> +#include <vector> #include "./UbTuple.h" @@ -51,127 +51,115 @@ // //========================================================================= -//Macro UB_FUNCTION: figures out the method/function name (platform dependant) +// Macro UB_FUNCTION: figures out the method/function name (platform dependant) #if defined(__GNUC__) || (defined(__MWERKS__) && (__MWERKS__ >= 0x3000)) || (defined(__ICC) && (__ICC >= 600)) - # define UB_FUNCTION __PRETTY_FUNCTION__ +#define UB_FUNCTION __PRETTY_FUNCTION__ #elif defined(__DMC__) && (__DMC__ >= 0x810) - # define UB_FUNCTION __PRETTY_FUNCTION__ +#define UB_FUNCTION __PRETTY_FUNCTION__ #elif defined(__FUNCSIG__) - # define UB_FUNCTION __FUNCSIG__ +#define UB_FUNCTION __FUNCSIG__ #elif (defined(__INTEL_COMPILER) && (__INTEL_COMPILER >= 600)) || (defined(__IBMCPP__) && (__IBMCPP__ >= 500)) - # define UB_FUNCTION __FUNCTION__ +#define UB_FUNCTION __FUNCTION__ #elif defined(__BORLANDC__) && (__BORLANDC__ >= 0x550) - # define UB_FUNCTION __FUNC__ +#define UB_FUNCTION __FUNC__ #elif defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901) - # define UB_FUNCTION __func__ +#define UB_FUNCTION __func__ #else - # define UB_FUNCTION "(unknown)" +#define UB_FUNCTION "(unknown)" #endif -//Helper Marco -#define UB_EXARGS __FILE__,__LINE__,UB_FUNCTION +// Helper Marco +#define UB_EXARGS __FILE__, __LINE__, UB_FUNCTION #ifdef CAB_BOOST - #define UB_THROW(e) throw boost::enable_current_exception(e) +#define UB_THROW(e) throw boost::enable_current_exception(e) #else - #define UB_THROW(e) throw e +#define UB_THROW(e) throw e #endif class UbException : public std::runtime_error { public: - using ExceptionData = UbTuple<std::string, int, std::string, std::string>; + using ExceptionData = UbTuple<std::string, int, std::string, std::string>; + public: - ////////////////////////////////////////////////////////////////////////// - //constructors - UbException() - : std::runtime_error("") - { - } - /*==========================================================*/ - UbException(const std::string& str) - : std::runtime_error("") - { - this->addInfo(str); - } - /*==========================================================*/ - UbException(const std::string& file, const int& line, const std::string& err_str) - : std::runtime_error("") - { - this->addInfo(file,line,"unknown",err_str); - } - /*==========================================================*/ - //UbException(const char* file, const int& line, const char* function, const std::string& err_str) - UbException(const std::string& file, const int& line, const std::string& function, const std::string& err_str) - : std::runtime_error("") - { - this->addInfo(file,line,function,err_str); - } - ////////////////////////////////////////////////////////////////////////// - //destructor - ~UbException() noexcept override = default; - ////////////////////////////////////////////////////////////////////////// - //virtual public methods - //returns exception-string - const char* what() const noexcept override - { - exceptionString = this->toString(); - return exceptionString.c_str(); //ansonsten ist das Verhalten anschliessend undefiniert! - } - /*==========================================================*/ - virtual void addInfo(const std::string& err_str) - { - exceptionData.push_back( makeUbTuple( (std::string)"-", 0, (std::string)"unknown", err_str) ); - } - /*==========================================================*/ - //add exception - virtual void addInfo(const std::string& file, const int& line, const std::string& function, const std::string& err_str) - { - exceptionData.push_back( makeUbTuple( file, line, function, err_str ) ); - } - /*==========================================================*/ - //returns exception-string with all calles exceptions - virtual const std::vector<std::string> getInfo() const - { - std::vector<std::string> tmp; - for(std::size_t i=0; i<exceptionData.size(); i++) - { - std::stringstream str; - str << val<1>( exceptionData[i] ) << ", " - << val<2>( exceptionData[i] ) << ", " - << val<3>( exceptionData[i] ) << ", " - << val<4>( exceptionData[i] ); - tmp.push_back( str.str()); - } - return tmp; - } - /*==========================================================*/ - //returns exception-string with all calles exceptions and detailes informations - virtual std::string toString() const - { - std::stringstream str("UbExeption"); - - for(std::size_t i=0; i<exceptionData.size(); i++) - str<<(std::string)"caller[" << i << "]\n" - <<" - file: "<< val<1>( exceptionData[i] )<<"\n" - <<" - line: "<< val<2>( exceptionData[i] )<<"\n" - <<" - function: "<< val<3>( exceptionData[i] )<<"\n" - <<" - what: "<< val<4>( exceptionData[i] )<< std::endl; + ////////////////////////////////////////////////////////////////////////// + // constructors + UbException() : std::runtime_error("") {} + /*==========================================================*/ + UbException(const std::string &str) : std::runtime_error("") { this->addInfo(str); } + /*==========================================================*/ + UbException(const std::string &file, const int &line, const std::string &err_str) : std::runtime_error("") + { + this->addInfo(file, line, "unknown", err_str); + } + /*==========================================================*/ + // UbException(const char* file, const int& line, const char* function, const std::string& err_str) + UbException(const std::string &file, const int &line, const std::string &function, const std::string &err_str) + : std::runtime_error("") + { + this->addInfo(file, line, function, err_str); + } + ////////////////////////////////////////////////////////////////////////// + // destructor + ~UbException() noexcept override = default; + ////////////////////////////////////////////////////////////////////////// + // virtual public methods + // returns exception-string + const char *what() const noexcept override + { + exceptionString = this->toString(); + return exceptionString.c_str(); // ansonsten ist das Verhalten anschliessend undefiniert! + } + /*==========================================================*/ + virtual void addInfo(const std::string &err_str) + { + exceptionData.push_back(makeUbTuple((std::string) "-", 0, (std::string) "unknown", err_str)); + } + /*==========================================================*/ + // add exception + virtual void addInfo(const std::string &file, const int &line, const std::string &function, + const std::string &err_str) + { + exceptionData.push_back(makeUbTuple(file, line, function, err_str)); + } + /*==========================================================*/ + // returns exception-string with all calles exceptions + virtual const std::vector<std::string> getInfo() const + { + std::vector<std::string> tmp; + for (std::size_t i = 0; i < exceptionData.size(); i++) { + std::stringstream str; + str << val<1>(exceptionData[i]) << ", " << val<2>(exceptionData[i]) << ", " << val<3>(exceptionData[i]) + << ", " << val<4>(exceptionData[i]); + tmp.push_back(str.str()); + } + return tmp; + } + /*==========================================================*/ + // returns exception-string with all calles exceptions and detailes informations + virtual std::string toString() const + { + std::stringstream str("UbExeption"); - return str.str(); - } + for (std::size_t i = 0; i < exceptionData.size(); i++) + str << (std::string) "caller[" << i << "]\n" + << " - file: " << val<1>(exceptionData[i]) << "\n" + << " - line: " << val<2>(exceptionData[i]) << "\n" + << " - function: " << val<3>(exceptionData[i]) << "\n" + << " - what: " << val<4>(exceptionData[i]) << std::endl; + + return str.str(); + } protected: - ////////////////////////////////////////////////////////////////////////// - //protected member - std::vector< ExceptionData > exceptionData; - mutable std::string exceptionString; + ////////////////////////////////////////////////////////////////////////// + // protected member + std::vector<ExceptionData> exceptionData; + mutable std::string exceptionString; }; -//overlading operator << -inline std::ostream& operator<<(std::ostream& os, const UbException& e) -{ - return os<<e.toString(); -} +// overlading operator << +inline std::ostream &operator<<(std::ostream &os, const UbException &e) { return os << e.toString(); } -#endif //UBEXCEPTION_H +#endif // UBEXCEPTION_H diff --git a/src/basics/basics/utilities/UbFileInput.h b/src/basics/basics/utilities/UbFileInput.h index 006c0b98781f3fa0d738bc2f41ee242a9d7daa33..d3128830be296c1250617d82b4190c618a49335e 100644 --- a/src/basics/basics/utilities/UbFileInput.h +++ b/src/basics/basics/utilities/UbFileInput.h @@ -33,65 +33,64 @@ usage: ... class UbFileInput { public: - enum FILETYPE {ASCII, BINARY}; + enum FILETYPE { ASCII, BINARY }; public: - UbFileInput() : filename("") { } - virtual ~UbFileInput() = default; - - virtual bool operator!() { return !(infile); } - virtual bool isOpen() { return !(!(infile)); } - - virtual bool open(std::string filename)=0; - virtual void close() { infile.close(); } - virtual int eof() { return infile.eof(); } - - virtual void skipLine()=0; // Springt zur naechsten Zeile - virtual void readLine()=0; - virtual std::string readStringLine()=0; - virtual int readInteger()=0; // Liest einen Int-Wert ein - virtual std::size_t readSize_t()=0; - virtual double readDouble()=0; // Liest einen double-Wert ein - virtual float readFloat()=0; // Liest einen float-Wert ein - virtual bool readBool()=0; // Liest einen bool-Wert ein - virtual char readChar()=0; // Liest einen char-Wert ein - virtual std::string readString()=0; // Liest ein Wort ein - virtual std::string readLineTill(char stop)=0; // Liest gesamte Zeile ein bis zu einem bestimmten Zeichen - virtual std::string parseString()=0; // Liest - - virtual void setCommentIndicator(char commentindicator) {this->commentindicator = commentindicator;} - - virtual bool containsString( const std::string& var)=0; - virtual void setPosAfterLineWithString( const std::string& var)=0; - virtual int readIntegerAfterString( const std::string& var)=0; - virtual double readDoubleAfterString( const std::string& var)=0; - virtual bool readBoolAfterString( const std::string& var)=0; - virtual std::string readStringAfterString( const std::string& var)=0; - - virtual std::string getFileName() {return this->filename;} - - //returns file extension: - //e.g. "./../test/ich.inp" -> "inp", "./../test/ich" -> "" - virtual std::string getFileExtension() - { - std::size_t pos1 = filename.rfind("/"); - if(pos1==std::string::npos) pos1 = 0; - std::size_t pos2 = filename.rfind("."); - if(pos2!=std::string::npos && pos2>pos1) - return filename.substr(pos2+1); - - return ""; - } - - //returns "ASCII", "BINARY" - virtual FILETYPE getFileType()=0; + UbFileInput() : filename("") {} + virtual ~UbFileInput() = default; + + virtual bool operator!() { return !(infile); } + virtual bool isOpen() { return !(!(infile)); } + + virtual bool open(std::string filename) = 0; + virtual void close() { infile.close(); } + virtual int eof() { return infile.eof(); } + + virtual void skipLine() = 0; // Springt zur naechsten Zeile + virtual void readLine() = 0; + virtual std::string readStringLine() = 0; + virtual int readInteger() = 0; // Liest einen Int-Wert ein + virtual std::size_t readSize_t() = 0; + virtual double readDouble() = 0; // Liest einen double-Wert ein + virtual float readFloat() = 0; // Liest einen float-Wert ein + virtual bool readBool() = 0; // Liest einen bool-Wert ein + virtual char readChar() = 0; // Liest einen char-Wert ein + virtual std::string readString() = 0; // Liest ein Wort ein + virtual std::string readLineTill(char stop) = 0; // Liest gesamte Zeile ein bis zu einem bestimmten Zeichen + virtual std::string parseString() = 0; // Liest + + virtual void setCommentIndicator(char commentindicator) { this->commentindicator = commentindicator; } + + virtual bool containsString(const std::string &var) = 0; + virtual void setPosAfterLineWithString(const std::string &var) = 0; + virtual int readIntegerAfterString(const std::string &var) = 0; + virtual double readDoubleAfterString(const std::string &var) = 0; + virtual bool readBoolAfterString(const std::string &var) = 0; + virtual std::string readStringAfterString(const std::string &var) = 0; + + virtual std::string getFileName() { return this->filename; } + + // returns file extension: + // e.g. "./../test/ich.inp" -> "inp", "./../test/ich" -> "" + virtual std::string getFileExtension() + { + std::size_t pos1 = filename.rfind("/"); + if (pos1 == std::string::npos) + pos1 = 0; + std::size_t pos2 = filename.rfind("."); + if (pos2 != std::string::npos && pos2 > pos1) + return filename.substr(pos2 + 1); + + return ""; + } + + // returns "ASCII", "BINARY" + virtual FILETYPE getFileType() = 0; protected: - std::ifstream infile; - std::string filename; - char commentindicator{'C'}; + std::ifstream infile; + std::string filename; + char commentindicator{ 'C' }; }; -#endif //UBFILEINPUT_H - - +#endif // UBFILEINPUT_H diff --git a/src/basics/basics/utilities/UbFileInputASCII.cpp b/src/basics/basics/utilities/UbFileInputASCII.cpp index 84a6ff49053c6460147296155951d4c98427a28d..12ce32ab032579976d3b3f97d53e5ae4a2584f78 100644 --- a/src/basics/basics/utilities/UbFileInputASCII.cpp +++ b/src/basics/basics/utilities/UbFileInputASCII.cpp @@ -5,30 +5,31 @@ using namespace std; UbFileInputASCII::UbFileInputASCII(string filename) { - this->filename = filename; - this->commentindicator = 'C'; + this->filename = filename; + this->commentindicator = 'C'; - infile.open(filename.c_str()); + infile.open(filename.c_str()); - //if(!infile) UB_THROW( UbException((string)("UbFileInputASCII::UbFileInputASCII(string filename, int how) couldn't open file:\n "+filename)) ); + // if(!infile) UB_THROW( UbException((string)("UbFileInputASCII::UbFileInputASCII(string filename, int how) couldn't + // open file:\n "+filename)) ); } /*==========================================================*/ bool UbFileInputASCII::open(string filename) { - infile.close(); - infile.clear(); //setzt flags zurueck + infile.close(); + infile.clear(); // setzt flags zurueck - this->filename = filename; - infile.open(this->filename.c_str()); + this->filename = filename; + infile.open(this->filename.c_str()); - return infile.is_open(); + return infile.is_open(); } /*==========================================================*/ int UbFileInputASCII::readInteger() { - int dummy; - infile>>dummy; - return dummy; + int dummy; + infile >> dummy; + return dummy; } /*==========================================================*/ long long UbFileInputASCII::readLongLong() @@ -38,197 +39,210 @@ long long UbFileInputASCII::readLongLong() return dummy; } /*==========================================================*/ -string UbFileInputASCII::getFileName() -{ - return this->filename; -} +string UbFileInputASCII::getFileName() { return this->filename; } /*==========================================================*/ void UbFileInputASCII::skipLine() { - string dummy; - getline(infile, dummy); + string dummy; + getline(infile, dummy); } /*==========================================================*/ void UbFileInputASCII::readLine() { - string dummy; - getline(infile, dummy); + string dummy; + getline(infile, dummy); } /*==========================================================*/ string UbFileInputASCII::readStringLine() { - string dummy; - getline(infile, dummy); - return dummy; + string dummy; + getline(infile, dummy); + return dummy; } /*==========================================================*/ string UbFileInputASCII::readLineTill(char stop) { - string dummy; - getline(infile, dummy, stop); - return dummy; + string dummy; + getline(infile, dummy, stop); + return dummy; } /*==========================================================*/ string UbFileInputASCII::parseString() { - string dummy; - getline(infile, dummy, ' '); - return dummy; + string dummy; + getline(infile, dummy, ' '); + return dummy; } /*==========================================================*/ double UbFileInputASCII::readDouble() { - double dummy; - infile>>dummy; - return dummy; + double dummy; + infile >> dummy; + return dummy; } /*==========================================================*/ float UbFileInputASCII::readFloat() { - float dummy; - infile>>dummy; - return dummy; + float dummy; + infile >> dummy; + return dummy; } /*==========================================================*/ string UbFileInputASCII::readString() { - string dummy; - infile>>dummy; - return dummy; + string dummy; + infile >> dummy; + return dummy; } /*==========================================================*/ char UbFileInputASCII::readChar() { - int dummy; - infile>>dummy; - return (char)dummy; + int dummy; + infile >> dummy; + return (char)dummy; } /*==========================================================*/ std::size_t UbFileInputASCII::readSize_t() { - std::size_t dummy; - infile>>dummy; - return dummy; + std::size_t dummy; + infile >> dummy; + return dummy; } /*==========================================================*/ -void UbFileInputASCII::setPosAfterLineWithString(const string& var) +void UbFileInputASCII::setPosAfterLineWithString(const string &var) { - infile.seekg(0L, ios::beg); //Positionszeiger der Datei auf den Anfang setzen - char line[512]; - do - { - infile.getline(line,512); - if(infile.eof()) UB_THROW( UbException(UB_EXARGS,"error at reading in file \""+filename+"\" -> string "+var+" wasn't found in "+this->filename) ); - }while (strstr(line,var.c_str()) != line); // Ende Schleife, wenn varname ganz in zeile vorkommt + infile.seekg(0L, ios::beg); // Positionszeiger der Datei auf den Anfang setzen + char line[512]; + do { + infile.getline(line, 512); + if (infile.eof()) + UB_THROW(UbException(UB_EXARGS, "error at reading in file \"" + filename + "\" -> string " + var + + " wasn't found in " + this->filename)); + } while (strstr(line, var.c_str()) != line); // Ende Schleife, wenn varname ganz in zeile vorkommt } /*==========================================================*/ -bool UbFileInputASCII::containsString(const string& var) +bool UbFileInputASCII::containsString(const string &var) { - infile.clear(); // setzt den EOF-Status zurueck (wird durch infile.seekg() NICHT getan!!!) + infile.clear(); // setzt den EOF-Status zurueck (wird durch infile.seekg() NICHT getan!!!) - infile.seekg(0L, ios::beg); //Positionszeiger der Datei auf den Anfang setzen - char line[512]; - do - { - infile.getline(line,512); - if(infile.eof()) return false; - }while (strstr(line,var.c_str()) != line); // Ende Schleife, wenn varname ganz in zeile vorkommt + infile.seekg(0L, ios::beg); // Positionszeiger der Datei auf den Anfang setzen + char line[512]; + do { + infile.getline(line, 512); + if (infile.eof()) + return false; + } while (strstr(line, var.c_str()) != line); // Ende Schleife, wenn varname ganz in zeile vorkommt - return true; + return true; } /*==========================================================*/ -int UbFileInputASCII::readIntegerAfterString(const string& var) +int UbFileInputASCII::readIntegerAfterString(const string &var) // last change [10.3.2004] at [9:46] -//suchts in einer Datei nach varname und gibt den dahinter stehenden int-Wert zurueck -//z.B. timesteps 9 +// suchts in einer Datei nach varname und gibt den dahinter stehenden int-Wert zurueck +// z.B. timesteps 9 { - infile.clear(); // setzt den EOF-Status zurueck (wird durch infile.seekg() NICHT getan!!!) - - infile.seekg(0L, ios::beg); //Positionszeiger der Datei auf den Anfang setzen + infile.clear(); // setzt den EOF-Status zurueck (wird durch infile.seekg() NICHT getan!!!) - char line[512]; + infile.seekg(0L, ios::beg); // Positionszeiger der Datei auf den Anfang setzen - do - { - infile.getline(line,512); - if(infile.eof()) UB_THROW( UbException(UB_EXARGS,"error at reading in file \""+filename+"\" -> "+var+" wasn't found in "+this->filename) ); - }while (strstr(line,var.c_str()) != line); // Ende Schleife, wenn varname ganz in zeile vorkommt + char line[512]; - strcpy (line, (line+strlen(var.c_str()))); // zeile um "varname" kuerzen - while ((line[0] == ' ') || (line[0] == '\t')) strcpy (line, (line+1)); // Whitespaces entfernen + do { + infile.getline(line, 512); + if (infile.eof()) + UB_THROW(UbException(UB_EXARGS, "error at reading in file \"" + filename + "\" -> " + var + + " wasn't found in " + this->filename)); + } while (strstr(line, var.c_str()) != line); // Ende Schleife, wenn varname ganz in zeile vorkommt - return(atoi(line)); // Umwandlung in int + strcpy(line, (line + strlen(var.c_str()))); // zeile um "varname" kuerzen + while ((line[0] == ' ') || (line[0] == '\t')) + strcpy(line, (line + 1)); // Whitespaces entfernen + + return (atoi(line)); // Umwandlung in int } /*==========================================================*/ // last change [10.3.2004] at [9:46] -//sucht in einer Datei nach varname und gibt den dahinter stehenden int-Wert zurueck -//z.B. nue 9.5 -double UbFileInputASCII::readDoubleAfterString(const string& var) +// sucht in einer Datei nach varname und gibt den dahinter stehenden int-Wert zurueck +// z.B. nue 9.5 +double UbFileInputASCII::readDoubleAfterString(const string &var) { - infile.clear(); // setzt den EOF-Status zurueck (wird durch infile.seekg() NICHT getan!!!) - - infile.seekg(0L, ios::beg); //Positionszeiger der Datei auf den Anfang setzen + infile.clear(); // setzt den EOF-Status zurueck (wird durch infile.seekg() NICHT getan!!!) - char line[512]; + infile.seekg(0L, ios::beg); // Positionszeiger der Datei auf den Anfang setzen - do - { - infile.getline(line,512); - if(infile.eof()) UB_THROW( UbException(UB_EXARGS,"error at reading in file \""+filename+"\" -> "+var+" wasn't found in "+this->filename) ); - }while (/*!strncmp(varname,line,sizeof(varname))==0*/strstr(line,var.c_str()) != line); // Ende Schleife, wenn varname ganz in zeile vorkommt + char line[512]; + do { + infile.getline(line, 512); + if (infile.eof()) + UB_THROW(UbException(UB_EXARGS, "error at reading in file \"" + filename + "\" -> " + var + + " wasn't found in " + this->filename)); + } while (/*!strncmp(varname,line,sizeof(varname))==0*/ strstr(line, var.c_str()) != + line); // Ende Schleife, wenn varname ganz in zeile vorkommt - strcpy (line, (line+strlen(var.c_str()))); // zeile um "varname" kuerzen - while ((line[0] == ' ') || (line[0] == '\t')) strcpy (line, (line+1)); // Whitespaces entfernen + strcpy(line, (line + strlen(var.c_str()))); // zeile um "varname" kuerzen + while ((line[0] == ' ') || (line[0] == '\t')) + strcpy(line, (line + 1)); // Whitespaces entfernen - return (atof(line)); // Umwandlung in double + return (atof(line)); // Umwandlung in double } /*==========================================================*/ // [9.9.2002] // liefert string-Wert der hinter dem uebergebenen char feld in der datei infile steht // zudem wird der wert in die uebergebene variable value uebertragen (falls man das ergebniss als char benoetig) -string UbFileInputASCII::readStringAfterString(const string& var)//,char *value) +string UbFileInputASCII::readStringAfterString(const string &var) //,char *value) { - infile.clear(); // setzt den EOF-Status zurueck (wird durch infile.seekg() NICHT getan!!!) - - infile.seekg(0L, ios::beg); //Positionszeiger der Datei auf den Anfang setzen + infile.clear(); // setzt den EOF-Status zurueck (wird durch infile.seekg() NICHT getan!!!) + + infile.seekg(0L, ios::beg); // Positionszeiger der Datei auf den Anfang setzen - char line[512]; - //string line_copy[512]; + char line[512]; + // string line_copy[512]; - do{ - infile.getline(line,512); - if(infile.eof()) UB_THROW( UbException(UB_EXARGS,"error at reading in file \""+filename+"\" -> "+var+" wasn't found in "+this->filename) ); - }while (strstr(line,var.c_str()) != line); // Ende Schleife, wenn varname ganz in zeile vorkommt + do { + infile.getline(line, 512); + if (infile.eof()) + UB_THROW(UbException(UB_EXARGS, "error at reading in file \"" + filename + "\" -> " + var + + " wasn't found in " + this->filename)); + } while (strstr(line, var.c_str()) != line); // Ende Schleife, wenn varname ganz in zeile vorkommt - strcpy (line, (line+strlen(var.c_str()))); // zeile um "varname" kuerzen - while ((line[0] == ' ') || (line[0] == '\t')) strcpy (line, (line+1)); // Whitespaces entfernen + strcpy(line, (line + strlen(var.c_str()))); // zeile um "varname" kuerzen + while ((line[0] == ' ') || (line[0] == '\t')) + strcpy(line, (line + 1)); // Whitespaces entfernen - char *p; - p=strtok(line," "); //schneidet alles "ab und inklusive space " nach namen ab - p=strtok(line,"\t");//schneidet alles "ab und inklusive tab " nach namen ab + char *p; + p = strtok(line, " "); // schneidet alles "ab und inklusive space " nach namen ab + p = strtok(line, "\t"); // schneidet alles "ab und inklusive tab " nach namen ab - return static_cast<string>(p); // Umwandlung in string + return static_cast<string>(p); // Umwandlung in string } /*==========================================================*/ // last change [10.3.2004] at [9:46] -//sucht in einer Datei nach varname und gibt den dahinter stehenden int-Wert zurueck -//z.B. nue 9.5 -bool UbFileInputASCII::readBoolAfterString(const string& var) +// sucht in einer Datei nach varname und gibt den dahinter stehenden int-Wert zurueck +// z.B. nue 9.5 +bool UbFileInputASCII::readBoolAfterString(const string &var) { - if(this->readStringAfterString(var) == "true" ) return true; - else if(this->readStringAfterString(var) == "false") return false; - else UB_THROW( UbException(UB_EXARGS,"error at reading in file \""+filename+"\" -> expression after "+var+" is not equal to 'true' or 'false' in "+this->filename) ); + if (this->readStringAfterString(var) == "true") + return true; + else if (this->readStringAfterString(var) == "false") + return false; + else + UB_THROW(UbException(UB_EXARGS, "error at reading in file \"" + filename + "\" -> expression after " + var + + " is not equal to 'true' or 'false' in " + this->filename)); } /*==========================================================*/ // last change [10.3.2004] at [9:46] -//sucht in einer Datei nach varname und gibt den dahinter stehenden int-Wert zurueck -//z.B. nue 9.5 +// sucht in einer Datei nach varname und gibt den dahinter stehenden int-Wert zurueck +// z.B. nue 9.5 bool UbFileInputASCII::readBool() { - string tmp = this->readString(); - if( tmp == "true" ) return true; - else if(tmp == "false") return false; - else UB_THROW( UbException(UB_EXARGS,"error at reading in file \""+filename+"\" -> expression=\""+tmp+"\" is not equal to 'true' or 'false' in "+this->filename) ); + string tmp = this->readString(); + if (tmp == "true") + return true; + else if (tmp == "false") + return false; + else + UB_THROW(UbException(UB_EXARGS, "error at reading in file \"" + filename + "\" -> expression=\"" + tmp + + "\" is not equal to 'true' or 'false' in " + this->filename)); } diff --git a/src/basics/basics/utilities/UbFileInputASCII.h b/src/basics/basics/utilities/UbFileInputASCII.h index 40d5528c8b2aaefc427a7998c948d827c446f222..65cd28921ce99e04ad483cc397fd0aff076ec54c 100644 --- a/src/basics/basics/utilities/UbFileInputASCII.h +++ b/src/basics/basics/utilities/UbFileInputASCII.h @@ -24,55 +24,52 @@ <BR><BR> @author <A HREF="mailto:muffmolch@gmx.de">S. Freudiger</A> @version 1.0 - 23.11.04 -*/ +*/ /* usage: ... */ class BASICS_EXPORT UbFileInputASCII : public UbFileInput -{ +{ public: - UbFileInputASCII() : UbFileInput() { } - UbFileInputASCII(std::string filename); - - bool open(std::string filename) override; - - std::string getFileName() override; - void skipLine() override; // Springt zur naechsten Zeile - - void readLine() override; - std::string readStringLine() override; - int readInteger() override; // Liest einen Int-Wert ein - long long readLongLong(); // Liest einen long-Wert ein - - std::size_t readSize_t() override; - double readDouble() override; // Liest einen double-Wert ein - float readFloat() override; // Liest einen float-Wert ein - bool readBool() override; // Liest einen bool-Wert ein - char readChar() override; // Liest einen char-Wert ein - std::string readString() override; // Liest ein Wort ein - std::string readLineTill(char stop) override; // Liest gesamte Zeile ein bis zu einem bestimmten Zeichen - std::string parseString() override; - - - bool containsString(const std::string& var) override; - void setPosAfterLineWithString(const std::string& var) override; - int readIntegerAfterString(const std::string& var) override; - double readDoubleAfterString(const std::string& var) override; - bool readBoolAfterString(const std::string& var) override; - std::string readStringAfterString(const std::string& var) override; - - FILETYPE getFileType() override { return ASCII; } - - template< typename T > - friend inline UbFileInputASCII& operator>>(UbFileInputASCII& file, T& data) - { - file.infile>>data; - return file; - } + UbFileInputASCII() : UbFileInput() {} + UbFileInputASCII(std::string filename); + + bool open(std::string filename) override; + + std::string getFileName() override; + void skipLine() override; // Springt zur naechsten Zeile + + void readLine() override; + std::string readStringLine() override; + int readInteger() override; // Liest einen Int-Wert ein + long long readLongLong(); // Liest einen long-Wert ein + + std::size_t readSize_t() override; + double readDouble() override; // Liest einen double-Wert ein + float readFloat() override; // Liest einen float-Wert ein + bool readBool() override; // Liest einen bool-Wert ein + char readChar() override; // Liest einen char-Wert ein + std::string readString() override; // Liest ein Wort ein + std::string readLineTill(char stop) override; // Liest gesamte Zeile ein bis zu einem bestimmten Zeichen + std::string parseString() override; + + bool containsString(const std::string &var) override; + void setPosAfterLineWithString(const std::string &var) override; + int readIntegerAfterString(const std::string &var) override; + double readDoubleAfterString(const std::string &var) override; + bool readBoolAfterString(const std::string &var) override; + std::string readStringAfterString(const std::string &var) override; + + FILETYPE getFileType() override { return ASCII; } + + template <typename T> + friend inline UbFileInputASCII &operator>>(UbFileInputASCII &file, T &data) + { + file.infile >> data; + return file; + } }; -#endif //UBFILEINPUTASCII_H - - +#endif // UBFILEINPUTASCII_H diff --git a/src/basics/basics/utilities/UbFileInputBinary.cpp b/src/basics/basics/utilities/UbFileInputBinary.cpp index 0cf6a5a85deab826f7a4ca6089fe2aedca39f3cb..120b4ab860d45dac3094b46c4bbad3f03fa65b6e 100644 --- a/src/basics/basics/utilities/UbFileInputBinary.cpp +++ b/src/basics/basics/utilities/UbFileInputBinary.cpp @@ -6,145 +6,145 @@ using namespace std; /*==========================================================*/ UbFileInputBinary::UbFileInputBinary(string filename) { - this->filename = filename; - infile.open(filename.c_str(), ios::in | ios::binary); + this->filename = filename; + infile.open(filename.c_str(), ios::in | ios::binary); } /*==========================================================*/ bool UbFileInputBinary::open(string filename) { - infile.close(); - infile.clear(); //setzt flags zurueck - - this->filename = filename; - infile.open(this->filename.c_str(), ios::in | ios::binary); + infile.close(); + infile.clear(); // setzt flags zurueck - return infile.is_open(); + this->filename = filename; + infile.open(this->filename.c_str(), ios::in | ios::binary); + + return infile.is_open(); } /*==========================================================*/ -int UbFileInputBinary::readInteger() +int UbFileInputBinary::readInteger() { - int dummy; - infile.read((char*)&dummy,sizeof(int)); - return dummy; + int dummy; + infile.read((char *)&dummy, sizeof(int)); + return dummy; } /*==========================================================*/ -std::size_t UbFileInputBinary::readSize_t() +std::size_t UbFileInputBinary::readSize_t() { - std::size_t dummy; - infile.read((char*)&dummy,sizeof(std::size_t)); - return dummy; + std::size_t dummy; + infile.read((char *)&dummy, sizeof(std::size_t)); + return dummy; } /*==========================================================*/ -double UbFileInputBinary::readDouble() +double UbFileInputBinary::readDouble() { - double dummy; - infile.read((char*)&dummy,sizeof(double)); - return dummy; + double dummy; + infile.read((char *)&dummy, sizeof(double)); + return dummy; } /*==========================================================*/ -float UbFileInputBinary::readFloat() +float UbFileInputBinary::readFloat() { - float dummy; - infile.read((char*)&dummy,sizeof(float)); - return dummy; + float dummy; + infile.read((char *)&dummy, sizeof(float)); + return dummy; } /*==========================================================*/ -char UbFileInputBinary::readChar() +char UbFileInputBinary::readChar() { - char dummy; - infile.read((char*)&dummy,sizeof(char)); - return dummy; + char dummy; + infile.read((char *)&dummy, sizeof(char)); + return dummy; } /*==========================================================*/ -string UbFileInputBinary::readString() +string UbFileInputBinary::readString() { - char c; - infile.read(&c,sizeof(char)); - while(c==' ' || c=='\t') infile.read(&c,sizeof(char)); - - string dummy; - dummy+=c; + char c; + infile.read(&c, sizeof(char)); + while (c == ' ' || c == '\t') + infile.read(&c, sizeof(char)); + + string dummy; + dummy += c; - infile.read(&c,sizeof(char)); - while(c!='\0' && c!=' ' && c!='\t' && c!='\n') - { - dummy+=c; - infile.read(&c,sizeof(char)); - } - return dummy; + infile.read(&c, sizeof(char)); + while (c != '\0' && c != ' ' && c != '\t' && c != '\n') { + dummy += c; + infile.read(&c, sizeof(char)); + } + return dummy; } /*==========================================================*/ -bool UbFileInputBinary::readBool() +bool UbFileInputBinary::readBool() { - bool dummy; - infile.read((char*)&dummy,sizeof(bool)); - return dummy; + bool dummy; + infile.read((char *)&dummy, sizeof(bool)); + return dummy; } /*==========================================================*/ -void UbFileInputBinary::skipLine() +void UbFileInputBinary::skipLine() { - char c; - do{ - infile.read(&c,sizeof(char)); - }while(c!='\n'); + char c; + do { + infile.read(&c, sizeof(char)); + } while (c != '\n'); } /*==========================================================*/ -void UbFileInputBinary::readLine() +void UbFileInputBinary::readLine() { - char c; - infile.read(&c,sizeof(char)); - while(c!='\n') infile.read(&c,sizeof(char)); + char c; + infile.read(&c, sizeof(char)); + while (c != '\n') + infile.read(&c, sizeof(char)); } /*==========================================================*/ -string UbFileInputBinary::readStringLine() +string UbFileInputBinary::readStringLine() { - char c; - string dummy; - infile.read(&c,sizeof(char)); - while(c!='\n') - { - dummy+=c; - infile.read(&c,sizeof(char)); - } - return dummy; + char c; + string dummy; + infile.read(&c, sizeof(char)); + while (c != '\n') { + dummy += c; + infile.read(&c, sizeof(char)); + } + return dummy; } /*==========================================================*/ -string UbFileInputBinary::readLineTill(char /*stop*/) +string UbFileInputBinary::readLineTill(char /*stop*/) { - UB_THROW( UbException(UB_EXARGS,"method makes no sense for binary streams") ); + UB_THROW(UbException(UB_EXARGS, "method makes no sense for binary streams")); } /*==========================================================*/ -string UbFileInputBinary::parseString() +string UbFileInputBinary::parseString() { - UB_THROW( UbException(UB_EXARGS,"method makes no sense for binary streams") ); + UB_THROW(UbException(UB_EXARGS, "method makes no sense for binary streams")); } /*==========================================================*/ -bool UbFileInputBinary::containsString(const string& /*var*/) +bool UbFileInputBinary::containsString(const string & /*var*/) { - UB_THROW( UbException(UB_EXARGS,"method makes no sense for binary streams") ); + UB_THROW(UbException(UB_EXARGS, "method makes no sense for binary streams")); } /*==========================================================*/ -void UbFileInputBinary::setPosAfterLineWithString(const string& /*var*/) +void UbFileInputBinary::setPosAfterLineWithString(const string & /*var*/) { - UB_THROW( UbException(UB_EXARGS,"method makes no sense for binary streams") ); + UB_THROW(UbException(UB_EXARGS, "method makes no sense for binary streams")); } /*==========================================================*/ -int UbFileInputBinary::readIntegerAfterString(const string& /*var*/) +int UbFileInputBinary::readIntegerAfterString(const string & /*var*/) { - UB_THROW( UbException(UB_EXARGS,"method makes no sense for binary streams") ); + UB_THROW(UbException(UB_EXARGS, "method makes no sense for binary streams")); } /*==========================================================*/ -double UbFileInputBinary::readDoubleAfterString(const string& /*var*/) +double UbFileInputBinary::readDoubleAfterString(const string & /*var*/) { - UB_THROW( UbException(UB_EXARGS,"method makes no sense for binary streams") ); + UB_THROW(UbException(UB_EXARGS, "method makes no sense for binary streams")); } /*==========================================================*/ -string UbFileInputBinary::readStringAfterString(const string& /*var*/) +string UbFileInputBinary::readStringAfterString(const string & /*var*/) { - UB_THROW( UbException(UB_EXARGS,"method makes no sense for binary streams") ); + UB_THROW(UbException(UB_EXARGS, "method makes no sense for binary streams")); } /*==========================================================*/ -bool UbFileInputBinary::readBoolAfterString(const string& /*var*/) +bool UbFileInputBinary::readBoolAfterString(const string & /*var*/) { - UB_THROW( UbException(UB_EXARGS,"method makes no sense for binary streams") ); + UB_THROW(UbException(UB_EXARGS, "method makes no sense for binary streams")); } diff --git a/src/basics/basics/utilities/UbFileInputBinary.h b/src/basics/basics/utilities/UbFileInputBinary.h index 06086639323cffc8714e8bac64585127c422cfcc..b1e40d396c6948ef474dd23eab5e04767b6d8d2d 100644 --- a/src/basics/basics/utilities/UbFileInputBinary.h +++ b/src/basics/basics/utilities/UbFileInputBinary.h @@ -22,61 +22,57 @@ <BR><BR> @author <A HREF="mailto:muffmolch@gmx.de">S. Freudiger</A> @version 1.0 - 23.11.04 -*/ +*/ /* usage: ... */ class UbFileInputBinary : public UbFileInput -{ +{ public: - UbFileInputBinary() : UbFileInput() { } - UbFileInputBinary(std::string filename); - - bool open(std::string filename) override; + UbFileInputBinary() : UbFileInput() {} + UbFileInputBinary(std::string filename); - void skipLine() override; // Springt zur naechsten Zeile - void readLine() override; - std::string readStringLine() override; - std::size_t readSize_t() override; - int readInteger() override; // Liest einen Int-Wert ein - double readDouble() override; // Liest einen double-Wert ein - float readFloat() override; // Liest einen float-Wert ein - bool readBool() override; // Liest einen bool-Wert ein - char readChar() override; // Liest einen char-Wert ein - std::string readString() override; // Liest ein Wort ein - std::string readLineTill(char stop) override; // Liest gesamte Zeile ein bis zu einem bestimmten Zeichen - std::string parseString() override; // Liest + bool open(std::string filename) override; - bool containsString(const std::string& var) override; - void setPosAfterLineWithString(const std::string& var) override; - int readIntegerAfterString(const std::string& var) override; - double readDoubleAfterString(const std::string& var) override; - bool readBoolAfterString(const std::string& var) override; - std::string readStringAfterString(const std::string& var) override; + void skipLine() override; // Springt zur naechsten Zeile + void readLine() override; + std::string readStringLine() override; + std::size_t readSize_t() override; + int readInteger() override; // Liest einen Int-Wert ein + double readDouble() override; // Liest einen double-Wert ein + float readFloat() override; // Liest einen float-Wert ein + bool readBool() override; // Liest einen bool-Wert ein + char readChar() override; // Liest einen char-Wert ein + std::string readString() override; // Liest ein Wort ein + std::string readLineTill(char stop) override; // Liest gesamte Zeile ein bis zu einem bestimmten Zeichen + std::string parseString() override; // Liest - FILETYPE getFileType() override { return BINARY; } + bool containsString(const std::string &var) override; + void setPosAfterLineWithString(const std::string &var) override; + int readIntegerAfterString(const std::string &var) override; + double readDoubleAfterString(const std::string &var) override; + bool readBoolAfterString(const std::string &var) override; + std::string readStringAfterString(const std::string &var) override; - template< typename T > - friend inline UbFileInputBinary& operator>>(UbFileInputBinary& file, T& data) - { - file.infile.read((char*)&data,sizeof(T)); - return file; - } + FILETYPE getFileType() override { return BINARY; } - template< typename T> - void readVector(std::vector<T>& v) - { - size_t size = v.size(); - if (size > 0) - { - infile.read((char*)&v[0], sizeof(T)*size); - } - } + template <typename T> + friend inline UbFileInputBinary &operator>>(UbFileInputBinary &file, T &data) + { + file.infile.read((char *)&data, sizeof(T)); + return file; + } + template <typename T> + void readVector(std::vector<T> &v) + { + size_t size = v.size(); + if (size > 0) { + infile.read((char *)&v[0], sizeof(T) * size); + } + } }; #endif - - diff --git a/src/basics/basics/utilities/UbFileOutput.h b/src/basics/basics/utilities/UbFileOutput.h index 38c0928088d4598f0416fabaea7ebab3385607b8..7e3e12d4ce2725073ed153d4cad9985664664cd1 100644 --- a/src/basics/basics/utilities/UbFileOutput.h +++ b/src/basics/basics/utilities/UbFileOutput.h @@ -5,10 +5,10 @@ // |___/_/_/ \__/\__,_/\__,_/_/_/ /_/\__,_/_/\__,_/____/ // #ifndef UBFILEOUTPUT_H -#define UBFILEOUTPUT_H +#define UBFILEOUTPUT_H -#include <iomanip> #include <fstream> +#include <iomanip> #include <iostream> #include <string> @@ -22,7 +22,7 @@ <BR><BR> @author <A HREF="mailto:muffmolch@gmx.de">S. Freudiger</A> @version 1.0 - 23.11.04 -*/ +*/ /* usage: ... @@ -31,63 +31,65 @@ usage: ... class UbFileOutput { public: - enum CREATEOPTION {OUTFILE=0, INANDOUTFILE=1, APPENDFILE=2}; - enum FILETYPE {ASCII, BINARY}; + enum CREATEOPTION { OUTFILE = 0, INANDOUTFILE = 1, APPENDFILE = 2 }; + enum FILETYPE { ASCII, BINARY }; public: - UbFileOutput() : filename("") { } - UbFileOutput(const std::string& filename) : filename(filename) { } - virtual ~UbFileOutput() { outfile.flush(); } - - virtual bool open(const std::string& filename, CREATEOPTION opt=OUTFILE) = 0; - - virtual bool operator!() { return !(outfile); } - virtual bool isOpen() { return !(!(outfile)); } - - virtual void flush() { outfile.flush(); } - virtual void close() { outfile.close(); } - - virtual void writeInteger(const int& value, const int& width=0)=0; - virtual void writeDouble(const double& value, const int& width=0)=0; - virtual void writeFloat(const float& value, const int& width=0)=0; - virtual void writeBool(const bool& value, const int& width=0)=0; - virtual void writeSize_t(const std::size_t& value, const int& width=0)=0; - virtual void writeChar(const char& value, const int& width=0)=0; - virtual void writeString(const std::string& value, const int& width=0)=0; - virtual void writeStringOnly(const std::string& value)=0; - virtual void writeLine(const std::string& value, const int& width=0)=0; - virtual void writeLine()=0; - - virtual void writeCommentLine(const std::string& line)=0; - virtual void writeCommentLine(char indicator, const std::string& line)=0; - virtual void writeCopyOfFile(const std::string& filename)=0; - - virtual void setCommentIndicator(char commentindicator) {this->commentindicator = commentindicator;} - - virtual void setPrecision(const int& precision)=0; - virtual int getPrecision()=0; - - //returns "ASCII", "BINARY" - virtual FILETYPE getFileType()=0; - - //returns file extension: - //e.g. "./../test/ich.inp" -> "inp", "./../test/ich" -> "" - virtual std::string getFileExtension() - { - std::size_t pos1 = filename.rfind("/"); - if(pos1==std::string::npos) pos1 = 0; - std::size_t pos2 = filename.rfind("."); - if(pos2!=std::string::npos && pos2>pos1) - return filename.substr(pos2+1); - - return ""; - } - - virtual std::string getFileName() {return this->filename;} + UbFileOutput() : filename("") {} + UbFileOutput(const std::string &filename) : filename(filename) {} + virtual ~UbFileOutput() { outfile.flush(); } + + virtual bool open(const std::string &filename, CREATEOPTION opt = OUTFILE) = 0; + + virtual bool operator!() { return !(outfile); } + virtual bool isOpen() { return !(!(outfile)); } + + virtual void flush() { outfile.flush(); } + virtual void close() { outfile.close(); } + + virtual void writeInteger(const int &value, const int &width = 0) = 0; + virtual void writeDouble(const double &value, const int &width = 0) = 0; + virtual void writeFloat(const float &value, const int &width = 0) = 0; + virtual void writeBool(const bool &value, const int &width = 0) = 0; + virtual void writeSize_t(const std::size_t &value, const int &width = 0) = 0; + virtual void writeChar(const char &value, const int &width = 0) = 0; + virtual void writeString(const std::string &value, const int &width = 0) = 0; + virtual void writeStringOnly(const std::string &value) = 0; + virtual void writeLine(const std::string &value, const int &width = 0) = 0; + virtual void writeLine() = 0; + + virtual void writeCommentLine(const std::string &line) = 0; + virtual void writeCommentLine(char indicator, const std::string &line) = 0; + virtual void writeCopyOfFile(const std::string &filename) = 0; + + virtual void setCommentIndicator(char commentindicator) { this->commentindicator = commentindicator; } + + virtual void setPrecision(const int &precision) = 0; + virtual int getPrecision() = 0; + + // returns "ASCII", "BINARY" + virtual FILETYPE getFileType() = 0; + + // returns file extension: + // e.g. "./../test/ich.inp" -> "inp", "./../test/ich" -> "" + virtual std::string getFileExtension() + { + std::size_t pos1 = filename.rfind("/"); + if (pos1 == std::string::npos) + pos1 = 0; + std::size_t pos2 = filename.rfind("."); + if (pos2 != std::string::npos && pos2 > pos1) + return filename.substr(pos2 + 1); + + return ""; + } + + virtual std::string getFileName() { return this->filename; } + protected: - std::ofstream outfile; - std::string filename; - char commentindicator{'C'}; + std::ofstream outfile; + std::string filename; + char commentindicator{ 'C' }; }; -#endif //UBFILEOUTPUT_H +#endif // UBFILEOUTPUT_H diff --git a/src/basics/basics/utilities/UbFileOutputASCII.cpp b/src/basics/basics/utilities/UbFileOutputASCII.cpp index 3a0930105e936982e664d48a6cbb0abf150f12d2..68bfc8b64ad2e10c5b8a76b0bcdc98bdd7fa019d 100644 --- a/src/basics/basics/utilities/UbFileOutputASCII.cpp +++ b/src/basics/basics/utilities/UbFileOutputASCII.cpp @@ -1,177 +1,171 @@ #include <basics/utilities/UbFileOutputASCII.h> -#include <basics/utilities/UbSystem.h> #include <basics/utilities/UbInfinity.h> #include <basics/utilities/UbMath.h> +#include <basics/utilities/UbSystem.h> #include <cstring> using namespace std; -UbFileOutputASCII::UbFileOutputASCII(const string& filename, const bool& createPath, const int& /*precision*/) - : UbFileOutput(filename) +UbFileOutputASCII::UbFileOutputASCII(const string &filename, const bool &createPath, const int & /*precision*/) + : UbFileOutput(filename) { - this->commentindicator = 'C'; - this->setPrecision(20); + this->commentindicator = 'C'; + this->setPrecision(20); + + outfile.open(filename.c_str(), ios::out); - outfile.open(filename.c_str(),ios::out); - - if(!outfile && createPath) - { - outfile.clear(); //flags ruecksetzen (ansonsten liefert utern if(!outfile) weiterhin true!!! - string path = UbSystem::getPathFromString(filename); - if(path.size()>0) - { - UbSystem::makeDirectory(path); - outfile.open(filename.c_str(),ios::out); - } - } + if (!outfile && createPath) { + outfile.clear(); // flags ruecksetzen (ansonsten liefert utern if(!outfile) weiterhin true!!! + string path = UbSystem::getPathFromString(filename); + if (path.size() > 0) { + UbSystem::makeDirectory(path); + outfile.open(filename.c_str(), ios::out); + } + } - if(!outfile) UB_THROW( UbException(UB_EXARGS,"couldn't open file:\n "+filename) ); + if (!outfile) + UB_THROW(UbException(UB_EXARGS, "couldn't open file:\n " + filename)); } /*==========================================================*/ -UbFileOutputASCII::UbFileOutputASCII(const std::string& filename, CREATEOPTION opt, const bool& createPath, const int& precision) - : UbFileOutput(filename) +UbFileOutputASCII::UbFileOutputASCII(const std::string &filename, CREATEOPTION opt, const bool &createPath, + const int &precision) + : UbFileOutput(filename) { - this->commentindicator = 'C'; - this->setPrecision(precision); - - if(!this->open(filename,opt) && createPath) - { - outfile.clear(); //flags ruecksetzen (ansonsten liefert utern if(!outfile) weiterhin true!!! - string path = UbSystem::getPathFromString(filename); - if(path.size()>0) UbSystem::makeDirectory(path); + this->commentindicator = 'C'; + this->setPrecision(precision); - this->open(filename,opt); - } + if (!this->open(filename, opt) && createPath) { + outfile.clear(); // flags ruecksetzen (ansonsten liefert utern if(!outfile) weiterhin true!!! + string path = UbSystem::getPathFromString(filename); + if (path.size() > 0) + UbSystem::makeDirectory(path); - if(!outfile) UB_THROW( UbException(UB_EXARGS,"couldn't open file:\n "+filename) ); + this->open(filename, opt); + } + + if (!outfile) + UB_THROW(UbException(UB_EXARGS, "couldn't open file:\n " + filename)); } /*==========================================================*/ -bool UbFileOutputASCII::open(const std::string& filename, CREATEOPTION opt) +bool UbFileOutputASCII::open(const std::string &filename, CREATEOPTION opt) { - outfile.close(); - outfile.clear(); //setzt flags zurueck - this->filename = filename; + outfile.close(); + outfile.clear(); // setzt flags zurueck + this->filename = filename; - if (opt==UbFileOutput::OUTFILE ) outfile.open(this->filename.c_str(),ios::out); - else if(opt==UbFileOutput::INANDOUTFILE ) outfile.open(this->filename.c_str(),ios::out | ios::in); - else if(opt==UbFileOutput::APPENDFILE ) outfile.open(this->filename.c_str(),ios::app); - else UB_THROW( UbException(UB_EXARGS,"undefined CREATEOPTION") ); + if (opt == UbFileOutput::OUTFILE) + outfile.open(this->filename.c_str(), ios::out); + else if (opt == UbFileOutput::INANDOUTFILE) + outfile.open(this->filename.c_str(), ios::out | ios::in); + else if (opt == UbFileOutput::APPENDFILE) + outfile.open(this->filename.c_str(), ios::app); + else + UB_THROW(UbException(UB_EXARGS, "undefined CREATEOPTION")); - return outfile.is_open(); + return outfile.is_open(); } /*==========================================================*/ -void UbFileOutputASCII::writeBool(const bool& value, const int& width) +void UbFileOutputASCII::writeBool(const bool &value, const int &width) { - outfile.width(width); - if(value) outfile<<"true "; - else outfile<<"false "; + outfile.width(width); + if (value) + outfile << "true "; + else + outfile << "false "; } /*==========================================================*/ -void UbFileOutputASCII::writeDouble(const double& value, const int& width) +void UbFileOutputASCII::writeDouble(const double &value, const int &width) { - outfile.width(width); - //Problem: Ub::inf wird gerundet - // -> beim Einlesen ist der Wert evtl zu gross und es kommt murks raus - // -> max Laenge darstellen und gut ist - if(UbMath::equal(value, (double)Ub::inf) ) - { - ios_base::fmtflags flags = outfile.flags(); - outfile<<setprecision(std::numeric_limits<double>::digits10+2); - outfile<<value<<" "; - outfile.flags(flags); - return; - } - outfile<<value<<" "; + outfile.width(width); + // Problem: Ub::inf wird gerundet + // -> beim Einlesen ist der Wert evtl zu gross und es kommt murks raus + // -> max Laenge darstellen und gut ist + if (UbMath::equal(value, (double)Ub::inf)) { + ios_base::fmtflags flags = outfile.flags(); + outfile << setprecision(std::numeric_limits<double>::digits10 + 2); + outfile << value << " "; + outfile.flags(flags); + return; + } + outfile << value << " "; } /*==========================================================*/ -void UbFileOutputASCII::writeFloat(const float& value, const int& width) +void UbFileOutputASCII::writeFloat(const float &value, const int &width) { - outfile.width(width); - //Problem: Ub::inf wird gerundet - // -> beim Einlesen ist der Wert evtl zu gross und es kommt murks raus - // -> max Laenge darstellen und gut ist - if(UbMath::equal(value, (float)Ub::inf) ) - { - ios_base::fmtflags flags = outfile.flags(); - outfile<<setprecision(std::numeric_limits<float>::digits10+2); - outfile<<value<<" "; - outfile.flags(flags); - return; - } - outfile<<value<<" "; + outfile.width(width); + // Problem: Ub::inf wird gerundet + // -> beim Einlesen ist der Wert evtl zu gross und es kommt murks raus + // -> max Laenge darstellen und gut ist + if (UbMath::equal(value, (float)Ub::inf)) { + ios_base::fmtflags flags = outfile.flags(); + outfile << setprecision(std::numeric_limits<float>::digits10 + 2); + outfile << value << " "; + outfile.flags(flags); + return; + } + outfile << value << " "; } /*==========================================================*/ -void UbFileOutputASCII::setPrecision(const int& precision) -{ - outfile<<setprecision(precision); -} +void UbFileOutputASCII::setPrecision(const int &precision) { outfile << setprecision(precision); } /*==========================================================*/ -void UbFileOutputASCII::writeInteger(const int& value, const int& width) +void UbFileOutputASCII::writeInteger(const int &value, const int &width) { - outfile.width(width); - outfile<<value<<" "; + outfile.width(width); + outfile << value << " "; } /*==========================================================*/ -void UbFileOutputASCII::writeSize_t(const std::size_t& value, const int& width) +void UbFileOutputASCII::writeSize_t(const std::size_t &value, const int &width) { - outfile.width(width); - outfile<<value<<" "; + outfile.width(width); + outfile << value << " "; } /*==========================================================*/ -void UbFileOutputASCII::writeChar(const char& value, const int& width) +void UbFileOutputASCII::writeChar(const char &value, const int &width) { - outfile.width(width); - outfile<<(int)value<<" "; + outfile.width(width); + outfile << (int)value << " "; } /*==========================================================*/ -void UbFileOutputASCII::writeString(const string& value, const int& width) +void UbFileOutputASCII::writeString(const string &value, const int &width) { - outfile.width(width); - outfile<<value.c_str()<<" "; + outfile.width(width); + outfile << value.c_str() << " "; } /*==========================================================*/ -void UbFileOutputASCII::writeStringOnly(const string& value) -{ - outfile<<value.c_str(); -} +void UbFileOutputASCII::writeStringOnly(const string &value) { outfile << value.c_str(); } /*==========================================================*/ -void UbFileOutputASCII::writeLine(const string& value, const int& width) +void UbFileOutputASCII::writeLine(const string &value, const int &width) { - outfile.width(width); - outfile<<value.c_str()<<endl; + outfile.width(width); + outfile << value.c_str() << endl; } /*==========================================================*/ -void UbFileOutputASCII::writeLine() -{ - outfile<<endl; -} +void UbFileOutputASCII::writeLine() { outfile << endl; } /*==========================================================*/ -void UbFileOutputASCII::writeCommentLine(const string& line) -{ - this->writeCommentLine(this->commentindicator, line); -} +void UbFileOutputASCII::writeCommentLine(const string &line) { this->writeCommentLine(this->commentindicator, line); } /*==========================================================*/ -void UbFileOutputASCII::writeCommentLine(char indicator, const string& line) +void UbFileOutputASCII::writeCommentLine(char indicator, const string &line) { - this->outfile<<indicator<<line<<endl; + this->outfile << indicator << line << endl; } /*==========================================================*/ -void UbFileOutputASCII::writeCopyOfFile(const string& filename) +void UbFileOutputASCII::writeCopyOfFile(const string &filename) { - ifstream infile(filename.c_str()); - if(!infile) UB_THROW( UbException(UB_EXARGS,"couldn't open file:\n "+filename) ); + ifstream infile(filename.c_str()); + if (!infile) + UB_THROW(UbException(UB_EXARGS, "couldn't open file:\n " + filename)); - try - { - char c; - while(infile.get(c)) - { - outfile.put(c); //=out<<c; - } - outfile.flush(); - infile.close(); - } - catch(std::exception& e) { UB_THROW( UbException(UB_EXARGS,"catched std::exception, error: "+(std::string)e.what()) ); } - catch(...) { UB_THROW( UbException(UB_EXARGS,"unknown error") ); } + try { + char c; + while (infile.get(c)) { + outfile.put(c); //=out<<c; + } + outfile.flush(); + infile.close(); + } catch (std::exception &e) { + UB_THROW(UbException(UB_EXARGS, "catched std::exception, error: " + (std::string)e.what())); + } catch (...) { + UB_THROW(UbException(UB_EXARGS, "unknown error")); + } } diff --git a/src/basics/basics/utilities/UbFileOutputASCII.h b/src/basics/basics/utilities/UbFileOutputASCII.h index 25041513f8989990b6cb99a80186b2049771bedc..e6d763561ba6e36dbceae844e4d0423692fa6a94 100644 --- a/src/basics/basics/utilities/UbFileOutputASCII.h +++ b/src/basics/basics/utilities/UbFileOutputASCII.h @@ -7,8 +7,8 @@ #ifndef UBFILEOUTPUTASCII_H #define UBFILEOUTPUTASCII_H -#include <iomanip> #include <fstream> +#include <iomanip> #include <iostream> #include "basics_export.h" @@ -24,7 +24,7 @@ <BR><BR> @author <A HREF="mailto:muffmolch@gmx.de">S. Freudiger</A> @version 1.0 - 23.11.04 -*/ +*/ /* usage: ... @@ -33,42 +33,41 @@ usage: ... class BASICS_EXPORT UbFileOutputASCII : public UbFileOutput { public: - UbFileOutputASCII() : UbFileOutput() {} - UbFileOutputASCII(const std::string& filename, const bool& createPath=true, const int& precision=15); - UbFileOutputASCII(const std::string& filename, CREATEOPTION opt, const bool& createPath=true, const int& precision=15); - - bool open(const std::string& filename, CREATEOPTION opt=OUTFILE) override; - - void writeBool(const bool& value, const int& width=0) override; - void writeDouble(const double& value, const int& width=0) override; - void writeFloat(const float& value, const int& width=0) override; - void writeInteger(const int& value, const int& width=0) override; - void writeSize_t(const std::size_t& value, const int& width=0) override; - void writeChar(const char& value, const int& width=0) override; - void writeString(const std::string& value, const int& width=0) override; - void writeStringOnly(const std::string& value) override; - void writeLine(const std::string& value, const int& width=0) override; - void writeLine() override; - - void setPrecision(const int& precision) override; - int getPrecision() override { return (int)outfile.precision(); } + UbFileOutputASCII() : UbFileOutput() {} + UbFileOutputASCII(const std::string &filename, const bool &createPath = true, const int &precision = 15); + UbFileOutputASCII(const std::string &filename, CREATEOPTION opt, const bool &createPath = true, + const int &precision = 15); - void setCommentIndicator(char commentindicator) override {this->commentindicator = commentindicator;} - - void writeCommentLine(const std::string& line) override; - void writeCommentLine(char indicator, const std::string& line) override; - void writeCopyOfFile(const std::string& filename) override; + bool open(const std::string &filename, CREATEOPTION opt = OUTFILE) override; - FILETYPE getFileType() override { return ASCII; } + void writeBool(const bool &value, const int &width = 0) override; + void writeDouble(const double &value, const int &width = 0) override; + void writeFloat(const float &value, const int &width = 0) override; + void writeInteger(const int &value, const int &width = 0) override; + void writeSize_t(const std::size_t &value, const int &width = 0) override; + void writeChar(const char &value, const int &width = 0) override; + void writeString(const std::string &value, const int &width = 0) override; + void writeStringOnly(const std::string &value) override; + void writeLine(const std::string &value, const int &width = 0) override; + void writeLine() override; - template< typename T > - friend inline UbFileOutputASCII& operator<<(UbFileOutputASCII& file, const T& data) - { - file.outfile<<data; - return file; - } -}; + void setPrecision(const int &precision) override; + int getPrecision() override { return (int)outfile.precision(); } -#endif + void setCommentIndicator(char commentindicator) override { this->commentindicator = commentindicator; } + void writeCommentLine(const std::string &line) override; + void writeCommentLine(char indicator, const std::string &line) override; + void writeCopyOfFile(const std::string &filename) override; + FILETYPE getFileType() override { return ASCII; } + + template <typename T> + friend inline UbFileOutputASCII &operator<<(UbFileOutputASCII &file, const T &data) + { + file.outfile << data; + return file; + } +}; + +#endif diff --git a/src/basics/basics/utilities/UbFileOutputBinary.cpp b/src/basics/basics/utilities/UbFileOutputBinary.cpp index a34d11441f6ac6176ab987bb52734af7e3dd2cdc..fa9ab7480f360e4d9a14098ffca8020f159cc76c 100644 --- a/src/basics/basics/utilities/UbFileOutputBinary.cpp +++ b/src/basics/basics/utilities/UbFileOutputBinary.cpp @@ -5,176 +5,172 @@ using namespace std; /*==========================================================*/ -UbFileOutputBinary::UbFileOutputBinary(const string& filename, const bool& createPath) +UbFileOutputBinary::UbFileOutputBinary(const string &filename, const bool &createPath) { - this->filename = filename; - this->commentindicator = 'C'; + this->filename = filename; + this->commentindicator = 'C'; - outfile.open(filename.c_str(),ios::out | ios::binary); + outfile.open(filename.c_str(), ios::out | ios::binary); - if(!outfile && createPath) - { - string path = UbSystem::getPathFromString(filename); - if(path.size()>0) - { - outfile.clear(); //flags ruecksetzen (ansonsten liefert utern if(!outfile) weiterhin true!!! - UbSystem::makeDirectory(path); - outfile.open(filename.c_str(),ios::out | ios::binary); - } - } - - if(!outfile) UB_THROW( UbException(UB_EXARGS,"couldn't open file:\n "+filename) ); + if (!outfile && createPath) { + string path = UbSystem::getPathFromString(filename); + if (path.size() > 0) { + outfile.clear(); // flags ruecksetzen (ansonsten liefert utern if(!outfile) weiterhin true!!! + UbSystem::makeDirectory(path); + outfile.open(filename.c_str(), ios::out | ios::binary); + } + } + if (!outfile) + UB_THROW(UbException(UB_EXARGS, "couldn't open file:\n " + filename)); } /*==========================================================*/ -UbFileOutputBinary::UbFileOutputBinary(const string& filename,UbFileOutput::CREATEOPTION opt, const bool& createPath) +UbFileOutputBinary::UbFileOutputBinary(const string &filename, UbFileOutput::CREATEOPTION opt, const bool &createPath) { - this->filename = filename; - this->commentindicator = 'C'; + this->filename = filename; + this->commentindicator = 'C'; - this->open(filename,opt); + this->open(filename, opt); - if(!this->open(filename,opt) && createPath) - { - string path = UbSystem::getPathFromString(filename); - if(path.size()>0) - { - outfile.clear(); //flags ruecksetzen (ansonsten liefert utern if(!outfile) weiterhin true!!! - UbSystem::makeDirectory(path,20); + if (!this->open(filename, opt) && createPath) { + string path = UbSystem::getPathFromString(filename); + if (path.size() > 0) { + outfile.clear(); // flags ruecksetzen (ansonsten liefert utern if(!outfile) weiterhin true!!! + UbSystem::makeDirectory(path, 20); - this->open(filename,opt); - } - } + this->open(filename, opt); + } + } - if(!outfile) UB_THROW( UbException(UB_EXARGS,"couldn't open file:\n "+filename) ); + if (!outfile) + UB_THROW(UbException(UB_EXARGS, "couldn't open file:\n " + filename)); } /*==========================================================*/ -bool UbFileOutputBinary::open(const string& filename, UbFileOutput::CREATEOPTION opt) +bool UbFileOutputBinary::open(const string &filename, UbFileOutput::CREATEOPTION opt) { - outfile.close(); - outfile.clear(); //setzt flags zurueck + outfile.close(); + outfile.clear(); // setzt flags zurueck - this->filename = filename; + this->filename = filename; - if (opt==UbFileOutput::OUTFILE ) outfile.open(this->filename.c_str(),ios::out | ios::binary); - else if(opt==UbFileOutput::APPENDFILE ) outfile.open(this->filename.c_str(),ios::app | ios::binary); - else if(opt==UbFileOutput::INANDOUTFILE) UB_THROW( UbException(UB_EXARGS,"undefined CREATEOPTION - INANDOUTFILE not possible for BINARY files") ); - else UB_THROW( UbException(UB_EXARGS,"undefined CREATEOPTION") ); + if (opt == UbFileOutput::OUTFILE) + outfile.open(this->filename.c_str(), ios::out | ios::binary); + else if (opt == UbFileOutput::APPENDFILE) + outfile.open(this->filename.c_str(), ios::app | ios::binary); + else if (opt == UbFileOutput::INANDOUTFILE) + UB_THROW(UbException(UB_EXARGS, "undefined CREATEOPTION - INANDOUTFILE not possible for BINARY files")); + else + UB_THROW(UbException(UB_EXARGS, "undefined CREATEOPTION")); - return outfile.is_open(); + return outfile.is_open(); } /*==========================================================*/ -void UbFileOutputBinary::writeBool(const bool& value, const int& /*width*/) +void UbFileOutputBinary::writeBool(const bool &value, const int & /*width*/) { - outfile.write((char*)&value,sizeof(bool)); + outfile.write((char *)&value, sizeof(bool)); } /*==========================================================*/ -void UbFileOutputBinary::writeDouble(const double& value, const int& /*width*/) +void UbFileOutputBinary::writeDouble(const double &value, const int & /*width*/) { - outfile.write((char*)&value,sizeof(double)); + outfile.write((char *)&value, sizeof(double)); } /*==========================================================*/ -void UbFileOutputBinary::writeFloat(const float& value, const int& /*width*/) +void UbFileOutputBinary::writeFloat(const float &value, const int & /*width*/) { - outfile.write((char*)&value,sizeof(float)); + outfile.write((char *)&value, sizeof(float)); } /*==========================================================*/ -void UbFileOutputBinary::setPrecision(const int& /*precision*/) -{ - UB_THROW( UbException(UB_EXARGS,"no way") ); -} +void UbFileOutputBinary::setPrecision(const int & /*precision*/) { UB_THROW(UbException(UB_EXARGS, "no way")); } /*==========================================================*/ -int UbFileOutputBinary::getPrecision() -{ - UB_THROW( UbException(UB_EXARGS,"no way") ); -} +int UbFileOutputBinary::getPrecision() { UB_THROW(UbException(UB_EXARGS, "no way")); } /*==========================================================*/ -void UbFileOutputBinary::writeInteger(const int& value, const int& /*width*/) +void UbFileOutputBinary::writeInteger(const int &value, const int & /*width*/) { - outfile.write((char*)&value,sizeof(value)); + outfile.write((char *)&value, sizeof(value)); } /*==========================================================*/ -void UbFileOutputBinary::writeSize_t(const std::size_t& value, const int& /*width*/) +void UbFileOutputBinary::writeSize_t(const std::size_t &value, const int & /*width*/) { - outfile.write((char*)&value,sizeof(value)); + outfile.write((char *)&value, sizeof(value)); } /*==========================================================*/ -void UbFileOutputBinary::writeChar(const char& value, const int& /*width*/) +void UbFileOutputBinary::writeChar(const char &value, const int & /*width*/) { - outfile.write((char*)&value,sizeof(value)); + outfile.write((char *)&value, sizeof(value)); } /*==========================================================*/ -void UbFileOutputBinary::writeString(const string& value, const int& /*width*/) +void UbFileOutputBinary::writeString(const string &value, const int & /*width*/) { - char c='\0'; - unsigned int length = (unsigned)value.length(); - - unsigned pos; - //whitespaces und tabs am stringanfang uebergehen - for(pos=0; pos<length; pos++) - if( value[pos]!=' ' && value[pos]!='\t' ) break; + char c = '\0'; + unsigned int length = (unsigned)value.length(); + + unsigned pos; + // whitespaces und tabs am stringanfang uebergehen + for (pos = 0; pos < length; pos++) + if (value[pos] != ' ' && value[pos] != '\t') + break; - while(pos<length) - { - while(pos<length && value[pos]!=' ' && value[pos]!='\t' && value[pos]!='\0') - { - outfile.write((char*)&(value[pos++]),sizeof(char)); - } + while (pos < length) { + while (pos < length && value[pos] != ' ' && value[pos] != '\t' && value[pos] != '\0') { + outfile.write((char *)&(value[pos++]), sizeof(char)); + } - outfile.write(&c,sizeof(char)); - pos++; + outfile.write(&c, sizeof(char)); + pos++; - while(pos<length && (value[pos]==' ' || value[pos]=='\t' || value[pos]=='\0') ) - { - pos++; - } - } + while (pos < length && (value[pos] == ' ' || value[pos] == '\t' || value[pos] == '\0')) { + pos++; + } + } } /*==========================================================*/ -void UbFileOutputBinary::writeStringOnly(const string& /*value*/) +void UbFileOutputBinary::writeStringOnly(const string & /*value*/) { - throw UbException(UB_EXARGS,"no way... causes to many errors"); // TODO: WTF? + throw UbException(UB_EXARGS, "no way... causes to many errors"); // TODO: WTF? } /*==========================================================*/ -void UbFileOutputBinary::writeLine(const std::string& value, const int& /*width*/) +void UbFileOutputBinary::writeLine(const std::string &value, const int & /*width*/) { - this->writeString(value); - char c='\n'; - outfile.write(&c,sizeof(char)); + this->writeString(value); + char c = '\n'; + outfile.write(&c, sizeof(char)); } /*==========================================================*/ -void UbFileOutputBinary::writeLine() +void UbFileOutputBinary::writeLine() { - char c='\n'; - outfile.write(&c,sizeof(char)); + char c = '\n'; + outfile.write(&c, sizeof(char)); } /*==========================================================*/ -void UbFileOutputBinary::writeCommentLine(const string& line) +void UbFileOutputBinary::writeCommentLine(const string &line) { - try { this->writeCommentLine(this->commentindicator, line); } - catch(...) { UB_THROW( UbException(UB_EXARGS,"unknown error") ); } + try { + this->writeCommentLine(this->commentindicator, line); + } catch (...) { + UB_THROW(UbException(UB_EXARGS, "unknown error")); + } } /*==========================================================*/ -void UbFileOutputBinary::writeCommentLine(char indicator, const string& line) +void UbFileOutputBinary::writeCommentLine(char indicator, const string &line) { - string dummy = indicator + line; - this->writeLine(dummy); + string dummy = indicator + line; + this->writeLine(dummy); } /*==========================================================*/ -void UbFileOutputBinary::writeCopyOfFile(const string& filename) +void UbFileOutputBinary::writeCopyOfFile(const string &filename) { - ifstream infile(filename.c_str(),ios::in | ios::binary); - if(!infile) UB_THROW( UbException(UB_EXARGS,"couldn't open file:\n "+filename) ); + ifstream infile(filename.c_str(), ios::in | ios::binary); + if (!infile) + UB_THROW(UbException(UB_EXARGS, "couldn't open file:\n " + filename)); - try - { - char c; - while(infile.get(c)) - { - outfile.put(c); //=out<<c; - } - outfile.flush(); - infile.close(); - } - catch(...) {UB_THROW( UbException(UB_EXARGS,"unknown error") );} + try { + char c; + while (infile.get(c)) { + outfile.put(c); //=out<<c; + } + outfile.flush(); + infile.close(); + } catch (...) { + UB_THROW(UbException(UB_EXARGS, "unknown error")); + } } diff --git a/src/basics/basics/utilities/UbFileOutputBinary.h b/src/basics/basics/utilities/UbFileOutputBinary.h index 11b62b791523e202cbc5ea0a8a1264ecfd24025b..fb4799d1761fbc7056e5b0c6050c385e95692073 100644 --- a/src/basics/basics/utilities/UbFileOutputBinary.h +++ b/src/basics/basics/utilities/UbFileOutputBinary.h @@ -7,11 +7,10 @@ #ifndef UBFILEOUTPUTBINARY_H #define UBFILEOUTPUTBINARY_H -#include <iomanip> #include <fstream> +#include <iomanip> #include <iostream> - #include <basics/utilities/UbException.h> #include <basics/utilities/UbFileOutput.h> @@ -23,7 +22,7 @@ <BR><BR> @author <A HREF="mailto:muffmolch@gmx.de">S. Freudiger</A> @version 1.0 - 23.11.04 -*/ +*/ /* usage: ... @@ -32,49 +31,46 @@ usage: ... class UbFileOutputBinary : public UbFileOutput { public: - UbFileOutputBinary() : UbFileOutput() {} - UbFileOutputBinary(const std::string& filename, const bool& createPath=true); - UbFileOutputBinary(const std::string& filename, UbFileOutput::CREATEOPTION opt, const bool& createPath); - - bool open(const std::string& filename, UbFileOutput::CREATEOPTION opt=OUTFILE) override; + UbFileOutputBinary() : UbFileOutput() {} + UbFileOutputBinary(const std::string &filename, const bool &createPath = true); + UbFileOutputBinary(const std::string &filename, UbFileOutput::CREATEOPTION opt, const bool &createPath); - void writeInteger(const int& value, const int& width=0) override; - void writeDouble(const double& value, const int& width=0) override; - void writeFloat(const float& value, const int& width=0) override; - void writeBool(const bool& value, const int& width=0) override; - void writeChar(const char& value, const int& width=0) override; - void writeSize_t(const std::size_t& value, const int& width=0) override; - void writeString(const std::string& value, const int& width=0) override; - void writeStringOnly(const std::string& value) override; - void writeLine(const std::string& value, const int& width=0) override; - void writeLine() override; - void writeCommentLine(const std::string& line) override; - void writeCommentLine(char indicator, const std::string& line) override; - void writeCopyOfFile(const std::string& filename) override; + bool open(const std::string &filename, UbFileOutput::CREATEOPTION opt = OUTFILE) override; - void setPrecision(const int& precision) override; - int getPrecision() override; + void writeInteger(const int &value, const int &width = 0) override; + void writeDouble(const double &value, const int &width = 0) override; + void writeFloat(const float &value, const int &width = 0) override; + void writeBool(const bool &value, const int &width = 0) override; + void writeChar(const char &value, const int &width = 0) override; + void writeSize_t(const std::size_t &value, const int &width = 0) override; + void writeString(const std::string &value, const int &width = 0) override; + void writeStringOnly(const std::string &value) override; + void writeLine(const std::string &value, const int &width = 0) override; + void writeLine() override; + void writeCommentLine(const std::string &line) override; + void writeCommentLine(char indicator, const std::string &line) override; + void writeCopyOfFile(const std::string &filename) override; - FILETYPE getFileType() override { return BINARY; } + void setPrecision(const int &precision) override; + int getPrecision() override; - template< typename T > - friend inline UbFileOutputBinary& operator<<(UbFileOutputBinary& file, const T& data) - { - file.outfile.write((char*)&data,sizeof(T)); - return file; - } + FILETYPE getFileType() override { return BINARY; } - template< typename T> - void writeVector(std::vector<T>& v) - { - size_t size = v.size(); - if (size > 0) - { - outfile.write((char*)&v[0],sizeof(T)*size); - } - } + template <typename T> + friend inline UbFileOutputBinary &operator<<(UbFileOutputBinary &file, const T &data) + { + file.outfile.write((char *)&data, sizeof(T)); + return file; + } + + template <typename T> + void writeVector(std::vector<T> &v) + { + size_t size = v.size(); + if (size > 0) { + outfile.write((char *)&v[0], sizeof(T) * size); + } + } }; #endif - - diff --git a/src/basics/basics/utilities/UbInfinity.h b/src/basics/basics/utilities/UbInfinity.h index 460c439ecd3141ab8bc1973934007acf58a42b50..d42b21a4285f5e62cc9f04483937dfd0740df780 100644 --- a/src/basics/basics/utilities/UbInfinity.h +++ b/src/basics/basics/utilities/UbInfinity.h @@ -1,28 +1,28 @@ //======================================================================================= -// ____ ____ __ ______ __________ __ __ __ __ -// \ \ | | | | | _ \ |___ ___| | | | | / \ | | -// \ \ | | | | | |_) | | | | | | | / \ | | -// \ \ | | | | | _ / | | | | | | / /\ \ | | -// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ -// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| -// \ \ | | ________________________________________________________________ -// \ \ | | | ______________________________________________________________| -// \ \| | | | __ __ __ __ ______ _______ -// \ | | |_____ | | | | | | | | | _ \ / _____) -// \ | | _____| | | | | | | | | | | \ \ \_______ +// ____ ____ __ ______ __________ __ __ __ __ +// \ \ | | | | | _ \ |___ ___| | | | | / \ | | +// \ \ | | | | | |_) | | | | | | | / \ | | +// \ \ | | | | | _ / | | | | | | / /\ \ | | +// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ +// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| +// \ \ | | ________________________________________________________________ +// \ \ | | | ______________________________________________________________| +// \ \| | | | __ __ __ __ ______ _______ +// \ | | |_____ | | | | | | | | | _ \ / _____) +// \ | | _____| | | | | | | | | | | \ \ \_______ // \ | | | | |_____ | \_/ | | | | |_/ / _____ | -// \ _____| |__| |________| \_______/ |__| |______/ (_______/ +// \ _____| |__| |________| \_______/ |__| |______/ (_______/ // -// This file is part of VirtualFluids. VirtualFluids is free software: you can +// This file is part of VirtualFluids. VirtualFluids is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of +// License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. -// -// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// +// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License along // with VirtualFluids (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>. // @@ -40,41 +40,42 @@ ////////////////////////////////////////////////////////////////////////// //! //! \brief UbNegInfinity -//! \details Note: The UbNegInfinity class cannot be instantiated on its own, but works +//! \details Note: The UbNegInfinity class cannot be instantiated on its own, but works //! as a base class for the Infinity class. //! ////////////////////////////////////////////////////////////////////////// class UbNegInfinity { - public: - //name Conversion operators - inline operator signed char() const { return UbLimits<signed char>::ninf(); } - inline operator char() const { return UbLimits<char>::ninf(); } - inline operator wchar_t() const { return UbLimits<wchar_t>::ninf(); } - inline operator short() const { return UbLimits<short>::ninf(); } - inline operator int() const { return UbLimits<int>::ninf(); } - inline operator long() const { return UbLimits<long>::ninf(); } - inline operator float() const { return UbLimits<float>::ninf(); } - inline operator double() const { return UbLimits<double>::ninf(); } - inline operator long double() const { return UbLimits<long double>::ninf(); } - - //! This function compares built-in data types with their largest possible value. The function - //! only works for built-in data types. The attempt to compare user-defined class types will - //! result in a compile time error. - template< typename T > - inline bool equal( const T& rhs ) const - { - UB_STATIC_ASSERT( std::numeric_limits<T>::is_specialized ); - return UbLimits<T>::ninf() == rhs; - } - protected: +public: + // name Conversion operators + inline operator signed char() const { return UbLimits<signed char>::ninf(); } + inline operator char() const { return UbLimits<char>::ninf(); } + inline operator wchar_t() const { return UbLimits<wchar_t>::ninf(); } + inline operator short() const { return UbLimits<short>::ninf(); } + inline operator int() const { return UbLimits<int>::ninf(); } + inline operator long() const { return UbLimits<long>::ninf(); } + inline operator float() const { return UbLimits<float>::ninf(); } + inline operator double() const { return UbLimits<double>::ninf(); } + inline operator long double() const { return UbLimits<long double>::ninf(); } + + //! This function compares built-in data types with their largest possible value. The function + //! only works for built-in data types. The attempt to compare user-defined class types will + //! result in a compile time error. + template <typename T> + inline bool equal(const T &rhs) const + { + UB_STATIC_ASSERT(std::numeric_limits<T>::is_specialized); + return UbLimits<T>::ninf() == rhs; + } + +protected: inline UbNegInfinity() = default; - private: - UbNegInfinity( const UbNegInfinity& ninf ); //copy constructor (private & undefined) - UbNegInfinity& operator=( const UbNegInfinity& ninf ); //copy assignment operator (private & undefined) - void* operator&() const; //address operator (private & undefined) +private: + UbNegInfinity(const UbNegInfinity &ninf); // copy constructor (private & undefined) + UbNegInfinity &operator=(const UbNegInfinity &ninf); // copy assignment operator (private & undefined) + void *operator&() const; // address operator (private & undefined) }; //================================================================================================= @@ -82,28 +83,28 @@ class UbNegInfinity // GLOBAL OPERATORS // //================================================================================================= -template< typename T > -inline bool operator==( const UbNegInfinity& lhs, const T& rhs ) +template <typename T> +inline bool operator==(const UbNegInfinity &lhs, const T &rhs) { - return lhs.equal( rhs ); + return lhs.equal(rhs); } //************************************************************************************************* -template< typename T > -inline bool operator==( const T& lhs, const UbNegInfinity& rhs ) +template <typename T> +inline bool operator==(const T &lhs, const UbNegInfinity &rhs) { - return rhs.equal( lhs ); + return rhs.equal(lhs); } //************************************************************************************************* -template< typename T > -inline bool operator!=( const UbNegInfinity& lhs, const T& rhs ) +template <typename T> +inline bool operator!=(const UbNegInfinity &lhs, const T &rhs) { - return !lhs.equal( rhs ); + return !lhs.equal(rhs); } //************************************************************************************************* -template< typename T > -inline bool operator!=( const T& lhs, const UbNegInfinity& rhs ) +template <typename T> +inline bool operator!=(const T &lhs, const UbNegInfinity &rhs) { - return !rhs.equal( lhs ); + return !rhs.equal(lhs); } ////////////////////////////////////////////////////////////////////////// @@ -111,61 +112,58 @@ inline bool operator!=( const T& lhs, const UbNegInfinity& rhs ) // UbInfinity // ////////////////////////////////////////////////////////////////////////// -class UbInfinity : public UbNegInfinity //um spaeter -UbInfinity leichter zu implementieren!!! +class UbInfinity : public UbNegInfinity // um spaeter -UbInfinity leichter zu implementieren!!! { - public: - inline UbInfinity() - : UbNegInfinity() - {} - - inline operator unsigned char() const { return UbLimits<unsigned char>::inf(); } - inline operator signed char() const { return UbLimits<signed char>::inf(); } - inline operator char() const { return UbLimits<char>::inf(); } - inline operator wchar_t() const { return UbLimits<wchar_t>::inf(); } - inline operator unsigned short() const { return UbLimits<unsigned short>::inf(); } - inline operator short() const { return UbLimits<short>::inf(); } - inline operator unsigned int() const { return UbLimits<unsigned int>::inf(); } - inline operator int() const { return UbLimits<int>::inf(); } - inline operator unsigned long() const { return UbLimits<unsigned long>::inf(); } - inline operator long() const { return UbLimits<long>::inf(); } - inline operator float() const { return UbLimits<float>::inf(); } - inline operator double() const { return UbLimits<double>::inf(); } - inline operator long double() const { return UbLimits<long double>::inf(); } - - inline const UbNegInfinity& operator-() const { return static_cast<const UbNegInfinity&>( *this ); } - - /*==========================================================*/ - template< typename T > - inline bool equal( const T& rhs ) const - { - UB_STATIC_ASSERT( std::numeric_limits<T>::is_specialized ); - return UbLimits<T>::inf() == rhs; - } - - private: - UbInfinity( const UbInfinity& inf ); //Copy constructor (private & undefined) - UbInfinity& operator=( const UbInfinity& inf ); //Copy assignment operator (private & undefined) - void* operator&() const; //Address operator (private & undefined) +public: + inline UbInfinity() : UbNegInfinity() {} + + inline operator unsigned char() const { return UbLimits<unsigned char>::inf(); } + inline operator signed char() const { return UbLimits<signed char>::inf(); } + inline operator char() const { return UbLimits<char>::inf(); } + inline operator wchar_t() const { return UbLimits<wchar_t>::inf(); } + inline operator unsigned short() const { return UbLimits<unsigned short>::inf(); } + inline operator short() const { return UbLimits<short>::inf(); } + inline operator unsigned int() const { return UbLimits<unsigned int>::inf(); } + inline operator int() const { return UbLimits<int>::inf(); } + inline operator unsigned long() const { return UbLimits<unsigned long>::inf(); } + inline operator long() const { return UbLimits<long>::inf(); } + inline operator float() const { return UbLimits<float>::inf(); } + inline operator double() const { return UbLimits<double>::inf(); } + inline operator long double() const { return UbLimits<long double>::inf(); } + + inline const UbNegInfinity &operator-() const { return static_cast<const UbNegInfinity &>(*this); } + + /*==========================================================*/ + template <typename T> + inline bool equal(const T &rhs) const + { + UB_STATIC_ASSERT(std::numeric_limits<T>::is_specialized); + return UbLimits<T>::inf() == rhs; + } + +private: + UbInfinity(const UbInfinity &inf); // Copy constructor (private & undefined) + UbInfinity &operator=(const UbInfinity &inf); // Copy assignment operator (private & undefined) + void *operator&() const; // Address operator (private & undefined) }; ////////////////////////////////////////////////////////////////////////// // GLOBAL OPERATORS ////////////////////////////////////////////////////////////////////////// -template< typename T > -inline bool operator==( const UbInfinity& lhs, const T& rhs ); +template <typename T> +inline bool operator==(const UbInfinity &lhs, const T &rhs); -template< typename T > -inline bool operator==( const T& lhs, const UbInfinity& rhs ); +template <typename T> +inline bool operator==(const T &lhs, const UbInfinity &rhs); -template< typename T > -inline bool operator!=( const UbInfinity& lhs, const T& rhs ); +template <typename T> +inline bool operator!=(const UbInfinity &lhs, const T &rhs); -template< typename T > -inline bool operator!=( const T& lhs, const UbInfinity& rhs ); +template <typename T> +inline bool operator!=(const T &lhs, const UbInfinity &rhs); //@} //************************************************************************************************* - //************************************************************************************************* /*!\brief Equality comparison between an Infinity object and a built-in data type. // \ingroup util @@ -173,28 +171,28 @@ inline bool operator!=( const T& lhs, const UbInfinity& rhs ); // This operator works only for built-in data types. The attempt to compare user-defined class // types will result in a compile time error. */ -template< typename T > -inline bool operator==( const UbInfinity& lhs, const T& rhs ) +template <typename T> +inline bool operator==(const UbInfinity &lhs, const T &rhs) { - return lhs.equal( rhs ); + return lhs.equal(rhs); } //************************************************************************************************* -template< typename T > -inline bool operator==( const T& lhs, const UbInfinity& rhs ) +template <typename T> +inline bool operator==(const T &lhs, const UbInfinity &rhs) { - return rhs.equal( lhs ); + return rhs.equal(lhs); } //************************************************************************************************* -template< typename T > -inline bool operator!=( const UbInfinity& lhs, const T& rhs ) +template <typename T> +inline bool operator!=(const UbInfinity &lhs, const T &rhs) { - return !lhs.equal( rhs ); + return !lhs.equal(rhs); } //************************************************************************************************* -template< typename T > -inline bool operator!=( const T& lhs, const UbInfinity& rhs ) +template <typename T> +inline bool operator!=(const T &lhs, const UbInfinity &rhs) { - return !rhs.equal( lhs ); + return !rhs.equal(lhs); } //************************************************************************************************* @@ -203,8 +201,8 @@ inline bool operator!=( const T& lhs, const UbInfinity& rhs ) ////////////////////////////////////////////////////////////////////////// namespace Ub { - //e.g. double x = UbSystem::inf; float x = -Ub::inf; - const UbInfinity inf; -} +// e.g. double x = UbSystem::inf; float x = -Ub::inf; +const UbInfinity inf; +} // namespace Ub -#endif //UB_INFINITY_H +#endif // UB_INFINITY_H diff --git a/src/basics/basics/utilities/UbKeys.h b/src/basics/basics/utilities/UbKeys.h index 29713e75626aab7c8207f8d2dc73b788ea32a9e7..60dfbf56bffcf0569a85ded55a276e489deba322 100644 --- a/src/basics/basics/utilities/UbKeys.h +++ b/src/basics/basics/utilities/UbKeys.h @@ -1,28 +1,28 @@ //======================================================================================= -// ____ ____ __ ______ __________ __ __ __ __ -// \ \ | | | | | _ \ |___ ___| | | | | / \ | | -// \ \ | | | | | |_) | | | | | | | / \ | | -// \ \ | | | | | _ / | | | | | | / /\ \ | | -// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ -// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| -// \ \ | | ________________________________________________________________ -// \ \ | | | ______________________________________________________________| -// \ \| | | | __ __ __ __ ______ _______ -// \ | | |_____ | | | | | | | | | _ \ / _____) -// \ | | _____| | | | | | | | | | | \ \ \_______ +// ____ ____ __ ______ __________ __ __ __ __ +// \ \ | | | | | _ \ |___ ___| | | | | / \ | | +// \ \ | | | | | |_) | | | | | | | / \ | | +// \ \ | | | | | _ / | | | | | | / /\ \ | | +// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ +// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| +// \ \ | | ________________________________________________________________ +// \ \ | | | ______________________________________________________________| +// \ \| | | | __ __ __ __ ______ _______ +// \ | | |_____ | | | | | | | | | _ \ / _____) +// \ | | _____| | | | | | | | | | | \ \ \_______ // \ | | | | |_____ | \_/ | | | | |_/ / _____ | -// \ _____| |__| |________| \_______/ |__| |______/ (_______/ +// \ _____| |__| |________| \_______/ |__| |______/ (_______/ // -// This file is part of VirtualFluids. VirtualFluids is free software: you can +// This file is part of VirtualFluids. VirtualFluids is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of +// License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. -// -// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// +// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License along // with VirtualFluids (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>. // @@ -35,270 +35,274 @@ #include <iostream> - #ifdef CAB_RCF - #include <3rdParty/rcf/RcfSerializationIncludes.h> -#endif //CAB_RCF +#include <3rdParty/rcf/RcfSerializationIncludes.h> +#endif // CAB_RCF ////////////////////////////////////////////////////////////////////////// //! -//! \brief +//! \brief //! namespace for global Keys (e.g. for STL-maps) //! ////////////////////////////////////////////////////////////////////////// namespace UbKeys { - //nested class - template< typename T1, typename T2 = T1 > - class Key2 - { - public: - ////////////////////////////////////////////////////////////////////////// - //Konstruktoren - Key2(const T1& t1, const T2& t2) - : t1(t1), t2(t2) - { - } - /*==========================================================*/ - Key2& operator=(const Key2& srcKey) - { - if(this == &srcKey ) return *this; - - t1 = srcKey.t1; - t2 = srcKey.t2; - - return *this; - } - /*==========================================================*/ - T1 getT1() const { return t1; } - T2 getT2() const { return t2; } - - ////////////////////////////////////////////////////////////////////////// - //global ueberladene Operatoren - friend inline bool operator<(const Key2& lhsKey,const Key2& rhsKey) - { - if( lhsKey.t1 < rhsKey.t1 ) return true; - if( lhsKey.t1 > rhsKey.t1 ) return false; - if( lhsKey.t2 < rhsKey.t2 ) return true; +// nested class +template <typename T1, typename T2 = T1> +class Key2 +{ +public: + ////////////////////////////////////////////////////////////////////////// + // Konstruktoren + Key2(const T1 &t1, const T2 &t2) : t1(t1), t2(t2) {} + /*==========================================================*/ + Key2 &operator=(const Key2 &srcKey) + { + if (this == &srcKey) + return *this; - return false; - } - /*==========================================================*/ - friend inline bool operator==(const Key2& lhsKey, const Key2& rhsKey) - { - if(lhsKey.t1 != rhsKey.t1 ) return false; - if(lhsKey.t2 != rhsKey.t2 ) return false; + t1 = srcKey.t1; + t2 = srcKey.t2; - return true; - } - //ueberladene Operatoren - friend inline bool operator!=(const Key2& lhsKey, const Key2& rhsKey) - { - return !(lhsKey == rhsKey); - } - //ueberladene Operatoren - /*==========================================================*/ - friend inline std::ostream& operator << (std::ostream& os, const Key2& key) - { - os<<"Key2<"<<typeid(T1).name()<<","<<typeid(T2).name()<<">,("<<key.t1<<","<<key.t2<<")"; - return os; - } - /*==========================================================*/ - #ifdef CAB_RCF - template<class Archive> - void serialize(Archive & ar, const unsigned int version) - { - ar & t1; - ar & t2; - } - #endif //CAB_RCF + return *this; + } + /*==========================================================*/ + T1 getT1() const { return t1; } + T2 getT2() const { return t2; } - private: - ////////////////////////////////////////////////////////////////////////// - //private Member - T1 t1; - T2 t2; + ////////////////////////////////////////////////////////////////////////// + // global ueberladene Operatoren + friend inline bool operator<(const Key2 &lhsKey, const Key2 &rhsKey) + { + if (lhsKey.t1 < rhsKey.t1) + return true; + if (lhsKey.t1 > rhsKey.t1) + return false; + if (lhsKey.t2 < rhsKey.t2) + return true; - }; + return false; + } + /*==========================================================*/ + friend inline bool operator==(const Key2 &lhsKey, const Key2 &rhsKey) + { + if (lhsKey.t1 != rhsKey.t1) + return false; + if (lhsKey.t2 != rhsKey.t2) + return false; - ////////////////////////////////////////////////////////////////////////// - // - ////////////////////////////////////////////////////////////////////////// - template< typename T1, typename T2 = T1, typename T3 = T1 > - class Key3 - { - public: - ////////////////////////////////////////////////////////////////////////// - //Konstruktoren - Key3() : t1(0), t2(0), t3(0) - { + return true; + } + // ueberladene Operatoren + friend inline bool operator!=(const Key2 &lhsKey, const Key2 &rhsKey) { return !(lhsKey == rhsKey); } + // ueberladene Operatoren + /*==========================================================*/ + friend inline std::ostream &operator<<(std::ostream &os, const Key2 &key) + { + os << "Key2<" << typeid(T1).name() << "," << typeid(T2).name() << ">,(" << key.t1 << "," << key.t2 << ")"; + return os; + } +/*==========================================================*/ +#ifdef CAB_RCF + template <class Archive> + void serialize(Archive &ar, const unsigned int version) + { + ar &t1; + ar &t2; + } +#endif // CAB_RCF - } - Key3(const T1& t1, const T2& t2, const T3& t3) - : t1(t1), t2(t2), t3(t3) - { - } - /*==========================================================*/ - T1 getT1() const { return t1; } - T2 getT2() const { return t2; } - T3 getT3() const { return t3; } - /*==========================================================*/ - Key3& operator=(const Key3& srcKey) - { - if(this == &srcKey ) return *this; +private: + ////////////////////////////////////////////////////////////////////////// + // private Member + T1 t1; + T2 t2; +}; - t1 = srcKey.t1; - t2 = srcKey.t2; - t3 = srcKey.t3; +////////////////////////////////////////////////////////////////////////// +// +////////////////////////////////////////////////////////////////////////// +template <typename T1, typename T2 = T1, typename T3 = T1> +class Key3 +{ +public: + ////////////////////////////////////////////////////////////////////////// + // Konstruktoren + Key3() : t1(0), t2(0), t3(0) {} + Key3(const T1 &t1, const T2 &t2, const T3 &t3) : t1(t1), t2(t2), t3(t3) {} + /*==========================================================*/ + T1 getT1() const { return t1; } + T2 getT2() const { return t2; } + T3 getT3() const { return t3; } + /*==========================================================*/ + Key3 &operator=(const Key3 &srcKey) + { + if (this == &srcKey) + return *this; - return *this; - } + t1 = srcKey.t1; + t2 = srcKey.t2; + t3 = srcKey.t3; - ////////////////////////////////////////////////////////////////////////// - //global ueberladene Operatoren - friend inline bool operator<(const Key3& lhsKey,const Key3& rhsKey) - { - if( lhsKey.t1 < rhsKey.t1 ) return true; - if( lhsKey.t1 > rhsKey.t1 ) return false; - if( lhsKey.t2 < rhsKey.t2 ) return true; - if( lhsKey.t2 > rhsKey.t2 ) return false; - if( lhsKey.t3 < rhsKey.t3 ) return true; + return *this; + } - return false; - } - /*==========================================================*/ - friend inline bool operator==(const Key3& lhsKey,const Key3& rhsKey) - { - if(lhsKey.t1 != rhsKey.t1 ) return false; - if(lhsKey.t2 != rhsKey.t2 ) return false; - if(lhsKey.t3 != rhsKey.t3 ) return false; + ////////////////////////////////////////////////////////////////////////// + // global ueberladene Operatoren + friend inline bool operator<(const Key3 &lhsKey, const Key3 &rhsKey) + { + if (lhsKey.t1 < rhsKey.t1) + return true; + if (lhsKey.t1 > rhsKey.t1) + return false; + if (lhsKey.t2 < rhsKey.t2) + return true; + if (lhsKey.t2 > rhsKey.t2) + return false; + if (lhsKey.t3 < rhsKey.t3) + return true; - return true; - } - /*==========================================================*/ - //ueberladene Operatoren - friend inline bool operator!=(const Key3& lhsKey, const Key3& rhsKey) - { - return !(lhsKey == rhsKey); - } + return false; + } + /*==========================================================*/ + friend inline bool operator==(const Key3 &lhsKey, const Key3 &rhsKey) + { + if (lhsKey.t1 != rhsKey.t1) + return false; + if (lhsKey.t2 != rhsKey.t2) + return false; + if (lhsKey.t3 != rhsKey.t3) + return false; - //ueberladene Operatoren - /*==========================================================*/ - friend inline std::ostream& operator << (std::ostream& os, const Key3& key) - { - os<<"Key3<"<<typeid(T1).name()<<","<<typeid(T2).name()<<","<<typeid(T3).name(); - os<<">,("<<key.t1<<","<<key.t2<<","<<key.t3<<")"; - return os; - } - /*==========================================================*/ - #ifdef CAB_RCF - template<class Archive> - void serialize(Archive & ar, const unsigned int version) - { - ar & t1; - ar & t2; - ar & t3; - } - #endif //CAB_RCF + return true; + } + /*==========================================================*/ + // ueberladene Operatoren + friend inline bool operator!=(const Key3 &lhsKey, const Key3 &rhsKey) { return !(lhsKey == rhsKey); } - private: - ////////////////////////////////////////////////////////////////////////// - //private Member - T1 t1; - T2 t2; - T3 t3; - }; + // ueberladene Operatoren + /*==========================================================*/ + friend inline std::ostream &operator<<(std::ostream &os, const Key3 &key) + { + os << "Key3<" << typeid(T1).name() << "," << typeid(T2).name() << "," << typeid(T3).name(); + os << ">,(" << key.t1 << "," << key.t2 << "," << key.t3 << ")"; + return os; + } +/*==========================================================*/ +#ifdef CAB_RCF + template <class Archive> + void serialize(Archive &ar, const unsigned int version) + { + ar &t1; + ar &t2; + ar &t3; + } +#endif // CAB_RCF - ////////////////////////////////////////////////////////////////////////// - // - ////////////////////////////////////////////////////////////////////////// - template< typename T1, typename T2 = T1, typename T3 = T1, typename T4 = T1 > - class Key4 - { - public: - ////////////////////////////////////////////////////////////////////////// - //Konstruktoren - Key4(const T1& t1, const T2& t2, const T3& t3, const T4& t4) - : t1(t1), t2(t2), t3(t3), t4(t4) - { - } - /*==========================================================*/ - T1 getT1() const { return t1; } - T2 getT2() const { return t2; } - T3 getT3() const { return t3; } - T4 getT4() const { return t4; } - /*==========================================================*/ - Key4& operator=(const Key4& srcKey) - { - if(this == &srcKey ) return *this; +private: + ////////////////////////////////////////////////////////////////////////// + // private Member + T1 t1; + T2 t2; + T3 t3; +}; - t1 = srcKey.t1; - t2 = srcKey.t2; - t3 = srcKey.t3; - t4 = srcKey.t4; +////////////////////////////////////////////////////////////////////////// +// +////////////////////////////////////////////////////////////////////////// +template <typename T1, typename T2 = T1, typename T3 = T1, typename T4 = T1> +class Key4 +{ +public: + ////////////////////////////////////////////////////////////////////////// + // Konstruktoren + Key4(const T1 &t1, const T2 &t2, const T3 &t3, const T4 &t4) : t1(t1), t2(t2), t3(t3), t4(t4) {} + /*==========================================================*/ + T1 getT1() const { return t1; } + T2 getT2() const { return t2; } + T3 getT3() const { return t3; } + T4 getT4() const { return t4; } + /*==========================================================*/ + Key4 &operator=(const Key4 &srcKey) + { + if (this == &srcKey) + return *this; - return *this; - } - ////////////////////////////////////////////////////////////////////////// - //global ueberladene Operatoren - friend inline bool operator<(const Key4& lhsKey,const Key4& rhsKey) - { - if( lhsKey.t1 < rhsKey.t1 ) return true; - if( lhsKey.t1 > rhsKey.t1 ) return false; - if( lhsKey.t2 < rhsKey.t2 ) return true; - if( lhsKey.t2 > rhsKey.t2 ) return false; - if( lhsKey.t3 < rhsKey.t3 ) return true; - if( lhsKey.t3 > rhsKey.t3 ) return false; - if( lhsKey.t4 < rhsKey.t4 ) return true; + t1 = srcKey.t1; + t2 = srcKey.t2; + t3 = srcKey.t3; + t4 = srcKey.t4; - return false; - } - /*==========================================================*/ - friend inline bool operator==(const Key4& lhsKey,const Key4& rhsKey) - { - if(lhsKey.t1 != rhsKey.t1 ) return false; - if(lhsKey.t2 != rhsKey.t2 ) return false; - if(lhsKey.t3 != rhsKey.t3 ) return false; - if(lhsKey.t4 != rhsKey.t4 ) return false; + return *this; + } + ////////////////////////////////////////////////////////////////////////// + // global ueberladene Operatoren + friend inline bool operator<(const Key4 &lhsKey, const Key4 &rhsKey) + { + if (lhsKey.t1 < rhsKey.t1) + return true; + if (lhsKey.t1 > rhsKey.t1) + return false; + if (lhsKey.t2 < rhsKey.t2) + return true; + if (lhsKey.t2 > rhsKey.t2) + return false; + if (lhsKey.t3 < rhsKey.t3) + return true; + if (lhsKey.t3 > rhsKey.t3) + return false; + if (lhsKey.t4 < rhsKey.t4) + return true; - return true; - } + return false; + } + /*==========================================================*/ + friend inline bool operator==(const Key4 &lhsKey, const Key4 &rhsKey) + { + if (lhsKey.t1 != rhsKey.t1) + return false; + if (lhsKey.t2 != rhsKey.t2) + return false; + if (lhsKey.t3 != rhsKey.t3) + return false; + if (lhsKey.t4 != rhsKey.t4) + return false; - //ueberladene Operatoren - friend inline bool operator!=(const Key4& lhsKey, const Key4& rhsKey) - { - return !(lhsKey == rhsKey); - } - //ueberladene Operatoren - /*==========================================================*/ - friend inline std::ostream& operator << (std::ostream& os, const Key4& key) - { - os<<"Key4<"<<typeid(T1).name()<<","<<typeid(T2).name()<<","<<typeid(T3).name()<<","<<typeid(T4).name(); - os<<">,("<<key.t1<<","<<key.t2<<","<<key.t3<<","<<key.t4<<")"; - return os; - } - /*==========================================================*/ - #ifdef CAB_RCF - template<class Archive> - void serialize(Archive & ar, const unsigned int version) - { - ar & t1; - ar & t2; - ar & t3; - ar & t4; - } - #endif //CAB_RCF + return true; + } - private: - ////////////////////////////////////////////////////////////////////////// - //private Member - T1 t1; - T2 t2; - T3 t3; - T4 t4; + // ueberladene Operatoren + friend inline bool operator!=(const Key4 &lhsKey, const Key4 &rhsKey) { return !(lhsKey == rhsKey); } + // ueberladene Operatoren + /*==========================================================*/ + friend inline std::ostream &operator<<(std::ostream &os, const Key4 &key) + { + os << "Key4<" << typeid(T1).name() << "," << typeid(T2).name() << "," << typeid(T3).name() << "," + << typeid(T4).name(); + os << ">,(" << key.t1 << "," << key.t2 << "," << key.t3 << "," << key.t4 << ")"; + return os; + } +/*==========================================================*/ +#ifdef CAB_RCF + template <class Archive> + void serialize(Archive &ar, const unsigned int version) + { + ar &t1; + ar &t2; + ar &t3; + ar &t4; + } +#endif // CAB_RCF - }; -} +private: + ////////////////////////////////////////////////////////////////////////// + // private Member + T1 t1; + T2 t2; + T3 t3; + T4 t4; +}; +} // namespace UbKeys -#endif //UBKEYS_H +#endif // UBKEYS_H diff --git a/src/basics/basics/utilities/UbLimits.h b/src/basics/basics/utilities/UbLimits.h index 282ea2c74a151265957018dc805e4f1c369a86b6..385f1f7e9d1f0cde2f05c2fac6c25f9333ea6293 100644 --- a/src/basics/basics/utilities/UbLimits.h +++ b/src/basics/basics/utilities/UbLimits.h @@ -1,28 +1,28 @@ //======================================================================================= -// ____ ____ __ ______ __________ __ __ __ __ -// \ \ | | | | | _ \ |___ ___| | | | | / \ | | -// \ \ | | | | | |_) | | | | | | | / \ | | -// \ \ | | | | | _ / | | | | | | / /\ \ | | -// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ -// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| -// \ \ | | ________________________________________________________________ -// \ \ | | | ______________________________________________________________| -// \ \| | | | __ __ __ __ ______ _______ -// \ | | |_____ | | | | | | | | | _ \ / _____) -// \ | | _____| | | | | | | | | | | \ \ \_______ +// ____ ____ __ ______ __________ __ __ __ __ +// \ \ | | | | | _ \ |___ ___| | | | | / \ | | +// \ \ | | | | | |_) | | | | | | | / \ | | +// \ \ | | | | | _ / | | | | | | / /\ \ | | +// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ +// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| +// \ \ | | ________________________________________________________________ +// \ \ | | | ______________________________________________________________| +// \ \| | | | __ __ __ __ ______ _______ +// \ | | |_____ | | | | | | | | | _ \ / _____) +// \ | | _____| | | | | | | | | | | \ \ \_______ // \ | | | | |_____ | \_/ | | | | |_/ / _____ | -// \ _____| |__| |________| \_______/ |__| |______/ (_______/ +// \ _____| |__| |________| \_______/ |__| |______/ (_______/ // -// This file is part of VirtualFluids. VirtualFluids is free software: you can +// This file is part of VirtualFluids. VirtualFluids is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of +// License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. -// -// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// +// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License along // with VirtualFluids (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>. // @@ -33,7 +33,6 @@ #ifndef UB_LIMITS_H #define UB_LIMITS_H - //************************************************************************************************* // Includes //************************************************************************************************* @@ -43,123 +42,111 @@ ////////////////////////////////////////////////////////////////////////// // CLASS DEFINITION ////////////////////////////////////////////////////////////////////////// -template< typename T > -struct UbLimits {}; +template <typename T> +struct UbLimits { +}; ////////////////////////////////////////////////////////////////////////// // SPECIALIZATIONS ////////////////////////////////////////////////////////////////////////// -template<> -struct UbLimits<unsigned char> -{ - //return the largest possible positive unsigned char value - static inline unsigned char inf() { return std::numeric_limits<unsigned char>::max(); } +template <> +struct UbLimits<unsigned char> { + // return the largest possible positive unsigned char value + static inline unsigned char inf() { return std::numeric_limits<unsigned char>::max(); } }; //************************************************************************************************* -template<> -struct UbLimits<char> -{ - //return the largest possible positive char value. */ - static inline char inf () { return std::numeric_limits<char>::max(); } - //return the largest possible negative char value - static inline char ninf() { return std::numeric_limits<char>::min(); } +template <> +struct UbLimits<char> { + // return the largest possible positive char value. */ + static inline char inf() { return std::numeric_limits<char>::max(); } + // return the largest possible negative char value + static inline char ninf() { return std::numeric_limits<char>::min(); } }; //************************************************************************************************* -template<> -struct UbLimits<signed char> -{ - //return the largest possible positive signed char value - static inline signed char inf () { return std::numeric_limits<signed char>::max(); } +template <> +struct UbLimits<signed char> { + // return the largest possible positive signed char value + static inline signed char inf() { return std::numeric_limits<signed char>::max(); } - //return The largest possible negative signed char value - static inline signed char ninf() { return std::numeric_limits<signed char>::min(); } + // return The largest possible negative signed char value + static inline signed char ninf() { return std::numeric_limits<signed char>::min(); } }; //************************************************************************************************* -template<> -struct UbLimits<wchar_t> -{ - //return The largest possible positive wchar_t value - static inline wchar_t inf () { return std::numeric_limits<wchar_t>::max(); } - //return The largest possible negative wchar_t value - static inline wchar_t ninf() { return std::numeric_limits<wchar_t>::min(); } +template <> +struct UbLimits<wchar_t> { + // return The largest possible positive wchar_t value + static inline wchar_t inf() { return std::numeric_limits<wchar_t>::max(); } + // return The largest possible negative wchar_t value + static inline wchar_t ninf() { return std::numeric_limits<wchar_t>::min(); } }; //************************************************************************************************* -template<> -struct UbLimits<unsigned short> -{ - //return The largest possible positive unsigned short value - static inline unsigned short inf() { return std::numeric_limits<unsigned short>::max(); } +template <> +struct UbLimits<unsigned short> { + // return The largest possible positive unsigned short value + static inline unsigned short inf() { return std::numeric_limits<unsigned short>::max(); } }; //************************************************************************************************* -template<> -struct UbLimits<short> -{ - //return The largest possible positive short value - static inline short inf () { return std::numeric_limits<short>::max(); } - //return The largest possible negative short value - static inline short ninf() { return std::numeric_limits<short>::min(); } +template <> +struct UbLimits<short> { + // return The largest possible positive short value + static inline short inf() { return std::numeric_limits<short>::max(); } + // return The largest possible negative short value + static inline short ninf() { return std::numeric_limits<short>::min(); } }; //************************************************************************************************* -template<> -struct UbLimits<unsigned int> -{ - //return The largest possible positive unsigned int value - static inline unsigned int inf() { return std::numeric_limits<unsigned int>::max(); } +template <> +struct UbLimits<unsigned int> { + // return The largest possible positive unsigned int value + static inline unsigned int inf() { return std::numeric_limits<unsigned int>::max(); } }; //************************************************************************************************* -template<> -struct UbLimits<int> -{ - //return The largest possible positive int value - static inline int inf () { return std::numeric_limits<int>::max(); } +template <> +struct UbLimits<int> { + // return The largest possible positive int value + static inline int inf() { return std::numeric_limits<int>::max(); } - //return The largest possible negative int value - static inline int ninf() { return std::numeric_limits<int>::min(); } + // return The largest possible negative int value + static inline int ninf() { return std::numeric_limits<int>::min(); } }; //************************************************************************************************* -template<> -struct UbLimits<unsigned long> -{ - //return The largest possible positive unsigned long value - static inline unsigned long inf() { return std::numeric_limits<unsigned long>::max(); } +template <> +struct UbLimits<unsigned long> { + // return The largest possible positive unsigned long value + static inline unsigned long inf() { return std::numeric_limits<unsigned long>::max(); } }; //************************************************************************************************* -template<> -struct UbLimits<long> -{ - //return The largest possible positive long value - static inline long inf () { return std::numeric_limits<long>::max(); } +template <> +struct UbLimits<long> { + // return The largest possible positive long value + static inline long inf() { return std::numeric_limits<long>::max(); } - //return The largest possible negative long value - static inline long ninf() { return std::numeric_limits<long>::min(); } + // return The largest possible negative long value + static inline long ninf() { return std::numeric_limits<long>::min(); } }; //************************************************************************************************* -template<> -struct UbLimits<float> -{ - //return The largest possible positive float value - static inline float inf () { return std::numeric_limits<float>::max(); } +template <> +struct UbLimits<float> { + // return The largest possible positive float value + static inline float inf() { return std::numeric_limits<float>::max(); } - //return The largest possible negative float value - static inline float ninf() { return -std::numeric_limits<float>::max(); } + // return The largest possible negative float value + static inline float ninf() { return -std::numeric_limits<float>::max(); } }; //************************************************************************************************* -template<> -struct UbLimits<double> -{ - //return The largest possible positive double value - static inline double inf () { return std::numeric_limits<double>::max(); } - //return The largest possible negative double value - static inline double ninf() { return -std::numeric_limits<double>::max(); } +template <> +struct UbLimits<double> { + // return The largest possible positive double value + static inline double inf() { return std::numeric_limits<double>::max(); } + // return The largest possible negative double value + static inline double ninf() { return -std::numeric_limits<double>::max(); } }; //************************************************************************************************* -template<> -struct UbLimits<long double> -{ - //return The largest possible positive long double value - static inline long double inf () { return std::numeric_limits<long double>::max(); } - //return The largest possible negative long double value - static inline long double ninf() { return -std::numeric_limits<long double>::max(); } +template <> +struct UbLimits<long double> { + // return The largest possible positive long double value + static inline long double inf() { return std::numeric_limits<long double>::max(); } + // return The largest possible negative long double value + static inline long double ninf() { return -std::numeric_limits<long double>::max(); } }; -#endif //UB_LIMITS_H +#endif // UB_LIMITS_H diff --git a/src/basics/basics/utilities/UbLogger.cpp b/src/basics/basics/utilities/UbLogger.cpp index 29834020f0fdd85ffc4603a0202e4748582a3e1e..b8c28cd0d4ebeadb436965a7f12f39d6393202e4 100644 --- a/src/basics/basics/utilities/UbLogger.cpp +++ b/src/basics/basics/utilities/UbLogger.cpp @@ -1,28 +1,28 @@ //======================================================================================= -// ____ ____ __ ______ __________ __ __ __ __ -// \ \ | | | | | _ \ |___ ___| | | | | / \ | | -// \ \ | | | | | |_) | | | | | | | / \ | | -// \ \ | | | | | _ / | | | | | | / /\ \ | | -// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ -// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| -// \ \ | | ________________________________________________________________ -// \ \ | | | ______________________________________________________________| -// \ \| | | | __ __ __ __ ______ _______ -// \ | | |_____ | | | | | | | | | _ \ / _____) -// \ | | _____| | | | | | | | | | | \ \ \_______ +// ____ ____ __ ______ __________ __ __ __ __ +// \ \ | | | | | _ \ |___ ___| | | | | / \ | | +// \ \ | | | | | |_) | | | | | | | / \ | | +// \ \ | | | | | _ / | | | | | | / /\ \ | | +// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ +// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| +// \ \ | | ________________________________________________________________ +// \ \ | | | ______________________________________________________________| +// \ \| | | | __ __ __ __ ______ _______ +// \ | | |_____ | | | | | | | | | _ \ / _____) +// \ | | _____| | | | | | | | | | | \ \ \_______ // \ | | | | |_____ | \_/ | | | | |_/ / _____ | -// \ _____| |__| |________| \_______/ |__| |______/ (_______/ +// \ _____| |__| |________| \_______/ |__| |______/ (_______/ // -// This file is part of VirtualFluids. VirtualFluids is free software: you can +// This file is part of VirtualFluids. VirtualFluids is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of +// License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. -// -// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// +// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License along // with VirtualFluids (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>. // @@ -37,4 +37,3 @@ boost::mutex Output2Stream::mtx; #endif // CAB_BOOST - diff --git a/src/basics/basics/utilities/UbLogger.h b/src/basics/basics/utilities/UbLogger.h index e30157cb56c8979f2b3fffb27129008626c66fba..d350a763721b4b5fc1c2736fa56e2fff66a3eee0 100644 --- a/src/basics/basics/utilities/UbLogger.h +++ b/src/basics/basics/utilities/UbLogger.h @@ -1,28 +1,28 @@ //======================================================================================= -// ____ ____ __ ______ __________ __ __ __ __ -// \ \ | | | | | _ \ |___ ___| | | | | / \ | | -// \ \ | | | | | |_) | | | | | | | / \ | | -// \ \ | | | | | _ / | | | | | | / /\ \ | | -// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ -// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| -// \ \ | | ________________________________________________________________ -// \ \ | | | ______________________________________________________________| -// \ \| | | | __ __ __ __ ______ _______ -// \ | | |_____ | | | | | | | | | _ \ / _____) -// \ | | _____| | | | | | | | | | | \ \ \_______ +// ____ ____ __ ______ __________ __ __ __ __ +// \ \ | | | | | _ \ |___ ___| | | | | / \ | | +// \ \ | | | | | |_) | | | | | | | / \ | | +// \ \ | | | | | _ / | | | | | | / /\ \ | | +// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ +// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| +// \ \ | | ________________________________________________________________ +// \ \ | | | ______________________________________________________________| +// \ \| | | | __ __ __ __ ______ _______ +// \ | | |_____ | | | | | | | | | _ \ / _____) +// \ | | _____| | | | | | | | | | | \ \ \_______ // \ | | | | |_____ | \_/ | | | | |_/ / _____ | -// \ _____| |__| |________| \_______/ |__| |______/ (_______/ +// \ _____| |__| |________| \_______/ |__| |______/ (_______/ // -// This file is part of VirtualFluids. VirtualFluids is free software: you can +// This file is part of VirtualFluids. VirtualFluids is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of +// License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. -// -// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// +// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License along // with VirtualFluids (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>. // @@ -33,53 +33,52 @@ #ifndef UBLOGGER_H #define UBLOGGER_H -#include <sstream> -#include <string> -#include <iostream> #include <fstream> #include <iomanip> +#include <iostream> +#include <sstream> +#include <string> -#if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(_WIN64) || defined(__WIN64__) - #include <windows.h> +#if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(_WIN64) || defined(__WIN64__) +#include <windows.h> #else - #include <sys/time.h> +#include <sys/time.h> #endif #if defined(CAB_BOOST) && !defined(NO_THREADSAFE_LOGGING) - #include <boost/thread.hpp> +#include <boost/thread.hpp> #endif // CAB_BOOST - - -enum LogLevel {logERROR, logWARNING, logINFO, logDEBUG, logDEBUG1, logDEBUG2, logDEBUG3, logDEBUG4, logDEBUG5}; +enum LogLevel { logERROR, logWARNING, logINFO, logDEBUG, logDEBUG1, logDEBUG2, logDEBUG3, logDEBUG4, logDEBUG5 }; ////////////////////////////////////////////////////////////////////////// // template <typename OutputPolicy> class Log - declaration ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// //! -//! \brief +//! \brief //! C++ Logger //! \details Functionality: //! Per logentry an object of type UbLogger is generated, the log string is passed to this object and -//! upon destruction of the object the string is written to a file or the screen depending on +//! upon destruction of the object the string is written to a file or the screen depending on //! the policy (=template paramter). Multiple log level are supported. //! //! helpermakro: UBLOG //! -//! Example 1: +//! Example 1: //! \code -//! UBLOG(logINFO) << "Klasse::foo entered"; //endl is not required +//! UBLOG(logINFO) << "Klasse::foo entered"; //endl is not required //! \endcode //! -//! Example 2: +//! Example 2: //! \code //! try //! { //! UbLog::reportingLevel() = UbLog::logLevelFromString("DEBUG3"); //! //UbLog::output_policy::setStream(&std::cerr); //<- clog is stdandard -//! UbLog::output_policy::setStream("c:/temp/out.txt"); //you can not open these -> error message -> log is output in cerr -//! +//! UbLog::output_policy::setStream("c:/temp/out.txt"); //you can not open these -> error message -> log is output +//! in cerr +//! //! int count = 3; //! UBLOG(logINFO, "A loop with " << count << " iterations"); //! for (int i = 0; i != count; ++i) @@ -100,7 +99,7 @@ enum LogLevel {logERROR, logWARNING, logINFO, logDEBUG, logDEBUG1, logDEBUG2, lo //! UBLOG(logERROR) << e.what(); //! } //! \endcode -//! Idee based on: +//! Idee based on: //! Paper by Dr. Dobbs Portal, //! September 05, 2007, //! Logging In C++ @@ -108,20 +107,22 @@ enum LogLevel {logERROR, logWARNING, logINFO, logDEBUG, logDEBUG1, logDEBUG2, lo ////////////////////////////////////////////////////////////////////////// template <typename OutputPolicy> class UbLogger -{ +{ public: - using output_policy = OutputPolicy; + using output_policy = OutputPolicy; + public: UbLogger(); virtual ~UbLogger(); - std::ostringstream& get(const LogLevel& level = logINFO); + std::ostringstream &get(const LogLevel &level = logINFO); + public: - //static, weil man so spaeter die ObjErstellunge ersparen kann, - //falls level kleiner als Level - static LogLevel& reportingLevel(); - - static std::string logLevelToString(const LogLevel& level); - static LogLevel logLevelFromString(const std::string& level); + // static, weil man so spaeter die ObjErstellunge ersparen kann, + // falls level kleiner als Level + static LogLevel &reportingLevel(); + + static std::string logLevelToString(const LogLevel &level); + static LogLevel logLevelFromString(const std::string &level); static std::string logTimeString(); @@ -129,27 +130,26 @@ protected: std::ostringstream os; private: - UbLogger(const UbLogger&); - UbLogger& operator =(const UbLogger&); + UbLogger(const UbLogger &); + UbLogger &operator=(const UbLogger &); }; ////////////////////////////////////////////////////////////////////////// // template <typename OutputPolicy> class Log - implementation ////////////////////////////////////////////////////////////////////////// template <typename OutputPolicy> -UbLogger<OutputPolicy>::UbLogger() -= default; +UbLogger<OutputPolicy>::UbLogger() = default; /*==========================================================*/ template <typename OutputPolicy> -std::ostringstream& UbLogger<OutputPolicy>::get(const LogLevel& level) +std::ostringstream &UbLogger<OutputPolicy>::get(const LogLevel &level) { - os << logTimeString() << " " << std::setw(6) + os << logTimeString() << " " << std::setw(6) #if defined(CAB_BOOST) && !defined(NO_MT_LOGGING) - <<boost::this_thread::get_id() << " " + << boost::this_thread::get_id() << " " #endif - << std::setw(8) << std::left << UbLogger<OutputPolicy>::logLevelToString(level) << ": " - << std::string(level > logDEBUG ? 3*(level - logDEBUG) : 0, ' '); //<baumartiger output :D - + << std::setw(8) << std::left << UbLogger<OutputPolicy>::logLevelToString(level) << ": " + << std::string(level > logDEBUG ? 3 * (level - logDEBUG) : 0, ' '); //<baumartiger output :D + return os; } /*==========================================================*/ @@ -161,72 +161,82 @@ UbLogger<OutputPolicy>::~UbLogger() } /*==========================================================*/ template <typename OutputPolicy> -LogLevel& UbLogger<OutputPolicy>::reportingLevel() +LogLevel &UbLogger<OutputPolicy>::reportingLevel() { static LogLevel reportLevel = logINFO; return reportLevel; } /*==========================================================*/ template <typename OutputPolicy> -std::string UbLogger<OutputPolicy>::logLevelToString(const LogLevel& level) +std::string UbLogger<OutputPolicy>::logLevelToString(const LogLevel &level) { - static std::string const buffer[] = {"ERROR", "WARNING", "INFO", "DEBUG", "DEBUG1", "DEBUG2", "DEBUG3", "DEBUG4", "DEBUG5"}; - return buffer[level]; + static std::string const buffer[] = { "ERROR", "WARNING", "INFO", "DEBUG", "DEBUG1", + "DEBUG2", "DEBUG3", "DEBUG4", "DEBUG5" }; + return buffer[level]; } /*==========================================================*/ template <typename OutputPolicy> -LogLevel UbLogger<OutputPolicy>::logLevelFromString(const std::string& level) +LogLevel UbLogger<OutputPolicy>::logLevelFromString(const std::string &level) { - if (level == "DEBUG5" ) return logDEBUG5; - if (level == "DEBUG4" ) return logDEBUG4; - if (level == "DEBUG3" ) return logDEBUG3; - if (level == "DEBUG2" ) return logDEBUG2; - if (level == "DEBUG1" ) return logDEBUG1; - if (level == "DEBUG" ) return logDEBUG; - if (level == "INFO" ) return logINFO; - if (level == "WARNING") return logWARNING; - if (level == "ERROR" ) return logERROR; - - UbLogger<OutputPolicy>().get(logWARNING) << "UbLogger<OutputPolicy>::logLevelFromString(level) - unknown logging level '" << level << "'. Using INFO level as default."; - return logINFO; + if (level == "DEBUG5") + return logDEBUG5; + if (level == "DEBUG4") + return logDEBUG4; + if (level == "DEBUG3") + return logDEBUG3; + if (level == "DEBUG2") + return logDEBUG2; + if (level == "DEBUG1") + return logDEBUG1; + if (level == "DEBUG") + return logDEBUG; + if (level == "INFO") + return logINFO; + if (level == "WARNING") + return logWARNING; + if (level == "ERROR") + return logERROR; + + UbLogger<OutputPolicy>().get(logWARNING) + << "UbLogger<OutputPolicy>::logLevelFromString(level) - unknown logging level '" << level + << "'. Using INFO level as default."; + return logINFO; } ////////////////////////////////////////////////////////////////////////// // logTimeString ////////////////////////////////////////////////////////////////////////// -#if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(_WIN64) || defined(__WIN64__) +#if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(_WIN64) || defined(__WIN64__) template <typename OutputPolicy> inline std::string UbLogger<OutputPolicy>::logTimeString() { - const int MAX_LEN = 200; - char buffer[MAX_LEN]; - if (GetTimeFormatA(LOCALE_USER_DEFAULT, 0, 0, "HH':'mm':'ss", buffer, MAX_LEN) == 0 ) - { - return "Error in std::string UbLogger<OutputPolicy>::logTimeString()"; - } + const int MAX_LEN = 200; + char buffer[MAX_LEN]; + if (GetTimeFormatA(LOCALE_USER_DEFAULT, 0, 0, "HH':'mm':'ss", buffer, MAX_LEN) == 0) { + return "Error in std::string UbLogger<OutputPolicy>::logTimeString()"; + } - char result[100] = {0}; - static DWORD first = GetTickCount(); - std::sprintf(result, "%s.%03ld", buffer, (long)(GetTickCount() - first) % 1000); - return result; + char result[100] = { 0 }; + static DWORD first = GetTickCount(); + std::sprintf(result, "%s.%03ld", buffer, (long)(GetTickCount() - first) % 1000); + return result; } #else template <typename OutputPolicy> inline std::string UbLogger<OutputPolicy>::logTimeString() { - char buffer[11]; - time_t t; - time(&t); - tm r = {0}; - strftime(buffer, sizeof(buffer), "%X", localtime_r(&t, &r)); - struct timeval tv; - gettimeofday(&tv, 0); - char result[100] = {0}; - std::sprintf(result, "%s.%03ld", buffer, (long)tv.tv_usec / 1000); - return result; + char buffer[11]; + time_t t; + time(&t); + tm r = { 0 }; + strftime(buffer, sizeof(buffer), "%X", localtime_r(&t, &r)); + struct timeval tv; + gettimeofday(&tv, 0); + char result[100] = { 0 }; + std::sprintf(result, "%s.%03ld", buffer, (long)tv.tv_usec / 1000); + return result; } -#endif - +#endif ////////////////////////////////////////////////////////////////////////// //! Implementation of OutputPolicy) @@ -234,140 +244,140 @@ inline std::string UbLogger<OutputPolicy>::logTimeString() class Output2Stream // implementation of OutputPolicy { public: - static std::ostream*& getStream(); - static void output(const std::string& msg); - - //!creates output-file-stream (of file opening fails -> stream is set to std::cerr) - static void setStream(const std::string& filename); - - //!direct set outputstream, gcControl = true -> object will be deleted by Output2Stream - static void setStream(std::ostream* pStream, const bool& gcControl = false); + static std::ostream *&getStream(); + static void output(const std::string &msg); + + //! creates output-file-stream (of file opening fails -> stream is set to std::cerr) + static void setStream(const std::string &filename); + + //! direct set outputstream, gcControl = true -> object will be deleted by Output2Stream + static void setStream(std::ostream *pStream, const bool &gcControl = false); protected: #if defined(CAB_BOOST) && !defined(NO_MT_LOGGING) - static boost::mutex mtx; + static boost::mutex mtx; #endif }; /*==========================================================*/ -inline std::ostream*& Output2Stream::getStream() +inline std::ostream *&Output2Stream::getStream() { - static std::ostream* pStream = &std::clog; - return pStream; + static std::ostream *pStream = &std::clog; + return pStream; } /*==========================================================*/ -inline void Output2Stream::setStream(std::ostream* pFile, const bool& gcControl) +inline void Output2Stream::setStream(std::ostream *pFile, const bool &gcControl) { #if defined(CAB_BOOST) && !defined(NO_MT_LOGGING) - boost::mutex::scoped_lock lock(mtx); + boost::mutex::scoped_lock lock(mtx); #endif - static bool s_gcControl = false; - - if( s_gcControl && Output2Stream::getStream() ) - { - delete Output2Stream::getStream(); - } - - s_gcControl = gcControl; - - Output2Stream::getStream() = pFile; + static bool s_gcControl = false; + + if (s_gcControl && Output2Stream::getStream()) { + delete Output2Stream::getStream(); + } + + s_gcControl = gcControl; + + Output2Stream::getStream() = pFile; } /*==========================================================*/ -inline void Output2Stream::setStream(const std::string& filename) +inline void Output2Stream::setStream(const std::string &filename) { - std::ofstream* file = new std::ofstream( filename.c_str() ); - if( !(*file) ) - { - delete file; - Output2Stream::setStream(&std::cerr, false); - UbLogger<Output2Stream>().get(logERROR) << " Output2Stream::setStream(const std::string& filename) could not open file " - << filename << " -> std::cerr is used instead " << std::endl; - return; - } - std::cout<<"UbLog writes to "<<filename<<std::endl; - Output2Stream::setStream(file,true); + std::ofstream *file = new std::ofstream(filename.c_str()); + if (!(*file)) { + delete file; + Output2Stream::setStream(&std::cerr, false); + UbLogger<Output2Stream>().get(logERROR) + << " Output2Stream::setStream(const std::string& filename) could not open file " << filename + << " -> std::cerr is used instead " << std::endl; + return; + } + std::cout << "UbLog writes to " << filename << std::endl; + Output2Stream::setStream(file, true); } /*==========================================================*/ -inline void Output2Stream::output(const std::string& msg) +inline void Output2Stream::output(const std::string &msg) { #if defined(CAB_BOOST) && !defined(NO_MT_LOGGING) - boost::mutex::scoped_lock lock(mtx); + boost::mutex::scoped_lock lock(mtx); #endif - std::ostream* pStream = getStream(); - if (!pStream) return; - (*pStream) << msg << std::flush; + std::ostream *pStream = getStream(); + if (!pStream) + return; + (*pStream) << msg << std::flush; } ////////////////////////////////////////////////////////////////////////// // UbLog ////////////////////////////////////////////////////////////////////////// -class UbLog : public UbLogger< Output2Stream > +class UbLog : public UbLogger<Output2Stream> { - }; -//Macro to limit compiler-side maxLevel +// Macro to limit compiler-side maxLevel #ifndef UBLOG_MAX_LEVEL - #define UBLOG_MAX_LEVEL logDEBUG5 +#define UBLOG_MAX_LEVEL logDEBUG5 #endif ////////////////////////////////////////////////////////////////////////// // example UBLOG(logINFO) << "das ist ein log eintrag"; ////////////////////////////////////////////////////////////////////////// -#define UBLOG(level, logtext) \ - if(level <= UBLOG_MAX_LEVEL && level <= UbLog::reportingLevel() && Output2Stream::getStream()) \ - { \ - UbLog().get(level) << logtext; \ - } - +#define UBLOG(level, logtext) \ + if (level <= UBLOG_MAX_LEVEL && level <= UbLog::reportingLevel() && Output2Stream::getStream()) { \ + UbLog().get(level) << logtext; \ + } + ////////////////////////////////////////////////////////////////////////// -//makro 2 fuer korrekten MultiLineOutput (teuer!!) +// makro 2 fuer korrekten MultiLineOutput (teuer!!) // example1: UBLOGML(logINFO, "line1"<<endl<<"line2"<<endl<<"line3" ) // example2: UBLOGML(logINFO, "line1\nline2\nendl\nline3" ) ////////////////////////////////////////////////////////////////////////// -#define UBLOGML(level, multiline) \ - if(level > UBLOG_MAX_LEVEL || level > UbLog::reportingLevel() || !Output2Stream::getStream()) ; \ - else \ - { \ - std::ostringstream output; \ - output << multiline; \ - std::istringstream input( output.str() ); \ - while(!input.eof()) \ - { \ - std::string dummy; \ - getline(input,dummy,'\n'); \ - UbLog().get(level) << dummy; \ - } \ - } +#define UBLOGML(level, multiline) \ + if (level > UBLOG_MAX_LEVEL || level > UbLog::reportingLevel() || !Output2Stream::getStream()) \ + ; \ + else { \ + std::ostringstream output; \ + output << multiline; \ + std::istringstream input(output.str()); \ + while (!input.eof()) { \ + std::string dummy; \ + getline(input, dummy, '\n'); \ + UbLog().get(level) << dummy; \ + } \ + } ////////////////////////////////////////////////////////////////////////// -//makro3, falls auch bildschirmausgabe erwuenscht +// makro3, falls auch bildschirmausgabe erwuenscht // -> es wird sowohl ins logfile als auch auf den "stream" geschrieben // wenn reporting level und level passen :D -//example1: UBLOG2ML(logINFO, std::cout, "line1"<<endl<<"line2"<<endl<<"line3" ) -//example2: UBLOG2ML(logINFO, std::cout, "line1\nline2\nendl\nline3" ) +// example1: UBLOG2ML(logINFO, std::cout, "line1"<<endl<<"line2"<<endl<<"line3" ) +// example2: UBLOG2ML(logINFO, std::cout, "line1\nline2\nendl\nline3" ) ////////////////////////////////////////////////////////////////////////// -#define UBLOG2(level, stream, text ) \ - if(level > UBLOG_MAX_LEVEL || level > UbLog::reportingLevel() || !Output2Stream::getStream()) ; \ - else { stream << text <<std::endl; UbLog().get(level) << text; } +#define UBLOG2(level, stream, text) \ + if (level > UBLOG_MAX_LEVEL || level > UbLog::reportingLevel() || !Output2Stream::getStream()) \ + ; \ + else { \ + stream << text << std::endl; \ + UbLog().get(level) << text; \ + } ////////////////////////////////////////////////////////////////////////// -//makro4, wie 3 nur mit multiline -//example: UBLOG2(logINFO, std::cout, "test" ) +// makro4, wie 3 nur mit multiline +// example: UBLOG2(logINFO, std::cout, "test" ) ////////////////////////////////////////////////////////////////////////// -#define UBLOG2ML(level, stream, multiline ) \ - if(level > UBLOG_MAX_LEVEL || level > UbLog::reportingLevel() || !Output2Stream::getStream()) ; \ - else \ - { \ - stream << multiline << std::endl; \ - std::ostringstream output; \ - output << multiline; \ - std::istringstream input( output.str() ); \ - while(!input.eof()) \ - { \ - std::string dummy; \ - getline(input,dummy,'\n'); \ - UbLog().get(level) << dummy; \ - } \ - } +#define UBLOG2ML(level, stream, multiline) \ + if (level > UBLOG_MAX_LEVEL || level > UbLog::reportingLevel() || !Output2Stream::getStream()) \ + ; \ + else { \ + stream << multiline << std::endl; \ + std::ostringstream output; \ + output << multiline; \ + std::istringstream input(output.str()); \ + while (!input.eof()) { \ + std::string dummy; \ + getline(input, dummy, '\n'); \ + UbLog().get(level) << dummy; \ + } \ + } ////////////////////////////////////////////////////////////////////////// // example 2 @@ -376,8 +386,9 @@ class UbLog : public UbLogger< Output2Stream > // { // UbLog::reportingLevel() = UbLog::logLevelFromString("DEBUG3"); // //UbLog::output_policy::setStream(&std::cerr); //<- clog ist stdandard -// UbLog::output_policy::setStream("c:/temp/out.txt"); //kann man diese nicht oeffnen -> fehlermeldung -> Log wird in cerr ausgegben -// +// UbLog::output_policy::setStream("c:/temp/out.txt"); //kann man diese nicht oeffnen -> fehlermeldung -> Log wird +// in cerr ausgegben +// // int count = 3; // UBLOG(logINFO, "A loop with " << count << " iterations"); // for (int i = 0; i != count; ++i) @@ -398,5 +409,4 @@ class UbLog : public UbLogger< Output2Stream > // UBLOG(logERROR) << e.what(); // } - -#endif //UBLOGGER_H +#endif // UBLOGGER_H diff --git a/src/basics/basics/utilities/UbMath.cpp b/src/basics/basics/utilities/UbMath.cpp index ffed193fbfc2b269740e213ede6146462f4512b6..d929f55c64b8929ac87ad3e94d06d87e0ab6ce62 100644 --- a/src/basics/basics/utilities/UbMath.cpp +++ b/src/basics/basics/utilities/UbMath.cpp @@ -1,28 +1,28 @@ //======================================================================================= -// ____ ____ __ ______ __________ __ __ __ __ -// \ \ | | | | | _ \ |___ ___| | | | | / \ | | -// \ \ | | | | | |_) | | | | | | | / \ | | -// \ \ | | | | | _ / | | | | | | / /\ \ | | -// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ -// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| -// \ \ | | ________________________________________________________________ -// \ \ | | | ______________________________________________________________| -// \ \| | | | __ __ __ __ ______ _______ -// \ | | |_____ | | | | | | | | | _ \ / _____) -// \ | | _____| | | | | | | | | | | \ \ \_______ +// ____ ____ __ ______ __________ __ __ __ __ +// \ \ | | | | | _ \ |___ ___| | | | | / \ | | +// \ \ | | | | | |_) | | | | | | | / \ | | +// \ \ | | | | | _ / | | | | | | / /\ \ | | +// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ +// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| +// \ \ | | ________________________________________________________________ +// \ \ | | | ______________________________________________________________| +// \ \| | | | __ __ __ __ ______ _______ +// \ | | |_____ | | | | | | | | | _ \ / _____) +// \ | | _____| | | | | | | | | | | \ \ \_______ // \ | | | | |_____ | \_/ | | | | |_/ / _____ | -// \ _____| |__| |________| \_______/ |__| |______/ (_______/ +// \ _____| |__| |________| \_______/ |__| |______/ (_______/ // -// This file is part of VirtualFluids. VirtualFluids is free software: you can +// This file is part of VirtualFluids. VirtualFluids is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of +// License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. -// -// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// +// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License along // with VirtualFluids (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>. // @@ -30,9 +30,8 @@ //! \ingroup utilities //! \author Soeren Freudiger, Sebastian Geller //======================================================================================= -#include <basics/utilities/UbMath.h> #include <basics/utilities/UbInfinity.h> +#include <basics/utilities/UbMath.h> #include <cstring> //for memcmp - -const double UbMath::PI = 4.0* std::atan(1.0); //3.1415926535897932384626433832795 +const double UbMath::PI = 4.0 * std::atan(1.0); // 3.1415926535897932384626433832795 diff --git a/src/basics/basics/utilities/UbMath.h b/src/basics/basics/utilities/UbMath.h index 195dda3998120d85f506b8faf09409858a6a0a52..fe6b01140a4f1675335e3e4f8c9a542055881727 100644 --- a/src/basics/basics/utilities/UbMath.h +++ b/src/basics/basics/utilities/UbMath.h @@ -1,28 +1,28 @@ //======================================================================================= -// ____ ____ __ ______ __________ __ __ __ __ -// \ \ | | | | | _ \ |___ ___| | | | | / \ | | -// \ \ | | | | | |_) | | | | | | | / \ | | -// \ \ | | | | | _ / | | | | | | / /\ \ | | -// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ -// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| -// \ \ | | ________________________________________________________________ -// \ \ | | | ______________________________________________________________| -// \ \| | | | __ __ __ __ ______ _______ -// \ | | |_____ | | | | | | | | | _ \ / _____) -// \ | | _____| | | | | | | | | | | \ \ \_______ +// ____ ____ __ ______ __________ __ __ __ __ +// \ \ | | | | | _ \ |___ ___| | | | | / \ | | +// \ \ | | | | | |_) | | | | | | | / \ | | +// \ \ | | | | | _ / | | | | | | / /\ \ | | +// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ +// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| +// \ \ | | ________________________________________________________________ +// \ \ | | | ______________________________________________________________| +// \ \| | | | __ __ __ __ ______ _______ +// \ | | |_____ | | | | | | | | | _ \ / _____) +// \ | | _____| | | | | | | | | | | \ \ \_______ // \ | | | | |_____ | \_/ | | | | |_/ / _____ | -// \ _____| |__| |________| \_______/ |__| |______/ (_______/ +// \ _____| |__| |________| \_______/ |__| |______/ (_______/ // -// This file is part of VirtualFluids. VirtualFluids is free software: you can +// This file is part of VirtualFluids. VirtualFluids is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of +// License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. -// -// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// +// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License along // with VirtualFluids (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>. // @@ -33,468 +33,474 @@ #ifndef UBMATH_H #define UBMATH_H +#include <basics/utilities/UbEqual.h> +#include <basics/utilities/UbSystem.h> +#include <cassert> #include <cmath> -#include <limits> #include <iostream> -#include <cassert> -#include <basics/utilities/UbSystem.h> -#include <basics/utilities/UbEqual.h> +#include <limits> + +namespace UbMath +{ +extern const double PI; -namespace UbMath -{ - extern const double PI; - - - ////////////////////////////////////////////////////////////////////////// - //Hilfsfunktion fuer Genauigkeit - template< typename T > - struct Epsilon { }; +////////////////////////////////////////////////////////////////////////// +// Hilfsfunktion fuer Genauigkeit +template <typename T> +struct Epsilon { +}; - ////////////////////////////////////////////////////////////////////////// - // SPECIALIZATIONS von Epsilon - ////////////////////////////////////////////////////////////////////////// - template<> - struct Epsilon<double> { static inline double val() { return 1.0E-11; } }; - template<> - struct Epsilon<float> { static inline float val() { return 1.0E-7f; } }; - template<> - struct Epsilon<long double> { static inline long double val() { return 1.0E-15; } }; - template<> - struct Epsilon<int> { static inline int val() { return 0; } }; +////////////////////////////////////////////////////////////////////////// +// SPECIALIZATIONS von Epsilon +////////////////////////////////////////////////////////////////////////// +template <> +struct Epsilon<double> { + static inline double val() { return 1.0E-11; } +}; +template <> +struct Epsilon<float> { + static inline float val() { return 1.0E-7f; } +}; +template <> +struct Epsilon<long double> { + static inline long double val() { return 1.0E-15; } +}; +template <> +struct Epsilon<int> { + static inline int val() { return 0; } +}; + +/*=======================================================*/ +// ------------------------------------------------------------------------------------------------- +// Funktion berechnet den Logarithmus einer Zahl z bzgl. der Basis b +// ------------------------------------------------------------------------------------------------- +template <typename T> +inline T log(const T &z, const T &base) +{ + if (::log(base) == 0) + return 1.0f; + return ::log(z) / ::log(base); +} +/*=======================================================*/ +// double x = UbMath::getNegativeInfinity<double>(); +template <typename T> +inline T getNegativeInfinity() +{ + // assert(std::numeric_limits<T>::has_infinity); + UB_STATIC_ASSERT(std::numeric_limits<T>::has_infinity); + return -std::numeric_limits<T>::infinity(); +} +/*=======================================================*/ +// double x = UbMath::getPositiveInfinity<double>(); +template <typename T> +inline T getPositiveInfinity() +{ + // assert(std::numeric_limits<T>::has_infinity); + UB_STATIC_ASSERT(std::numeric_limits<T>::has_infinity); + return std::numeric_limits<T>::infinity(); +} +/*=======================================================*/ +// double x; bool b = UbMath::isInfinity(x); +template <typename T> +inline bool isInfinity(const T &value) +{ + if (value == getNegativeInfinity<T>()) + return true; + if (value == getPositiveInfinity<T>()) + return true; + return false; +} +/*=======================================================*/ +// double x = UbMath::getNaN<double>(x); +template <typename T> +inline T getNaN() +{ + UB_STATIC_ASSERT(std::numeric_limits<T>::has_quiet_NaN); + return std::numeric_limits<T>::quiet_NaN(); +} +/*=======================================================*/ +// double x; bool b = UbMath::isNaN(x); +// x!=x liefert bei #QNAN "true"! +template <typename T> +inline bool isNaN(const T &x) +{ + UB_STATIC_ASSERT(std::numeric_limits<T>::has_quiet_NaN); + return (x != x); +} +/*=======================================================*/ +template <typename T> +inline T getEqualityEpsilon() +{ + return Epsilon<T>::val(); +} +/*=======================================================*/ +template <typename T> +inline bool zero(const T &value) +{ + return std::fabs(value) < Epsilon<T>::val(); + // return value >= -UbMath::EPSILON && value <= UbMath::EPSILON; +} +/*=======================================================*/ +// spezialisierung fuer ints +template <> +inline bool zero(const int &value) +{ + return value == 0; +} +/*=======================================================*/ +template <typename T1, typename T2> +inline bool zero(const T1 &value1, const T2 &value2) +{ + return !(!UbMath::zero(value1) || !UbMath::zero(value2)); +} +/*=======================================================*/ +template <typename T1, typename T2, typename T3> +inline bool zero(const T1 &value1, const T2 &value2, const T3 &value3) +{ + return !(!UbMath::zero(value1) || !UbMath::zero(value2, value3)); +} +/*=======================================================*/ +template <typename T> +inline bool negative(const T &value) +{ + return value < -Epsilon<T>::val(); +} +/*=======================================================*/ +template <typename T> +inline bool nonPositive(const T &value) +{ + return value <= Epsilon<T>::val(); +} +/*=======================================================*/ +template <typename T> +inline bool positive(const T &value) +{ + return value > +Epsilon<T>::val(); +} +/*=======================================================*/ +template <typename T> +inline bool nonNegative(const T &value) +{ + return value >= -Epsilon<T>::val(); +} +/*=======================================================*/ +template <typename T1, typename T2> +inline bool equal(const T1 &value, const T2 &reference) +{ + using High = typename UbEqualTrait<T1, T2>::High; + return std::fabs(value - reference) < Epsilon<High>::val(); +} +/*=======================================================*/ +template <typename T1, typename T2, typename T3> +inline bool equal(const T1 &val1, const T2 &val2, const T3 &val3) +{ + return (UbMath::equal(val1, val2) && UbMath::equal(val1, val3)); +} +/*=======================================================*/ +template <typename T1, typename T2> +inline bool less(const T1 &value, const T2 &reference) +{ + using High = typename UbEqualTrait<T1, T2>::High; + return value < reference - Epsilon<High>::val(); +} +/*=======================================================*/ +template <typename T1, typename T2> +inline bool lessEqual(const T1 &value, const T2 &reference) +{ + using High = typename UbEqualTrait<T1, T2>::High; + return value <= reference + Epsilon<High>::val(); +} +/*=======================================================*/ +template <typename T1, typename T2> +inline bool greater(const T1 &value, const T2 &reference) +{ + using High = typename UbEqualTrait<T1, T2>::High; + return value > reference + Epsilon<High>::val(); +} +/*=======================================================*/ +template <typename T1, typename T2> +inline bool greaterEqual(const T1 &value, const T2 &reference) +{ + using High = typename UbEqualTrait<T1, T2>::High; + return value >= reference - Epsilon<High>::val(); +} +/*=======================================================*/ +template <typename T> +inline T round(const T &value, const int &decimalPlaces) +{ + return static_cast<T>(floor(value * pow(10.0, decimalPlaces) + 0.5) * pow(10.0, -decimalPlaces)); +} +/*=======================================================*/ +template <typename T> +inline int integerRounding(const T &value) +{ + return static_cast<int>(UbMath::zero(value) ? 0 : ((value < 0.0) ? (value - 0.5) : (value + 0.5))); +} +/*=======================================================*/ +template <typename T> +inline T getRad(const T °rees) +{ + return degrees * static_cast<T>(UbMath::PI / 180.0); +} +/*=======================================================*/ +template <typename T> +inline T getDegrees(const T &rad) +{ + return rad * static_cast<T>(UbMath::PI / 180.0); +} +/*=======================================================*/ +// aus wildmagic +template <typename T> +inline T ACos(const T &fValue) +{ + if (-1.0 < fValue) { + if (fValue < 1.0) + return static_cast<T>(acos(fValue)); + else + return static_cast<T>(0.0); + } else + return static_cast<T>(PI); +} +/*=======================================================*/ +template <typename T> +inline T ASin(const T &fValue) +{ + double HALF_PI = 0.5 * UbMath::PI; + if (-1.0 < fValue) { + if (fValue < 1.0) + return static_cast<T>(asin(fValue)); + else + return static_cast<T>(HALF_PI); + } else + return -static_cast<T>(HALF_PI); +} +/*=======================================================*/ +template <typename T> +inline T invSqrt(const T &fValue) +{ + return static_cast<T>(1.0 / sqrt(fValue)); +} - /*=======================================================*/ - // ------------------------------------------------------------------------------------------------- - // Funktion berechnet den Logarithmus einer Zahl z bzgl. der Basis b - // ------------------------------------------------------------------------------------------------- - template<typename T> - inline T log(const T& z, const T& base) - { - if( ::log(base)==0 ) return 1.0f; - return ::log(z) / ::log(base); - } - /*=======================================================*/ - //double x = UbMath::getNegativeInfinity<double>(); - template<typename T> - inline T getNegativeInfinity() - { - //assert(std::numeric_limits<T>::has_infinity); - UB_STATIC_ASSERT(std::numeric_limits<T>::has_infinity); - return -std::numeric_limits<T>::infinity(); - } - /*=======================================================*/ - //double x = UbMath::getPositiveInfinity<double>(); - template<typename T> - inline T getPositiveInfinity() - { - //assert(std::numeric_limits<T>::has_infinity); - UB_STATIC_ASSERT(std::numeric_limits<T>::has_infinity); - return std::numeric_limits<T>::infinity(); - } - /*=======================================================*/ - //double x; bool b = UbMath::isInfinity(x); - template<typename T> - inline bool isInfinity(const T& value) - { - if(value==getNegativeInfinity<T>()) return true; - if(value==getPositiveInfinity<T>()) return true; - return false; - } - /*=======================================================*/ - //double x = UbMath::getNaN<double>(x); - template<typename T> - inline T getNaN() - { - UB_STATIC_ASSERT(std::numeric_limits<T>::has_quiet_NaN); - return std::numeric_limits<T>::quiet_NaN(); - } - /*=======================================================*/ - //double x; bool b = UbMath::isNaN(x); - // x!=x liefert bei #QNAN "true"! - template<typename T> - inline bool isNaN(const T& x) - { - UB_STATIC_ASSERT(std::numeric_limits<T>::has_quiet_NaN); - return (x != x); - } - /*=======================================================*/ - template<typename T> - inline T getEqualityEpsilon() - { - return Epsilon<T>::val(); - } - /*=======================================================*/ - template<typename T> - inline bool zero(const T& value) - { - return std::fabs( value ) < Epsilon<T>::val(); - //return value >= -UbMath::EPSILON && value <= UbMath::EPSILON; - } - /*=======================================================*/ - //spezialisierung fuer ints - template<> - inline bool zero(const int& value) - { - return value == 0; - } - /*=======================================================*/ - template<typename T1, typename T2> - inline bool zero(const T1& value1, const T2& value2) - { - return !(!UbMath::zero(value1) || !UbMath::zero(value2)); - } - /*=======================================================*/ - template<typename T1, typename T2, typename T3> - inline bool zero(const T1& value1, const T2& value2, const T3& value3) - { - return !(!UbMath::zero(value1) || !UbMath::zero(value2,value3)); - } - /*=======================================================*/ - template<typename T> - inline bool negative(const T& value) - { - return value < -Epsilon<T>::val(); - } - /*=======================================================*/ - template<typename T> - inline bool nonPositive(const T& value) - { - return value <= Epsilon<T>::val(); - } - /*=======================================================*/ - template<typename T> - inline bool positive(const T& value) - { - return value > +Epsilon<T>::val(); - } - /*=======================================================*/ - template<typename T> - inline bool nonNegative(const T& value) - { - return value >= -Epsilon<T>::val(); - } - /*=======================================================*/ - template<typename T1, typename T2> - inline bool equal(const T1& value, const T2& reference) - { - using High = typename UbEqualTrait<T1, T2>::High; - return std::fabs(value-reference) < Epsilon<High>::val(); - } - /*=======================================================*/ - template<typename T1, typename T2, typename T3> - inline bool equal(const T1& val1, const T2& val2, const T3& val3) - { - return ( UbMath::equal(val1,val2) && UbMath::equal(val1,val3) ); - } - /*=======================================================*/ - template<typename T1, typename T2> - inline bool less(const T1& value, const T2& reference) - { - using High = typename UbEqualTrait<T1, T2>::High; - return value < reference - Epsilon<High>::val(); - } - /*=======================================================*/ - template<typename T1, typename T2> - inline bool lessEqual(const T1& value, const T2& reference) - { - using High = typename UbEqualTrait<T1, T2>::High; - return value <= reference + Epsilon<High>::val(); - } - /*=======================================================*/ - template<typename T1, typename T2> - inline bool greater(const T1& value, const T2& reference) - { - using High = typename UbEqualTrait<T1, T2>::High; - return value > reference + Epsilon<High>::val(); - } - /*=======================================================*/ - template<typename T1, typename T2> - inline bool greaterEqual(const T1& value, const T2& reference) - { - using High = typename UbEqualTrait<T1, T2>::High; - return value >= reference - Epsilon<High>::val(); - } - /*=======================================================*/ - template<typename T> - inline T round(const T& value, const int& decimalPlaces) - { - return static_cast<T>(floor(value * pow( 10.0, decimalPlaces) + 0.5 ) * pow(10.0, -decimalPlaces)); - } - /*=======================================================*/ - template<typename T> - inline int integerRounding(const T& value) - { - return static_cast<int>( UbMath::zero(value) ? 0 : ( (value<0.0) ? (value-0.5) : (value+0.5) ) ); - } - /*=======================================================*/ - template<typename T> - inline T getRad(const T& degrees) - { - return degrees*static_cast<T>(UbMath::PI/180.0); - } - /*=======================================================*/ - template<typename T> - inline T getDegrees(const T& rad) - { - return rad*static_cast<T>(UbMath::PI/180.0); - } - /*=======================================================*/ - //aus wildmagic - template<typename T> - inline T ACos (const T& fValue) - { - if ( -1.0 < fValue ) - { - if ( fValue < 1.0 ) return static_cast<T>( acos(fValue) ); - else return static_cast<T>( 0.0 ); - } - else return static_cast<T>( PI ); - } - /*=======================================================*/ - template<typename T> - inline T ASin(const T& fValue) - { - double HALF_PI = 0.5*UbMath::PI; - if ( -1.0 < fValue ) - { - if ( fValue < 1.0 ) return static_cast<T>( asin(fValue) ); - else return static_cast<T>( HALF_PI ); - } - else return -static_cast<T>( HALF_PI ); - } - /*=======================================================*/ - template<typename T> - inline T invSqrt(const T& fValue) - { - return static_cast<T>(1.0/sqrt(fValue)); - } +/*=======================================================*/ +/** + * Returns true, if specified values a and b are less both values c and d. + * @param a the first value to check + * @param b the second value to check + * @param c the first value to check against + * @param d the second value to check against + * @return true, if specified values a and b are less both values c and d + **/ +template <typename T1, typename T2, typename T3, typename T4> +inline bool less2(const T1 &value1, const T2 &value2, T3 toBeLessAs1, T4 toBeLessAs2) +{ + return (less(value1, toBeLessAs1) && less(value1, toBeLessAs2) && less(value2, toBeLessAs1) && + less(value2, toBeLessAs2)); +} +/*=======================================================*/ +template <typename T1, typename T2, typename T3, typename T4> +inline bool greater2(const T1 &value1, const T2 &value2, T3 toBeGreaterAs1, T4 toBeGreaterAs2) +{ + return (greater(value1, toBeGreaterAs1) && greater(value1, toBeGreaterAs2) && greater(value2, toBeGreaterAs1) && + greater(value2, toBeGreaterAs2)); +} +/*=======================================================*/ +template <typename T1, typename T2, typename T3> +inline bool inClosedInterval(const T1 &value, const T2 &threshold1, const T3 &threshold2) +{ + if (threshold1 < threshold2) { + return (greaterEqual(value, threshold1) && lessEqual(value, threshold2)); + } - /*=======================================================*/ - /** - * Returns true, if specified values a and b are less both values c and d. - * @param a the first value to check - * @param b the second value to check - * @param c the first value to check against - * @param d the second value to check against - * @return true, if specified values a and b are less both values c and d - **/ - template<typename T1, typename T2, typename T3, typename T4> - inline bool less2(const T1& value1, const T2& value2, T3 toBeLessAs1, T4 toBeLessAs2) - { - return ( less(value1,toBeLessAs1) - && less(value1,toBeLessAs2) - && less(value2,toBeLessAs1) - && less(value2,toBeLessAs2) ); - } - /*=======================================================*/ - template<typename T1, typename T2, typename T3, typename T4> - inline bool greater2(const T1& value1, const T2& value2, T3 toBeGreaterAs1, T4 toBeGreaterAs2) - { - return ( greater(value1,toBeGreaterAs1) - && greater(value1,toBeGreaterAs2) - && greater(value2,toBeGreaterAs1) - && greater(value2,toBeGreaterAs2) ); - } - /*=======================================================*/ - template<typename T1, typename T2, typename T3> - inline bool inClosedInterval(const T1& value, const T2& threshold1, const T3& threshold2) - { - if(threshold1 < threshold2) - { - return ( greaterEqual( value, threshold1) && lessEqual( value, threshold2) ); - } + return (greaterEqual(value, threshold2) && lessEqual(value, threshold1)); +} +/*=======================================================*/ +template <typename T1, typename T2, typename T3> +inline bool inOpenInterval(const T1 &value, const T2 &threshold1, const T3 &threshold2) +{ + if (threshold1 < threshold2) { + return (greater(value, threshold1) && less(value, threshold2)); + } - return ( greaterEqual( value, threshold2) && lessEqual( value, threshold1) ); - } - /*=======================================================*/ - template<typename T1, typename T2, typename T3> - inline bool inOpenInterval(const T1& value, const T2& threshold1, const T3& threshold2) - { - if(threshold1 < threshold2) - { - return (greater( value, threshold1) && less( value, threshold2)); - } + return (greater(value, threshold2) && less(value, threshold1)); +} +/*=======================================================*/ +template <typename T1, typename T2, typename T3> +inline double adaptToClosedInterval(const T1 &value, const T2 &threshold1, const T3 &threshold2) +{ + if (threshold1 < threshold2) { + if (less(value, threshold1)) + return threshold1; + else if (greater(value, threshold2)) + return threshold2; + } else { + if (less(value, threshold2)) + return threshold2; + else if (greater(value, threshold1)) + return threshold1; + } + return value; +} +/*=======================================================*/ +// ------------------------------------------------------------------------------------------------- +// Funktion berechnet den groessten gemeinsamen Teiler zweier Zahlen (MK) +// ------------------------------------------------------------------------------------------------- +/*=======================================================*/ +inline int calcGgt(int val1, int val2) +{ + if (val1 < val2) + std::swap(val1, val2); + int ggt = val2; + while (ggt > 1) { + if ((val1 % ggt) == 0 && (val2 % ggt) == 0) + break; - return (greater( value, threshold2) && less( value, threshold1)); - } - /*=======================================================*/ - template<typename T1, typename T2, typename T3> - inline double adaptToClosedInterval(const T1& value, const T2& threshold1, const T3& threshold2) - { - if(threshold1 < threshold2) - { - if ( less( value, threshold1) ) return threshold1; - else if( greater(value, threshold2) ) return threshold2; - } - else - { - if ( less( value, threshold2) ) return threshold2; - else if( greater(value, threshold1) ) return threshold1; - } - return value; - } - /*=======================================================*/ - // ------------------------------------------------------------------------------------------------- - // Funktion berechnet den groessten gemeinsamen Teiler zweier Zahlen (MK) - // ------------------------------------------------------------------------------------------------- - /*=======================================================*/ - inline int calcGgt(int val1, int val2) - { - if( val1 < val2 ) std::swap(val1,val2); - int ggt=val2; - while(ggt > 1) - { - if( (val1%ggt)==0 && (val2%ggt)==0 ) break; + ggt -= 1; + } + return ggt; +} +/*=======================================================*/ +// ------------------------------------------------------------------------------------------------- +// Funktion berechnet den groessten gemeinsamen Teiler von drei Zahlen (MK) +// ------------------------------------------------------------------------------------------------- +inline int calcGgt(int val1, const int &val2, int val3) { return UbMath::calcGgt(UbMath::calcGgt(val1, val2), val3); } +/*=======================================================*/ +// returns the max of c2 values +// to avoid errors at mixed argument-types use: double myMax = max<double>(2,2.3); +template <typename T> +inline const T &max(const T &a1, const T &a2) +{ + return (a1 < a2) ? a2 : a1; +} +/*=======================================================*/ +template <typename T> +inline const T &max(const T &a1, const T &a2, const T &a3) +{ + return max(max(a1, a2), a3); +} +/*=======================================================*/ +template <typename T> +inline const T &max(const T &a1, const T &a2, const T &a3, const T &a4) +{ + return max(max(max(a1, a2), a3), a4); +} +/*=======================================================*/ +template <typename T> +inline const T &min(const T &a1, const T &a2) +{ + return (a1 < a2) ? a1 : a2; +} +/*=======================================================*/ +template <typename T> +inline const T &min(const T &a1, const T &a2, const T &a3) +{ + return min(min(a1, a2), a3); +} +/*=======================================================*/ +template <typename T> +inline const T &min(const T &a1, const T &a2, const T &a3, const T &a4) +{ + return min(min(min(a1, a2), a3), a4); - ggt -=1; - } - return ggt; - } - /*=======================================================*/ - // ------------------------------------------------------------------------------------------------- - // Funktion berechnet den groessten gemeinsamen Teiler von drei Zahlen (MK) - // ------------------------------------------------------------------------------------------------- - inline int calcGgt(int val1, const int& val2, int val3) - { - return UbMath::calcGgt( UbMath::calcGgt(val1, val2), val3 ); - } - /*=======================================================*/ - //returns the max of c2 values - //to avoid errors at mixed argument-types use: double myMax = max<double>(2,2.3); - template< typename T > - inline const T& max(const T& a1, const T& a2) - { - return (a1<a2) ? a2 : a1; - } - /*=======================================================*/ - template< typename T > - inline const T& max(const T& a1, const T& a2, const T& a3) - { - return max(max(a1,a2),a3); - } - /*=======================================================*/ - template< typename T > - inline const T& max(const T& a1, const T& a2, const T& a3, const T& a4) - { - return max(max(max(a1,a2),a3),a4); - } - /*=======================================================*/ - template< typename T > - inline const T& min(const T& a1,const T& a2) - { - return (a1<a2) ? a1 : a2; - } - /*=======================================================*/ - template< typename T > - inline const T& min(const T& a1, const T& a2, const T& a3) - { - return min(min(a1,a2),a3); - } - /*=======================================================*/ - template< typename T > - inline const T& min(const T& a1, const T& a2, const T& a3, const T& a4) - { - return min(min(min(a1,a2),a3),a4); - -// double tmp = a1; -// if(tmp>a2) tmp=a2; -// if(tmp>a3) tmp=a3; -// if(tmp>a4) tmp=a4; -// return tmp; - } + // double tmp = a1; + // if(tmp>a2) tmp=a2; + // if(tmp>a3) tmp=a3; + // if(tmp>a4) tmp=a4; + // return tmp; +} - ////////////////////////////////////////////////////////////////////////// - // - //constants - // - ////////////////////////////////////////////////////////////////////////// - static const double c8o27 = 8. / 27.; - static const double c2o27 = 2. / 27.; - static const double c1o54 = 1. / 54.; - static const double c1o216 = 1. / 216.; - static const double c9o2 = 9. / 2.; //4.5 - static const double c9o4 = 9. / 4.; //2.25 - static const double c3o9 = 3. / 9.; - static const double c3o54 = 3. / 54.; - static const double c3o216 = 3. / 216.; +////////////////////////////////////////////////////////////////////////// +// +// constants +// +////////////////////////////////////////////////////////////////////////// +static const double c8o27 = 8. / 27.; +static const double c2o27 = 2. / 27.; +static const double c1o54 = 1. / 54.; +static const double c1o216 = 1. / 216.; +static const double c9o2 = 9. / 2.; // 4.5 +static const double c9o4 = 9. / 4.; // 2.25 +static const double c3o9 = 3. / 9.; +static const double c3o54 = 3. / 54.; +static const double c3o216 = 3. / 216.; - static const double c1o27 = 1. / 27.; +static const double c1o27 = 1. / 27.; - static const double c1o72 = 1. / 72.; //0.01388888 - static const double c1o36 = 1. / 36.; //0.02777777 - static const double c1o48 = 1. / 48.; //0.02083333 - static const double c1o32 = 1. / 32.; //0.03125 - static const double c1o24 = 1. / 24.; //0.04166666 - static const double c1o20 = 1. / 20.; //0.05 - static const double c1o18 = 1. / 18.; //0.05555555 - static const double c1o16 = 1. / 16.; //0.0625 - static const double c1o12 = 1. / 12.; //0.08333333 - static const double c1o9 = 1. / 9.; //0.11111111 - static const double c1o8 = 1. / 8.; //0.125 - static const double c1o6 = 1. / 6.; //0.16666666 - static const double c1o5 = 1. / 5.; //0.2 - static const double c1o4 = 1. / 4.; //0.25 - static const double c1o100 = 1. / 100.; - static const double c5o16 = 5. / 16.; //0.3125 - static const double c1o3 = 1. / 3.; //0.33333333 - static const double c3o8 = 3. / 8.; //0.375 - static const double c4o9 = 4. / 9.; //0.44444444 - static const double c1o2 = 1. / 2.; //0.5 - static const double c9o16 = 9. / 16.; //0.5625 - static const double c2o3 = 2. / 3.; //0.66666666 - static const double c3o4 = 3. / 4.; //0.75 - static const double c3o2 = 3. / 2.; //1.5 - static const double c4o3 = 4. / 3.; //1.33333333 - static const double c5o3 = 5. / 3.; //1.66666666 - static const double c9o5 = 9. / 5.; //1.8 - static const double c2o9 = 2. / 9.; //0.22222222 - static const double one_over_sqrt2 = 1.0 / sqrt(2.0); //0.707106781 - static const double one_over_sqrt3 = 1.0 / sqrt(3.0); //0.577350269 - static const double sqrt2 = sqrt(2.0); //1.4142135 - static const double sqrt3 = sqrt(3.0); //1.7320508 - static const double zeroReal = 0.0; - static const double c1 = 1.0; - static const double c2 = 2.0; - static const double c3 = 3.0; - static const double c4 = 4.0; - static const double c5 = 5.0; - static const double c6 = 6.0; - static const double c7 = 7.0; - static const double c8 = 8.0; - static const double c9 = 9.0; - static const double c14 = 14.0; - static const double c15 = 15.0; - static const double c16 = 16.0; - static const double c18 = 18.0; - static const double c21 = 21.0; - static const double c24 = 24.0; - static const double c28 = 28.0; - static const double c29 = 29.0; - static const double c36 = 36.0; - static const double c48 = 48.0; - static const double c50 = 50.0; - static const double c56 = 56.0; - static const double c152 = 152.0; - static const double c130 = 130.0; - static const double one = 1.0; - static const double two = 2.0; - static const double three = 3.0; - static const double four = 4.0; - static const double five = 5.0; - static const double six = 6.0; - static const double seven = 7.0; - static const double eight = 8.0; - static const double nine = 9.0; - static const double fourteen = 14.0; - static const double fiveteen = 15.0; - static const double sixteen = 16.0; - static const double twentyone = 21.0; - static const double twentyfour = 24.0; - static const double twentyeight = 28.0; - static const double twentynine = 29.0; - static const double fourtyeight = 48.0; - static const double fifty = 50.0; - static const double fiftysix = 56.0; +static const double c1o72 = 1. / 72.; // 0.01388888 +static const double c1o36 = 1. / 36.; // 0.02777777 +static const double c1o48 = 1. / 48.; // 0.02083333 +static const double c1o32 = 1. / 32.; // 0.03125 +static const double c1o24 = 1. / 24.; // 0.04166666 +static const double c1o20 = 1. / 20.; // 0.05 +static const double c1o18 = 1. / 18.; // 0.05555555 +static const double c1o16 = 1. / 16.; // 0.0625 +static const double c1o12 = 1. / 12.; // 0.08333333 +static const double c1o9 = 1. / 9.; // 0.11111111 +static const double c1o8 = 1. / 8.; // 0.125 +static const double c1o6 = 1. / 6.; // 0.16666666 +static const double c1o5 = 1. / 5.; // 0.2 +static const double c1o4 = 1. / 4.; // 0.25 +static const double c1o100 = 1. / 100.; +static const double c5o16 = 5. / 16.; // 0.3125 +static const double c1o3 = 1. / 3.; // 0.33333333 +static const double c3o8 = 3. / 8.; // 0.375 +static const double c4o9 = 4. / 9.; // 0.44444444 +static const double c1o2 = 1. / 2.; // 0.5 +static const double c9o16 = 9. / 16.; // 0.5625 +static const double c2o3 = 2. / 3.; // 0.66666666 +static const double c3o4 = 3. / 4.; // 0.75 +static const double c3o2 = 3. / 2.; // 1.5 +static const double c4o3 = 4. / 3.; // 1.33333333 +static const double c5o3 = 5. / 3.; // 1.66666666 +static const double c9o5 = 9. / 5.; // 1.8 +static const double c2o9 = 2. / 9.; // 0.22222222 +static const double one_over_sqrt2 = 1.0 / sqrt(2.0); // 0.707106781 +static const double one_over_sqrt3 = 1.0 / sqrt(3.0); // 0.577350269 +static const double sqrt2 = sqrt(2.0); // 1.4142135 +static const double sqrt3 = sqrt(3.0); // 1.7320508 +static const double zeroReal = 0.0; +static const double c1 = 1.0; +static const double c2 = 2.0; +static const double c3 = 3.0; +static const double c4 = 4.0; +static const double c5 = 5.0; +static const double c6 = 6.0; +static const double c7 = 7.0; +static const double c8 = 8.0; +static const double c9 = 9.0; +static const double c14 = 14.0; +static const double c15 = 15.0; +static const double c16 = 16.0; +static const double c18 = 18.0; +static const double c21 = 21.0; +static const double c24 = 24.0; +static const double c28 = 28.0; +static const double c29 = 29.0; +static const double c36 = 36.0; +static const double c48 = 48.0; +static const double c50 = 50.0; +static const double c56 = 56.0; +static const double c152 = 152.0; +static const double c130 = 130.0; +static const double one = 1.0; +static const double two = 2.0; +static const double three = 3.0; +static const double four = 4.0; +static const double five = 5.0; +static const double six = 6.0; +static const double seven = 7.0; +static const double eight = 8.0; +static const double nine = 9.0; +static const double fourteen = 14.0; +static const double fiveteen = 15.0; +static const double sixteen = 16.0; +static const double twentyone = 21.0; +static const double twentyfour = 24.0; +static const double twentyeight = 28.0; +static const double twentynine = 29.0; +static const double fourtyeight = 48.0; +static const double fifty = 50.0; +static const double fiftysix = 56.0; -} +} // namespace UbMath #endif diff --git a/src/basics/basics/utilities/UbNupsTimer.h b/src/basics/basics/utilities/UbNupsTimer.h index b4668ba91be3997922502956fd618da0521907c1..ca576fa6ce53c4bfaa48aed26463e12108745c94 100644 --- a/src/basics/basics/utilities/UbNupsTimer.h +++ b/src/basics/basics/utilities/UbNupsTimer.h @@ -5,7 +5,6 @@ #include <sstream> #include <vector> - /*=========================================================================*/ /* UbNupsTimer */ /* */ @@ -14,80 +13,81 @@ This Class provides the base for ... <BR><BR> @author <A HREF="mailto:muffmolch@gmx.de">S. Freudiger</A> @version 1.0 - 01.11.04 -*/ +*/ class UbNupsTimer : public UbTiming { public: - UbNupsTimer() : UbTiming() - { - mTempNodes = 0.0; - mNofNodes.resize(0); - mDurations.resize(0); - } - /*==========================================================*/ - UbNupsTimer(std::string name) : UbTiming(name) - { - mNofNodes.resize(0); - mDurations.resize(0); - mTempNodes = 0.0; - } - /*==========================================================*/ - void initTiming() override - { - UbTiming::initTiming(); - mNofNodes.resize(0); - mDurations.resize(0); - mTempNodes = 0.0; - } - /*==========================================================*/ - void startNUPSTiming(double nofNodes) - { - mTempNodes=nofNodes; - UbTiming::startTiming(); - } - /*==========================================================*/ - void endTiming() override - { - UbTiming::endTiming(); - //save #node and time informations - mNofNodes.push_back(mTempNodes); - mDurations.push_back(UbTiming::getDuration()); - //reset internal timecounter - UbTiming::initTiming(); - } - /*==========================================================*/ - double getAverageNups() - { - double averageNups = 0.0; - for(int i=0;i<(int)mNofNodes.size();i++) - averageNups+=mNofNodes.at(i)/mDurations.at(i); - - return averageNups/(double)mNofNodes.size(); - } - /*==========================================================*/ - double getSumOfDuration() - { - double duration = 0.0; - for(int i=0;i<(int)mDurations.size();i++) duration+=mDurations.at(i); - return duration; - } - /*==========================================================*/ - std::string getNupsString() - { - std::stringstream ss; - ss<<"saved nups informations"<<std::endl; - for(int i=0;i<(int)mNofNodes.size();i++) - ss<<mNofNodes.at(i)<<"nodes/"<<mDurations.at(i)<<"sec="<<mNofNodes.at(i)/mDurations.at(i)<<"nups\n"; - return ss.str(); - } + UbNupsTimer() : UbTiming() + { + mTempNodes = 0.0; + mNofNodes.resize(0); + mDurations.resize(0); + } + /*==========================================================*/ + UbNupsTimer(std::string name) : UbTiming(name) + { + mNofNodes.resize(0); + mDurations.resize(0); + mTempNodes = 0.0; + } + /*==========================================================*/ + void initTiming() override + { + UbTiming::initTiming(); + mNofNodes.resize(0); + mDurations.resize(0); + mTempNodes = 0.0; + } + /*==========================================================*/ + void startNUPSTiming(double nofNodes) + { + mTempNodes = nofNodes; + UbTiming::startTiming(); + } + /*==========================================================*/ + void endTiming() override + { + UbTiming::endTiming(); + // save #node and time informations + mNofNodes.push_back(mTempNodes); + mDurations.push_back(UbTiming::getDuration()); + // reset internal timecounter + UbTiming::initTiming(); + } + /*==========================================================*/ + double getAverageNups() + { + double averageNups = 0.0; + for (int i = 0; i < (int)mNofNodes.size(); i++) + averageNups += mNofNodes.at(i) / mDurations.at(i); -protected: + return averageNups / (double)mNofNodes.size(); + } + /*==========================================================*/ + double getSumOfDuration() + { + double duration = 0.0; + for (int i = 0; i < (int)mDurations.size(); i++) + duration += mDurations.at(i); + return duration; + } + /*==========================================================*/ + std::string getNupsString() + { + std::stringstream ss; + ss << "saved nups informations" << std::endl; + for (int i = 0; i < (int)mNofNodes.size(); i++) + ss << mNofNodes.at(i) << "nodes/" << mDurations.at(i) << "sec=" << mNofNodes.at(i) / mDurations.at(i) + << "nups\n"; + return ss.str(); + } +protected: private: - std::vector<double> mNofNodes; - std::vector<double> mDurations; - - double mTempNodes; + std::vector<double> mNofNodes; + std::vector<double> mDurations; + + double mTempNodes; }; #endif diff --git a/src/basics/basics/utilities/UbObservable.h b/src/basics/basics/utilities/UbObservable.h index f877718f185615bd0645d8b54fd74b35eba4f476..0cbbe5655a47a9f238d038358d1b9855e4e52f80 100644 --- a/src/basics/basics/utilities/UbObservable.h +++ b/src/basics/basics/utilities/UbObservable.h @@ -1,28 +1,28 @@ //======================================================================================= -// ____ ____ __ ______ __________ __ __ __ __ -// \ \ | | | | | _ \ |___ ___| | | | | / \ | | -// \ \ | | | | | |_) | | | | | | | / \ | | -// \ \ | | | | | _ / | | | | | | / /\ \ | | -// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ -// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| -// \ \ | | ________________________________________________________________ -// \ \ | | | ______________________________________________________________| -// \ \| | | | __ __ __ __ ______ _______ -// \ | | |_____ | | | | | | | | | _ \ / _____) -// \ | | _____| | | | | | | | | | | \ \ \_______ +// ____ ____ __ ______ __________ __ __ __ __ +// \ \ | | | | | _ \ |___ ___| | | | | / \ | | +// \ \ | | | | | |_) | | | | | | | / \ | | +// \ \ | | | | | _ / | | | | | | / /\ \ | | +// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ +// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| +// \ \ | | ________________________________________________________________ +// \ \ | | | ______________________________________________________________| +// \ \| | | | __ __ __ __ ______ _______ +// \ | | |_____ | | | | | | | | | _ \ / _____) +// \ | | _____| | | | | | | | | | | \ \ \_______ // \ | | | | |_____ | \_/ | | | | |_/ / _____ | -// \ _____| |__| |________| \_______/ |__| |______/ (_______/ +// \ _____| |__| |________| \_______/ |__| |______/ (_______/ // -// This file is part of VirtualFluids. VirtualFluids is free software: you can +// This file is part of VirtualFluids. VirtualFluids is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of +// License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. -// -// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// +// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License along // with VirtualFluids (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>. // @@ -33,8 +33,8 @@ #ifndef UBOBSERVABLE_H #define UBOBSERVABLE_H -#include <list> #include <iostream> +#include <list> #include <basics/utilities/UbObserver.h> @@ -49,8 +49,8 @@ class UbObserver; //! this destructor is called AFTER the destructor of the //! child classes. if you down_cast the pointer sent with the //! objectWillBeDeleted(UbObserver* objpointer) then have to go this: -//! -//! if(dynamic_cast<UbObserver*>(observedObj)==objpointer) +//! +//! if(dynamic_cast<UbObserver*>(observedObj)==objpointer) //! (e.g.) observedObj=NULL; //! example: see end of file //! @@ -66,159 +66,149 @@ class UbObserver; //! ////////////////////////////////////////////////////////////////////////// -class UbObservable +class UbObservable { protected: - /*======================================================================*/ - /* Konstruktoren */ - /* */ - /** - Creates a UbObservable itself to be the object to be observed. - Usually this constructor is used in extended classes. - */ - UbObservable() - = default; - - UbObservable(const UbObservable& /*src*/) - { - //no copy of observers !!! - } - - //falls irgendein schlaumeier den =operator von UbObservable aufrufen sollte, - //dann macht diesr auch keine kopie! (Allg: zuweisungsoperatoren werden nie vererbt - UbObservable& operator=(const UbObservable& /*src*/) - { - return *this; - } - - // /** - // Creates a UbObservable for the specified Object to be observed. - // Usually this constructor is used in associating UbObservable. - // @param object Object to be observed - // */ + /*======================================================================*/ + /* Konstruktoren */ + /* */ + /** + Creates a UbObservable itself to be the object to be observed. + Usually this constructor is used in extended classes. + */ + UbObservable() = default; + + UbObservable(const UbObservable & /*src*/) + { + // no copy of observers !!! + } + + // falls irgendein schlaumeier den =operator von UbObservable aufrufen sollte, + // dann macht diesr auch keine kopie! (Allg: zuweisungsoperatoren werden nie vererbt + UbObservable &operator=(const UbObservable & /*src*/) { return *this; } + + // /** + // Creates a UbObservable for the specified Object to be observed. + // Usually this constructor is used in associating UbObservable. + // @param object Object to be observed + // */ public: - /*======================================================================*/ - /* Destruktor */ - /* */ - /** - */ - virtual ~UbObservable() - { - this->notifyObserversObjectWillBeDeleted(); - } + /*======================================================================*/ + /* Destruktor */ + /* */ + /** + */ + virtual ~UbObservable() { this->notifyObserversObjectWillBeDeleted(); } + + /*======================================================================*/ + /* methods */ + /* */ - /*======================================================================*/ - /* methods */ - /* */ - - /** - Adds an UbObserver to the observerlist. - @param observer the observer to add to this observable (note that an observer may observe c1 observable more than once) - */ - virtual void addObserver(UbObserver* observer) - { - if(!observer) return; - for(std::list<UbObserver*>::iterator pos=mObserverList.begin();pos!=mObserverList.end();++pos) - { - if(*pos == observer) return; - } - this->mObserverList.push_back(observer); - } - /** - Deletes an UbObserver from the observerlist. - @param observer the observer to remove from this observable (note that all observers identical are deleted) - ( delete means delete Heap... but here we're only removing a pointer) - */ - virtual void removeObserver(UbObserver* observer) - { - if(!observer) return; - this->mObserverList.remove(observer); + /** + Adds an UbObserver to the observerlist. + @param observer the observer to add to this observable (note that an observer may observe c1 observable more than + once) + */ + virtual void addObserver(UbObserver *observer) + { + if (!observer) + return; + for (std::list<UbObserver *>::iterator pos = mObserverList.begin(); pos != mObserverList.end(); ++pos) { + if (*pos == observer) + return; + } + this->mObserverList.push_back(observer); + } + /** + Deletes an UbObserver from the observerlist. + @param observer the observer to remove from this observable (note that all observers identical are deleted) + ( delete means delete Heap... but here we're only removing a pointer) + */ + virtual void removeObserver(UbObserver *observer) + { + if (!observer) + return; + this->mObserverList.remove(observer); + } + /** + Deletes all Observers from the observerlist. + ( delete means delete Heap... but here we're only removing a pointer) + */ + virtual void removeAllObservers() { this->mObserverList.clear(); } - } - /** - Deletes all Observers from the observerlist. - ( delete means delete Heap... but here we're only removing a pointer) - */ - virtual void removeAllObservers() - { - this->mObserverList.clear(); - } - - /** - Checks whether the specified UbObserver observes this observable. - @param observer the observer to remove from this observable (note that all observers identical are deleted) - @return true if the specified observer observes this observable - */ - virtual bool isObservedBy(UbObserver* observer) - { - if(!observer) return false; - for(std::list<UbObserver*>::iterator pos=mObserverList.begin();pos!=mObserverList.end();++pos) - { - if(*pos == observer) return true; - } - return false; - } - /** - Notifies all of its observers that something happened. Does nothing, if the observed object is null. - Calls the Method UbObserver.objectChanged(Object) with the object of this observable as parameter. - The Method UbObserver.objectChanged(Object) must be defined - by each class implementing the interface TiObserver - */ - virtual void notifyObserversObjectChanged() - { - std::list<UbObserver*>::iterator tmp_pos; //es kann sein, dass der aktuelle observer waehrend - //objectChanged() removed wird... - for(std::list<UbObserver*>::iterator pos=mObserverList.begin();pos!=mObserverList.end();) - { - //cout<<"in notifyObserversObjectChanged\n"; - //cout<<this->mObserverList.size()<<endl; + /** + Checks whether the specified UbObserver observes this observable. + @param observer the observer to remove from this observable (note that all observers identical are deleted) + @return true if the specified observer observes this observable + */ + virtual bool isObservedBy(UbObserver *observer) + { + if (!observer) + return false; + for (std::list<UbObserver *>::iterator pos = mObserverList.begin(); pos != mObserverList.end(); ++pos) { + if (*pos == observer) + return true; + } + return false; + } + /** + Notifies all of its observers that something happened. Does nothing, if the observed object is null. + Calls the Method UbObserver.objectChanged(Object) with the object of this observable as parameter. + The Method UbObserver.objectChanged(Object) must be defined + by each class implementing the interface TiObserver + */ + virtual void notifyObserversObjectChanged() + { + std::list<UbObserver *>::iterator tmp_pos; // es kann sein, dass der aktuelle observer waehrend + // objectChanged() removed wird... + for (std::list<UbObserver *>::iterator pos = mObserverList.begin(); pos != mObserverList.end();) { + // cout<<"in notifyObserversObjectChanged\n"; + // cout<<this->mObserverList.size()<<endl; - tmp_pos = pos++; // erst tmp_pos=pos und dann pos++ - (*tmp_pos)->objectChanged(this); - } - } + tmp_pos = pos++; // erst tmp_pos=pos und dann pos++ + (*tmp_pos)->objectChanged(this); + } + } - std::list<UbObserver*>* getObserverList() { return &mObserverList;} + std::list<UbObserver *> *getObserverList() { return &mObserverList; } - virtual std::string toString() { return "UbObservable - toString()"; } + virtual std::string toString() { return "UbObservable - toString()"; } private: - /** - Notifies all of its observers that something happened. Does nothing, if the observed object is null. - Calls the Method UbObserver.objectChanged(Object) with the object of this observable as parameter. - The Method UbObserver.objectChanged(Object) must be defined - by each class implementing the interface TiObserver - */ - virtual void notifyObserversObjectWillBeDeleted() - { - std::list<UbObserver*>::iterator tmp_pos; //es kann sein, dass der aktuelle observer waehrend - //objectWillBeDeleted() removed wird... - for(std::list<UbObserver*>::iterator pos=mObserverList.begin();pos!=mObserverList.end();) - { - //cout<<"in notifyObserversObjectWillBeDeleted\n"; - //cout<<this->mObserverList.size()<<endl; + /** + Notifies all of its observers that something happened. Does nothing, if the observed object is null. + Calls the Method UbObserver.objectChanged(Object) with the object of this observable as parameter. + The Method UbObserver.objectChanged(Object) must be defined + by each class implementing the interface TiObserver + */ + virtual void notifyObserversObjectWillBeDeleted() + { + std::list<UbObserver *>::iterator tmp_pos; // es kann sein, dass der aktuelle observer waehrend + // objectWillBeDeleted() removed wird... + for (std::list<UbObserver *>::iterator pos = mObserverList.begin(); pos != mObserverList.end();) { + // cout<<"in notifyObserversObjectWillBeDeleted\n"; + // cout<<this->mObserverList.size()<<endl; - tmp_pos = pos++; - (*tmp_pos)->objectWillBeDeleted(this); - } - } + tmp_pos = pos++; + (*tmp_pos)->objectWillBeDeleted(this); + } + } - std::list<UbObserver*> mObserverList; + std::list<UbObserver *> mObserverList; }; /*=========================================================================*/ - #ifdef RCF_USE_SF_SERIALIZATION - SF_NO_CTOR(UbObservable); -#endif //RCF_USE_SF_SERIALIZATION +SF_NO_CTOR(UbObservable); +#endif // RCF_USE_SF_SERIALIZATION #endif -//// E X A M P L E +//// E X A M P L E ////=================== -//class Point : public UbObservable +// class Point : public UbObservable //{ -//public: +// public: // Point(){x=y=0;} // ~Point(){} // void setXCorrdinates(int x,int y) @@ -226,14 +216,14 @@ private: // this->x = x; this->y = y; // this->notifyObserverObjectChanged(); // } -//private: +// private: // int x,y; //}; -//class VisPoint : public UbObserver +// class VisPoint : public UbObserver //{ -//public: +// public: // VisPoint(Point* point) -// { +// { // this->point = point; // this->point->addObserver(this); // } @@ -264,6 +254,6 @@ private: // //was hingegen immer moeglich sein sollte: // //if(dynamic_cast<void*>(objectForDeletion)==dynamic_cast<void*>(this->point)) // } -//private: +// private: // Point* point; //}; diff --git a/src/basics/basics/utilities/UbObserver.h b/src/basics/basics/utilities/UbObserver.h index dab5d28c0cc83a4a73fdba8d9be7f979f9d96c2b..ecba69207f2c7f76d36ef0699b23eb0c088968a6 100644 --- a/src/basics/basics/utilities/UbObserver.h +++ b/src/basics/basics/utilities/UbObserver.h @@ -1,28 +1,28 @@ //======================================================================================= -// ____ ____ __ ______ __________ __ __ __ __ -// \ \ | | | | | _ \ |___ ___| | | | | / \ | | -// \ \ | | | | | |_) | | | | | | | / \ | | -// \ \ | | | | | _ / | | | | | | / /\ \ | | -// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ -// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| -// \ \ | | ________________________________________________________________ -// \ \ | | | ______________________________________________________________| -// \ \| | | | __ __ __ __ ______ _______ -// \ | | |_____ | | | | | | | | | _ \ / _____) -// \ | | _____| | | | | | | | | | | \ \ \_______ +// ____ ____ __ ______ __________ __ __ __ __ +// \ \ | | | | | _ \ |___ ___| | | | | / \ | | +// \ \ | | | | | |_) | | | | | | | / \ | | +// \ \ | | | | | _ / | | | | | | / /\ \ | | +// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ +// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| +// \ \ | | ________________________________________________________________ +// \ \ | | | ______________________________________________________________| +// \ \| | | | __ __ __ __ ______ _______ +// \ | | |_____ | | | | | | | | | _ \ / _____) +// \ | | _____| | | | | | | | | | | \ \ \_______ // \ | | | | |_____ | \_/ | | | | |_/ / _____ | -// \ _____| |__| |________| \_______/ |__| |______/ (_______/ +// \ _____| |__| |________| \_______/ |__| |______/ (_______/ // -// This file is part of VirtualFluids. VirtualFluids is free software: you can +// This file is part of VirtualFluids. VirtualFluids is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of +// License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. -// -// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// +// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License along // with VirtualFluids (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>. // @@ -46,33 +46,29 @@ class UbObservable; //! ////////////////////////////////////////////////////////////////////////// -class UbObserver +class UbObserver { protected: - - UbObserver()= default; + UbObserver() = default; public: + virtual ~UbObserver() = default; - virtual ~UbObserver()= default; - - /*======================================================================*/ - /* Methods */ - /* */ - /*! - This function is called when the observable indicated that an object - has changed. - \param changedObject Object which has changed - */ - virtual void objectChanged(UbObservable* changedObject)=0; - /*! - This function is called when the observable indicated that an object - should be deleted. - \param objectForDeletion Object which should be deleted - */ - virtual void objectWillBeDeleted(UbObservable* objectForDeletion)=0; + /*======================================================================*/ + /* Methods */ + /* */ + /*! + This function is called when the observable indicated that an object + has changed. + \param changedObject Object which has changed + */ + virtual void objectChanged(UbObservable *changedObject) = 0; + /*! + This function is called when the observable indicated that an object + should be deleted. + \param objectForDeletion Object which should be deleted + */ + virtual void objectWillBeDeleted(UbObservable *objectForDeletion) = 0; }; #endif - - diff --git a/src/basics/basics/utilities/UbRandom.h b/src/basics/basics/utilities/UbRandom.h index dd3b4671e69e504db5f3fdb3cba0c4a2ad7c8b43..aed28014b0a866f9223162dc9a07237c7da4b1b0 100644 --- a/src/basics/basics/utilities/UbRandom.h +++ b/src/basics/basics/utilities/UbRandom.h @@ -4,13 +4,13 @@ // | |/ / / / / /_/ /_/ / /_/ / / __/ / / /_/ / / /_/ (__ ) // |___/_/_/ \__/\__,_/\__,_/_/_/ /_/\__,_/_/\__,_/____/ // -#ifndef UBRANDOM_H -#define UBRANDOM_H +#ifndef UBRANDOM_H +#define UBRANDOM_H -#include <cstdlib> -#include <ctime> -#include <cassert> -#include <cmath> +#include <cassert> +#include <cmath> +#include <cstdlib> +#include <ctime> /*=========================================================================*/ /* UbRandom */ @@ -20,41 +20,41 @@ generates a random number <BR><BR> @author <A HREF="mailto:muffmolch@gmx.de">S. Freudiger</A> @version 1.0 - 04.10.2007 -*/ +*/ /* -usage: - int main() - { - char* hand[] = {"Schere", "Stein", "Papier"}; - for (unsigned u = 0; u < 20; u++) - { - cout << hand[UbRandom::rand(0, 2, 1)] << endl; - } +usage: + int main() + { + char* hand[] = {"Schere", "Stein", "Papier"}; + for (unsigned u = 0; u < 20; u++) + { + cout << hand[UbRandom::rand(0, 2, 1)] << endl; + } - return 0; - } + return 0; + } */ -class UbRandom -{ -private: - UbRandom() { std::srand(static_cast<int>(std::time(NULL))); } +class UbRandom +{ +private: + UbRandom() { std::srand(static_cast<int>(std::time(NULL))); } -public: - //returns arbitrary int value element of [min ; max] - static inline int rand(const int& min, const int& max) - { - static UbRandom dummy; - assert(max - min < RAND_MAX); - return ( min + std::rand() % (max - min + 1) ); - } - //returns arbitrary float value element of "( (max - min) / gran ) * [min ; max]" - //with other words: val = min+n*(max-min)/gran, n=0..gran-1 - static inline double rand(const double& min, const double& max, const double& gran) - { - static UbRandom dummy; - return (min + std::floor( std::rand() / (1.0 + RAND_MAX) * gran)* (max - min) / gran); - } -}; +public: + // returns arbitrary int value element of [min ; max] + static inline int rand(const int &min, const int &max) + { + static UbRandom dummy; + assert(max - min < RAND_MAX); + return (min + std::rand() % (max - min + 1)); + } + // returns arbitrary float value element of "( (max - min) / gran ) * [min ; max]" + // with other words: val = min+n*(max-min)/gran, n=0..gran-1 + static inline double rand(const double &min, const double &max, const double &gran) + { + static UbRandom dummy; + return (min + std::floor(std::rand() / (1.0 + RAND_MAX) * gran) * (max - min) / gran); + } +}; -#endif //UBRANDOM_H +#endif // UBRANDOM_H diff --git a/src/basics/basics/utilities/UbScheduler.h b/src/basics/basics/utilities/UbScheduler.h index fcb410b2270843ee8e6c8a274228be71446d2841..08bb38ba8ae8755d8ef1e38cd92279e26b994610 100644 --- a/src/basics/basics/utilities/UbScheduler.h +++ b/src/basics/basics/utilities/UbScheduler.h @@ -1,28 +1,28 @@ //======================================================================================= -// ____ ____ __ ______ __________ __ __ __ __ -// \ \ | | | | | _ \ |___ ___| | | | | / \ | | -// \ \ | | | | | |_) | | | | | | | / \ | | -// \ \ | | | | | _ / | | | | | | / /\ \ | | -// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ -// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| -// \ \ | | ________________________________________________________________ -// \ \ | | | ______________________________________________________________| -// \ \| | | | __ __ __ __ ______ _______ -// \ | | |_____ | | | | | | | | | _ \ / _____) -// \ | | _____| | | | | | | | | | | \ \ \_______ +// ____ ____ __ ______ __________ __ __ __ __ +// \ \ | | | | | _ \ |___ ___| | | | | / \ | | +// \ \ | | | | | |_) | | | | | | | / \ | | +// \ \ | | | | | _ / | | | | | | / /\ \ | | +// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ +// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| +// \ \ | | ________________________________________________________________ +// \ \ | | | ______________________________________________________________| +// \ \| | | | __ __ __ __ ______ _______ +// \ | | |_____ | | | | | | | | | _ \ / _____) +// \ | | _____| | | | | | | | | | | \ \ \_______ // \ | | | | |_____ | \_/ | | | | |_/ / _____ | -// \ _____| |__| |________| \_______/ |__| |______/ (_______/ +// \ _____| |__| |________| \_______/ |__| |______/ (_______/ // -// This file is part of VirtualFluids. VirtualFluids is free software: you can +// This file is part of VirtualFluids. VirtualFluids is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of +// License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. -// -// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// +// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License along // with VirtualFluids (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>. // @@ -33,22 +33,22 @@ #ifndef UBSCHEDULER_H #define UBSCHEDULER_H +#include <algorithm> +#include <cassert> +#include <iomanip> #include <iostream> -#include <string> #include <limits> -#include <cassert> #include <sstream> -#include <iomanip> -#include <algorithm> +#include <string> -#include <basics/utilities/UbSystem.h> -#include <basics/utilities/UbMath.h> -#include <basics/utilities/UbInfinity.h> #include <basics/utilities/UbComparators.h> +#include <basics/utilities/UbInfinity.h> +#include <basics/utilities/UbMath.h> +#include <basics/utilities/UbSystem.h> ////////////////////////////////////////////////////////////////////////// //! -//! \brief A class implements scheduling. +//! \brief A class implements scheduling. //! \details This class is not thread save. //! ////////////////////////////////////////////////////////////////////////// @@ -56,276 +56,278 @@ class UbScheduler { public: - class UbSchedule - { - friend class UbScheduler; - public: - UbSchedule() : step(Ub::inf), begin(Ub::inf), end(Ub::inf) { } - UbSchedule(const double& step, const double& begin=0.0, const double& end=Ub::inf) - : step(step), begin(begin), end(end) - { - } - double getStep() const { return this->step; } - double getBegin() const { return this->begin; } - double getEnd() const { return this->end; } - - /*==========================================================*/ - std::string toString() { std::stringstream text; text<<*this; return text.str(); } - /*==========================================================*/ - friend inline std::ostream& operator << (std::ostream& os, const UbSchedule& schedule) - { - os<<"Schedule[start,end,step]=["<<schedule.begin<<", "<<schedule.end<<", "<<schedule.step<<"]"; - return os; - } + class UbSchedule + { + friend class UbScheduler; - private: - double step, begin, end; - }; + public: + UbSchedule() : step(Ub::inf), begin(Ub::inf), end(Ub::inf) {} + UbSchedule(const double &step, const double &begin = 0.0, const double &end = Ub::inf) + : step(step), begin(begin), end(end) + { + } + double getStep() const { return this->step; } + double getBegin() const { return this->begin; } + double getEnd() const { return this->end; } + + /*==========================================================*/ + std::string toString() + { + std::stringstream text; + text << *this; + return text.str(); + } + /*==========================================================*/ + friend inline std::ostream &operator<<(std::ostream &os, const UbSchedule &schedule) + { + os << "Schedule[start,end,step]=[" << schedule.begin << ", " << schedule.end << ", " << schedule.step + << "]"; + return os; + } + + private: + double step, begin, end; + }; public: - UbScheduler() - { - this->initVals(); - } - /*==========================================================*/ - UbScheduler(const double& step,const double& begin=0, const double& end=Ub::inf ) - { - this->initVals(); - this->addSchedule(step,begin,end); - } - /*==========================================================*/ - UbScheduler(const UbSchedule& schedule) - { - this->initVals(); - this->addSchedule(schedule); - } - /*==========================================================*/ - virtual ~UbScheduler() = default; - /*==========================================================*/ - inline void addSchedule(const UbSchedule& schedule) - { - this->addSchedule(schedule.step, schedule.begin, schedule.end); - } - /*==========================================================*/ - bool addSchedule(const double& step, const double& begin, double end) - { - if( UbMath::zero(step) || begin>end ) - { - std::cerr<<"UbScheduler::addSchedule - invalid Schedule:\n\t"<<UbSchedule(step, begin, end)<<std::endl; - return false; - } - - if( UbMath::less( end, (double)Ub::inf ) ) - { - //es kann vorkommen, dass man mit dem intervall nicht genau auf den letzten wert kommt - //(z.B. step=2; start=0; end=9; -> ende wird angepasst) - //also wenn end-begin>Ub::inf ist, dann geht es halt nicht.. ein cast in long double half hier nichts - double multiplier=0.0; - double fractpart = modf( (end-begin)/step, &multiplier); - if( !UbMath::zero(fractpart) ) - { - //tmp-speicherung (fuer cerr) - fractpart = end; - //neues ende - end = begin+multiplier*step; - - std::cerr<<"Warning: UbScheduler::addSchedule - " - <<"end of schedule was adapted to intervall \n\t" - <<"from "<< UbSchedule(step, begin, fractpart) <<" to "<< UbSchedule(step, begin, end) <<std::endl; - } - } + UbScheduler() { this->initVals(); } + /*==========================================================*/ + UbScheduler(const double &step, const double &begin = 0, const double &end = Ub::inf) + { + this->initVals(); + this->addSchedule(step, begin, end); + } + /*==========================================================*/ + UbScheduler(const UbSchedule &schedule) + { + this->initVals(); + this->addSchedule(schedule); + } + /*==========================================================*/ + virtual ~UbScheduler() = default; + /*==========================================================*/ + inline void addSchedule(const UbSchedule &schedule) + { + this->addSchedule(schedule.step, schedule.begin, schedule.end); + } + /*==========================================================*/ + bool addSchedule(const double &step, const double &begin, double end) + { + if (UbMath::zero(step) || begin > end) { + std::cerr << "UbScheduler::addSchedule - invalid Schedule:\n\t" << UbSchedule(step, begin, end) + << std::endl; + return false; + } + + if (UbMath::less(end, (double)Ub::inf)) { + // es kann vorkommen, dass man mit dem intervall nicht genau auf den letzten wert kommt + //(z.B. step=2; start=0; end=9; -> ende wird angepasst) + // also wenn end-begin>Ub::inf ist, dann geht es halt nicht.. ein cast in long double half hier nichts + double multiplier = 0.0; + double fractpart = modf((end - begin) / step, &multiplier); + if (!UbMath::zero(fractpart)) { + // tmp-speicherung (fuer cerr) + fractpart = end; + // neues ende + end = begin + multiplier * step; + + std::cerr << "Warning: UbScheduler::addSchedule - " + << "end of schedule was adapted to intervall \n\t" + << "from " << UbSchedule(step, begin, fractpart) << " to " << UbSchedule(step, begin, end) + << std::endl; + } + } + + // nu aber: + schedules.emplace_back(step, begin, end); - //nu aber: - schedules.emplace_back(step, begin, end); + if (end > maxT) + maxT = end; - if( end>maxT ) maxT = end; + double potentialDueTime; + if (calcNextDueTimeForSchedule(schedules.back(), lastUsedT, potentialDueTime) && + potentialDueTime < nextDueTime) { + nextDueTime = potentialDueTime; + } - double potentialDueTime; - if( calcNextDueTimeForSchedule(schedules.back(), lastUsedT, potentialDueTime) - && potentialDueTime < nextDueTime ) - { - nextDueTime = potentialDueTime; - } + return true; + } + /*==========================================================*/ + // returns true if scheduler contains schedules + bool hasSchedules() const { return !schedules.empty(); } + /*==========================================================*/ + // time bei dem das letzte mal isDue(time) true war + double getLastDueTime() const { return lastDueTime; } + /*==========================================================*/ + // time bei dem das naechste mal isDue(time) true ergibt + double getNextDueTime() const { return nextDueTime; } + /*==========================================================*/ + // maxDueTime (maxTime der Schedules! + double getMaxDueTime() const { return this->maxT; } + /*==========================================================*/ + bool isDue(const double &t) + { + lastUsedT = t; + if (UbMath::greaterEqual(t, nextDueTime)) { + // groesser maxT is nicht + if (UbMath::greater(t, maxT)) + return false; - return true; - } - /*==========================================================*/ - //returns true if scheduler contains schedules - bool hasSchedules() const { return !schedules.empty(); } - /*==========================================================*/ - //time bei dem das letzte mal isDue(time) true war - double getLastDueTime() const { return lastDueTime; } - /*==========================================================*/ - //time bei dem das naechste mal isDue(time) true ergibt - double getNextDueTime() const { return nextDueTime; } - /*==========================================================*/ - //maxDueTime (maxTime der Schedules! - double getMaxDueTime() const { return this->maxT; } - /*==========================================================*/ - bool isDue(const double& t) - { - lastUsedT = t; - if( UbMath::greaterEqual(t,nextDueTime) ) - { - //groesser maxT is nicht - if( UbMath::greater(t,maxT) ) return false; - - //temp var - double actDueTime = nextDueTime; + // temp var + double actDueTime = nextDueTime; - //um Suche nach nextDueTime bei "Zukunfts-t" zu optimieren, setzt man die "start"-suchzeit auf "t-1": - nextDueTime = t-1; //t-1 deshlab, damit falls z.B. while Schleife nicht durchlaufen wird - //die folgende if Abfrage nicht faelschlicher Weise true ist! - while( UbMath::greaterEqual(t,nextDueTime) && !UbMath::equal(nextDueTime, maxT) ) - { - double tmpNextDueTime = maxT, potentialDueTime=-1.0; - for(std::size_t i=0; i<schedules.size(); i++) - { - if( calcNextDueTimeForSchedule(schedules[i], nextDueTime, potentialDueTime) - && potentialDueTime < tmpNextDueTime ) - { - assert( nextDueTime < potentialDueTime ); - tmpNextDueTime = potentialDueTime; - } + // um Suche nach nextDueTime bei "Zukunfts-t" zu optimieren, setzt man die "start"-suchzeit auf "t-1": + nextDueTime = t - 1; // t-1 deshlab, damit falls z.B. while Schleife nicht durchlaufen wird + // die folgende if Abfrage nicht faelschlicher Weise true ist! + while (UbMath::greaterEqual(t, nextDueTime) && !UbMath::equal(nextDueTime, maxT)) { + double tmpNextDueTime = maxT, potentialDueTime = -1.0; + for (std::size_t i = 0; i < schedules.size(); i++) { + if (calcNextDueTimeForSchedule(schedules[i], nextDueTime, potentialDueTime) && + potentialDueTime < tmpNextDueTime) { + assert(nextDueTime < potentialDueTime); + tmpNextDueTime = potentialDueTime; + } + } + actDueTime = nextDueTime; + nextDueTime = tmpNextDueTime; } - actDueTime = nextDueTime; - nextDueTime = tmpNextDueTime; - } - //wenn t = der aktuuellen oder gar schon der naechstmoeglichen ist (hierbei wurde - //zuvor actDueTime und nextDueTime ggf. angepasst) - //Bsp.: nextDuTime war 5, aber fuer t=400 gilt andere schedule -> Bsp actDue=350 und nextDue 405 - if( UbMath::equal(t,actDueTime) - || UbMath::equal(t,nextDueTime) ) - { - lastDueTime = t; - return true; - } - } - else if( UbMath::lessEqual(t, lastDueTime) ) - { - if(UbMath::equal(t, lastDueTime) ) return true; //braucht man, wenn man fuer dasselbe t isDue(t) aufruft - else - { - //Fall: Zeit liegt faktisch in der Vergangenheit -> neu initialsisieren - double tmpNextDueTime = maxT, potentialDueTime=-1.0; - for(size_t i=0; i<schedules.size(); i++) - { - if( calcNextDueTimeForSchedule(schedules[i], t-1, potentialDueTime) - && potentialDueTime < tmpNextDueTime ) - { - tmpNextDueTime = potentialDueTime; - } + // wenn t = der aktuuellen oder gar schon der naechstmoeglichen ist (hierbei wurde + // zuvor actDueTime und nextDueTime ggf. angepasst) + // Bsp.: nextDuTime war 5, aber fuer t=400 gilt andere schedule -> Bsp actDue=350 und nextDue 405 + if (UbMath::equal(t, actDueTime) || UbMath::equal(t, nextDueTime)) { + lastDueTime = t; + return true; } - nextDueTime = tmpNextDueTime; + } else if (UbMath::lessEqual(t, lastDueTime)) { + if (UbMath::equal(t, lastDueTime)) + return true; // braucht man, wenn man fuer dasselbe t isDue(t) aufruft + else { + // Fall: Zeit liegt faktisch in der Vergangenheit -> neu initialsisieren + double tmpNextDueTime = maxT, potentialDueTime = -1.0; + for (size_t i = 0; i < schedules.size(); i++) { + if (calcNextDueTimeForSchedule(schedules[i], t - 1, potentialDueTime) && + potentialDueTime < tmpNextDueTime) { + tmpNextDueTime = potentialDueTime; + } + } + nextDueTime = tmpNextDueTime; - return UbMath::equal(t, nextDueTime); - } - } + return UbMath::equal(t, nextDueTime); + } + } - return false; - } - /*==========================================================*/ - inline double getMinBegin( ) const - { - if( schedules.empty() ) return Ub::inf; - return std::min_element(schedules.begin(), schedules.end(),UbComparators::membercomp(&UbSchedule::getBegin) )->getBegin(); - } - /*==========================================================*/ - inline double getMaxBegin( ) const - { - if( schedules.empty() ) return Ub::inf; - return std::max_element(schedules.begin(), schedules.end(),UbComparators::membercomp(&UbSchedule::getBegin) )->getBegin(); - } - /*==========================================================*/ - inline double getMinEnd( ) const - { - if( schedules.empty() ) return Ub::inf; - return std::min_element(schedules.begin(), schedules.end(),UbComparators::membercomp(&UbSchedule::getEnd) )->getEnd(); - } - /*==========================================================*/ - inline double getMaxEnd( ) const - { - if( schedules.empty() ) return Ub::inf; - return std::max_element(schedules.begin(), schedules.end(),UbComparators::membercomp(&UbSchedule::getEnd) )->getEnd(); - } - /*==========================================================*/ - inline double getMinStep( ) const - { - if( schedules.empty() ) return Ub::inf; - return std::min_element(schedules.begin(), schedules.end(),UbComparators::membercomp(&UbSchedule::getStep) )->getStep(); - } - /*==========================================================*/ - inline double getMaxStep( ) const - { - if( schedules.empty() ) return Ub::inf; - return std::max_element(schedules.begin(), schedules.end(),UbComparators::membercomp(&UbSchedule::getStep) )->getStep(); - } - /*==========================================================*/ - inline std::string toString() const - { - std::stringstream text; - text<<*this; - return text.str(); - } - /*==========================================================*/ - friend inline std::ostream& operator << (std::ostream& os, const UbScheduler& scheduler) - { - os<<"UbScheduler\n"; - os<<"Schedule | start | end | intervall "<<std::endl; - for(std::size_t i=0; i<scheduler.schedules.size(); i++) - os<<std::setw(9)<<i<<"|" - <<std::setw(19)<<scheduler.schedules[i].getBegin()<<"|" - <<std::setw(19)<<scheduler.schedules[i].getEnd() <<"|" - <<std::setw(19)<<scheduler.schedules[i].getStep() <<std::endl; - return os; - } + return false; + } + /*==========================================================*/ + inline double getMinBegin() const + { + if (schedules.empty()) + return Ub::inf; + return std::min_element(schedules.begin(), schedules.end(), UbComparators::membercomp(&UbSchedule::getBegin)) + ->getBegin(); + } + /*==========================================================*/ + inline double getMaxBegin() const + { + if (schedules.empty()) + return Ub::inf; + return std::max_element(schedules.begin(), schedules.end(), UbComparators::membercomp(&UbSchedule::getBegin)) + ->getBegin(); + } + /*==========================================================*/ + inline double getMinEnd() const + { + if (schedules.empty()) + return Ub::inf; + return std::min_element(schedules.begin(), schedules.end(), UbComparators::membercomp(&UbSchedule::getEnd)) + ->getEnd(); + } + /*==========================================================*/ + inline double getMaxEnd() const + { + if (schedules.empty()) + return Ub::inf; + return std::max_element(schedules.begin(), schedules.end(), UbComparators::membercomp(&UbSchedule::getEnd)) + ->getEnd(); + } + /*==========================================================*/ + inline double getMinStep() const + { + if (schedules.empty()) + return Ub::inf; + return std::min_element(schedules.begin(), schedules.end(), UbComparators::membercomp(&UbSchedule::getStep)) + ->getStep(); + } + /*==========================================================*/ + inline double getMaxStep() const + { + if (schedules.empty()) + return Ub::inf; + return std::max_element(schedules.begin(), schedules.end(), UbComparators::membercomp(&UbSchedule::getStep)) + ->getStep(); + } + /*==========================================================*/ + inline std::string toString() const + { + std::stringstream text; + text << *this; + return text.str(); + } + /*==========================================================*/ + friend inline std::ostream &operator<<(std::ostream &os, const UbScheduler &scheduler) + { + os << "UbScheduler\n"; + os << "Schedule | start | end | intervall " << std::endl; + for (std::size_t i = 0; i < scheduler.schedules.size(); i++) + os << std::setw(9) << i << "|" << std::setw(19) << scheduler.schedules[i].getBegin() << "|" << std::setw(19) + << scheduler.schedules[i].getEnd() << "|" << std::setw(19) << scheduler.schedules[i].getStep() + << std::endl; + return os; + } protected: - /*==========================================================*/ - void initVals() - { - lastUsedT = -Ub::inf; - lastDueTime = -Ub::inf; - nextDueTime = Ub::inf; - maxT = -Ub::inf; - } - /*==========================================================*/ - // calculates next due time for a schedule - // with nextDueTime > searchStart - bool calcNextDueTimeForSchedule(const UbSchedule& schedule, const double& searchStart, double& nextDueTime ) - { - if ( UbMath::greater(searchStart, schedule.end ) ) return false; - else if( UbMath::less( searchStart, schedule.begin) ) nextDueTime = schedule.begin; - else - { - nextDueTime = schedule.begin + ((int)((searchStart-schedule.begin)/schedule.step)+1)*schedule.step; - if( UbMath::less( nextDueTime, searchStart ) - || UbMath::greater(nextDueTime, schedule.end) ) - { + /*==========================================================*/ + void initVals() + { + lastUsedT = -Ub::inf; + lastDueTime = -Ub::inf; + nextDueTime = Ub::inf; + maxT = -Ub::inf; + } + /*==========================================================*/ + // calculates next due time for a schedule + // with nextDueTime > searchStart + bool calcNextDueTimeForSchedule(const UbSchedule &schedule, const double &searchStart, double &nextDueTime) + { + if (UbMath::greater(searchStart, schedule.end)) return false; - } - } - return true; - } + else if (UbMath::less(searchStart, schedule.begin)) + nextDueTime = schedule.begin; + else { + nextDueTime = schedule.begin + ((int)((searchStart - schedule.begin) / schedule.step) + 1) * schedule.step; + if (UbMath::less(nextDueTime, searchStart) || UbMath::greater(nextDueTime, schedule.end)) { + return false; + } + } + return true; + } protected: - double lastUsedT; - double lastDueTime; - double nextDueTime; - double maxT; - - std::vector<UbSchedule> schedules; + double lastUsedT; + double lastDueTime; + double nextDueTime; + double maxT; + + std::vector<UbSchedule> schedules; }; using UbSchedule = UbScheduler::UbSchedule; -#endif //UBSCHEDULER_H +#endif // UBSCHEDULER_H - - -//int main(int argc, char** argv) -//{ +// int main(int argc, char** argv) +//{ // UbScheduler writeSchedule; //// writeSchedule.addSchedule(0,2000,100); //// writeSchedule.addSchedule(3005,4500,300); @@ -343,4 +345,3 @@ using UbSchedule = UbScheduler::UbSchedule; // } // return 0; //} - diff --git a/src/basics/basics/utilities/UbStringInputASCII.cpp b/src/basics/basics/utilities/UbStringInputASCII.cpp index b100a51c377f26f2aed2b0b7e197237c0b7a4953..6a04f86aeb8d5b7be9e96ca39d1808b987c1f711 100644 --- a/src/basics/basics/utilities/UbStringInputASCII.cpp +++ b/src/basics/basics/utilities/UbStringInputASCII.cpp @@ -1,10 +1,10 @@ //#include <basics/utilities/UbStringInputASCII.h> //#include <cstring> // -//using namespace std; +// using namespace std; // // -//UbStringInputASCII::UbStringInputASCII(string inputString) : UbFileInputASCII("") +// UbStringInputASCII::UbStringInputASCII(string inputString) : UbFileInputASCII("") //{ // instream.str(inputString); // @@ -16,88 +16,88 @@ // //} ///*==========================================================*/ -//int UbStringInputASCII::readInteger() +// int UbStringInputASCII::readInteger() //{ // int dummy; // instream>>dummy; // return dummy; //} ///*==========================================================*/ -//std::size_t UbStringInputASCII::readSize_t() +// std::size_t UbStringInputASCII::readSize_t() //{ // std::size_t dummy; // instream>>dummy; // return dummy; //} ///*==========================================================*/ -//string UbStringInputASCII::getFileName() +// string UbStringInputASCII::getFileName() //{ // return this->filename; //} // ///*==========================================================*/ -//void UbStringInputASCII::skipLine() +// void UbStringInputASCII::skipLine() //{ // string dummy; // getline(instream, dummy); //} ///*==========================================================*/ -//void UbStringInputASCII::readLine() +// void UbStringInputASCII::readLine() //{ // string dummy; // getline(instream, dummy); //} ///*==========================================================*/ -//string UbStringInputASCII::readStringLine() +// string UbStringInputASCII::readStringLine() //{ // string dummy; // getline(instream, dummy); // return dummy; //} ///*==========================================================*/ -//string UbStringInputASCII::readLineTill(char stop) +// string UbStringInputASCII::readLineTill(char stop) //{ // string dummy; // getline(instream, dummy, stop); // return dummy; //} ///*==========================================================*/ -//string UbStringInputASCII::parseString() +// string UbStringInputASCII::parseString() //{ // string dummy; // getline(instream, dummy, ' '); // return dummy; //} ///*==========================================================*/ -//double UbStringInputASCII::readDouble() +// double UbStringInputASCII::readDouble() //{ // double dummy; // instream>>dummy; // return dummy; //} ///*==========================================================*/ -//float UbStringInputASCII::readFloat() +// float UbStringInputASCII::readFloat() //{ // float dummy; // instream>>dummy; // return dummy; //} ///*==========================================================*/ -//char UbStringInputASCII::readChar() +// char UbStringInputASCII::readChar() //{ // char dummy; // instream>>dummy; // return dummy; //} ///*==========================================================*/ -//string UbStringInputASCII::readString() +// string UbStringInputASCII::readString() //{ // string dummy; // instream>>dummy; // return dummy; //} ///*==========================================================*/ -//bool UbStringInputASCII::containsString(string var) +// bool UbStringInputASCII::containsString(string var) //{ // instream.seekg(0L, ios::beg); //Positionszeiger der Datei auf den Anfang setzen // char line[512]; @@ -110,7 +110,7 @@ // return true; //} ///*==========================================================*/ -//void UbStringInputASCII::setPosAfterLineWithString(string var) +// void UbStringInputASCII::setPosAfterLineWithString(string var) //{ // instream.seekg(0L, ios::beg); //Positionszeiger der Datei auf den Anfang setzen // char line[512]; @@ -121,7 +121,7 @@ // }while (strstr(line,var.c_str()) != line); // Ende Schleife, wenn varname ganz in zeile vorkommt //} ///*==========================================================*/ -//int UbStringInputASCII::readIntegerAfterString(string var) +// int UbStringInputASCII::readIntegerAfterString(string var) //// last change [10.3.2004] at [9:46] ////suchts in einer Datei nach varname und gibt den dahinter stehenden int-Wert zurueck ////z.B. timesteps 9 @@ -145,7 +145,7 @@ //// last change [10.3.2004] at [9:46] ////sucht in einer Datei nach varname und gibt den dahinter stehenden int-Wert zurueck ////z.B. nue 9.5 -//double UbStringInputASCII::readDoubleAfterString(string var) +// double UbStringInputASCII::readDoubleAfterString(string var) //{ // instream.seekg(0L, ios::beg); //Positionszeiger der Datei auf den Anfang setzen // @@ -155,7 +155,8 @@ // { // instream.getline(line,512); // if(instream.eof()) UB_THROW( UbException(UB_EXARGS,var+" wasn't found in "+this->filename) ); -// }while (/*!strncmp(varname,line,sizeof(varname))==0*/strstr(line,var.c_str()) != line); // Ende Schleife, wenn varname ganz in zeile vorkommt +// }while (/*!strncmp(varname,line,sizeof(varname))==0*/strstr(line,var.c_str()) != line); // Ende Schleife, wenn +// varname ganz in zeile vorkommt // // // strcpy (line, (line+strlen(var.c_str()))); // zeile um "varname" kuerzen @@ -167,7 +168,7 @@ //// [9.9.2002] //// liefert sring-Wert der hinter dem uebergebenen char feld in der datei instream steht //// zudem wird der wert in die uebergebene variable value uebertragen (falls man das ergebniss als char benoetig) -//string UbStringInputASCII::readStringAfterString(string var) +// string UbStringInputASCII::readStringAfterString(string var) //{ // instream.seekg(0L, ios::beg); //Positionszeiger der Datei auf den Anfang setzen // @@ -192,7 +193,7 @@ //// last change [10.3.2004] at [9:46] ////sucht in einer Datei nach varname und gibt den dahinter stehenden int-Wert zurueck ////z.B. nue 9.5 -//bool UbStringInputASCII::readBoolAfterString(string var) +// bool UbStringInputASCII::readBoolAfterString(string var) //{ // if(this->readStringAfterString(var.c_str()) == "true" ) return true; // else if(this->readStringAfterString(var.c_str()) == "false") return false; @@ -202,7 +203,7 @@ //// last change [10.3.2004] at [9:46] ////sucht in einer Datei nach varname und gibt den dahinter stehenden int-Wert zurueck ////z.B. nue 9.5 -//bool UbStringInputASCII::readBool() +// bool UbStringInputASCII::readBool() //{ // string tmp = this->readString(); // if( tmp == "true" ) return true; diff --git a/src/basics/basics/utilities/UbStringInputASCII.h b/src/basics/basics/utilities/UbStringInputASCII.h index eb2e01376952c56fe6a48489201c357f39a69933..d83adde4dee62f703a6a6070b7a2c0eb6c66360f 100644 --- a/src/basics/basics/utilities/UbStringInputASCII.h +++ b/src/basics/basics/utilities/UbStringInputASCII.h @@ -16,9 +16,9 @@ // //#include <basics/utilities/UbFileInputASCII.h> // -//class UbStringInputASCII : public UbFileInputASCII +// class UbStringInputASCII : public UbFileInputASCII //{ -//public: +// public: // UbStringInputASCII(std::string inputString); // // std::string getFileName(); @@ -45,7 +45,7 @@ // // FILETYPE getFileType() { return ASCII; } // -//private: +// private: // std::istringstream instream; //}; // diff --git a/src/basics/basics/utilities/UbSystem.h b/src/basics/basics/utilities/UbSystem.h index 975e7027525c0c6f0b115279db08c006ddd8788b..8e676811a152b176efd617a944f4e22ea538721e 100644 --- a/src/basics/basics/utilities/UbSystem.h +++ b/src/basics/basics/utilities/UbSystem.h @@ -1,28 +1,28 @@ //======================================================================================= -// ____ ____ __ ______ __________ __ __ __ __ -// \ \ | | | | | _ \ |___ ___| | | | | / \ | | -// \ \ | | | | | |_) | | | | | | | / \ | | -// \ \ | | | | | _ / | | | | | | / /\ \ | | -// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ -// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| -// \ \ | | ________________________________________________________________ -// \ \ | | | ______________________________________________________________| -// \ \| | | | __ __ __ __ ______ _______ -// \ | | |_____ | | | | | | | | | _ \ / _____) -// \ | | _____| | | | | | | | | | | \ \ \_______ +// ____ ____ __ ______ __________ __ __ __ __ +// \ \ | | | | | _ \ |___ ___| | | | | / \ | | +// \ \ | | | | | |_) | | | | | | | / \ | | +// \ \ | | | | | _ / | | | | | | / /\ \ | | +// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ +// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| +// \ \ | | ________________________________________________________________ +// \ \ | | | ______________________________________________________________| +// \ \| | | | __ __ __ __ ______ _______ +// \ | | |_____ | | | | | | | | | _ \ / _____) +// \ | | _____| | | | | | | | | | | \ \ \_______ // \ | | | | |_____ | \_/ | | | | |_/ / _____ | -// \ _____| |__| |________| \_______/ |__| |______/ (_______/ +// \ _____| |__| |________| \_______/ |__| |______/ (_______/ // -// This file is part of VirtualFluids. VirtualFluids is free software: you can +// This file is part of VirtualFluids. VirtualFluids is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of +// License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. -// -// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// +// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License along // with VirtualFluids (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>. // @@ -34,60 +34,59 @@ #define UBSYSTEM_H #if defined(_WIN32) || defined(_WIN64) - #define UBSYSTEM_WINDOWS - #include <process.h> - #include <io.h> - #include <direct.h> - //#ifndef _WINSOCK2API_ //ansonsten gibt es mecker bei #include "Windows.h" und ::Sleep() - // #define _WINSOCK2API_ - // #include<WinSock2.h> - //#endif - #include <windows.h> - //#include <Windows.h> - //#include <tchar.h> +#define UBSYSTEM_WINDOWS +#include <direct.h> +#include <io.h> +#include <process.h> +//#ifndef _WINSOCK2API_ //ansonsten gibt es mecker bei #include "Windows.h" und ::Sleep() +// #define _WINSOCK2API_ +// #include<WinSock2.h> +//#endif +#include <windows.h> +//#include <Windows.h> +//#include <tchar.h> #elif defined(__APPLE__) - #define UBSYSTEM_APPLE - #include "dirent.h" - #include "sys/stat.h" - #include <sys/syscall.h> - #include <sys/stat.h> - #include <unistd.h> +#define UBSYSTEM_APPLE +#include "dirent.h" +#include "sys/stat.h" +#include <sys/stat.h> +#include <sys/syscall.h> +#include <unistd.h> #elif (defined(__amd64) || defined(__amd64__) || defined(__unix__)) && !defined(__AIX__) - #define UBSYSTEM_LINUX - #include "dirent.h" - #include <sys/stat.h> - #include <unistd.h> - #include <cstring> +#define UBSYSTEM_LINUX +#include "dirent.h" +#include <cstring> +#include <sys/stat.h> +#include <unistd.h> #elif defined(__AIX__) - #define UBSYSTEM_AIX - #include "dirent.h" - #include <unistd.h> - #include <sys/stat.h> - #include <sys/types.h> +#define UBSYSTEM_AIX +#include "dirent.h" +#include <sys/stat.h> +#include <sys/types.h> +#include <unistd.h> #else - #error "UbSystem::UnknownMachine" +#error "UbSystem::UnknownMachine" #endif #if defined(__unix__) && defined(__CYGWIN__) - #define UBSYSTEM_CYGWIN - #include <windows.h> +#define UBSYSTEM_CYGWIN +#include <windows.h> #elif defined(__unix__) - #include <sys/syscall.h> +#include <sys/syscall.h> #endif -#if defined(min) || defined(max) //daruch kann man sich spaeter #undef min; #undef max erparen -# error add NOMINMAX to preprocessor defines +#if defined(min) || defined(max) // daruch kann man sich spaeter #undef min; #undef max erparen +#error add NOMINMAX to preprocessor defines #endif - -#include <iostream> -#include <iomanip> -#include <string> -#include <sstream> #include <algorithm> -#include <typeinfo> #include <cctype> //for toupper #include <ctime> +#include <iomanip> +#include <iostream> +#include <sstream> +#include <string> +#include <typeinfo> #include <basics/utilities/UbException.h> #include <basics/utilities/UbLogger.h> @@ -96,475 +95,463 @@ #include <boost/thread.hpp> #endif // CAB_BOOST -//DEFINE TO STRING -//e.g. #define FOO hallo +// DEFINE TO STRING +// e.g. #define FOO hallo // -> QUOTEME(FOO) == "hallo" #define _QUOTEME(x) #x #define QUOTEME(x) _QUOTEME(x) -//allg.: -//const int * C1 -> C1 is variable pointer to a constant integer -//int const * C2 -> C2 is variable pointer to a constant integer (same as above) -//int * const C3 -> C3 is constant pointer to a variable integer -//int const * const C4 -> C4 is constant pointer to a constant integer +// allg.: +// const int * C1 -> C1 is variable pointer to a constant integer +// int const * C2 -> C2 is variable pointer to a constant integer (same as above) +// int * const C3 -> C3 is constant pointer to a variable integer +// int const * const C4 -> C4 is constant pointer to a constant integer ////////////////////////////////////////////////////////////////////////// -//UbSystem +// UbSystem ////////////////////////////////////////////////////////////////////////// namespace UbSystem { - template<bool> struct ub_static_assert; //deklaration (ub_xxx da static_assert in C++0x ein keyword werden wird) - template<> struct ub_static_assert<true>{}; //deklaration + definition der spezialisierung fuer "true" - //ub_static_assert<false> fuehrt zu compiler fehler, da dafuer - //keine implementierung vorhanden! //UB_STATIC_ASSERT(false) - - /*==========================================================*/ - inline void sleepMs(const unsigned int& msec) - { - #if defined(UBSYSTEM_WINDOWS) - ::Sleep( (msec==0) ? 1 : msec ); // +1 here causes a context switch if SleepMSec(0) is called - #elif (defined(UBSYSTEM_LINUX) || defined(UBSYSTEM_APPLE) || defined(UBSYSTEM_AIX)) && !defined(UBSYSTEM_CYGWIN) - ::usleep(1000*msec); - #elif defined(UBSYSTEM_CYGWIN) - ::Sleep( (msec==0) ? 1 : msec ); - #else - #error "UbSystem::sleepMSec - UnknownMachine" - #endif - } - /*==========================================================*/ - inline void sleepS(const unsigned int& sec) - { - #if defined(UBSYSTEM_WINDOWS) || defined(UBSYSTEM_CYGWIN) - ::Sleep( (sec==0) ? 1 : sec*1000 ); // +1 here causes a context switch if sleepS(0) is called - #elif defined(UBSYSTEM_LINUX) || defined(UBSYSTEM_APPLE) || defined(UBSYSTEM_AIX) && !defined(UBSYSTEM_CYGWIN) - ::sleep(sec); - #else - #error "UbSystem::sleepS - UnknownMachine" - #endif - } - /*==========================================================*/ - //checks if the bits of bitmask are set in value - template<typename T> - inline bool bitCheck(const T& value, const T& bitmask) - { - return ( (value & bitmask) == bitmask); - } - /*==========================================================*/ - //checks if the bits of bitmask are set in value - template<typename T> - inline void setBit(T& value, const T& bitmask) - { - value |= bitmask; - } - /*==========================================================*/ - template<typename T> - inline void unsetBit(T& value, const T& bitmask) - { - value &= ~bitmask; - } - /*==========================================================*/ - //returns bitmask as string e.g. 0001 0100 1101 - template<typename T> - inline std::string getBitString(const T& value) - { - std::stringstream text; - for(int i=sizeof(value)*8-1/*8 bits per byte*/; i>=0; i--) - { - text<<(char) ( ((value>>i) & 1) + '0'); - if(i%4 == 0 && i>0) text<<' '; - } - return text.str(); - } - /*==========================================================*/ - //converts string to type T - // usage: int x = stringTo<int>("123"); - template<typename T> - inline T stringTo(const std::string& s) - { - std::istringstream iss(s); - T x; - iss >> x; - if(!iss) - UB_THROW( UbException(UB_EXARGS," cannot convert \""+s+"\" to type <"+static_cast<std::string>(typeid(x).name())+">") ); - - return x; - } - /*==========================================================*/ - // usage: string s = toString(x); - template<typename T> - inline std::string toString(const T& x, int precision=15) - { - std::ostringstream oss; - oss<<std::setprecision(precision); - oss<<x; - return oss.str(); - } - /*==========================================================*/ - //e.g. str="iHcsnW" -> "IHCSNW" - inline std::string toUpperString(const std::string& str) - { - std::string tmp(str); - std::transform(tmp.begin(),tmp.end(),tmp.begin(), static_cast<int (*)(int)>(std::toupper)); - - return tmp; - } - /*==========================================================*/ - //e.g. str="iHcsnW" -> "ihcsnw" - inline std::string toLowerString(const std::string& str) - { - std::string tmp(str); - std::transform(tmp.begin(),tmp.end(),tmp.begin(), static_cast<int (*)(int)>(std::tolower)); - - return tmp; - } - /*==========================================================*/ - // usage: std::string s = replaceInString(str,"\\","/"); - // std::string s = replaceInString(str,"ich","du"); - static std::string replaceInString(std::string original, const std::string& replace, const std::string& replaceWith ) - { - size_t pos=0; - while( (pos=original.find(replace,pos))!=std::string::npos ) - { - original.replace(pos,replace.size(),replaceWith); - pos+=replaceWith.size(); - } - return original; - } - /*==========================================================*/ - //returns content of an enviroment variable - inline std::string getEnv(const std::string& var) - { - char* str = getenv( var.c_str()); - if( str == NULL ) - { - return std::string(""); - } - - return static_cast<std::string>( str ); - } - /*==========================================================*/ - inline bool isDirectory(const std::string& dir, const unsigned& /*attemptions*/ = 3) - { - if( dir.empty() ) - UB_THROW( UbException(UB_EXARGS,"dir is empty") ); - - std::string path = UbSystem::replaceInString(dir,"\\","/"); - - #if defined UBSYSTEM_WINDOWS - #ifndef _UNICODE - if( _access(path.c_str(), 0 ) == -1 ) return false; - #else - if( _waccess(path.c_str(), 0 ) == -1 ) return false; - #endif - #elif defined(UBSYSTEM_LINUX) || defined(UBSYSTEM_APPLE) || defined(UBSYSTEM_AIX) - struct stat stFileInfo; - if( stat(path.c_str(),&stFileInfo) != 0) - { - return false; - } - #endif - - return true; - } - /*==========================================================*/ - // usage: makeDirectory("c:/temp"); - // makeDirectory("c:/temp/"); - // return: true -> successful - // false -> failed - #if defined(CAB_BOOST) - static boost::mutex mtx_makeDirectory; - #endif - inline bool makeDirectory(const std::string& dir, const unsigned& attemptions = 3) - { - UBLOG(logDEBUG5,"UbSystem::makeDirectory - start, dir="<<dir<<" #attemptions="<<attemptions); - - if( dir.empty() ) UB_THROW( UbException(UB_EXARGS,"dir is empty") ); - std::string path = UbSystem::replaceInString(dir,"\\","/"); - - bool dirCreated = true; - #if defined UBSYSTEM_WINDOWS - if(path[path.size()-1] != '/') path+="/"; - size_t pos = 0; - while( ( pos=path.find("/",pos+1) ) != std::string::npos ) - { - std::string tmpdir = path.substr(0,pos); - #if defined(CAB_BOOST) - boost::mutex::scoped_lock lock(mtx_makeDirectory); - #endif - if( - #ifndef _UNICODE - _access(tmpdir.c_str(), 0 ) == -1 && _mkdir(tmpdir.c_str() ) == -1 - #else - _waccess(tmpdir.c_str(), 0) == -1 && _wmkdir(tmpdir.c_str()) == -1 - #endif - ) - { - UBLOG(logDEBUG5,"UbSystem::makeDirectory- dir=\""<<tmpdir<<"\" doesn't exit or makedir failed"); - dirCreated = false; - break; - } - } - #elif defined(UBSYSTEM_LINUX) || defined(UBSYSTEM_APPLE) || defined(UBSYSTEM_AIX) - std::string command = "mkdir -p \""+path+"\""; - { - #if defined(CAB_BOOST) - boost::mutex::scoped_lock lock(mtx_makeDirectory); - #endif - if(system(command.c_str())!=0) - { - UBLOG(logDEBUG5,"UbSystem::makeDirectory- dir=\""<<path<<"\" doesn't exit or makedir failed"); - dirCreated = false; - } - } - #else - #error "UbSystem::makeDirectory - UnknownMachine" - #endif - - if(!dirCreated && attemptions > 1) - { - UBLOG(logDEBUG5,"UbSystem::makeDirectory - internal call of UbSystem::makeDirectory"); - UbSystem::sleepMs(500); - dirCreated = UbSystem::makeDirectory(path, attemptions-1); - } - - UBLOG(logDEBUG5,"UbSystem::makeDirectory - end (success="<<dirCreated<<", attemptions = "<<attemptions<<")"); - return dirCreated; - } - /*==========================================================*/ -#if defined(CAB_BOOST) - static boost::mutex mtx_removeDirectory; +template <bool> +struct ub_static_assert; // deklaration (ub_xxx da static_assert in C++0x ein keyword werden wird) +template <> +struct ub_static_assert<true> { +}; // deklaration + definition der spezialisierung fuer "true" + // ub_static_assert<false> fuehrt zu compiler fehler, da dafuer + // keine implementierung vorhanden! //UB_STATIC_ASSERT(false) + +/*==========================================================*/ +inline void sleepMs(const unsigned int &msec) +{ +#if defined(UBSYSTEM_WINDOWS) + ::Sleep((msec == 0) ? 1 : msec); // +1 here causes a context switch if SleepMSec(0) is called +#elif (defined(UBSYSTEM_LINUX) || defined(UBSYSTEM_APPLE) || defined(UBSYSTEM_AIX)) && !defined(UBSYSTEM_CYGWIN) + ::usleep(1000 * msec); +#elif defined(UBSYSTEM_CYGWIN) + ::Sleep((msec == 0) ? 1 : msec); +#else +#error "UbSystem::sleepMSec - UnknownMachine" +#endif +} +/*==========================================================*/ +inline void sleepS(const unsigned int &sec) +{ +#if defined(UBSYSTEM_WINDOWS) || defined(UBSYSTEM_CYGWIN) + ::Sleep((sec == 0) ? 1 : sec * 1000); // +1 here causes a context switch if sleepS(0) is called +#elif defined(UBSYSTEM_LINUX) || defined(UBSYSTEM_APPLE) || defined(UBSYSTEM_AIX) && !defined(UBSYSTEM_CYGWIN) + ::sleep(sec); +#else +#error "UbSystem::sleepS - UnknownMachine" +#endif +} +/*==========================================================*/ +// checks if the bits of bitmask are set in value +template <typename T> +inline bool bitCheck(const T &value, const T &bitmask) +{ + return ((value & bitmask) == bitmask); +} +/*==========================================================*/ +// checks if the bits of bitmask are set in value +template <typename T> +inline void setBit(T &value, const T &bitmask) +{ + value |= bitmask; +} +/*==========================================================*/ +template <typename T> +inline void unsetBit(T &value, const T &bitmask) +{ + value &= ~bitmask; +} +/*==========================================================*/ +// returns bitmask as string e.g. 0001 0100 1101 +template <typename T> +inline std::string getBitString(const T &value) +{ + std::stringstream text; + for (int i = sizeof(value) * 8 - 1 /*8 bits per byte*/; i >= 0; i--) { + text << (char)(((value >> i) & 1) + '0'); + if (i % 4 == 0 && i > 0) + text << ' '; + } + return text.str(); +} +/*==========================================================*/ +// converts string to type T +// usage: int x = stringTo<int>("123"); +template <typename T> +inline T stringTo(const std::string &s) +{ + std::istringstream iss(s); + T x; + iss >> x; + if (!iss) + UB_THROW(UbException(UB_EXARGS, " cannot convert \"" + s + "\" to type <" + + static_cast<std::string>(typeid(x).name()) + ">")); + + return x; +} +/*==========================================================*/ +// usage: string s = toString(x); +template <typename T> +inline std::string toString(const T &x, int precision = 15) +{ + std::ostringstream oss; + oss << std::setprecision(precision); + oss << x; + return oss.str(); +} +/*==========================================================*/ +// e.g. str="iHcsnW" -> "IHCSNW" +inline std::string toUpperString(const std::string &str) +{ + std::string tmp(str); + std::transform(tmp.begin(), tmp.end(), tmp.begin(), static_cast<int (*)(int)>(std::toupper)); + + return tmp; +} +/*==========================================================*/ +// e.g. str="iHcsnW" -> "ihcsnw" +inline std::string toLowerString(const std::string &str) +{ + std::string tmp(str); + std::transform(tmp.begin(), tmp.end(), tmp.begin(), static_cast<int (*)(int)>(std::tolower)); + + return tmp; +} +/*==========================================================*/ +// usage: std::string s = replaceInString(str,"\\","/"); +// std::string s = replaceInString(str,"ich","du"); +static std::string replaceInString(std::string original, const std::string &replace, const std::string &replaceWith) +{ + size_t pos = 0; + while ((pos = original.find(replace, pos)) != std::string::npos) { + original.replace(pos, replace.size(), replaceWith); + pos += replaceWith.size(); + } + return original; +} +/*==========================================================*/ +// returns content of an enviroment variable +inline std::string getEnv(const std::string &var) +{ + char *str = getenv(var.c_str()); + if (str == NULL) { + return std::string(""); + } + + return static_cast<std::string>(str); +} +/*==========================================================*/ +inline bool isDirectory(const std::string &dir, const unsigned & /*attemptions*/ = 3) +{ + if (dir.empty()) + UB_THROW(UbException(UB_EXARGS, "dir is empty")); + + std::string path = UbSystem::replaceInString(dir, "\\", "/"); + +#if defined UBSYSTEM_WINDOWS +#ifndef _UNICODE + if (_access(path.c_str(), 0) == -1) + return false; +#else + if (_waccess(path.c_str(), 0) == -1) + return false; +#endif +#elif defined(UBSYSTEM_LINUX) || defined(UBSYSTEM_APPLE) || defined(UBSYSTEM_AIX) + struct stat stFileInfo; + if (stat(path.c_str(), &stFileInfo) != 0) { + return false; + } #endif - inline int removeDirectory(const std::string& dir) - { - #if defined(CAB_BOOST) - boost::mutex::scoped_lock lock(mtx_removeDirectory); - #endif - std::string command = "rmdir \""+dir+"\""; - return std::system(command.c_str()); - } - /*==========================================================*/ - // usage : getPathFromString("c:/temp/foo.txt"); - //returns: "c:/temp" - // usage : getPathFromString("c:\\temp\\foo.txt"); - //returns: "c:/temp" - // usage : getPathFromString("foo.txt"); - // returns: "" - inline std::string getPathFromString(const std::string& fileStringWithPath) - { - std::string tmp = UbSystem::replaceInString(fileStringWithPath,"\\","/"); - std::size_t last = tmp.rfind("/"); - if(last!=std::string::npos) tmp.resize(last); - else tmp = ""; - return tmp; - } - /*==========================================================*/ - // usage : getFilenameFromString("c:/temp/foo.txt"); - // returns: "foo.txt" - // usage : getFilenameFromString("c:/temp/foo.txt",false); - // returns: "foo" - // usage : getFilenameFromString("c:/temp/"); - // returns: "" - inline std::string getFilenameFromString(const std::string& fileStringWithPath, bool withExtension = true) - { - std::string tmp = UbSystem::replaceInString(fileStringWithPath,"\\","/"); - - //remove path - std::size_t last = tmp.rfind("/"); - if(last!=std::string::npos && (last+1)<tmp.size()) tmp.erase(0,last+1); - - //remove extension - if(!withExtension) - { - last = tmp.rfind("."); - if(last!=std::string::npos) tmp.erase(last); - } - - return tmp; - } - /*==========================================================*/ - inline int getProcessID() - { - #if defined UBSYSTEM_WINDOWS - return _getpid(); - #elif defined(UBSYSTEM_LINUX) || defined(UBSYSTEM_APPLE) || defined(UBSYSTEM_AIX) - return getpid(); - #else - #error "int UbSystem::getProcessID() - UnknownMachine" - #endif - } - /*==========================================================*/ - inline unsigned long getCurrentThreadID() - { - #if defined UBSYSTEM_WINDOWS || defined(UBSYSTEM_CYGWIN) - return (unsigned long)GetCurrentThreadId(); - #elif defined(UBSYSTEM_APPLE) - uint64_t tid; - pthread_threadid_np(nullptr, &tid); - return (unsigned long)tid; - #elif defined(UBSYSTEM_LINUX) - return (unsigned long)syscall(SYS_gettid); - #elif defined(UBSYSTEM_AIX) - return (unsigned long) getpid(); //WORKAROUND for IBM (for get thread id is another function necessary) - #else - #error "unsigned long UbSystem::getCurrentThreadID() - UnknownMachine" - #endif - } - /*==========================================================*/ - inline bool isBigEndian() - { - short word = 0x4321; - if((*(char*)& word) != 0x21 ) return true; - else return false; - } - /*==========================================================*/ - inline bool isLittleEndian() - { - return !isBigEndian(); - } - /*==========================================================*/ - inline std::string getTimeStamp() - { - time_t t = time(NULL); - tm* localTime = localtime(&t); - - std::stringstream tmp; - tmp.fill('0'); - - tmp << localTime->tm_year+1900 - << "." << std::setw(2) <<localTime->tm_mon+1 - << "." << std::setw(2) << localTime->tm_mday - << "@" << std::setw(2) << localTime->tm_hour - << "." << std::setw(2) << localTime->tm_min - << "." << std::setw(2) << localTime->tm_sec ; - - return tmp.str(); - } - /*==========================================================*/ - //swap Byte Order - //usage: int test = 8; - // swapByteOrder((unsigned char*)& test, sizeof(int)) - //#define ByteSwap5(x) ByteSwap((unsigned char *) &x,sizeof(x)) - inline void swapByteOrder(unsigned char* toSwap, int length) - { - int i = 0; - int j = length-1; - while(i<j) - { - std::swap(toSwap[i], toSwap[j]); - i++, j--; - } - } - ////////////////////////////////////////////////////////////////////////// - //get host name - inline std::string getMachineName() - { - char Name[150]; + + return true; +} +/*==========================================================*/ +// usage: makeDirectory("c:/temp"); +// makeDirectory("c:/temp/"); +// return: true -> successful +// false -> failed +#if defined(CAB_BOOST) +static boost::mutex mtx_makeDirectory; +#endif +inline bool makeDirectory(const std::string &dir, const unsigned &attemptions = 3) +{ + UBLOG(logDEBUG5, "UbSystem::makeDirectory - start, dir=" << dir << " #attemptions=" << attemptions); + + if (dir.empty()) + UB_THROW(UbException(UB_EXARGS, "dir is empty")); + std::string path = UbSystem::replaceInString(dir, "\\", "/"); + + bool dirCreated = true; +#if defined UBSYSTEM_WINDOWS + if (path[path.size() - 1] != '/') + path += "/"; + size_t pos = 0; + while ((pos = path.find("/", pos + 1)) != std::string::npos) { + std::string tmpdir = path.substr(0, pos); +#if defined(CAB_BOOST) + boost::mutex::scoped_lock lock(mtx_makeDirectory); +#endif + if ( +#ifndef _UNICODE + _access(tmpdir.c_str(), 0) == -1 && _mkdir(tmpdir.c_str()) == -1 +#else + _waccess(tmpdir.c_str(), 0) == -1 && _wmkdir(tmpdir.c_str()) == -1 +#endif + ) { + UBLOG(logDEBUG5, "UbSystem::makeDirectory- dir=\"" << tmpdir << "\" doesn't exit or makedir failed"); + dirCreated = false; + break; + } + } +#elif defined(UBSYSTEM_LINUX) || defined(UBSYSTEM_APPLE) || defined(UBSYSTEM_AIX) + std::string command = "mkdir -p \"" + path + "\""; + { +#if defined(CAB_BOOST) + boost::mutex::scoped_lock lock(mtx_makeDirectory); +#endif + if (system(command.c_str()) != 0) { + UBLOG(logDEBUG5, "UbSystem::makeDirectory- dir=\"" << path << "\" doesn't exit or makedir failed"); + dirCreated = false; + } + } +#else +#error "UbSystem::makeDirectory - UnknownMachine" +#endif + + if (!dirCreated && attemptions > 1) { + UBLOG(logDEBUG5, "UbSystem::makeDirectory - internal call of UbSystem::makeDirectory"); + UbSystem::sleepMs(500); + dirCreated = UbSystem::makeDirectory(path, attemptions - 1); + } + + UBLOG(logDEBUG5, + "UbSystem::makeDirectory - end (success=" << dirCreated << ", attemptions = " << attemptions << ")"); + return dirCreated; +} +/*==========================================================*/ +#if defined(CAB_BOOST) +static boost::mutex mtx_removeDirectory; +#endif +inline int removeDirectory(const std::string &dir) +{ +#if defined(CAB_BOOST) + boost::mutex::scoped_lock lock(mtx_removeDirectory); +#endif + std::string command = "rmdir \"" + dir + "\""; + return std::system(command.c_str()); +} +/*==========================================================*/ +// usage : getPathFromString("c:/temp/foo.txt"); +// returns: "c:/temp" +// usage : getPathFromString("c:\\temp\\foo.txt"); +// returns: "c:/temp" +// usage : getPathFromString("foo.txt"); +// returns: "" +inline std::string getPathFromString(const std::string &fileStringWithPath) +{ + std::string tmp = UbSystem::replaceInString(fileStringWithPath, "\\", "/"); + std::size_t last = tmp.rfind("/"); + if (last != std::string::npos) + tmp.resize(last); + else + tmp = ""; + return tmp; +} +/*==========================================================*/ +// usage : getFilenameFromString("c:/temp/foo.txt"); +// returns: "foo.txt" +// usage : getFilenameFromString("c:/temp/foo.txt",false); +// returns: "foo" +// usage : getFilenameFromString("c:/temp/"); +// returns: "" +inline std::string getFilenameFromString(const std::string &fileStringWithPath, bool withExtension = true) +{ + std::string tmp = UbSystem::replaceInString(fileStringWithPath, "\\", "/"); + + // remove path + std::size_t last = tmp.rfind("/"); + if (last != std::string::npos && (last + 1) < tmp.size()) + tmp.erase(0, last + 1); + + // remove extension + if (!withExtension) { + last = tmp.rfind("."); + if (last != std::string::npos) + tmp.erase(last); + } + + return tmp; +} +/*==========================================================*/ +inline int getProcessID() +{ +#if defined UBSYSTEM_WINDOWS + return _getpid(); +#elif defined(UBSYSTEM_LINUX) || defined(UBSYSTEM_APPLE) || defined(UBSYSTEM_AIX) + return getpid(); +#else +#error "int UbSystem::getProcessID() - UnknownMachine" +#endif +} +/*==========================================================*/ +inline unsigned long getCurrentThreadID() +{ +#if defined UBSYSTEM_WINDOWS || defined(UBSYSTEM_CYGWIN) + return (unsigned long)GetCurrentThreadId(); +#elif defined(UBSYSTEM_APPLE) + uint64_t tid; + pthread_threadid_np(nullptr, &tid); + return (unsigned long)tid; +#elif defined(UBSYSTEM_LINUX) + return (unsigned long)syscall(SYS_gettid); +#elif defined(UBSYSTEM_AIX) + return (unsigned long)getpid(); // WORKAROUND for IBM (for get thread id is another function necessary) +#else +#error "unsigned long UbSystem::getCurrentThreadID() - UnknownMachine" +#endif +} +/*==========================================================*/ +inline bool isBigEndian() +{ + short word = 0x4321; + if ((*(char *)&word) != 0x21) + return true; + else + return false; +} +/*==========================================================*/ +inline bool isLittleEndian() { return !isBigEndian(); } +/*==========================================================*/ +inline std::string getTimeStamp() +{ + time_t t = time(NULL); + tm *localTime = localtime(&t); + + std::stringstream tmp; + tmp.fill('0'); + + tmp << localTime->tm_year + 1900 << "." << std::setw(2) << localTime->tm_mon + 1 << "." << std::setw(2) + << localTime->tm_mday << "@" << std::setw(2) << localTime->tm_hour << "." << std::setw(2) << localTime->tm_min + << "." << std::setw(2) << localTime->tm_sec; + + return tmp.str(); +} +/*==========================================================*/ +// swap Byte Order +// usage: int test = 8; +// swapByteOrder((unsigned char*)& test, sizeof(int)) +//#define ByteSwap5(x) ByteSwap((unsigned char *) &x,sizeof(x)) +inline void swapByteOrder(unsigned char *toSwap, int length) +{ + int i = 0; + int j = length - 1; + while (i < j) { + std::swap(toSwap[i], toSwap[j]); + i++, j--; + } +} +////////////////////////////////////////////////////////////////////////// +// get host name +inline std::string getMachineName() +{ + char Name[150]; #if defined(UBSYSTEM_WINDOWS) || defined(UBSYSTEM_CYGWIN) - TCHAR infoBuf[150]; - DWORD bufCharCount = 150; - memset(Name, 0, 150); - if (GetComputerName(infoBuf, &bufCharCount)) - { - for (int i = 0; i<150; i++) - { + TCHAR infoBuf[150]; + DWORD bufCharCount = 150; + memset(Name, 0, 150); + if (GetComputerName(infoBuf, &bufCharCount)) { + for (int i = 0; i < 150; i++) { Name[i] = infoBuf[i]; - } - } - else - { - strcpy_s(Name, "Unknown_Host_Name"); - } + } + } else { + strcpy_s(Name, "Unknown_Host_Name"); + } #elif (defined(UBSYSTEM_LINUX) || defined(UBSYSTEM_APPLE) || defined(UBSYSTEM_AIX)) && !defined(UBSYSTEM_CYGWIN) - memset(Name, 0, 150); - gethostname(Name, 150); + memset(Name, 0, 150); + gethostname(Name, 150); #endif - return std::string(Name); - } - - ////////////////////////////////////////////////////////////////////////// - // generic IfThenElse - start - ////////////////////////////////////////////////////////////////////////// - // primary template: yield second or third argument depending on first argument - template<bool C, typename Ta, typename Tb> - class IfThenElse; - - // partial specialization: true yields second argument - template<typename Ta, typename Tb> - class IfThenElse<true, Ta, Tb> { - public: - using ResultT = Ta; - }; - - // partial specialization: false yields third argument - template<typename Ta, typename Tb> - class IfThenElse<false, Ta, Tb> { - public: - using ResultT = Tb; - }; - ////////////////////////////////////////////////////////////////////////// - // generic IfThenElse - end - ////////////////////////////////////////////////////////////////////////// - - ////////////////////////////////////////////////////////////////////////// - //help struct for overloading methods in template classes for specific types - ////////////////////////////////////////////////////////////////////////// - template< typename T> - struct type2type - { - using type = T; - }; - - - ////////////////////////////////////////////////////////////////////////// - // pair selector - ////////////////////////////////////////////////////////////////////////// - template <typename Pair> - struct select1st - { - using argument_type = Pair ; - using result_type = typename Pair::first_type ; - - const result_type& operator()(const argument_type &p) const - { - return p.first ; - } - }; - - template <typename Pair> - struct select2nd - { - using argument_type = Pair ; - using result_type = typename Pair::second_type ; - - const result_type& operator()(const argument_type &p) const - { - return p.second ; - } - }; + return std::string(Name); +} +////////////////////////////////////////////////////////////////////////// +// generic IfThenElse - start +////////////////////////////////////////////////////////////////////////// +// primary template: yield second or third argument depending on first argument +template <bool C, typename Ta, typename Tb> +class IfThenElse; + +// partial specialization: true yields second argument +template <typename Ta, typename Tb> +class IfThenElse<true, Ta, Tb> +{ +public: + using ResultT = Ta; +}; + +// partial specialization: false yields third argument +template <typename Ta, typename Tb> +class IfThenElse<false, Ta, Tb> +{ +public: + using ResultT = Tb; +}; +////////////////////////////////////////////////////////////////////////// +// generic IfThenElse - end +////////////////////////////////////////////////////////////////////////// + +////////////////////////////////////////////////////////////////////////// +// help struct for overloading methods in template classes for specific types +////////////////////////////////////////////////////////////////////////// +template <typename T> +struct type2type { + using type = T; }; -#define UB_STATIC_ASSERT(expr) static_cast<void>(sizeof( UbSystem::ub_static_assert<expr> )); -//zum ueberpruefen von STATISCHEN ausdruecken waehrend der compile-zeit +////////////////////////////////////////////////////////////////////////// +// pair selector +////////////////////////////////////////////////////////////////////////// +template <typename Pair> +struct select1st { + using argument_type = Pair; + using result_type = typename Pair::first_type; + + const result_type &operator()(const argument_type &p) const { return p.first; } +}; + +template <typename Pair> +struct select2nd { + using argument_type = Pair; + using result_type = typename Pair::second_type; + + const result_type &operator()(const argument_type &p) const { return p.second; } +}; + +}; // namespace UbSystem + +#define UB_STATIC_ASSERT(expr) static_cast<void>(sizeof(UbSystem::ub_static_assert<expr>)); +// zum ueberpruefen von STATISCHEN ausdruecken waehrend der compile-zeit //--> Ausdruecke muessen schon ZUR compilerzeit auswertbar sein !!! -//Anwendung z.B. zur Ueberpruefung von Funktionalitaeten, wie z.B. bei UbMath::getNegativeInfinity<double>(); +// Anwendung z.B. zur Ueberpruefung von Funktionalitaeten, wie z.B. bei UbMath::getNegativeInfinity<double>(); // -//Grund fuer macro ist einfach, dass es besser anzuwenden ist in der praxis! -//ansonsten wuerde es so aussehen: +// Grund fuer macro ist einfach, dass es besser anzuwenden ist in der praxis! +// ansonsten wuerde es so aussehen: // UbSystem::ub_static_assert< aaa == 1 > test(); // da ist UB_STATIC_ASSERT(aaa == 1); schoener // -//um das zu vermeiden machtman hier diesen static_cast<void>(sizeof(...) ) -//Code-Snippet: +// um das zu vermeiden machtman hier diesen static_cast<void>(sizeof(...) ) +// Code-Snippet: // struct Test { const static bool m_const_bool = true; bool m_bool; }; // int main() { // UB_STATIC_ASSERT( Test::m_const_bool == true ); // --> okay, assert bestanden // UB_STATIC_ASSERT( Test::m_const_bool == false); //: -// --> assert nicht bestanden z.B. error C2027: use of undefined type 'UbSystem::ub_static_assert<__formal> with __formal = false --> funzt nicht. fehler im code -// UB_STATIC_ASSERT( Test::m_bool == true ); +// --> assert nicht bestanden z.B. error C2027: use of undefined type 'UbSystem::ub_static_assert<__formal> with +// __formal = false --> funzt nicht. fehler im code UB_STATIC_ASSERT( Test::m_bool == true ); // --> nicht erlaubt, da m_bool nicht statisch und nicht const ist. //} -#endif //UBSYSTEM_H +#endif // UBSYSTEM_H diff --git a/src/basics/basics/utilities/UbTiming.h b/src/basics/basics/utilities/UbTiming.h index 35181c4198b818458145a4fa3879f355b24b6536..a99c4ec39acfa64c99bb2a61a8ceec4fc8ba604a 100644 --- a/src/basics/basics/utilities/UbTiming.h +++ b/src/basics/basics/utilities/UbTiming.h @@ -1,28 +1,28 @@ //======================================================================================= -// ____ ____ __ ______ __________ __ __ __ __ -// \ \ | | | | | _ \ |___ ___| | | | | / \ | | -// \ \ | | | | | |_) | | | | | | | / \ | | -// \ \ | | | | | _ / | | | | | | / /\ \ | | -// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ -// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| -// \ \ | | ________________________________________________________________ -// \ \ | | | ______________________________________________________________| -// \ \| | | | __ __ __ __ ______ _______ -// \ | | |_____ | | | | | | | | | _ \ / _____) -// \ | | _____| | | | | | | | | | | \ \ \_______ +// ____ ____ __ ______ __________ __ __ __ __ +// \ \ | | | | | _ \ |___ ___| | | | | / \ | | +// \ \ | | | | | |_) | | | | | | | / \ | | +// \ \ | | | | | _ / | | | | | | / /\ \ | | +// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ +// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| +// \ \ | | ________________________________________________________________ +// \ \ | | | ______________________________________________________________| +// \ \| | | | __ __ __ __ ______ _______ +// \ | | |_____ | | | | | | | | | _ \ / _____) +// \ | | _____| | | | | | | | | | | \ \ \_______ // \ | | | | |_____ | \_/ | | | | |_/ / _____ | -// \ _____| |__| |________| \_______/ |__| |______/ (_______/ +// \ _____| |__| |________| \_______/ |__| |______/ (_______/ // -// This file is part of VirtualFluids. VirtualFluids is free software: you can +// This file is part of VirtualFluids. VirtualFluids is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of +// License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. -// -// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// +// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License along // with VirtualFluids (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>. // @@ -33,344 +33,321 @@ #ifndef UBTIMING_H #define UBTIMING_H -#include <string> -#include <limits> +#include <ctime> #include <iostream> +#include <limits> #include <sstream> +#include <string> #include <vector> -#include <ctime> #ifdef VF_MPI - #include <mpi.h> - #include <basics/parallel/PbMpi.h> -#endif //VF_MPI +#include <basics/parallel/PbMpi.h> +#include <mpi.h> +#endif // VF_MPI class UbTiming { public: - UbTiming() - { - this->duration = 0.0; - this->deltaT = 0.0; - this->startTime = 0; - this->name = "noname"; - } - /*==========================================================*/ - UbTiming(const std::string& name) - { - this->duration = 0.0; - this->deltaT = 0.0; - this->startTime = 0; - this->name = name; - } - /*==========================================================*/ - virtual ~UbTiming() = default; - /*==========================================================*/ - virtual void initTiming() - { - this->duration = 0.0; - } - /*==========================================================*/ - virtual void startTiming() - { - #if defined(VF_MPI) && !defined(CAB_RUBY) - this->startTime = PbMpi::Wtime(); - #else - this->startTime = (double)clock(); - #endif //VF_MPI - } - /*==========================================================*/ - virtual void initAndStartTiming() - { - this->initTiming(); - this->startTiming(); - } - /*==========================================================*/ - virtual void endTiming() - { - this->stopTiming(); - } - /*==========================================================*/ - virtual void stopTiming() - { - #if defined(VF_MPI) && !defined(CAB_RUBY) - this->deltaT = PbMpi::Wtime()-this->startTime; - #else - this->deltaT = ((double)clock()-this->startTime)/(double)CLOCKS_PER_SEC; - #endif //VF_MPI + UbTiming() + { + this->duration = 0.0; + this->deltaT = 0.0; + this->startTime = 0; + this->name = "noname"; + } + /*==========================================================*/ + UbTiming(const std::string &name) + { + this->duration = 0.0; + this->deltaT = 0.0; + this->startTime = 0; + this->name = name; + } + /*==========================================================*/ + virtual ~UbTiming() = default; + /*==========================================================*/ + virtual void initTiming() { this->duration = 0.0; } + /*==========================================================*/ + virtual void startTiming() + { +#if defined(VF_MPI) && !defined(CAB_RUBY) + this->startTime = PbMpi::Wtime(); +#else + this->startTime = (double)clock(); +#endif // VF_MPI + } + /*==========================================================*/ + virtual void initAndStartTiming() + { + this->initTiming(); + this->startTiming(); + } + /*==========================================================*/ + virtual void endTiming() { this->stopTiming(); } + /*==========================================================*/ + virtual void stopTiming() + { +#if defined(VF_MPI) && !defined(CAB_RUBY) + this->deltaT = PbMpi::Wtime() - this->startTime; +#else + this->deltaT = ((double)clock() - this->startTime) / (double)CLOCKS_PER_SEC; +#endif // VF_MPI - this->duration += this->deltaT; - } - /*==========================================================*/ - virtual double getDuration() const - { - return this->duration; - } - /*==========================================================*/ - virtual void setName(const std::string& name) - { - this->name = name; - } - /*==========================================================*/ - virtual std::string getName() const - { - return this->name; - } - /*==========================================================*/ - void start() - { - this->duration = 0.0; + this->duration += this->deltaT; + } + /*==========================================================*/ + virtual double getDuration() const { return this->duration; } + /*==========================================================*/ + virtual void setName(const std::string &name) { this->name = name; } + /*==========================================================*/ + virtual std::string getName() const { return this->name; } + /*==========================================================*/ + void start() + { + this->duration = 0.0; - #if defined(VF_MPI) && !defined(CAB_RUBY) - this->startTime = PbMpi::Wtime(); - #else - this->startTime = (double)clock(); - #endif //VF_MPI - } - /*==========================================================*/ - void pause() - { - #if defined(VF_MPI) && !defined(CAB_RUBY) - this->duration += PbMpi::Wtime()-this->startTime; - #else - this->duration +=((double)clock()-this->startTime)/(double)CLOCKS_PER_SEC; - #endif //VF_MPI - } - /*==========================================================*/ - void unpause() - { - #if defined(VF_MPI) && !defined(CAB_RUBY) - this->startTime = PbMpi::Wtime(); - #else - this->startTime = (double)clock(); - #endif //VF_MPI - } - /*==========================================================*/ - void stop() - { - #if defined(VF_MPI) && !defined(CAB_RUBY) - this->duration += PbMpi::Wtime()-this->startTime; - #else - this->duration +=((double)clock()-this->startTime)/(double)CLOCKS_PER_SEC; - #endif //VF_MPI - } - /*==========================================================*/ - double getTicks() const - { - #if defined(VF_MPI) && !defined(CAB_RUBY) - return PbMpi::Wtick(); - #else - return double(1.0)/double(CLOCKS_PER_SEC); - #endif //VF_MPI - } +#if defined(VF_MPI) && !defined(CAB_RUBY) + this->startTime = PbMpi::Wtime(); +#else + this->startTime = (double)clock(); +#endif // VF_MPI + } + /*==========================================================*/ + void pause() + { +#if defined(VF_MPI) && !defined(CAB_RUBY) + this->duration += PbMpi::Wtime() - this->startTime; +#else + this->duration += ((double)clock() - this->startTime) / (double)CLOCKS_PER_SEC; +#endif // VF_MPI + } + /*==========================================================*/ + void unpause() + { +#if defined(VF_MPI) && !defined(CAB_RUBY) + this->startTime = PbMpi::Wtime(); +#else + this->startTime = (double)clock(); +#endif // VF_MPI + } + /*==========================================================*/ + void stop() + { +#if defined(VF_MPI) && !defined(CAB_RUBY) + this->duration += PbMpi::Wtime() - this->startTime; +#else + this->duration += ((double)clock() - this->startTime) / (double)CLOCKS_PER_SEC; +#endif // VF_MPI + } + /*==========================================================*/ + double getTicks() const + { +#if defined(VF_MPI) && !defined(CAB_RUBY) + return PbMpi::Wtick(); +#else + return double(1.0) / double(CLOCKS_PER_SEC); +#endif // VF_MPI + } protected: - std::string name; + std::string name; - double startTime; - double duration; - double deltaT; + double startTime; + double duration; + double deltaT; }; #include <basics/utilities/UbSystem.h> //for definitons of system/OS type -#ifdef UBSYSTEM_APPLE //Apple hack - #include <mach/mach_time.h> - #include <ctime> - #include <cstdio> - inline void mach_absolute_difference(const uint64_t& end, const uint64_t& start, struct timespec *tp) - { - uint64_t difference = end - start; - static mach_timebase_info_data_t info = {0,0}; - - if (info.denom == 0) - mach_timebase_info(&info); - - uint64_t elapsednano = difference * (info.numer / info.denom); - - tp->tv_sec = elapsednano * 1e-9; - tp->tv_nsec = elapsednano - (tp->tv_sec * 1e9); - } +#ifdef UBSYSTEM_APPLE // Apple hack +#include <cstdio> +#include <ctime> +#include <mach/mach_time.h> +inline void mach_absolute_difference(const uint64_t &end, const uint64_t &start, struct timespec *tp) +{ + uint64_t difference = end - start; + static mach_timebase_info_data_t info = { 0, 0 }; + + if (info.denom == 0) + mach_timebase_info(&info); + + uint64_t elapsednano = difference * (info.numer / info.denom); + + tp->tv_sec = elapsednano * 1e-9; + tp->tv_nsec = elapsednano - (tp->tv_sec * 1e9); +} #elif defined(UBSYSTEM_LINUX) || defined(UBSYSTEM_AIX) - #include <ctime> - #include <unistd.h> // for sysconf - #include <pthread.h> +#include <ctime> +#include <pthread.h> +#include <unistd.h> // for sysconf #endif /*=========================================================================*/ -//! \brief Time Measuring -//! \details +//! \brief Time Measuring +//! \details //! example: //! \code -//! t=0 start -//! t=1 +//! t=0 start +//! t=1 //! t=2 stop -> return 2; getLapTime=2; getTotalTime 2; getLapTimes: 2 -//! t=3 -//! t=4 +//! t=3 +//! t=4 //! t=5 stop -> return 3; getLapTime=3; getTotalTime 5; getLapTimes: 2,3 //! t=6 stop -> return 1; getLapTime=1; getTotalTime 6; getLapTimes: 2,3,1 -//! t=7 -//! t=8 start ->no consideration of time 7 and 8 -//! t=9 +//! t=7 +//! t=8 start ->no consideration of time 7 and 8 +//! t=9 //! t=10 stop -> return 2; getLapTime=2; getTotalTime 8; getLapTimes: 2,3,1,2 //! t=11 resetAndStart -> Timer is reset and restarted //! t=12 -//! t=13 +//! t=13 //! t=14 stop -> return 3; getLapTime=3; getTotalTime 3; getLapTimes: 3 //! \endcode class UbTimer { public: - UbTimer(const bool& storeLapTimes = false) - : name("unamed"), storeLapTimes(storeLapTimes) - - { + UbTimer(const bool &storeLapTimes = false) : name("unamed"), storeLapTimes(storeLapTimes) {} + /*==========================================================*/ + UbTimer(const std::string &name, const bool &storeLapTimes = false) : name(name), storeLapTimes(storeLapTimes) {} + /*==========================================================*/ + virtual ~UbTimer() = default; + /*==========================================================*/ + double getLapTime() const { return this->lapTime; } + std::vector<double> getLapTimes() const { return this->lapTimes; } + void setName(const std::string &name) { this->name = name; } + std::string getName() const { return this->name; } + bool isRunning() const { return isMeasuring; } + bool isStoringLapTimes() const { return storeLapTimes; } + /*==========================================================*/ + void setStoreLapTimes(const bool &storeLapTimes) { this->storeLapTimes = storeLapTimes; } + /*==========================================================*/ + void start() + { + this->isMeasuring = true; + +#if defined(VF_MPI) && !defined(CAB_RUBY) + this->startTime = PbMpi::Wtime(); +#elif defined(UBSYSTEM_APPLE) + this->startTime = mach_absolute_time(); +#elif defined(UBSYSTEM_LINUX) || defined(UBSYSTEM_AIX) + timespec tp; + clock_gettime(CLOCK_REALTIME, &tp); + this->startTime = (double)(tp.tv_sec) * 1.0e9 + (double)(tp.tv_nsec); +#else + this->startTime = (double)clock(); +#endif // VF_MPI + } + /*==========================================================*/ + void resetAndStart() + { + this->reset(); + this->start(); + } + /*==========================================================*/ + // stop: - stops the calculation and returns the time elapsed since last start/stop + // - timing continues + double stop() + { + // if start() was never activated before: + if (!isMeasuring) + return 0.0; - } - /*==========================================================*/ - UbTimer(const std::string& name, const bool& storeLapTimes = false) - : name(name), storeLapTimes(storeLapTimes) - { +#if defined(VF_MPI) && !defined(CAB_RUBY) + double actTime = PbMpi::Wtime(); + this->lapTime = actTime - this->startTime; +#elif defined(UBSYSTEM_APPLE) + double actTime = mach_absolute_time(); + timespec tp; + mach_absolute_difference(actTime, this->startTime, &tp); + this->lapTime = tp.tv_sec + tp.tv_nsec * 1e-9; +#elif defined(UBSYSTEM_LINUX) || defined(UBSYSTEM_AIX) + timespec tp; + clock_gettime(CLOCK_REALTIME, &tp); + double actTime = (double)(tp.tv_sec) * 1.0e9 + (double)(tp.tv_nsec); + this->lapTime = (actTime - this->startTime) * 1.0e-9; +#else + double actTime = (double)clock(); + this->lapTime = (actTime - this->startTime) / (double)CLOCKS_PER_SEC; +#endif // VF_MPI - } - /*==========================================================*/ - virtual ~UbTimer() = default; - /*==========================================================*/ - double getLapTime() const { return this->lapTime; } - std::vector<double> getLapTimes() const { return this->lapTimes; } - void setName(const std::string& name) { this->name = name; } - std::string getName() const { return this->name; } - bool isRunning() const { return isMeasuring; } - bool isStoringLapTimes() const { return storeLapTimes; } - /*==========================================================*/ - void setStoreLapTimes(const bool& storeLapTimes) { this->storeLapTimes = storeLapTimes; } - /*==========================================================*/ - void start() - { - this->isMeasuring = true; + this->startTime = actTime; + this->totalTime += this->lapTime; + if (storeLapTimes) + lapTimes.push_back(this->lapTime); - #if defined(VF_MPI) && !defined(CAB_RUBY) - this->startTime = PbMpi::Wtime(); - #elif defined(UBSYSTEM_APPLE) - this->startTime = mach_absolute_time(); - #elif defined(UBSYSTEM_LINUX) || defined(UBSYSTEM_AIX) - timespec tp; - clock_gettime(CLOCK_REALTIME,&tp); - this->startTime = (double)(tp.tv_sec)*1.0e9 + (double)(tp.tv_nsec); - #else - this->startTime = (double)clock(); - #endif //VF_MPI - } - /*==========================================================*/ - void resetAndStart() { this->reset(); this->start(); } - /*==========================================================*/ - //stop: - stops the calculation and returns the time elapsed since last start/stop - // - timing continues - double stop() - { - //if start() was never activated before: - if(!isMeasuring) return 0.0; - - #if defined(VF_MPI) && !defined(CAB_RUBY) - double actTime = PbMpi::Wtime(); - this->lapTime = actTime-this->startTime; - #elif defined(UBSYSTEM_APPLE) - double actTime = mach_absolute_time(); - timespec tp; - mach_absolute_difference(actTime, this->startTime, &tp); - this->lapTime = tp.tv_sec + tp.tv_nsec*1e-9; - #elif defined(UBSYSTEM_LINUX) || defined(UBSYSTEM_AIX) - timespec tp; - clock_gettime(CLOCK_REALTIME,&tp); - double actTime = (double)(tp.tv_sec)*1.0e9 + (double)(tp.tv_nsec); - this->lapTime = (actTime-this->startTime)*1.0e-9; - #else - double actTime = (double)clock(); - this->lapTime = (actTime-this->startTime)/(double)CLOCKS_PER_SEC; - #endif //VF_MPI - - this->startTime = actTime; - this->totalTime += this->lapTime; - if(storeLapTimes) lapTimes.push_back(this->lapTime); + return lapTime; + } + /*==========================================================*/ + void reset() + { + this->isMeasuring = false; - return lapTime; - } - /*==========================================================*/ - void reset() - { - this->isMeasuring = false; - - this->startTime = 0.0; - this->totalTime = 0.0; - this->lapTime = 0.0; + this->startTime = 0.0; + this->totalTime = 0.0; + this->lapTime = 0.0; - lapTimes.resize(0); - } - /*==========================================================*/ - double getCurrentLapTime() const - { - //if start() was never activated before: - if(!isMeasuring) return 0.0; - - #if defined(VF_MPI) && !defined(CAB_RUBY) - return PbMpi::Wtime() - this->startTime; - #elif defined(UBSYSTEM_APPLE) - timespec tp; - mach_absolute_difference(mach_absolute_time(), this->startTime, &tp); - return tp.tv_sec + tp.tv_nsec*1e-9; - #elif defined(UBSYSTEM_LINUX) || defined(UBSYSTEM_AIX) - timespec tp; - clock_gettime(CLOCK_REALTIME,&tp); - return ((double)(tp.tv_sec)*1.0e9 + (double)(tp.tv_nsec) - this->startTime)*1.0e-9; - #else - return ( (double)clock() - this->startTime ) / (double)CLOCKS_PER_SEC; - #endif //VF_MPI - - } - /*==========================================================*/ - double getTotalTime() const - { - return this->totalTime; - } - /*==========================================================*/ - std::string toString() - { - std::stringstream text; - text<<*this; - return text.str(); - } + lapTimes.resize(0); + } + /*==========================================================*/ + double getCurrentLapTime() const + { + // if start() was never activated before: + if (!isMeasuring) + return 0.0; - //ueberladene Operatoren - /*==========================================================*/ - friend inline std::ostream& operator << (std::ostream& os, const UbTimer& timer) - { - os<<"UbTimer[totalTime="<<timer.totalTime<<"sec, lapTimes("; - for(std::size_t i=0; i<timer.lapTimes.size(); i++) os<<timer.lapTimes[i]<<","; - os<<")]"; - return os; - } +#if defined(VF_MPI) && !defined(CAB_RUBY) + return PbMpi::Wtime() - this->startTime; +#elif defined(UBSYSTEM_APPLE) + timespec tp; + mach_absolute_difference(mach_absolute_time(), this->startTime, &tp); + return tp.tv_sec + tp.tv_nsec * 1e-9; +#elif defined(UBSYSTEM_LINUX) || defined(UBSYSTEM_AIX) + timespec tp; + clock_gettime(CLOCK_REALTIME, &tp); + return ((double)(tp.tv_sec) * 1.0e9 + (double)(tp.tv_nsec) - this->startTime) * 1.0e-9; +#else + return ((double)clock() - this->startTime) / (double)CLOCKS_PER_SEC; +#endif // VF_MPI + } + /*==========================================================*/ + double getTotalTime() const { return this->totalTime; } + /*==========================================================*/ + std::string toString() + { + std::stringstream text; + text << *this; + return text.str(); + } + // ueberladene Operatoren + /*==========================================================*/ + friend inline std::ostream &operator<<(std::ostream &os, const UbTimer &timer) + { + os << "UbTimer[totalTime=" << timer.totalTime << "sec, lapTimes("; + for (std::size_t i = 0; i < timer.lapTimes.size(); i++) + os << timer.lapTimes[i] << ","; + os << ")]"; + return os; + } protected: - std::string name; - bool isMeasuring{false}; - bool storeLapTimes; + std::string name; + bool isMeasuring{ false }; + bool storeLapTimes; - double startTime{0.0}; - double totalTime{0.0}; - double lapTime{0.0}; - - std::vector<double> lapTimes; -}; + double startTime{ 0.0 }; + double totalTime{ 0.0 }; + double lapTime{ 0.0 }; + std::vector<double> lapTimes; +}; /*=========================================================================*/ -//! \brief Time Measuring -//! -//! \details UbProressTimer measures the time from its instantiation to destruction and spend the elapsed time on "os" in [s] -//! example: -//! \code +//! \brief Time Measuring +//! +//! \details UbProressTimer measures the time from its instantiation to destruction and spend the elapsed time on "os" +//! in [s] example: \code //! { //! UbProgressTimer timer; //! UbSystem::sleepS(10); @@ -380,36 +357,29 @@ protected: class UbProgressTimer : public UbTimer { public: - UbProgressTimer(const UbProgressTimer& rhs) = delete; + UbProgressTimer(const UbProgressTimer &rhs) = delete; - explicit UbProgressTimer( std::ostream & os = std::cout ) - : UbTimer(),os(os) - { - this->start(); - } - /*==========================================================*/ - ~UbProgressTimer() override - { - // A) Throwing an exception from a destructor is a Bad Thing. - // B) The progress_timer destructor does output which may throw. - // C) A progress_timer is usually not critical to the application. - // Therefore, wrap the I/O in a try block, catch and ignore all exceptions. - try + explicit UbProgressTimer(std::ostream &os = std::cout) : UbTimer(), os(os) { this->start(); } + /*==========================================================*/ + ~UbProgressTimer() override { - // use istream instead of ios_base to workaround GNU problem (Greg Chicares) - std::istream::fmtflags old_flags = os.setf( std::istream::fixed, - std::istream::floatfield ); - std::streamsize old_prec = os.precision( 2 ); - os << stop() << " s" << std::endl; - os.flags( old_flags ); - os.precision( old_prec ); + // A) Throwing an exception from a destructor is a Bad Thing. + // B) The progress_timer destructor does output which may throw. + // C) A progress_timer is usually not critical to the application. + // Therefore, wrap the I/O in a try block, catch and ignore all exceptions. + try { + // use istream instead of ios_base to workaround GNU problem (Greg Chicares) + std::istream::fmtflags old_flags = os.setf(std::istream::fixed, std::istream::floatfield); + std::streamsize old_prec = os.precision(2); + os << stop() << " s" << std::endl; + os.flags(old_flags); + os.precision(old_prec); + } catch (...) { + } // eat any exceptions } - catch (...) {} // eat any exceptions - } private: - std::ostream & os; + std::ostream &os; }; - -#endif //UBTIMING_H +#endif // UBTIMING_H diff --git a/src/basics/basics/utilities/UbTuple.h b/src/basics/basics/utilities/UbTuple.h index f081f2e9e0a054e320a2dfb1fd6e6e49d0489216..fe9c787cead38621beafab3d082122277bdcff73 100644 --- a/src/basics/basics/utilities/UbTuple.h +++ b/src/basics/basics/utilities/UbTuple.h @@ -1,28 +1,28 @@ //======================================================================================= -// ____ ____ __ ______ __________ __ __ __ __ -// \ \ | | | | | _ \ |___ ___| | | | | / \ | | -// \ \ | | | | | |_) | | | | | | | / \ | | -// \ \ | | | | | _ / | | | | | | / /\ \ | | -// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ -// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| -// \ \ | | ________________________________________________________________ -// \ \ | | | ______________________________________________________________| -// \ \| | | | __ __ __ __ ______ _______ -// \ | | |_____ | | | | | | | | | _ \ / _____) -// \ | | _____| | | | | | | | | | | \ \ \_______ +// ____ ____ __ ______ __________ __ __ __ __ +// \ \ | | | | | _ \ |___ ___| | | | | / \ | | +// \ \ | | | | | |_) | | | | | | | / \ | | +// \ \ | | | | | _ / | | | | | | / /\ \ | | +// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ +// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| +// \ \ | | ________________________________________________________________ +// \ \ | | | ______________________________________________________________| +// \ \| | | | __ __ __ __ ______ _______ +// \ | | |_____ | | | | | | | | | _ \ / _____) +// \ | | _____| | | | | | | | | | | \ \ \_______ // \ | | | | |_____ | \_/ | | | | |_/ / _____ | -// \ _____| |__| |________| \_______/ |__| |______/ (_______/ +// \ _____| |__| |________| \_______/ |__| |______/ (_______/ // -// This file is part of VirtualFluids. VirtualFluids is free software: you can +// This file is part of VirtualFluids. VirtualFluids is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of +// License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. -// -// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// +// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License along // with VirtualFluids (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>. // @@ -34,8 +34,8 @@ #define UBTUPLE_H #include <iostream> -#include <string> #include <ostream> +#include <string> ////////////////////////////////////////////////////////////////////////// //! \brief A class implements a tuple @@ -62,7 +62,7 @@ //! val<2>(t3) = 42; //! val<3>(t3) = 0.2; //! t3 = makeUbTuple(false, 23, 13.13); -//! +//! //! std::cout << val<1>(t3) << ", "; //! std::cout << val<2>(t3) << ", "; //! std::cout << val<3>(t3) << std::endl; @@ -75,343 +75,347 @@ //! \endcode template <typename T> -class UbTypeOp // primary template -{ +class UbTypeOp // primary template +{ public: - using ArgT = T; - using BareT = T; - using ConstT = const T; - using RefT = T &; - using RefBareT = T &; - using RefConstT = const T &; + using ArgT = T; + using BareT = T; + using ConstT = const T; + using RefT = T &; + using RefBareT = T &; + using RefConstT = const T &; }; /**** end of typeop1.hpp ****/ // partial specialization for const /********************************** -* typeop2.hpp: -**********************************/ + * typeop2.hpp: + **********************************/ template <typename T> -class UbTypeOp <T const> // partial specialization for const types -{ - public: - using ArgT = const T; - using BareT = T; - using ConstT = const T; - using RefT = const T &; - using RefBareT = T &; - using RefConstT = const T &; +class UbTypeOp<T const> // partial specialization for const types +{ +public: + using ArgT = const T; + using BareT = T; + using ConstT = const T; + using RefT = const T &; + using RefBareT = T &; + using RefConstT = const T &; }; /**** end of typeop2.hpp ****/ // partial specialization for references /********************************** -* typeop3.hpp: -**********************************/ + * typeop3.hpp: + **********************************/ template <typename T> -class UbTypeOp <T&> // partial specialization for references +class UbTypeOp<T &> // partial specialization for references { public: - using ArgT = T &; - using BareT = typename UbTypeOp<T>::BareT; - using ConstT = const T; - using RefT = T &; - using RefBareT = typename UbTypeOp<T>::BareT &; - using RefConstT = const T &; + using ArgT = T &; + using BareT = typename UbTypeOp<T>::BareT; + using ConstT = const T; + using RefT = T &; + using RefBareT = typename UbTypeOp<T>::BareT &; + using RefConstT = const T &; }; /**** end of typeop3.hpp ****/ // full specialization for void /********************************** -* typeop4.hpp: -**********************************/ -template<> -class UbTypeOp <void> // full specialization for void + * typeop4.hpp: + **********************************/ +template <> +class UbTypeOp<void> // full specialization for void { public: - using ArgT = void; - using BareT = void; - using ConstT = const void; - using RefT = void; - using RefBareT = void; - using RefConstT = void; + using ArgT = void; + using BareT = void; + using ConstT = const void; + using RefT = void; + using RefBareT = void; + using RefConstT = void; }; /**** end of typeop4.hpp ****/ template <typename T1, typename T2> -class UbDuo; +class UbDuo; template <typename T1, typename T2> -std::ostream& operator << (std::ostream& os, UbDuo<T1, T2> const& d1); +std::ostream &operator<<(std::ostream &os, UbDuo<T1, T2> const &d1); -//duo1.hpp +// duo1.hpp template <typename T1, typename T2> -class UbDuo +class UbDuo { public: - using Type1 = T1; // type of first field - using Type2 = T2; // type of second field - enum { N = 2 }; // number of fields + using Type1 = T1; // type of first field + using Type2 = T2; // type of second field + enum { N = 2 }; // number of fields public: - // constructors - UbDuo() : value1(), value2() { } - UbDuo (T1 const & a, T2 const & b) : value1(a), value2(b) { } - - // for implicit type conversion during construction - template <typename U1, typename U2> - UbDuo (UbDuo<U1,U2> const & d) : value1(d.v1()), value2(d.v2()) { } - - // for implicit type conversion during assignments - template <typename U1, typename U2> - UbDuo<T1, T2>& operator = (UbDuo<U1,U2> const & d) - { - value1 = d.v1();//value1; - value2 = d.v2();//value2; - return *this; - } - - // field access - T1& v1() { return value1; } - T1 const& v1() const { return value1; } - - T2& v2() { return value2; } - T2 const& v2() const { return value2; } + // constructors + UbDuo() : value1(), value2() {} + UbDuo(T1 const &a, T2 const &b) : value1(a), value2(b) {} + + // for implicit type conversion during construction + template <typename U1, typename U2> + UbDuo(UbDuo<U1, U2> const &d) : value1(d.v1()), value2(d.v2()) + { + } + + // for implicit type conversion during assignments + template <typename U1, typename U2> + UbDuo<T1, T2> &operator=(UbDuo<U1, U2> const &d) + { + value1 = d.v1(); // value1; + value2 = d.v2(); // value2; + return *this; + } + + // field access + T1 &v1() { return value1; } + T1 const &v1() const { return value1; } + + T2 &v2() { return value2; } + T2 const &v2() const { return value2; } private: - T1 value1; // value of first field - T2 value2; // value of second field + T1 value1; // value of first field + T2 value2; // value of second field }; // comparison operators (allow mixed types): -template <typename T1, typename T2,typename U1, typename U2> -inline bool operator == (UbDuo<T1,T2> const& d1, UbDuo<U1,U2> const& d2) +template <typename T1, typename T2, typename U1, typename U2> +inline bool operator==(UbDuo<T1, T2> const &d1, UbDuo<U1, U2> const &d2) { - return d1.v1()==d2.v1() && d1.v2()==d2.v2(); + return d1.v1() == d2.v1() && d1.v2() == d2.v2(); } -template <typename T1, typename T2,typename U1, typename U2> -inline bool operator != (UbDuo<T1,T2> const& d1, UbDuo<U1,U2> const& d2) +template <typename T1, typename T2, typename U1, typename U2> +inline bool operator!=(UbDuo<T1, T2> const &d1, UbDuo<U1, U2> const &d2) { - return !(d1==d2); + return !(d1 == d2); } -template <typename T1, typename T2,typename U1, typename U2> -inline bool operator < (UbDuo<T1,T2> const& d1, UbDuo<U1,U2> const& d2) +template <typename T1, typename T2, typename U1, typename U2> +inline bool operator<(UbDuo<T1, T2> const &d1, UbDuo<U1, U2> const &d2) { - if (d1.v1() < d2.v1() ) return true; - else if(d1.v1() == d2.v1() ) return d1.v2() < d2.v2(); + if (d1.v1() < d2.v1()) + return true; + else if (d1.v1() == d2.v1()) + return d1.v2() < d2.v2(); - return false; + return false; } template <typename T1, typename T2> -std::ostream& operator << (std::ostream& os, UbDuo<T1, T2> const& d1) +std::ostream &operator<<(std::ostream &os, UbDuo<T1, T2> const &d1) { os << d1.v1() << ", " << d1.v2(); return os; } // convenience function for creation and initialization -template <typename T1, typename T2> -inline UbDuo<T1,T2> makeUbDuo(T1 const & a, T2 const & b) +template <typename T1, typename T2> +inline UbDuo<T1, T2> makeUbDuo(T1 const &a, T2 const &b) { - return UbDuo<T1,T2>(a,b); + return UbDuo<T1, T2>(a, b); } -//duo2.hpp +// duo2.hpp template <typename A, typename B, typename C> -class UbDuo<A, UbDuo<B,C> > +class UbDuo<A, UbDuo<B, C>> { public: - using T1 = A; // type of first field - using T2 = UbDuo<B, C>; // type of second field - enum { N = UbDuo<B,C>::N + 1 }; // number of fields - + using T1 = A; // type of first field + using T2 = UbDuo<B, C>; // type of second field + enum { N = UbDuo<B, C>::N + 1 }; // number of fields + public: - // constructors - UbDuo() : value1(), value2() { } - UbDuo (T1 const & a, T2 const & b) : value1(a), value2(b) { } - - // for implicit type conversion during construction - template <typename U1, typename U2> - UbDuo (UbDuo<U1,U2> const & d) : value1(d.v1()), value2(d.v2()) { } - - // for implicit type conversion during assignments - template <typename U1, typename U2> - UbDuo<T1, T2>& operator = (UbDuo<U1,U2> const & d) - { - value1 = d.v1();//value1; - value2 = d.v2();//value2; - return *this; - } - - // field access - T1& v1() { return value1; } - T1 const& v1() const { return value1; } - - T2& v2() { return value2; } - T2 const& v2() const { return value2; } + // constructors + UbDuo() : value1(), value2() {} + UbDuo(T1 const &a, T2 const &b) : value1(a), value2(b) {} + + // for implicit type conversion during construction + template <typename U1, typename U2> + UbDuo(UbDuo<U1, U2> const &d) : value1(d.v1()), value2(d.v2()) + { + } + + // for implicit type conversion during assignments + template <typename U1, typename U2> + UbDuo<T1, T2> &operator=(UbDuo<U1, U2> const &d) + { + value1 = d.v1(); // value1; + value2 = d.v2(); // value2; + return *this; + } + + // field access + T1 &v1() { return value1; } + T1 const &v1() const { return value1; } + + T2 &v2() { return value2; } + T2 const &v2() const { return value2; } private: - T1 value1; // value of first field - T2 value2; // value of second field + T1 value1; // value of first field + T2 value2; // value of second field }; -//duo3.hpp +// duo3.hpp // primary template for type of Nth field of (duo) T template <int N, typename T> -class UbDuoT +class UbDuoT { public: - using ResultT = void; // in general, the result type is void + using ResultT = void; // in general, the result type is void }; // specialization for 1st field of a plain duo template <typename A, typename B> -class UbDuoT<1, UbDuo<A,B> > +class UbDuoT<1, UbDuo<A, B>> { public: - using ResultT = A; + using ResultT = A; }; // specialization for 2nd field of a plain duo template <typename A, typename B> -class UbDuoT<2, UbDuo<A,B> > +class UbDuoT<2, UbDuo<A, B>> { public: - using ResultT = B; + using ResultT = B; }; // specialization for Nth field of a recursive duo template <int N, typename A, typename B, typename C> -class UbDuoT<N, UbDuo<A, UbDuo<B,C> > > +class UbDuoT<N, UbDuo<A, UbDuo<B, C>>> { public: - using ResultT = typename UbDuoT<N - 1, UbDuo<B, C> >::ResultT; + using ResultT = typename UbDuoT<N - 1, UbDuo<B, C>>::ResultT; }; // specialization for 1st field of a recursive duo template <typename A, typename B, typename C> -class UbDuoT<1, UbDuo<A, UbDuo<B,C> > > +class UbDuoT<1, UbDuo<A, UbDuo<B, C>>> { public: - using ResultT = A; + using ResultT = A; }; // specialization for 2nd field of a recursive duo template <typename A, typename B, typename C> -class UbDuoT<2, UbDuo<A, UbDuo<B,C> > > +class UbDuoT<2, UbDuo<A, UbDuo<B, C>>> { public: - using ResultT = B; + using ResultT = B; }; -//duo4.hpp +// duo4.hpp // primary template for value of Nth field of (duo) T template <int N, typename T> -class DuoValue +class DuoValue { public: - static void get(T&) { } // in general, we have no value - static void get(T const&) { } + static void get(T &) {} // in general, we have no value + static void get(T const &) {} }; // specialization for 1st field of a plain duo template <typename A, typename B> -class DuoValue<1, UbDuo<A, B> > +class DuoValue<1, UbDuo<A, B>> { public: - static A& get(UbDuo<A, B> &d) { return d.v1(); } - static A const& get(UbDuo<A, B> const &d) { return d.v1(); } + static A &get(UbDuo<A, B> &d) { return d.v1(); } + static A const &get(UbDuo<A, B> const &d) { return d.v1(); } }; // specialization for 2nd field of a plain duo template <typename A, typename B> -class DuoValue<2, UbDuo<A, B> > +class DuoValue<2, UbDuo<A, B>> { public: - static B& get(UbDuo<A, B> &d) { return d.v2(); } - static B const& get(UbDuo<A, B> const &d) { return d.v2(); } + static B &get(UbDuo<A, B> &d) { return d.v2(); } + static B const &get(UbDuo<A, B> const &d) { return d.v2(); } }; // specialization for Nth field of recursive duo template <int N, typename A, typename B, typename C> -struct DuoValue<N, UbDuo<A, UbDuo<B,C> > > -{ - static typename UbTypeOp<typename UbDuoT<N-1, UbDuo<B,C> >::ResultT>::RefT get(UbDuo<A, UbDuo<B,C> > &d) - { - return DuoValue<N-1, UbDuo<B,C> >::get(d.v2()); - } - static typename UbTypeOp<typename UbDuoT<N-1, UbDuo<B,C> >::ResultT>::RefConstT get(UbDuo<A, UbDuo<B,C> > const &d) - { - return DuoValue<N-1, UbDuo<B,C> >::get(d.v2()); - } +struct DuoValue<N, UbDuo<A, UbDuo<B, C>>> { + static typename UbTypeOp<typename UbDuoT<N - 1, UbDuo<B, C>>::ResultT>::RefT get(UbDuo<A, UbDuo<B, C>> &d) + { + return DuoValue<N - 1, UbDuo<B, C>>::get(d.v2()); + } + static typename UbTypeOp<typename UbDuoT<N - 1, UbDuo<B, C>>::ResultT>::RefConstT + get(UbDuo<A, UbDuo<B, C>> const &d) + { + return DuoValue<N - 1, UbDuo<B, C>>::get(d.v2()); + } }; // specialization for 1st field of recursive duo template <typename A, typename B, typename C> -class DuoValue<1, UbDuo<A, UbDuo<B,C> > > +class DuoValue<1, UbDuo<A, UbDuo<B, C>>> { public: - static A& get(UbDuo<A, UbDuo<B,C> > &d) { return d.v1(); } - static A const& get(UbDuo<A, UbDuo<B,C> > const &d) { return d.v1(); } + static A &get(UbDuo<A, UbDuo<B, C>> &d) { return d.v1(); } + static A const &get(UbDuo<A, UbDuo<B, C>> const &d) { return d.v1(); } }; // specialization for 2nd field of recursive duo template <typename A, typename B, typename C> -class DuoValue<2, UbDuo<A, UbDuo<B,C> > > +class DuoValue<2, UbDuo<A, UbDuo<B, C>>> { public: - static B& get(UbDuo<A, UbDuo<B,C> > &d) { return d.v2().v1(); } - static B const& get(UbDuo<A, UbDuo<B,C> > const &d) { return d.v2().v1(); } + static B &get(UbDuo<A, UbDuo<B, C>> &d) { return d.v2().v1(); } + static B const &get(UbDuo<A, UbDuo<B, C>> const &d) { return d.v2().v1(); } }; -//duo5.hpp +// duo5.hpp // return Nth value of variable duo -template <int N, typename A, typename B> -inline typename UbTypeOp<typename UbDuoT<N, UbDuo<A, B> >::ResultT>::RefT val(UbDuo<A, B>& d) +template <int N, typename A, typename B> +inline typename UbTypeOp<typename UbDuoT<N, UbDuo<A, B>>::ResultT>::RefT val(UbDuo<A, B> &d) { - return DuoValue<N, UbDuo<A, B> >::get(d); + return DuoValue<N, UbDuo<A, B>>::get(d); } // return Nth value of constant duo -template <int N, typename A, typename B> -inline typename UbTypeOp<typename UbDuoT<N, UbDuo<A, B> >::ResultT>::RefConstT val(UbDuo<A, B> const& d) +template <int N, typename A, typename B> +inline typename UbTypeOp<typename UbDuoT<N, UbDuo<A, B>>::ResultT>::RefConstT val(UbDuo<A, B> const &d) { - return DuoValue<N, UbDuo<A, B> >::get(d); + return DuoValue<N, UbDuo<A, B>>::get(d); } -//duo6.hpp +// duo6.hpp // partial specialization for UbDuo<> with only c1 field template <typename A> -struct UbDuo<A,void> -{ +struct UbDuo<A, void> { public: - using T1 = A; // type of first field - using T2 = void; // type of second field - enum { N = 1 }; // number of fields + using T1 = A; // type of first field + using T2 = void; // type of second field + enum { N = 1 }; // number of fields private: - T1 value1; // value of first field + T1 value1; // value of first field public: - // constructors - UbDuo() : value1() { } - UbDuo (T1 const & a) : value1(a) { } + // constructors + UbDuo() : value1() {} + UbDuo(T1 const &a) : value1(a) {} - // field access - T1& v1() { return value1; } - T1 const& v1() const { return value1; } - - void v2() { } - void v2() const { } + // field access + T1 &v1() { return value1; } + T1 const &v1() const { return value1; } + void v2() {} + void v2() const {} }; -//tupel1.hpp +// tupel1.hpp // type that represents unused type parameters -class UbNullT +class UbNullT { }; @@ -440,7 +444,7 @@ class UbNullT //! val<2>(t3) = 42; //! val<3>(t3) = 0.2; //! t3 = makeUbTuple(false, 23, 13.13); -//! +//! //! std::cout << val<1>(t3) << ", "; //! std::cout << val<2>(t3) << ", "; //! std::cout << val<3>(t3) << std::endl; @@ -453,181 +457,164 @@ class UbNullT //! \endcode // UbTuple<> in general derives from UbTuple<> with c1 more UbNullT -template <typename P1, - typename P2 = UbNullT, - typename P3 = UbNullT, - typename P4 = UbNullT, - typename P5 = UbNullT, - typename P6 = UbNullT, - typename P7 = UbNullT, - typename P8 = UbNullT > -class UbTuple : public UbDuo<P1, typename UbTuple<P2,P3,P4,P5,P6,P7,P8,UbNullT>::BaseT> +template <typename P1, typename P2 = UbNullT, typename P3 = UbNullT, typename P4 = UbNullT, typename P5 = UbNullT, + typename P6 = UbNullT, typename P7 = UbNullT, typename P8 = UbNullT> +class UbTuple : public UbDuo<P1, typename UbTuple<P2, P3, P4, P5, P6, P7, P8, UbNullT>::BaseT> { public: - using BaseT = UbDuo<P1, typename UbTuple<P2, P3, P4, P5, P6, P7, P8, UbNullT>::BaseT>; - - // constructor: - UbTuple() = default; - UbTuple( typename UbTypeOp<P1>::RefConstT a1, - typename UbTypeOp<P2>::RefConstT a2, - typename UbTypeOp<P3>::RefConstT a3 = UbNullT(), - typename UbTypeOp<P4>::RefConstT a4 = UbNullT(), - typename UbTypeOp<P5>::RefConstT a5 = UbNullT(), - typename UbTypeOp<P6>::RefConstT a6 = UbNullT(), - typename UbTypeOp<P7>::RefConstT a7 = UbNullT(), - typename UbTypeOp<P8>::RefConstT a8 = UbNullT() ) - : BaseT(a1, UbTuple<P2,P3,P4,P5,P6,P7,P8,UbNullT>(a2,a3,a4,a5,a6,a7,a8)) - { - } - - // for implicit type conversion during assignments - template <typename U1,typename U2, typename U3, typename U4, typename U5, typename U6, typename U7, typename U8 > - UbTuple<P1,P2,P3,P4,P5,P6,P7,P8>& operator = ( const UbTuple<U1,U2,U3,U4,U5,U6,U7,U8>& rhs) - { - this->BaseT::operator=( typename UbTuple<U1,U2,U3,U4,U5,U6,U7,U8>::BaseT(rhs) ); - return *this; - } - + using BaseT = UbDuo<P1, typename UbTuple<P2, P3, P4, P5, P6, P7, P8, UbNullT>::BaseT>; + + // constructor: + UbTuple() = default; + UbTuple(typename UbTypeOp<P1>::RefConstT a1, typename UbTypeOp<P2>::RefConstT a2, + typename UbTypeOp<P3>::RefConstT a3 = UbNullT(), typename UbTypeOp<P4>::RefConstT a4 = UbNullT(), + typename UbTypeOp<P5>::RefConstT a5 = UbNullT(), typename UbTypeOp<P6>::RefConstT a6 = UbNullT(), + typename UbTypeOp<P7>::RefConstT a7 = UbNullT(), typename UbTypeOp<P8>::RefConstT a8 = UbNullT()) + : BaseT(a1, UbTuple<P2, P3, P4, P5, P6, P7, P8, UbNullT>(a2, a3, a4, a5, a6, a7, a8)) + { + } + + // for implicit type conversion during assignments + template <typename U1, typename U2, typename U3, typename U4, typename U5, typename U6, typename U7, typename U8> + UbTuple<P1, P2, P3, P4, P5, P6, P7, P8> &operator=(const UbTuple<U1, U2, U3, U4, U5, U6, U7, U8> &rhs) + { + this->BaseT::operator=(typename UbTuple<U1, U2, U3, U4, U5, U6, U7, U8>::BaseT(rhs)); + return *this; + } }; // specialization to end deriving recursion template <typename P1, typename P2> -class UbTuple<P1,P2,UbNullT,UbNullT,UbNullT,UbNullT,UbNullT,UbNullT> : public UbDuo<P1,P2> { +class UbTuple<P1, P2, UbNullT, UbNullT, UbNullT, UbNullT, UbNullT, UbNullT> : public UbDuo<P1, P2> +{ public: - using BaseT = UbDuo<P1, P2>; - - // constructor: - UbTuple() = default; - UbTuple( typename UbTypeOp<P1>::RefConstT a1, - typename UbTypeOp<P2>::RefConstT a2, - typename UbTypeOp<UbNullT>::RefConstT = UbNullT(), - typename UbTypeOp<UbNullT>::RefConstT = UbNullT(), - typename UbTypeOp<UbNullT>::RefConstT = UbNullT(), - typename UbTypeOp<UbNullT>::RefConstT = UbNullT(), - typename UbTypeOp<UbNullT>::RefConstT = UbNullT(), - typename UbTypeOp<UbNullT>::RefConstT = UbNullT() ) - : BaseT(a1, a2) - { - } - - // for implicit type conversion during assignments - template <typename U1,typename U2 > - UbTuple<P1,P2>& operator = ( const UbTuple<U1,U2>& rhs) - { - this->BaseT::operator=( typename UbTuple<U1,U2>::BaseT(rhs) ); - return *this; - } - + using BaseT = UbDuo<P1, P2>; + + // constructor: + UbTuple() = default; + UbTuple(typename UbTypeOp<P1>::RefConstT a1, typename UbTypeOp<P2>::RefConstT a2, + typename UbTypeOp<UbNullT>::RefConstT = UbNullT(), typename UbTypeOp<UbNullT>::RefConstT = UbNullT(), + typename UbTypeOp<UbNullT>::RefConstT = UbNullT(), typename UbTypeOp<UbNullT>::RefConstT = UbNullT(), + typename UbTypeOp<UbNullT>::RefConstT = UbNullT(), typename UbTypeOp<UbNullT>::RefConstT = UbNullT()) + : BaseT(a1, a2) + { + } + + // for implicit type conversion during assignments + template <typename U1, typename U2> + UbTuple<P1, P2> &operator=(const UbTuple<U1, U2> &rhs) + { + this->BaseT::operator=(typename UbTuple<U1, U2>::BaseT(rhs)); + return *this; + } }; // specialization for singletons template <typename P1> -class UbTuple<P1,UbNullT,UbNullT,UbNullT,UbNullT,UbNullT,UbNullT,UbNullT> : public UbDuo<P1,void> +class UbTuple<P1, UbNullT, UbNullT, UbNullT, UbNullT, UbNullT, UbNullT, UbNullT> : public UbDuo<P1, void> { public: - using BaseT = UbDuo<P1, void>; - - // constructor: - UbTuple() = default; - UbTuple( typename UbTypeOp<P1>::RefConstT a1, - typename UbTypeOp<UbNullT>::RefConstT = UbNullT(), - typename UbTypeOp<UbNullT>::RefConstT = UbNullT(), - typename UbTypeOp<UbNullT>::RefConstT = UbNullT(), - typename UbTypeOp<UbNullT>::RefConstT = UbNullT(), - typename UbTypeOp<UbNullT>::RefConstT = UbNullT(), - typename UbTypeOp<UbNullT>::RefConstT = UbNullT(), - typename UbTypeOp<UbNullT>::RefConstT = UbNullT() ) - : BaseT(a1) - { - } - - // for implicit type conversion during assignments - template <typename U1 > - UbTuple<P1>& operator = ( const UbTuple<U1>& rhs) - { - this->v1() = rhs.v1(); - return *this; - } - + using BaseT = UbDuo<P1, void>; + + // constructor: + UbTuple() = default; + UbTuple(typename UbTypeOp<P1>::RefConstT a1, typename UbTypeOp<UbNullT>::RefConstT = UbNullT(), + typename UbTypeOp<UbNullT>::RefConstT = UbNullT(), typename UbTypeOp<UbNullT>::RefConstT = UbNullT(), + typename UbTypeOp<UbNullT>::RefConstT = UbNullT(), typename UbTypeOp<UbNullT>::RefConstT = UbNullT(), + typename UbTypeOp<UbNullT>::RefConstT = UbNullT(), typename UbTypeOp<UbNullT>::RefConstT = UbNullT()) + : BaseT(a1) + { + } + + // for implicit type conversion during assignments + template <typename U1> + UbTuple<P1> &operator=(const UbTuple<U1> &rhs) + { + this->v1() = rhs.v1(); + return *this; + } }; // convenience function for 1 argument -template <typename T1> +template <typename T1> inline UbTuple<T1> makeUbTuple(T1 const &a1) { - return UbTuple<T1>(a1); + return UbTuple<T1>(a1); } // convenience function for 2 arguments template <typename T1, typename T2> -inline UbTuple<T1,T2> makeUbTuple(T1 const &a1, T2 const &a2) +inline UbTuple<T1, T2> makeUbTuple(T1 const &a1, T2 const &a2) { - return UbTuple<T1,T2>(a1,a2); + return UbTuple<T1, T2>(a1, a2); } // convenience function for 3 arguments template <typename T1, typename T2, typename T3> -inline UbTuple<T1,T2,T3> makeUbTuple(T1 const &a1, T2 const &a2, T3 const &a3) +inline UbTuple<T1, T2, T3> makeUbTuple(T1 const &a1, T2 const &a2, T3 const &a3) { - return UbTuple<T1,T2,T3>(a1,a2,a3); + return UbTuple<T1, T2, T3>(a1, a2, a3); } // convenience function for 4 arguments template <typename T1, typename T2, typename T3, typename T4> -inline UbTuple<T1,T2,T3,T4> makeUbTuple(T1 const &a1, T2 const &a2, T3 const &a3, T4 const &a4) +inline UbTuple<T1, T2, T3, T4> makeUbTuple(T1 const &a1, T2 const &a2, T3 const &a3, T4 const &a4) { - return UbTuple<T1,T2,T3,T4>(a1,a2,a3,a4); + return UbTuple<T1, T2, T3, T4>(a1, a2, a3, a4); } // convenience function for 5 arguments template <typename T1, typename T2, typename T3, typename T4, typename T5> -inline UbTuple<T1,T2,T3,T4,T5> makeUbTuple(T1 const &a1, T2 const &a2, T3 const &a3, T4 const &a4,T5 const &a5) +inline UbTuple<T1, T2, T3, T4, T5> makeUbTuple(T1 const &a1, T2 const &a2, T3 const &a3, T4 const &a4, T5 const &a5) { - return UbTuple<T1,T2,T3,T4,T5>(a1,a2,a3,a4,a5); + return UbTuple<T1, T2, T3, T4, T5>(a1, a2, a3, a4, a5); } // convenience function for 6 arguments template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6> -inline UbTuple<T1,T2,T3,T4,T5,T6> makeUbTuple(T1 const &a1, T2 const &a2, T3 const &a3, T4 const &a4, T5 const &a5, T6 const &a6) +inline UbTuple<T1, T2, T3, T4, T5, T6> makeUbTuple(T1 const &a1, T2 const &a2, T3 const &a3, T4 const &a4, T5 const &a5, + T6 const &a6) { - return UbTuple<T1,T2,T3,T4,T5,T6>(a1,a2,a3,a4,a5,a6); + return UbTuple<T1, T2, T3, T4, T5, T6>(a1, a2, a3, a4, a5, a6); } // convenience function for 7 arguments template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7> -inline UbTuple<T1,T2,T3,T4,T5,T6,T7> makeUbTuple(T1 const &a1, T2 const &a2, T3 const &a3, T4 const &a4, T5 const &a5, T6 const &a6, T7 const &a7) +inline UbTuple<T1, T2, T3, T4, T5, T6, T7> makeUbTuple(T1 const &a1, T2 const &a2, T3 const &a3, T4 const &a4, + T5 const &a5, T6 const &a6, T7 const &a7) { - return UbTuple<T1,T2,T3,T4,T5,T6,T7>(a1,a2,a3,a4,a5,a6,a7); + return UbTuple<T1, T2, T3, T4, T5, T6, T7>(a1, a2, a3, a4, a5, a6, a7); } // convenience function for 8 arguments template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8> -inline UbTuple<T1,T2,T3,T4,T5,T6,T7,T8> makeUbTuple(T1 const &a1, T2 const &a2,T3 const &a3, T4 const &a4,T5 const &a5, T6 const &a6,T7 const &a7, T8 const &a8 ) +inline UbTuple<T1, T2, T3, T4, T5, T6, T7, T8> makeUbTuple(T1 const &a1, T2 const &a2, T3 const &a3, T4 const &a4, + T5 const &a5, T6 const &a6, T7 const &a7, T8 const &a8) { - return UbTuple<T1,T2,T3,T4,T5,T6,T7,T8>(a1,a2,a3,a4,a5,a6,a7,a8); + return UbTuple<T1, T2, T3, T4, T5, T6, T7, T8>(a1, a2, a3, a4, a5, a6, a7, a8); } -//some typedefs -using UbTupleFloat2 = UbTuple<float, float>; -using UbTupleFloat3 = UbTuple<float, float, float>; -using UbTupleInt2 = UbTuple<int, int>; -using UbTupleInt3 = UbTuple<int, int, int>; -using UbTupleInt4 = UbTuple<int, int, int, int>; -using UbTupleInt5 = UbTuple<int, int, int, int, int>; -using UbTupleInt6 = UbTuple<int, int, int, int, int, int>; -using UbTupleInt8 = UbTuple<int, int, int, int, int, int, int, int>; -using UbTupleUInt8 = UbTuple<unsigned int, unsigned int, unsigned int, unsigned int, unsigned int, unsigned int, unsigned int, unsigned int>; -using UbTupleDouble2 = UbTuple<double, double>; -using UbTupleDouble3 = UbTuple<double, double, double>; -using UbTupleDouble4 = UbTuple<double, double, double, double>; -using UbTupleDouble6 = UbTuple<double, double, double, double, double, double>; +// some typedefs +using UbTupleFloat2 = UbTuple<float, float>; +using UbTupleFloat3 = UbTuple<float, float, float>; +using UbTupleInt2 = UbTuple<int, int>; +using UbTupleInt3 = UbTuple<int, int, int>; +using UbTupleInt4 = UbTuple<int, int, int, int>; +using UbTupleInt5 = UbTuple<int, int, int, int, int>; +using UbTupleInt6 = UbTuple<int, int, int, int, int, int>; +using UbTupleInt8 = UbTuple<int, int, int, int, int, int, int, int>; +using UbTupleUInt8 = UbTuple<unsigned int, unsigned int, unsigned int, unsigned int, unsigned int, unsigned int, + unsigned int, unsigned int>; +using UbTupleDouble2 = UbTuple<double, double>; +using UbTupleDouble3 = UbTuple<double, double, double>; +using UbTupleDouble4 = UbTuple<double, double, double, double>; +using UbTupleDouble6 = UbTuple<double, double, double, double, double, double>; using UbTupleStringDouble2 = UbTuple<std::string, double, double>; using UbTupleStringDouble3 = UbTuple<std::string, double, double, double>; -using UbTupleStringInt3 = UbTuple<std::string, int, int, int>; -using UbTupleShort4 = UbTuple<short, short, short, short>; -using UbTupleBool3 = UbTuple<bool, bool, bool>; -using UbTupleIntDouble2 = UbTuple<int, double, double>; -using UbTupleIntBool = UbTuple<int, bool>; - +using UbTupleStringInt3 = UbTuple<std::string, int, int, int>; +using UbTupleShort4 = UbTuple<short, short, short, short>; +using UbTupleBool3 = UbTuple<bool, bool, bool>; +using UbTupleIntDouble2 = UbTuple<int, double, double>; +using UbTupleIntBool = UbTuple<int, bool>; -#endif //UBTUPLE_H +#endif // UBTUPLE_H diff --git a/src/basics/basics/utilities/Vector3D.cpp b/src/basics/basics/utilities/Vector3D.cpp index 75ab1b814c33f9f1d631dec6189d0117f6168b18..6ff9dc8738f869d75e7fc9870bb5bb7468d83468 100644 --- a/src/basics/basics/utilities/Vector3D.cpp +++ b/src/basics/basics/utilities/Vector3D.cpp @@ -1,28 +1,28 @@ //======================================================================================= -// ____ ____ __ ______ __________ __ __ __ __ -// \ \ | | | | | _ \ |___ ___| | | | | / \ | | -// \ \ | | | | | |_) | | | | | | | / \ | | -// \ \ | | | | | _ / | | | | | | / /\ \ | | -// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ -// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| -// \ \ | | ________________________________________________________________ -// \ \ | | | ______________________________________________________________| -// \ \| | | | __ __ __ __ ______ _______ -// \ | | |_____ | | | | | | | | | _ \ / _____) -// \ | | _____| | | | | | | | | | | \ \ \_______ +// ____ ____ __ ______ __________ __ __ __ __ +// \ \ | | | | | _ \ |___ ___| | | | | / \ | | +// \ \ | | | | | |_) | | | | | | | / \ | | +// \ \ | | | | | _ / | | | | | | / /\ \ | | +// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ +// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| +// \ \ | | ________________________________________________________________ +// \ \ | | | ______________________________________________________________| +// \ \| | | | __ __ __ __ ______ _______ +// \ | | |_____ | | | | | | | | | _ \ / _____) +// \ | | _____| | | | | | | | | | | \ \ \_______ // \ | | | | |_____ | \_/ | | | | |_/ / _____ | -// \ _____| |__| |________| \_______/ |__| |______/ (_______/ +// \ _____| |__| |________| \_______/ |__| |______/ (_______/ // -// This file is part of VirtualFluids. VirtualFluids is free software: you can +// This file is part of VirtualFluids. VirtualFluids is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of +// License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. -// -// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// +// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License along // with VirtualFluids (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>. // @@ -35,611 +35,490 @@ #include <cassert> #include <sstream> -#include <basics/utilities/UbMath.h> #include <basics/utilities/UbInfinity.h> +#include <basics/utilities/UbMath.h> - - -const Vector3D Vector3D::ZERO(0.0,0.0,0.0); -const Vector3D Vector3D::UNIT_X1(1.0,0.0,0.0); -const Vector3D Vector3D::UNIT_X2(0.0,1.0,0.0); -const Vector3D Vector3D::UNIT_X3(0.0,0.0,1.0); +const Vector3D Vector3D::ZERO(0.0, 0.0, 0.0); +const Vector3D Vector3D::UNIT_X1(1.0, 0.0, 0.0); +const Vector3D Vector3D::UNIT_X2(0.0, 1.0, 0.0); +const Vector3D Vector3D::UNIT_X3(0.0, 0.0, 1.0); /*=======================================================*/ -Vector3D::Vector3D() -{ - m_afTuple[0] = 0.0; - m_afTuple[1] = 0.0; - m_afTuple[2] = 0.0; -} -/*=======================================================*/ -Vector3D::Vector3D(const double& fX, const double& fY, const double& fZ) +Vector3D::Vector3D() { - m_afTuple[0] = fX; - m_afTuple[1] = fY; - m_afTuple[2] = fZ; + m_afTuple[0] = 0.0; + m_afTuple[1] = 0.0; + m_afTuple[2] = 0.0; } /*=======================================================*/ -Vector3D::Vector3D (const Vector3D& rkV) +Vector3D::Vector3D(const double &fX, const double &fY, const double &fZ) { - m_afTuple[0] = rkV.m_afTuple[0]; - m_afTuple[1] = rkV.m_afTuple[1]; - m_afTuple[2] = rkV.m_afTuple[2]; + m_afTuple[0] = fX; + m_afTuple[1] = fY; + m_afTuple[2] = fZ; } /*=======================================================*/ -std::string Vector3D::toString() const +Vector3D::Vector3D(const Vector3D &rkV) { - std::stringstream os; - os<< "Vector3D["<<m_afTuple[0]<<","<<m_afTuple[1]<<","<<m_afTuple[2]<<"]"; - return os.str(); + m_afTuple[0] = rkV.m_afTuple[0]; + m_afTuple[1] = rkV.m_afTuple[1]; + m_afTuple[2] = rkV.m_afTuple[2]; } /*=======================================================*/ -Vector3D::operator const double*() const +std::string Vector3D::toString() const { - return m_afTuple; + std::stringstream os; + os << "Vector3D[" << m_afTuple[0] << "," << m_afTuple[1] << "," << m_afTuple[2] << "]"; + return os.str(); } /*=======================================================*/ -Vector3D::operator double*() -{ - return m_afTuple; -} +Vector3D::operator const double *() const { return m_afTuple; } /*=======================================================*/ -double Vector3D::operator[](const int& i) const -{ - assert( i >= 0 && i <= 2 ); - return m_afTuple[i]; -} +Vector3D::operator double *() { return m_afTuple; } /*=======================================================*/ -double& Vector3D::operator[](const int& i) +double Vector3D::operator[](const int &i) const { - assert( i >= 0 && i <= 2 ); - return m_afTuple[i]; + assert(i >= 0 && i <= 2); + return m_afTuple[i]; } /*=======================================================*/ -double Vector3D::X1() const +double &Vector3D::operator[](const int &i) { - return m_afTuple[0]; + assert(i >= 0 && i <= 2); + return m_afTuple[i]; } /*=======================================================*/ -double& Vector3D::X1() -{ - return m_afTuple[0]; -} +double Vector3D::X1() const { return m_afTuple[0]; } /*=======================================================*/ -double Vector3D::X2() const -{ - return m_afTuple[1]; -} +double &Vector3D::X1() { return m_afTuple[0]; } /*=======================================================*/ -double& Vector3D::X2() -{ - return m_afTuple[1]; -} +double Vector3D::X2() const { return m_afTuple[1]; } /*=======================================================*/ -double Vector3D::X3() const -{ - return m_afTuple[2]; -} +double &Vector3D::X2() { return m_afTuple[1]; } /*=======================================================*/ -double& Vector3D::X3() -{ - return m_afTuple[2]; -} +double Vector3D::X3() const { return m_afTuple[2]; } /*=======================================================*/ -Vector3D& Vector3D::operator=(const Vector3D& rkV) +double &Vector3D::X3() { return m_afTuple[2]; } +/*=======================================================*/ +Vector3D &Vector3D::operator=(const Vector3D &rkV) { - if(this == &rkV) + if (this == &rkV) return *this; - m_afTuple[0] = rkV.m_afTuple[0]; - m_afTuple[1] = rkV.m_afTuple[1]; - m_afTuple[2] = rkV.m_afTuple[2]; - return *this; + m_afTuple[0] = rkV.m_afTuple[0]; + m_afTuple[1] = rkV.m_afTuple[1]; + m_afTuple[2] = rkV.m_afTuple[2]; + return *this; } /*=======================================================*/ -int Vector3D::CompareArrays(const Vector3D& rkV) const -{ - return memcmp(m_afTuple,rkV.m_afTuple,3*sizeof(double)); -} +int Vector3D::CompareArrays(const Vector3D &rkV) const { return memcmp(m_afTuple, rkV.m_afTuple, 3 * sizeof(double)); } /*=======================================================*/ -bool Vector3D::operator==(const Vector3D& rkV) const -{ - return CompareArrays(rkV) == 0; -} +bool Vector3D::operator==(const Vector3D &rkV) const { return CompareArrays(rkV) == 0; } /*=======================================================*/ -bool Vector3D::operator!=(const Vector3D& rkV) const -{ - return CompareArrays(rkV) != 0; -} +bool Vector3D::operator!=(const Vector3D &rkV) const { return CompareArrays(rkV) != 0; } /*=======================================================*/ -bool Vector3D::operator<(const Vector3D& rkV) const -{ - return CompareArrays(rkV) < 0; -} +bool Vector3D::operator<(const Vector3D &rkV) const { return CompareArrays(rkV) < 0; } /*=======================================================*/ -bool Vector3D::operator<=(const Vector3D& rkV) const -{ - return CompareArrays(rkV) <= 0; -} +bool Vector3D::operator<=(const Vector3D &rkV) const { return CompareArrays(rkV) <= 0; } /*=======================================================*/ -bool Vector3D::operator> (const Vector3D& rkV) const -{ - return CompareArrays(rkV) > 0; -} +bool Vector3D::operator>(const Vector3D &rkV) const { return CompareArrays(rkV) > 0; } /*=======================================================*/ -bool Vector3D::operator>=(const Vector3D& rkV) const -{ - return CompareArrays(rkV) >= 0; -} +bool Vector3D::operator>=(const Vector3D &rkV) const { return CompareArrays(rkV) >= 0; } /*=======================================================*/ -Vector3D Vector3D::operator+(const Vector3D& rkV) const +Vector3D Vector3D::operator+(const Vector3D &rkV) const { - return Vector3D( m_afTuple[0]+rkV.m_afTuple[0], - m_afTuple[1]+rkV.m_afTuple[1], - m_afTuple[2]+rkV.m_afTuple[2] ); + return Vector3D(m_afTuple[0] + rkV.m_afTuple[0], m_afTuple[1] + rkV.m_afTuple[1], m_afTuple[2] + rkV.m_afTuple[2]); } /*=======================================================*/ -Vector3D Vector3D::Add(Vector3D& vector) +Vector3D Vector3D::Add(Vector3D &vector) { - return Vector3D( m_afTuple[0]+vector.m_afTuple[0], - m_afTuple[1]+vector.m_afTuple[1], - m_afTuple[2]+vector.m_afTuple[2] ); + return Vector3D(m_afTuple[0] + vector.m_afTuple[0], m_afTuple[1] + vector.m_afTuple[1], + m_afTuple[2] + vector.m_afTuple[2]); } /*=======================================================*/ -Vector3D Vector3D::operator- (const Vector3D& rkV) const +Vector3D Vector3D::operator-(const Vector3D &rkV) const { - return Vector3D( m_afTuple[0]-rkV.m_afTuple[0], - m_afTuple[1]-rkV.m_afTuple[1], - m_afTuple[2]-rkV.m_afTuple[2] ); + return Vector3D(m_afTuple[0] - rkV.m_afTuple[0], m_afTuple[1] - rkV.m_afTuple[1], m_afTuple[2] - rkV.m_afTuple[2]); } /*=======================================================*/ -Vector3D Vector3D::Subtract(Vector3D& vector) +Vector3D Vector3D::Subtract(Vector3D &vector) { - return Vector3D( m_afTuple[0]-vector.m_afTuple[0], - m_afTuple[1]-vector.m_afTuple[1], - m_afTuple[2]-vector.m_afTuple[2] ); + return Vector3D(m_afTuple[0] - vector.m_afTuple[0], m_afTuple[1] - vector.m_afTuple[1], + m_afTuple[2] - vector.m_afTuple[2]); } /*=======================================================*/ -Vector3D Vector3D::operator*(const double& fScalar) const +Vector3D Vector3D::operator*(const double &fScalar) const { - return Vector3D( fScalar*m_afTuple[0], - fScalar*m_afTuple[1], - fScalar*m_afTuple[2] ); + return Vector3D(fScalar * m_afTuple[0], fScalar * m_afTuple[1], fScalar * m_afTuple[2]); } /*=======================================================*/ -Vector3D Vector3D::operator/(const double& fScalar) const +Vector3D Vector3D::operator/(const double &fScalar) const { - Vector3D kQuot; + Vector3D kQuot; - if ( fScalar != 0.0 ) - { - double fInvScalar = 1.0/fScalar; - kQuot.m_afTuple[0] = fInvScalar*m_afTuple[0]; - kQuot.m_afTuple[1] = fInvScalar*m_afTuple[1]; - kQuot.m_afTuple[2] = fInvScalar*m_afTuple[2]; - } - else - { - kQuot.m_afTuple[0] = Ub::inf; - kQuot.m_afTuple[1] = Ub::inf; - kQuot.m_afTuple[2] = Ub::inf; - } + if (fScalar != 0.0) { + double fInvScalar = 1.0 / fScalar; + kQuot.m_afTuple[0] = fInvScalar * m_afTuple[0]; + kQuot.m_afTuple[1] = fInvScalar * m_afTuple[1]; + kQuot.m_afTuple[2] = fInvScalar * m_afTuple[2]; + } else { + kQuot.m_afTuple[0] = Ub::inf; + kQuot.m_afTuple[1] = Ub::inf; + kQuot.m_afTuple[2] = Ub::inf; + } - return kQuot; + return kQuot; } /*=======================================================*/ -Vector3D Vector3D::operator-() const -{ - return Vector3D( -m_afTuple[0], - -m_afTuple[1], - -m_afTuple[2] ); -} +Vector3D Vector3D::operator-() const { return Vector3D(-m_afTuple[0], -m_afTuple[1], -m_afTuple[2]); } /*=======================================================*/ -Vector3D& Vector3D::operator+=(const Vector3D& rkV) +Vector3D &Vector3D::operator+=(const Vector3D &rkV) { - m_afTuple[0] += rkV.m_afTuple[0]; - m_afTuple[1] += rkV.m_afTuple[1]; - m_afTuple[2] += rkV.m_afTuple[2]; - return *this; + m_afTuple[0] += rkV.m_afTuple[0]; + m_afTuple[1] += rkV.m_afTuple[1]; + m_afTuple[2] += rkV.m_afTuple[2]; + return *this; } /*=======================================================*/ -Vector3D& Vector3D::operator-=(const Vector3D& rkV) +Vector3D &Vector3D::operator-=(const Vector3D &rkV) { - m_afTuple[0] -= rkV.m_afTuple[0]; - m_afTuple[1] -= rkV.m_afTuple[1]; - m_afTuple[2] -= rkV.m_afTuple[2]; - return *this; + m_afTuple[0] -= rkV.m_afTuple[0]; + m_afTuple[1] -= rkV.m_afTuple[1]; + m_afTuple[2] -= rkV.m_afTuple[2]; + return *this; } /*=======================================================*/ -Vector3D& Vector3D::operator*=(const double& fScalar) +Vector3D &Vector3D::operator*=(const double &fScalar) { - m_afTuple[0] *= fScalar; - m_afTuple[1] *= fScalar; - m_afTuple[2] *= fScalar; - return *this; + m_afTuple[0] *= fScalar; + m_afTuple[1] *= fScalar; + m_afTuple[2] *= fScalar; + return *this; } /*=======================================================*/ -Vector3D& Vector3D::operator/=(const double& fScalar) +Vector3D &Vector3D::operator/=(const double &fScalar) { - if ( !UbMath::zero(fScalar) ) - { - double fInvScalar = 1.0/fScalar; - m_afTuple[0] *= fInvScalar; - m_afTuple[1] *= fInvScalar; - m_afTuple[2] *= fInvScalar; - } - else - { - m_afTuple[0] = Ub::inf; - m_afTuple[1] = Ub::inf; - m_afTuple[2] = Ub::inf; - } + if (!UbMath::zero(fScalar)) { + double fInvScalar = 1.0 / fScalar; + m_afTuple[0] *= fInvScalar; + m_afTuple[1] *= fInvScalar; + m_afTuple[2] *= fInvScalar; + } else { + m_afTuple[0] = Ub::inf; + m_afTuple[1] = Ub::inf; + m_afTuple[2] = Ub::inf; + } - return *this; + return *this; } /*=======================================================*/ -Vector3D Vector3D::Scale(const double& x) +Vector3D Vector3D::Scale(const double &x) { - Vector3D PointA(0.0,0.0,0.0); - PointA.m_afTuple[0] = x * m_afTuple[0]; - PointA.m_afTuple[1] = x * m_afTuple[1]; - PointA.m_afTuple[2] = x * m_afTuple[2]; - return PointA; + Vector3D PointA(0.0, 0.0, 0.0); + PointA.m_afTuple[0] = x * m_afTuple[0]; + PointA.m_afTuple[1] = x * m_afTuple[1]; + PointA.m_afTuple[2] = x * m_afTuple[2]; + return PointA; } /*=======================================================*/ double Vector3D::Length() const { - return std::sqrt( m_afTuple[0]*m_afTuple[0] + - m_afTuple[1]*m_afTuple[1] + - m_afTuple[2]*m_afTuple[2] ); + return std::sqrt(m_afTuple[0] * m_afTuple[0] + m_afTuple[1] * m_afTuple[1] + m_afTuple[2] * m_afTuple[2]); } /*=======================================================*/ double Vector3D::SquaredLength() const { - return m_afTuple[0]*m_afTuple[0] + - m_afTuple[1]*m_afTuple[1] + - m_afTuple[2]*m_afTuple[2]; + return m_afTuple[0] * m_afTuple[0] + m_afTuple[1] * m_afTuple[1] + m_afTuple[2] * m_afTuple[2]; } /*=======================================================*/ -double Vector3D::Dot(const Vector3D& rkV) const +double Vector3D::Dot(const Vector3D &rkV) const { - return m_afTuple[0]*rkV.m_afTuple[0] + - m_afTuple[1]*rkV.m_afTuple[1] + - m_afTuple[2]*rkV.m_afTuple[2]; + return m_afTuple[0] * rkV.m_afTuple[0] + m_afTuple[1] * rkV.m_afTuple[1] + m_afTuple[2] * rkV.m_afTuple[2]; } /*=======================================================*/ double Vector3D::Normalize() { - double fLength = Length(); + double fLength = Length(); - if( !UbMath::zero(fLength) ) - { - double fInvLength = 1.0/fLength; - m_afTuple[0] *= fInvLength; - m_afTuple[1] *= fInvLength; - m_afTuple[2] *= fInvLength; - } - else - { - fLength = 0.0; - m_afTuple[0] = 0.0; - m_afTuple[1] = 0.0; - m_afTuple[2] = 0.0; - } + if (!UbMath::zero(fLength)) { + double fInvLength = 1.0 / fLength; + m_afTuple[0] *= fInvLength; + m_afTuple[1] *= fInvLength; + m_afTuple[2] *= fInvLength; + } else { + fLength = 0.0; + m_afTuple[0] = 0.0; + m_afTuple[1] = 0.0; + m_afTuple[2] = 0.0; + } - return fLength; + return fLength; } /*=======================================================*/ -Vector3D Vector3D::Cross(const Vector3D& rkV) const +Vector3D Vector3D::Cross(const Vector3D &rkV) const { - return Vector3D( m_afTuple[1]*rkV.m_afTuple[2] - m_afTuple[2]*rkV.m_afTuple[1], - m_afTuple[2]*rkV.m_afTuple[0] - m_afTuple[0]*rkV.m_afTuple[2], - m_afTuple[0]*rkV.m_afTuple[1] - m_afTuple[1]*rkV.m_afTuple[0] ); + return Vector3D(m_afTuple[1] * rkV.m_afTuple[2] - m_afTuple[2] * rkV.m_afTuple[1], + m_afTuple[2] * rkV.m_afTuple[0] - m_afTuple[0] * rkV.m_afTuple[2], + m_afTuple[0] * rkV.m_afTuple[1] - m_afTuple[1] * rkV.m_afTuple[0]); } /*=======================================================*/ -Vector3D Vector3D::UnitCross(const Vector3D& rkV) const +Vector3D Vector3D::UnitCross(const Vector3D &rkV) const { - Vector3D kCross( m_afTuple[1]*rkV.m_afTuple[2] - m_afTuple[2]*rkV.m_afTuple[1], - m_afTuple[2]*rkV.m_afTuple[0] - m_afTuple[0]*rkV.m_afTuple[2], - m_afTuple[0]*rkV.m_afTuple[1] - m_afTuple[1]*rkV.m_afTuple[0] ); - kCross.Normalize(); - return kCross; + Vector3D kCross(m_afTuple[1] * rkV.m_afTuple[2] - m_afTuple[2] * rkV.m_afTuple[1], + m_afTuple[2] * rkV.m_afTuple[0] - m_afTuple[0] * rkV.m_afTuple[2], + m_afTuple[0] * rkV.m_afTuple[1] - m_afTuple[1] * rkV.m_afTuple[0]); + kCross.Normalize(); + return kCross; } /*=======================================================*/ -void Vector3D::GetBarycentrics(const Vector3D& rkV0,const Vector3D& rkV1, const Vector3D& rkV2,const Vector3D& rkV3, double afBary[4]) const +void Vector3D::GetBarycentrics(const Vector3D &rkV0, const Vector3D &rkV1, const Vector3D &rkV2, const Vector3D &rkV3, + double afBary[4]) const { - // compute the vectors relative to V3 of the tetrahedron - Vector3D akDiff[4] = { rkV0 - rkV3, - rkV1 - rkV3, - rkV2 - rkV3, - *this - rkV3 }; + // compute the vectors relative to V3 of the tetrahedron + Vector3D akDiff[4] = { rkV0 - rkV3, rkV1 - rkV3, rkV2 - rkV3, *this - rkV3 }; + + // If the vertices have large magnitude, the linear system of + // equations for computing barycentric coordinates can be + // ill-conditioned. To avoid this, uniformly scale the tetrahedron + // edges to be of order 1. The scaling of all differences does not + // change the barycentric coordinates. + double fMax = 0.0, fValue = 0.0; + for (int i = 0; i < 3; i++) + for (int j = 0; j < 3; j++) { + fValue = std::fabs(akDiff[i][j]); + if (fValue > fMax) + fMax = fValue; + } + + // scale down only large data + if (UbMath::greater(fMax, 1.0)) { + double fInvMax = ((double)1.0) / fMax; + for (int i = 0; i < 4; i++) + akDiff[i] *= fInvMax; + } - // If the vertices have large magnitude, the linear system of - // equations for computing barycentric coordinates can be - // ill-conditioned. To avoid this, uniformly scale the tetrahedron - // edges to be of order 1. The scaling of all differences does not - // change the barycentric coordinates. - double fMax = 0.0,fValue=0.0; - for(int i=0; i<3; i++) - for (int j=0; j<3; j++) - { - fValue = std::fabs(akDiff[i][j]); - if ( fValue > fMax ) fMax = fValue; - } - - // scale down only large data - if(UbMath::greater(fMax,1.0) ) - { - double fInvMax = ((double)1.0)/fMax; - for( int i=0; i<4; i++) - akDiff[i] *= fInvMax; - } + double fDet = akDiff[0].Dot(akDiff[1].Cross(akDiff[2])); + Vector3D kE1cE2 = akDiff[1].Cross(akDiff[2]); + Vector3D kE2cE0 = akDiff[2].Cross(akDiff[0]); + Vector3D kE0cE1 = akDiff[0].Cross(akDiff[1]); - double fDet = akDiff[0].Dot(akDiff[1].Cross(akDiff[2])); - Vector3D kE1cE2 = akDiff[1].Cross(akDiff[2]); - Vector3D kE2cE0 = akDiff[2].Cross(akDiff[0]); - Vector3D kE0cE1 = akDiff[0].Cross(akDiff[1]); - - if( !UbMath::zero( fDet ) ) - { - double fInvDet = 1.0/fDet; - afBary[0] = akDiff[3].Dot(kE1cE2)*fInvDet; - afBary[1] = akDiff[3].Dot(kE2cE0)*fInvDet; - afBary[2] = akDiff[3].Dot(kE0cE1)*fInvDet; - afBary[3] = 1.0 - afBary[0] - afBary[1] - afBary[2]; - } - else - { - // The tetrahedron is potentially flat. Determine the face of - // maximum area and compute barycentric coordinates with respect - // to that face. - Vector3D kE02 = rkV0 - rkV2; - Vector3D kE12 = rkV1 - rkV2; - Vector3D kE02cE12 = kE02.Cross(kE12); - double fMaxSqrArea = kE02cE12.SquaredLength(); - int iMaxIndex = 3; - double fSqrArea = kE0cE1.SquaredLength(); - if ( fSqrArea > fMaxSqrArea ) - { - iMaxIndex = 0; - fMaxSqrArea = fSqrArea; - } - fSqrArea = kE1cE2.SquaredLength(); - if ( fSqrArea > fMaxSqrArea ) - { - iMaxIndex = 1; - fMaxSqrArea = fSqrArea; - } - fSqrArea = kE2cE0.SquaredLength(); - if ( fSqrArea > fMaxSqrArea ) - { - iMaxIndex = 2; - fMaxSqrArea = fSqrArea; - } + if (!UbMath::zero(fDet)) { + double fInvDet = 1.0 / fDet; + afBary[0] = akDiff[3].Dot(kE1cE2) * fInvDet; + afBary[1] = akDiff[3].Dot(kE2cE0) * fInvDet; + afBary[2] = akDiff[3].Dot(kE0cE1) * fInvDet; + afBary[3] = 1.0 - afBary[0] - afBary[1] - afBary[2]; + } else { + // The tetrahedron is potentially flat. Determine the face of + // maximum area and compute barycentric coordinates with respect + // to that face. + Vector3D kE02 = rkV0 - rkV2; + Vector3D kE12 = rkV1 - rkV2; + Vector3D kE02cE12 = kE02.Cross(kE12); + double fMaxSqrArea = kE02cE12.SquaredLength(); + int iMaxIndex = 3; + double fSqrArea = kE0cE1.SquaredLength(); + if (fSqrArea > fMaxSqrArea) { + iMaxIndex = 0; + fMaxSqrArea = fSqrArea; + } + fSqrArea = kE1cE2.SquaredLength(); + if (fSqrArea > fMaxSqrArea) { + iMaxIndex = 1; + fMaxSqrArea = fSqrArea; + } + fSqrArea = kE2cE0.SquaredLength(); + if (fSqrArea > fMaxSqrArea) { + iMaxIndex = 2; + fMaxSqrArea = fSqrArea; + } - if (UbMath::greater(fMaxSqrArea,0.0) ) - { - double fInvSqrArea = 1.0/fMaxSqrArea; - Vector3D kTmp; - if( iMaxIndex==0 ) - { - kTmp = akDiff[3].Cross(akDiff[1]); - afBary[0] = kE0cE1.Dot(kTmp)*fInvSqrArea; - kTmp = akDiff[0].Cross(akDiff[3]); - afBary[1] = kE0cE1.Dot(kTmp)*fInvSqrArea; - afBary[2] = 0.0; - afBary[3] = 1.0 - afBary[0] - afBary[1]; - } - else if( iMaxIndex == 1 ) - { - afBary[0] = 0.0; - kTmp = akDiff[3].Cross(akDiff[2]); - afBary[1] = kE1cE2.Dot(kTmp)*fInvSqrArea; - kTmp = akDiff[1].Cross(akDiff[3]); - afBary[2] = kE1cE2.Dot(kTmp)*fInvSqrArea; - afBary[3] = 1.0 - afBary[1] - afBary[2]; - } - else if( iMaxIndex == 2 ) - { - kTmp = akDiff[2].Cross(akDiff[3]); - afBary[0] = kE2cE0.Dot(kTmp)*fInvSqrArea; - afBary[1] = 0.0; - kTmp = akDiff[3].Cross(akDiff[0]); - afBary[2] = kE2cE0.Dot(kTmp)*fInvSqrArea; - afBary[3] = 1.0 - afBary[0] - afBary[2]; - } - else - { - akDiff[3] = *this - rkV2; - kTmp = akDiff[3].Cross(kE12); - afBary[0] = kE02cE12.Dot(kTmp)*fInvSqrArea; - kTmp = kE02.Cross(akDiff[3]); - afBary[1] = kE02cE12.Dot(kTmp)*fInvSqrArea; - afBary[2] = 1.0 - afBary[0] - afBary[1]; - afBary[3] = 0.0; - } - } - else - { - // The tetrahedron is potentially a sliver. Determine the edge of - // maximum length and compute barycentric coordinates with respect - // to that edge. - double fMaxSqrLength = akDiff[0].SquaredLength(); - iMaxIndex = 0; // <V0,V3> - double fSqrLength = akDiff[1].SquaredLength(); - - if( fSqrLength > fMaxSqrLength ) - { - iMaxIndex = 1; // <V1,V3> - fMaxSqrLength = fSqrLength; - } - fSqrLength = akDiff[2].SquaredLength(); - - if( fSqrLength > fMaxSqrLength ) - { - iMaxIndex = 2; // <V2,V3> - fMaxSqrLength = fSqrLength; - } - fSqrLength = kE02.SquaredLength(); - - if( fSqrLength > fMaxSqrLength ) - { - iMaxIndex = 3; // <V0,V2> - fMaxSqrLength = fSqrLength; - } - fSqrLength = kE12.SquaredLength(); - - if( fSqrLength > fMaxSqrLength ) - { - iMaxIndex = 4; // <V1,V2> - fMaxSqrLength = fSqrLength; - } - - Vector3D kE01 = rkV0 - rkV1; - fSqrLength = kE01.SquaredLength(); - - if( fSqrLength > fMaxSqrLength ) - { - iMaxIndex = 5; // <V0,V1> - fMaxSqrLength = fSqrLength; - } + if (UbMath::greater(fMaxSqrArea, 0.0)) { + double fInvSqrArea = 1.0 / fMaxSqrArea; + Vector3D kTmp; + if (iMaxIndex == 0) { + kTmp = akDiff[3].Cross(akDiff[1]); + afBary[0] = kE0cE1.Dot(kTmp) * fInvSqrArea; + kTmp = akDiff[0].Cross(akDiff[3]); + afBary[1] = kE0cE1.Dot(kTmp) * fInvSqrArea; + afBary[2] = 0.0; + afBary[3] = 1.0 - afBary[0] - afBary[1]; + } else if (iMaxIndex == 1) { + afBary[0] = 0.0; + kTmp = akDiff[3].Cross(akDiff[2]); + afBary[1] = kE1cE2.Dot(kTmp) * fInvSqrArea; + kTmp = akDiff[1].Cross(akDiff[3]); + afBary[2] = kE1cE2.Dot(kTmp) * fInvSqrArea; + afBary[3] = 1.0 - afBary[1] - afBary[2]; + } else if (iMaxIndex == 2) { + kTmp = akDiff[2].Cross(akDiff[3]); + afBary[0] = kE2cE0.Dot(kTmp) * fInvSqrArea; + afBary[1] = 0.0; + kTmp = akDiff[3].Cross(akDiff[0]); + afBary[2] = kE2cE0.Dot(kTmp) * fInvSqrArea; + afBary[3] = 1.0 - afBary[0] - afBary[2]; + } else { + akDiff[3] = *this - rkV2; + kTmp = akDiff[3].Cross(kE12); + afBary[0] = kE02cE12.Dot(kTmp) * fInvSqrArea; + kTmp = kE02.Cross(akDiff[3]); + afBary[1] = kE02cE12.Dot(kTmp) * fInvSqrArea; + afBary[2] = 1.0 - afBary[0] - afBary[1]; + afBary[3] = 0.0; + } + } else { + // The tetrahedron is potentially a sliver. Determine the edge of + // maximum length and compute barycentric coordinates with respect + // to that edge. + double fMaxSqrLength = akDiff[0].SquaredLength(); + iMaxIndex = 0; // <V0,V3> + double fSqrLength = akDiff[1].SquaredLength(); - if(UbMath::greater(fMaxSqrLength, 0.0) ) - { - double fInvSqrLength = 1.0/fMaxSqrLength; - if( iMaxIndex == 0 ) - { - // P-V3 = t*(V0-V3) - afBary[0] = akDiff[3].Dot(akDiff[0])*fInvSqrLength; - afBary[1] = 0.0; - afBary[2] = 0.0; - afBary[3] = 1.0 - afBary[0]; + if (fSqrLength > fMaxSqrLength) { + iMaxIndex = 1; // <V1,V3> + fMaxSqrLength = fSqrLength; } - else if( iMaxIndex == 1 ) - { - // P-V3 = t*(V1-V3) - afBary[0] = 0.0; - afBary[1] = akDiff[3].Dot(akDiff[1])*fInvSqrLength; - afBary[2] = 0.0; - afBary[3] = 1.0 - afBary[1]; + fSqrLength = akDiff[2].SquaredLength(); + + if (fSqrLength > fMaxSqrLength) { + iMaxIndex = 2; // <V2,V3> + fMaxSqrLength = fSqrLength; } - else if( iMaxIndex == 2 ) - { - // P-V3 = t*(V2-V3) - afBary[0] = 0.0; - afBary[1] = 0.0; - afBary[2] = akDiff[3].Dot(akDiff[2])*fInvSqrLength; - afBary[3] = 1.0 - afBary[2]; + fSqrLength = kE02.SquaredLength(); + + if (fSqrLength > fMaxSqrLength) { + iMaxIndex = 3; // <V0,V2> + fMaxSqrLength = fSqrLength; } - else if( iMaxIndex == 3 ) - { - // P-V2 = t*(V0-V2) - akDiff[3] = *this - rkV2; - afBary[0] = akDiff[3].Dot(kE02)*fInvSqrLength; - afBary[1] = 0.0; - afBary[2] = 1.0 - afBary[0]; - afBary[3] = 0.0; + fSqrLength = kE12.SquaredLength(); + + if (fSqrLength > fMaxSqrLength) { + iMaxIndex = 4; // <V1,V2> + fMaxSqrLength = fSqrLength; } - else if( iMaxIndex == 4 ) - { - // P-V2 = t*(V1-V2) - akDiff[3] = *this - rkV2; - afBary[0] = 0.0; - afBary[1] = akDiff[3].Dot(kE12)*fInvSqrLength; - afBary[2] = 1.0 - afBary[1]; - afBary[3] = 0.0; + + Vector3D kE01 = rkV0 - rkV1; + fSqrLength = kE01.SquaredLength(); + + if (fSqrLength > fMaxSqrLength) { + iMaxIndex = 5; // <V0,V1> + fMaxSqrLength = fSqrLength; } - else - { - // P-V1 = t*(V0-V1) - akDiff[3] = *this - rkV1; - afBary[0] = akDiff[3].Dot(kE01)*fInvSqrLength; - afBary[1] = 1.0 - afBary[0]; - afBary[2] = 0.0; - afBary[3] = 0.0; + + if (UbMath::greater(fMaxSqrLength, 0.0)) { + double fInvSqrLength = 1.0 / fMaxSqrLength; + if (iMaxIndex == 0) { + // P-V3 = t*(V0-V3) + afBary[0] = akDiff[3].Dot(akDiff[0]) * fInvSqrLength; + afBary[1] = 0.0; + afBary[2] = 0.0; + afBary[3] = 1.0 - afBary[0]; + } else if (iMaxIndex == 1) { + // P-V3 = t*(V1-V3) + afBary[0] = 0.0; + afBary[1] = akDiff[3].Dot(akDiff[1]) * fInvSqrLength; + afBary[2] = 0.0; + afBary[3] = 1.0 - afBary[1]; + } else if (iMaxIndex == 2) { + // P-V3 = t*(V2-V3) + afBary[0] = 0.0; + afBary[1] = 0.0; + afBary[2] = akDiff[3].Dot(akDiff[2]) * fInvSqrLength; + afBary[3] = 1.0 - afBary[2]; + } else if (iMaxIndex == 3) { + // P-V2 = t*(V0-V2) + akDiff[3] = *this - rkV2; + afBary[0] = akDiff[3].Dot(kE02) * fInvSqrLength; + afBary[1] = 0.0; + afBary[2] = 1.0 - afBary[0]; + afBary[3] = 0.0; + } else if (iMaxIndex == 4) { + // P-V2 = t*(V1-V2) + akDiff[3] = *this - rkV2; + afBary[0] = 0.0; + afBary[1] = akDiff[3].Dot(kE12) * fInvSqrLength; + afBary[2] = 1.0 - afBary[1]; + afBary[3] = 0.0; + } else { + // P-V1 = t*(V0-V1) + akDiff[3] = *this - rkV1; + afBary[0] = akDiff[3].Dot(kE01) * fInvSqrLength; + afBary[1] = 1.0 - afBary[0]; + afBary[2] = 0.0; + afBary[3] = 0.0; + } + } else { + // tetrahedron is a nearly a point, just return equal weights + afBary[0] = 0.25; + afBary[1] = afBary[0]; + afBary[2] = afBary[0]; + afBary[3] = afBary[0]; } - } - else - { - // tetrahedron is a nearly a point, just return equal weights - afBary[0] = 0.25; - afBary[1] = afBary[0]; - afBary[2] = afBary[0]; - afBary[3] = afBary[0]; - } - } - } + } + } } /*=======================================================*/ -void Vector3D::Orthonormalize(Vector3D& rkU, Vector3D& rkV, Vector3D& rkW) +void Vector3D::Orthonormalize(Vector3D &rkU, Vector3D &rkV, Vector3D &rkW) { - // If the input vectors are v0, v1, and v2, then the Gram-Schmidt - // orthonormalization produces vectors u0, u1, and u2 as follows, - // - // u0 = v0/|v0| - // u1 = (v1-(u0*v1)u0)/|v1-(u0*v1)u0| - // u2 = (v2-(u0*v2)u0-(u1*v2)u1)/|v2-(u0*v2)u0-(u1*v2)u1| - // - // where |A| indicates length of vector A and A*B indicates dot - // product of vectors A and B. + // If the input vectors are v0, v1, and v2, then the Gram-Schmidt + // orthonormalization produces vectors u0, u1, and u2 as follows, + // + // u0 = v0/|v0| + // u1 = (v1-(u0*v1)u0)/|v1-(u0*v1)u0| + // u2 = (v2-(u0*v2)u0-(u1*v2)u1)/|v2-(u0*v2)u0-(u1*v2)u1| + // + // where |A| indicates length of vector A and A*B indicates dot + // product of vectors A and B. - // compute u0 - rkU.Normalize(); + // compute u0 + rkU.Normalize(); - // compute u1 - double fDot0 = rkU.Dot(rkV); - rkV -= fDot0*rkU; - rkV.Normalize(); + // compute u1 + double fDot0 = rkU.Dot(rkV); + rkV -= fDot0 * rkU; + rkV.Normalize(); - // compute u2 - double fDot1 = rkV.Dot(rkW); - fDot0 = rkU.Dot(rkW); - rkW -= fDot0*rkU + fDot1*rkV; - rkW.Normalize(); + // compute u2 + double fDot1 = rkV.Dot(rkW); + fDot0 = rkU.Dot(rkW); + rkW -= fDot0 * rkU + fDot1 * rkV; + rkW.Normalize(); } /*=======================================================*/ -void Vector3D::Orthonormalize(Vector3D* akV) -{ - Orthonormalize(akV[0],akV[1],akV[2]); -} +void Vector3D::Orthonormalize(Vector3D *akV) { Orthonormalize(akV[0], akV[1], akV[2]); } /*=======================================================*/ -void Vector3D::GenerateOrthonormalBasis(Vector3D& rkU, Vector3D& rkV,Vector3D& rkW, bool bUnitLengthW) +void Vector3D::GenerateOrthonormalBasis(Vector3D &rkU, Vector3D &rkV, Vector3D &rkW, bool bUnitLengthW) { - if ( !bUnitLengthW ) - rkW.Normalize(); + if (!bUnitLengthW) + rkW.Normalize(); - double fInvLength; + double fInvLength; - if (UbMath::greaterEqual( std::fabs(rkW.m_afTuple[0]),std::fabs(rkW.m_afTuple[1]) ) ) - { - // W.x or W.z is the largest magnitude component, swap them - fInvLength = UbMath::invSqrt(rkW.m_afTuple[0]*rkW.m_afTuple[0] + rkW.m_afTuple[2]*rkW.m_afTuple[2]); - rkU.m_afTuple[0] = -rkW.m_afTuple[2]*fInvLength; - rkU.m_afTuple[1] = (double)0.0; - rkU.m_afTuple[2] = +rkW.m_afTuple[0]*fInvLength; - } - else - { - // W.y or W.z is the largest magnitude component, swap them - fInvLength = UbMath::invSqrt(rkW.m_afTuple[1]*rkW.m_afTuple[1] + rkW.m_afTuple[2]*rkW.m_afTuple[2]); - rkU.m_afTuple[0] = (double)0.0; - rkU.m_afTuple[1] = +rkW.m_afTuple[2]*fInvLength; - rkU.m_afTuple[2] = -rkW.m_afTuple[1]*fInvLength; - } + if (UbMath::greaterEqual(std::fabs(rkW.m_afTuple[0]), std::fabs(rkW.m_afTuple[1]))) { + // W.x or W.z is the largest magnitude component, swap them + fInvLength = UbMath::invSqrt(rkW.m_afTuple[0] * rkW.m_afTuple[0] + rkW.m_afTuple[2] * rkW.m_afTuple[2]); + rkU.m_afTuple[0] = -rkW.m_afTuple[2] * fInvLength; + rkU.m_afTuple[1] = (double)0.0; + rkU.m_afTuple[2] = +rkW.m_afTuple[0] * fInvLength; + } else { + // W.y or W.z is the largest magnitude component, swap them + fInvLength = UbMath::invSqrt(rkW.m_afTuple[1] * rkW.m_afTuple[1] + rkW.m_afTuple[2] * rkW.m_afTuple[2]); + rkU.m_afTuple[0] = (double)0.0; + rkU.m_afTuple[1] = +rkW.m_afTuple[2] * fInvLength; + rkU.m_afTuple[2] = -rkW.m_afTuple[1] * fInvLength; + } - rkV = rkW.Cross(rkU); + rkV = rkW.Cross(rkU); } /*=======================================================*/ -//globaler operator* -Vector3D operator*(const double& fScalar, const Vector3D& rkV) +// globaler operator* +Vector3D operator*(const double &fScalar, const Vector3D &rkV) { - return Vector3D( fScalar*rkV[0], - fScalar*rkV[1], - fScalar*rkV[2] ); + return Vector3D(fScalar * rkV[0], fScalar * rkV[1], fScalar * rkV[2]); } /*=======================================================*/ -std::ostream& operator<< (std::ostream& os, const Vector3D& rkV) +std::ostream &operator<<(std::ostream &os, const Vector3D &rkV) { - os<<rkV.toString(); - return os; + os << rkV.toString(); + return os; } diff --git a/src/basics/basics/utilities/Vector3D.h b/src/basics/basics/utilities/Vector3D.h index 03f47b033604520ed05cc895e327fe7b34ed32f8..b278a80d732115a9b1183547e61ff1fe6e82d057 100644 --- a/src/basics/basics/utilities/Vector3D.h +++ b/src/basics/basics/utilities/Vector3D.h @@ -1,28 +1,28 @@ //======================================================================================= -// ____ ____ __ ______ __________ __ __ __ __ -// \ \ | | | | | _ \ |___ ___| | | | | / \ | | -// \ \ | | | | | |_) | | | | | | | / \ | | -// \ \ | | | | | _ / | | | | | | / /\ \ | | -// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ -// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| -// \ \ | | ________________________________________________________________ -// \ \ | | | ______________________________________________________________| -// \ \| | | | __ __ __ __ ______ _______ -// \ | | |_____ | | | | | | | | | _ \ / _____) -// \ | | _____| | | | | | | | | | | \ \ \_______ +// ____ ____ __ ______ __________ __ __ __ __ +// \ \ | | | | | _ \ |___ ___| | | | | / \ | | +// \ \ | | | | | |_) | | | | | | | / \ | | +// \ \ | | | | | _ / | | | | | | / /\ \ | | +// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ +// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| +// \ \ | | ________________________________________________________________ +// \ \ | | | ______________________________________________________________| +// \ \| | | | __ __ __ __ ______ _______ +// \ | | |_____ | | | | | | | | | _ \ / _____) +// \ | | _____| | | | | | | | | | | \ \ \_______ // \ | | | | |_____ | \_/ | | | | |_/ / _____ | -// \ _____| |__| |________| \_______/ |__| |______/ (_______/ +// \ _____| |__| |________| \_______/ |__| |______/ (_______/ // -// This file is part of VirtualFluids. VirtualFluids is free software: you can +// This file is part of VirtualFluids. VirtualFluids is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of +// License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. -// -// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// +// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License along // with VirtualFluids (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>. // @@ -35,102 +35,102 @@ #include <string> - class Vector3D - { - public: - // construction - Vector3D(); - Vector3D(const double& fX1, const double& fX2, const double& fX3); - Vector3D(const Vector3D& rkV); - - std::string toString() const; - - // coordinate access - operator const double*() const; - operator double*(); - double operator[](const int& i) const; - double& operator[](const int& i); - double X1() const; - double& X1(); - double X2() const; - double& X2(); - double X3() const; - double& X3(); - - // assignment - Vector3D& operator=(const Vector3D& rkV); - - // comparison - bool operator==(const Vector3D& rkV) const; - bool operator!=(const Vector3D& rkV) const; - bool operator< (const Vector3D& rkV) const; - bool operator<=(const Vector3D& rkV) const; - bool operator> (const Vector3D& rkV) const; - bool operator>=(const Vector3D& rkV) const; - - // arithmetic operations - Vector3D operator+(const Vector3D& rkV) const; - Vector3D operator-(const Vector3D& rkV) const; - Vector3D operator*(const double& fScalar) const; - Vector3D operator/(const double& fScalar) const; - Vector3D operator-() const; - - // arithmetic updates - Vector3D& operator+= (const Vector3D& rkV); - Vector3D& operator-= (const Vector3D& rkV); - Vector3D& operator*= (const double& fScalar); - Vector3D& operator/= (const double& fScalar); - - Vector3D Add(Vector3D& vector); - Vector3D Subtract(Vector3D& vector); - Vector3D Scale(const double& x); - - // vector operations - double Length () const; - double SquaredLength () const; - double Dot (const Vector3D& rkV) const; - double Normalize (); - - // The cross products are computed using the right-handed rule. Be aware - // that some graphics APIs use a left-handed rule. If you have to compute - // a cross product with these functions and send the result to the API - // that expects left-handed, you will need to change sign on the vector - // (replace each component value c by -c). - Vector3D Cross (const Vector3D& rkV) const; - Vector3D UnitCross (const Vector3D& rkV) const; - - // Compute the barycentric coordinates of the point with respect to the - // tetrahedron <V0,V1,V2,V3>, P = b0*V0 + b1*V1 + b2*V2 + b3*V3, where - // b0 + b1 + b2 + b3 = 1. - void GetBarycentrics (const Vector3D& rkV0, const Vector3D& rkV1, const Vector3D& rkV2, const Vector3D& rkV3, double afBary[4]) const; - - // Gram-Schmidt orthonormalization. Take linearly independent vectors - // U, V, and W and compute an orthonormal set (unit length, mutually - // perpendicular). - static void Orthonormalize (Vector3D& rkU, Vector3D& rkV, Vector3D& rkW); - static void Orthonormalize (Vector3D* akV); - - // Input W must be initialized to a nonzero vector, output is {U,V,W}, - // an orthonormal basis. A hint is provided about whether or not W - // is already unit length. - static void GenerateOrthonormalBasis (Vector3D& rkU, Vector3D& rkV, Vector3D& rkW, bool bUnitLengthW); - - // special vectors - static const Vector3D ZERO; - static const Vector3D UNIT_X1; - static const Vector3D UNIT_X2; - static const Vector3D UNIT_X3; - - protected: - // support for comparisons - int CompareArrays (const Vector3D& rkV) const; - - double m_afTuple[3]; - }; - - //globaler multiplaktor mit skalar - Vector3D operator*(const double& fScalar, const Vector3D& rkV); - std::ostream& operator<<(std::ostream& os, const Vector3D& rkV); - - +class Vector3D +{ +public: + // construction + Vector3D(); + Vector3D(const double &fX1, const double &fX2, const double &fX3); + Vector3D(const Vector3D &rkV); + + std::string toString() const; + + // coordinate access + operator const double *() const; + operator double *(); + double operator[](const int &i) const; + double &operator[](const int &i); + double X1() const; + double &X1(); + double X2() const; + double &X2(); + double X3() const; + double &X3(); + + // assignment + Vector3D &operator=(const Vector3D &rkV); + + // comparison + bool operator==(const Vector3D &rkV) const; + bool operator!=(const Vector3D &rkV) const; + bool operator<(const Vector3D &rkV) const; + bool operator<=(const Vector3D &rkV) const; + bool operator>(const Vector3D &rkV) const; + bool operator>=(const Vector3D &rkV) const; + + // arithmetic operations + Vector3D operator+(const Vector3D &rkV) const; + Vector3D operator-(const Vector3D &rkV) const; + Vector3D operator*(const double &fScalar) const; + Vector3D operator/(const double &fScalar) const; + Vector3D operator-() const; + + // arithmetic updates + Vector3D &operator+=(const Vector3D &rkV); + Vector3D &operator-=(const Vector3D &rkV); + Vector3D &operator*=(const double &fScalar); + Vector3D &operator/=(const double &fScalar); + + Vector3D Add(Vector3D &vector); + Vector3D Subtract(Vector3D &vector); + Vector3D Scale(const double &x); + + // vector operations + double Length() const; + double SquaredLength() const; + double Dot(const Vector3D &rkV) const; + double Normalize(); + + // The cross products are computed using the right-handed rule. Be aware + // that some graphics APIs use a left-handed rule. If you have to compute + // a cross product with these functions and send the result to the API + // that expects left-handed, you will need to change sign on the vector + // (replace each component value c by -c). + Vector3D Cross(const Vector3D &rkV) const; + Vector3D UnitCross(const Vector3D &rkV) const; + + // Compute the barycentric coordinates of the point with respect to the + // tetrahedron <V0,V1,V2,V3>, P = b0*V0 + b1*V1 + b2*V2 + b3*V3, where + // b0 + b1 + b2 + b3 = 1. + void GetBarycentrics(const Vector3D &rkV0, const Vector3D &rkV1, const Vector3D &rkV2, const Vector3D &rkV3, + double afBary[4]) const; + + // Gram-Schmidt orthonormalization. Take linearly independent vectors + // U, V, and W and compute an orthonormal set (unit length, mutually + // perpendicular). + static void Orthonormalize(Vector3D &rkU, Vector3D &rkV, Vector3D &rkW); + static void Orthonormalize(Vector3D *akV); + + // Input W must be initialized to a nonzero vector, output is {U,V,W}, + // an orthonormal basis. A hint is provided about whether or not W + // is already unit length. + static void GenerateOrthonormalBasis(Vector3D &rkU, Vector3D &rkV, Vector3D &rkW, bool bUnitLengthW); + + // special vectors + static const Vector3D ZERO; + static const Vector3D UNIT_X1; + static const Vector3D UNIT_X2; + static const Vector3D UNIT_X3; + +protected: + // support for comparisons + int CompareArrays(const Vector3D &rkV) const; + + double m_afTuple[3]; +}; + +// globaler multiplaktor mit skalar +Vector3D operator*(const double &fScalar, const Vector3D &rkV); +std::ostream &operator<<(std::ostream &os, const Vector3D &rkV); + #endif diff --git a/src/basics/basics/utilities/Vector3DTest.cpp b/src/basics/basics/utilities/Vector3DTest.cpp index a1d634f513b66bbe2df450cf5f492ebad62f7373..0aaf474569b4baf58d8166a94ed37c394053eca4 100644 --- a/src/basics/basics/utilities/Vector3DTest.cpp +++ b/src/basics/basics/utilities/Vector3DTest.cpp @@ -1,20 +1,22 @@ -#include "gmock/gmock.h" #include "Vector3D.h" +#include "gmock/gmock.h" #include <cmath> using namespace testing; -class Vector3DTest : public Test +class Vector3DTest : public Test { public: Vector3D vec1; Vector3D vec2; - void SetUp() override - { + void SetUp() override + { vec1[0] = vec1[1] = vec1[2] = 4.0f; - vec2[0] = 0.0f; vec2[0] = 2.4f; vec2[0] = -1.3f; + vec2[0] = 0.0f; + vec2[0] = 2.4f; + vec2[0] = -1.3f; } }; @@ -85,14 +87,14 @@ TEST_F(Vector3DTest, compareTwoVectors) ASSERT_TRUE(v == vec1); } // -//TEST_F(Vector3DTest, checkEuclideanDistance) +// TEST_F(Vector3DTest, checkEuclideanDistance) //{ // Vector3D v = Vector3D(3, 3, 3); // // ASSERT_FLOAT_EQ(v.getEuclideanDistanceTo(vec1), (float)sqrt(3)); //} // -//TEST_F(Vector3DTest, checkEuclideanDistanceWithNullVector_ExpectNull) +// TEST_F(Vector3DTest, checkEuclideanDistanceWithNullVector_ExpectNull) //{ // Vector3D v1 = Vector3D(0.0, 0.0, 0.0); // Vector3D v2 = Vector3D(0.0, 0.0, 0.0); @@ -100,7 +102,7 @@ TEST_F(Vector3DTest, compareTwoVectors) // ASSERT_THAT((double)v1.getEuclideanDistanceTo(v2), DoubleEq(0.0)); //} // -//TEST(Vector3DAngleTest, checkInnerAngleBetweenToVectors_ExpectRightAngle) +// TEST(Vector3DAngleTest, checkInnerAngleBetweenToVectors_ExpectRightAngle) //{ // Vector3D v1 = Vector3D(1.0, 4.0, -2.0); // Vector3D v2 = Vector3D(-3.0, 3.0, 1); @@ -108,7 +110,7 @@ TEST_F(Vector3DTest, compareTwoVectors) // ASSERT_THAT((int)floor(v1.getInnerAngle(v2)), Eq(69)); //} // -//TEST(Vector3DAngleTest, checkInnerAngleBetweenSameVectors_ExpectNull) +// TEST(Vector3DAngleTest, checkInnerAngleBetweenSameVectors_ExpectNull) //{ // Vector3D v1 = Vector3D(1.0, 4.0, -2.0); // Vector3D v2 = Vector3D(1.0, 4.0, -2.0); @@ -116,7 +118,7 @@ TEST_F(Vector3DTest, compareTwoVectors) // ASSERT_THAT((int)floor(v1.getInnerAngle(v2)), Eq(0.0)); //} // -//TEST(Vector3DAngleTest, checkInnerAngleBetweenNullVectors_ExpectNull) +// TEST(Vector3DAngleTest, checkInnerAngleBetweenNullVectors_ExpectNull) //{ // Vector3D v1 = Vector3D(0.0, 0.0, 0.0); // Vector3D v2 = Vector3D(0.0, 0.0, 0.0); @@ -125,7 +127,7 @@ TEST_F(Vector3DTest, compareTwoVectors) //} // // -//TEST(Vector3DAngleTest, checkInnerAngleBetweenSecondNullVectors_ExpectNull) +// TEST(Vector3DAngleTest, checkInnerAngleBetweenSecondNullVectors_ExpectNull) //{ // Vector3D v1 = Vector3D(1.0, 0.0, 0.0); // Vector3D v2 = Vector3D(0.0, 0.0, 0.0); @@ -133,7 +135,7 @@ TEST_F(Vector3DTest, compareTwoVectors) // ASSERT_THAT((int)floor(v1.getInnerAngle(v2)), Eq(0.0)); //} // -//TEST(Vector3DAngleTest, checkInnerAngleBetweenFirstNullVectors_ExpectNull) +// TEST(Vector3DAngleTest, checkInnerAngleBetweenFirstNullVectors_ExpectNull) //{ // Vector3D v1 = Vector3D(0.0, 0.0, 0.0); // Vector3D v2 = Vector3D(2.0, 0.0, 0.0); @@ -141,13 +143,12 @@ TEST_F(Vector3DTest, compareTwoVectors) // ASSERT_THAT((int)floor(v1.getInnerAngle(v2)), Eq(0.0)); //} - TEST_F(Vector3DTest, crossProductBetweenTwoVectors) { Vector3D v1 = Vector3D(-5.0, -5.0, 0.0); Vector3D v2 = Vector3D(5.0, 0.0, 10); - Vector3D crossProd = Vector3D(-50.0, 50.0, 25.0); + Vector3D crossProd = Vector3D(-50.0, 50.0, 25.0); Vector3D testCrossProduct = v1.Cross(v2); EXPECT_THAT(testCrossProduct[0], DoubleEq(crossProd[0])); diff --git a/src/basics/basics/writer/WbWriter.h b/src/basics/basics/writer/WbWriter.h index 8e5524416350c4704fc8a27882e6c9c61dc51c9f..26d43464c03311a2cbc14cd4fc9fe717d4b01531 100644 --- a/src/basics/basics/writer/WbWriter.h +++ b/src/basics/basics/writer/WbWriter.h @@ -1,28 +1,28 @@ //======================================================================================= -// ____ ____ __ ______ __________ __ __ __ __ -// \ \ | | | | | _ \ |___ ___| | | | | / \ | | -// \ \ | | | | | |_) | | | | | | | / \ | | -// \ \ | | | | | _ / | | | | | | / /\ \ | | -// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ -// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| -// \ \ | | ________________________________________________________________ -// \ \ | | | ______________________________________________________________| -// \ \| | | | __ __ __ __ ______ _______ -// \ | | |_____ | | | | | | | | | _ \ / _____) -// \ | | _____| | | | | | | | | | | \ \ \_______ +// ____ ____ __ ______ __________ __ __ __ __ +// \ \ | | | | | _ \ |___ ___| | | | | / \ | | +// \ \ | | | | | |_) | | | | | | | / \ | | +// \ \ | | | | | _ / | | | | | | / /\ \ | | +// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ +// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| +// \ \ | | ________________________________________________________________ +// \ \ | | | ______________________________________________________________| +// \ \| | | | __ __ __ __ ______ _______ +// \ | | |_____ | | | | | | | | | _ \ / _____) +// \ | | _____| | | | | | | | | | | \ \ \_______ // \ | | | | |_____ | \_/ | | | | |_/ / _____ | -// \ _____| |__| |________| \_______/ |__| |______/ (_______/ +// \ _____| |__| |________| \_______/ |__| |______/ (_______/ // -// This file is part of VirtualFluids. VirtualFluids is free software: you can +// This file is part of VirtualFluids. VirtualFluids is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of +// License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. -// -// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// +// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License along // with VirtualFluids (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>. // @@ -33,13 +33,12 @@ #ifndef WBWRITER_H #define WBWRITER_H -#include <vector> -#include <string> #include <fstream> -#include <sstream> #include <iostream> #include <map> - +#include <sstream> +#include <string> +#include <vector> #include <basics/utilities/UbException.h> #include <basics/utilities/UbSystem.h> @@ -48,64 +47,133 @@ class WbWriter { public: - ////////////////////////////////////////////////////////////////////////// - virtual ~WbWriter() = default; + ////////////////////////////////////////////////////////////////////////// + virtual ~WbWriter() = default; - ////////////////////////////////////////////////////////////////////////// - //rein virtuelle Methoden - virtual std::string getFileExtension() = 0; + ////////////////////////////////////////////////////////////////////////// + // rein virtuelle Methoden + virtual std::string getFileExtension() = 0; - ////////////////////////////////////////////////////////////////////////// - //nodes - virtual std::string writeNodes(const std::string& /*filename*/,std::vector< UbTupleFloat3 >& /*nodes*/) { throw UbException(UB_EXARGS,"not implemented for "+(std::string)typeid(*this).name() ); } - virtual std::string writeNodesWithNodeData(const std::string& /*filename*/,std::vector< UbTupleFloat3 >& /*nodes*/, std::vector<std::string >& /*datanames*/, std::vector<std::vector<double > >& /*nodedata*/) { throw UbException(UB_EXARGS,"not implemented for "+(std::string)typeid(*this).name() ); } - virtual std::string writeNodesWithNodeDataDouble(const std::string& /*filename*/,std::vector< UbTupleDouble3 >& /*nodes*/, std::vector<std::string >& /*datanames*/, std::vector<std::vector<double > >& /*nodedata*/) { throw UbException(UB_EXARGS,"not implemented for "+(std::string)typeid(*this).name() ); } + ////////////////////////////////////////////////////////////////////////// + // nodes + virtual std::string writeNodes(const std::string & /*filename*/, std::vector<UbTupleFloat3> & /*nodes*/) + { + throw UbException(UB_EXARGS, "not implemented for " + (std::string) typeid(*this).name()); + } + virtual std::string writeNodesWithNodeData(const std::string & /*filename*/, std::vector<UbTupleFloat3> & /*nodes*/, + std::vector<std::string> & /*datanames*/, + std::vector<std::vector<double>> & /*nodedata*/) + { + throw UbException(UB_EXARGS, "not implemented for " + (std::string) typeid(*this).name()); + } + virtual std::string writeNodesWithNodeDataDouble(const std::string & /*filename*/, + std::vector<UbTupleDouble3> & /*nodes*/, + std::vector<std::string> & /*datanames*/, + std::vector<std::vector<double>> & /*nodedata*/) + { + throw UbException(UB_EXARGS, "not implemented for " + (std::string) typeid(*this).name()); + } - ////////////////////////////////////////////////////////////////////////// - //lines - // 0 ---- 1 - //nodenumbering must start with 0! - virtual std::string writeLines(const std::string& /*filename*/,std::vector<UbTupleFloat3 >& /*nodes*/, std::vector<UbTupleInt2 >& /*lines*/) { throw UbException(UB_EXARGS,"not implemented for "+(std::string)typeid(*this).name() ); } - virtual std::string writeLinesWithNodeData(const std::string& /*filename*/,std::vector<UbTupleFloat3 >& /*nodes*/, std::vector<UbTupleInt2 >& /*lines*/) { throw UbException(UB_EXARGS,"not implemented for "+(std::string)typeid(*this).name() ); } + ////////////////////////////////////////////////////////////////////////// + // lines + // 0 ---- 1 + // nodenumbering must start with 0! + virtual std::string writeLines(const std::string & /*filename*/, std::vector<UbTupleFloat3> & /*nodes*/, + std::vector<UbTupleInt2> & /*lines*/) + { + throw UbException(UB_EXARGS, "not implemented for " + (std::string) typeid(*this).name()); + } + virtual std::string writeLinesWithNodeData(const std::string & /*filename*/, std::vector<UbTupleFloat3> & /*nodes*/, + std::vector<UbTupleInt2> & /*lines*/) + { + throw UbException(UB_EXARGS, "not implemented for " + (std::string) typeid(*this).name()); + } - ////////////////////////////////////////////////////////////////////////// - //triangles - //cell numbering: - // 2 - // - // 0 === 1 - //nodenumbering must start with 0! - virtual std::string writeTriangles(const std::string& /*filename*/,std::vector< UbTupleFloat3 >& /*nodes*/, std::vector< UbTupleInt3 >& /*cells*/){ throw UbException(UB_EXARGS,"not implemented for "+(std::string)typeid(*this).name() ); } - virtual std::string writeTrianglesWithNodeData(const std::string& /*filename*/,std::vector< UbTupleFloat3 >& /*nodes*/, std::vector< UbTupleInt3 >& /*cells*/, std::vector<std::string >& /*datanames*/, std::vector<std::vector<double > >& /*nodedata*/){ throw UbException(UB_EXARGS,"not implemented for "+(std::string)typeid(*this).name() ); } + ////////////////////////////////////////////////////////////////////////// + // triangles + // cell numbering: + // 2 + // + // 0 === 1 + // nodenumbering must start with 0! + virtual std::string writeTriangles(const std::string & /*filename*/, std::vector<UbTupleFloat3> & /*nodes*/, + std::vector<UbTupleInt3> & /*cells*/) + { + throw UbException(UB_EXARGS, "not implemented for " + (std::string) typeid(*this).name()); + } + virtual std::string writeTrianglesWithNodeData(const std::string & /*filename*/, + std::vector<UbTupleFloat3> & /*nodes*/, + std::vector<UbTupleInt3> & /*cells*/, + std::vector<std::string> & /*datanames*/, + std::vector<std::vector<double>> & /*nodedata*/) + { + throw UbException(UB_EXARGS, "not implemented for " + (std::string) typeid(*this).name()); + } - ////////////////////////////////////////////////////////////////////////// - //quads - //cell numbering: - // 3---2 - // | | - // 0---1 - //nodenumbering must start with 0! - virtual std::string writeQuads(const std::string& /*filename*/,std::vector< UbTupleFloat3 >& /*nodes*/, std::vector< UbTupleInt4 >& /*cells*/){ throw UbException(UB_EXARGS,"not implemented for "+(std::string)typeid(*this).name() ); } - virtual std::string writeQuadsWithNodeData(const std::string& /*filename*/,std::vector< UbTupleFloat3 >& /*nodes*/, std::vector< UbTupleInt4 >& /*cells*/, std::vector< std::string >& /*datanames*/, std::vector< std::vector< double > >& /*nodedata*/){ throw UbException(UB_EXARGS,"not implemented for "+(std::string)typeid(*this).name() ); } - virtual std::string writeQuadsWithCellData(const std::string& /*filename*/,std::vector< UbTupleFloat3 >& /*nodes*/, std::vector< UbTupleInt4 >& /*cells*/, std::vector< std::string >& /*datanames*/, std::vector< std::vector< double > >& /*celldata*/){ throw UbException(UB_EXARGS,"not implemented for "+(std::string)typeid(*this).name() ); } - virtual std::string writeQuadsWithNodeAndCellData(const std::string& /*filename*/,std::vector< UbTupleFloat3 >& /*nodes*/, std::vector< UbTupleInt4 >& /*cells*/, - std::vector< std::string >& /*nodedatanames*/, std::vector< std::vector< double > >& /*nodedata*/, std::vector< std::string >& /*celldatanames*/, std::vector< std::vector< double > >& /*celldata*/) { throw UbException(UB_EXARGS,"not implemented for "+(std::string)typeid(*this).name() ); } + ////////////////////////////////////////////////////////////////////////// + // quads + // cell numbering: + // 3---2 + // | | + // 0---1 + // nodenumbering must start with 0! + virtual std::string writeQuads(const std::string & /*filename*/, std::vector<UbTupleFloat3> & /*nodes*/, + std::vector<UbTupleInt4> & /*cells*/) + { + throw UbException(UB_EXARGS, "not implemented for " + (std::string) typeid(*this).name()); + } + virtual std::string writeQuadsWithNodeData(const std::string & /*filename*/, std::vector<UbTupleFloat3> & /*nodes*/, + std::vector<UbTupleInt4> & /*cells*/, + std::vector<std::string> & /*datanames*/, + std::vector<std::vector<double>> & /*nodedata*/) + { + throw UbException(UB_EXARGS, "not implemented for " + (std::string) typeid(*this).name()); + } + virtual std::string writeQuadsWithCellData(const std::string & /*filename*/, std::vector<UbTupleFloat3> & /*nodes*/, + std::vector<UbTupleInt4> & /*cells*/, + std::vector<std::string> & /*datanames*/, + std::vector<std::vector<double>> & /*celldata*/) + { + throw UbException(UB_EXARGS, "not implemented for " + (std::string) typeid(*this).name()); + } + virtual std::string writeQuadsWithNodeAndCellData( + const std::string & /*filename*/, std::vector<UbTupleFloat3> & /*nodes*/, std::vector<UbTupleInt4> & /*cells*/, + std::vector<std::string> & /*nodedatanames*/, std::vector<std::vector<double>> & /*nodedata*/, + std::vector<std::string> & /*celldatanames*/, std::vector<std::vector<double>> & /*celldata*/) + { + throw UbException(UB_EXARGS, "not implemented for " + (std::string) typeid(*this).name()); + } - ////////////////////////////////////////////////////////////////////////// - //octs - // 7 ---- 6 - // /| /| - // 4 +--- 5 | - // | | | | - // | 3 ---+ 2 - // |/ |/ - // 0 ---- 1 - virtual std::string writeOcts(const std::string& /*filename*/,std::vector< UbTupleFloat3 >& /*nodes*/, std::vector< UbTupleInt8 >& /*cells*/){ throw UbException(UB_EXARGS,"not implemented for "+(std::string)typeid(*this).name() ); } - virtual std::string writeOctsWithCellData(const std::string& /*filename*/,std::vector<UbTupleFloat3 >& /*nodes*/, std::vector<UbTupleInt8 >& /*cells*/, std::vector<std::string >& /*datanames*/, std::vector<std::vector<double > >& /*celldata*/){ throw UbException(UB_EXARGS,"not implemented for "+(std::string)typeid(*this).name() ); } - virtual std::string writeOctsWithNodeData(const std::string& /*filename*/,std::vector<UbTupleFloat3 >& /*nodes*/, std::vector<UbTupleUInt8 >& /*cells*/, std::vector<std::string >& /*datanames*/, std::vector<std::vector<double > >& /*nodedata*/){ throw UbException(UB_EXARGS,"not implemented for "+(std::string)typeid(*this).name() ); } + ////////////////////////////////////////////////////////////////////////// + // octs + // 7 ---- 6 + // /| /| + // 4 +--- 5 | + // | | | | + // | 3 ---+ 2 + // |/ |/ + // 0 ---- 1 + virtual std::string writeOcts(const std::string & /*filename*/, std::vector<UbTupleFloat3> & /*nodes*/, + std::vector<UbTupleInt8> & /*cells*/) + { + throw UbException(UB_EXARGS, "not implemented for " + (std::string) typeid(*this).name()); + } + virtual std::string writeOctsWithCellData(const std::string & /*filename*/, std::vector<UbTupleFloat3> & /*nodes*/, + std::vector<UbTupleInt8> & /*cells*/, + std::vector<std::string> & /*datanames*/, + std::vector<std::vector<double>> & /*celldata*/) + { + throw UbException(UB_EXARGS, "not implemented for " + (std::string) typeid(*this).name()); + } + virtual std::string writeOctsWithNodeData(const std::string & /*filename*/, std::vector<UbTupleFloat3> & /*nodes*/, + std::vector<UbTupleUInt8> & /*cells*/, + std::vector<std::string> & /*datanames*/, + std::vector<std::vector<double>> & /*nodedata*/) + { + throw UbException(UB_EXARGS, "not implemented for " + (std::string) typeid(*this).name()); + } private: - }; -#endif //WBWRITER_H +#endif // WBWRITER_H diff --git a/src/basics/basics/writer/WbWriterAvsASCII.cpp b/src/basics/basics/writer/WbWriterAvsASCII.cpp index f55b86405a920df20445dc20e752848a9bbd56c6..31b922c92df182da53539e12dd4f0ad18adca5c0 100644 --- a/src/basics/basics/writer/WbWriterAvsASCII.cpp +++ b/src/basics/basics/writer/WbWriterAvsASCII.cpp @@ -1,699 +1,865 @@ -#include <basics/writer/WbWriterAvsASCII.h> #include <basics/utilities/UbLogger.h> -#include <cstring> #include <basics/utilities/UbSystem.h> +#include <basics/writer/WbWriterAvsASCII.h> +#include <cstring> using namespace std; -std::string WbWriterAvsASCII::writeQuads(const std::string& filename,std::vector< UbTupleFloat3 >& nodes, std::vector< UbTupleInt4 >& cells) +std::string WbWriterAvsASCII::writeQuads(const std::string &filename, std::vector<UbTupleFloat3> &nodes, + std::vector<UbTupleInt4> &cells) { - string avsfilename = filename+getFileExtension(); - UBLOG(logDEBUG1,"WbWriterAvsASCII::writeQuads to "<<avsfilename<<" - start"); - - ofstream out(avsfilename.c_str(),ios::out|ios::binary); - if(!out) - { - out.clear(); //flags ruecksetzen (ansonsten liefert utern if(!outfile) weiterhin true!!! - string path = UbSystem::getPathFromString(avsfilename); - if(path.size()>0){UbSystem::makeDirectory(path);out.open(avsfilename.c_str(),ios::out|ios::binary);} - if(!out) throw UbException(UB_EXARGS,"couldn't open file "+avsfilename); - } - char magic = (char)7; - int idummy; - float fdummy; - - int nofNodes = (int)nodes.size(); - int nofCells = (int)cells.size(); - - int nofNodeData = 0; - int nofCellData = 0; - int nofModelData = 0; - int cellType = 3; //=quad - int nofNodesPerCell = 4; - - out.write((char*)&magic,sizeof(char)); - out.write((char*)&nofNodes,sizeof(int)); - out.write((char*)&nofCells,sizeof(int)); - out.write((char*)&nofNodeData,sizeof(int)); - out.write((char*)&nofCellData,sizeof(int)); - out.write((char*)&nofModelData,sizeof(int)); - - idummy = (int)nofCells*nofNodesPerCell; - out.write((char*)&idummy,sizeof(int)); //(nof nodes) * (nodes per cell) - for(int c=0; c<nofCells; c++) - { - idummy=c+1; out.write((char*)&idummy,sizeof(int)); //cell id - idummy=1; out.write((char*)&idummy,sizeof(int)); //mat - idummy=nofNodesPerCell; out.write((char*)&idummy,sizeof(int)); //nodes per cell - idummy=cellType; out.write((char*)&idummy,sizeof(int)); //cell type - } - //knotennummern der einzelnen zellen - for(int c=0; c<nofCells; c++) - { - idummy = val<1>(cells[c])+1; out.write((char*)&idummy,sizeof(int)); - idummy = val<2>(cells[c])+1; out.write((char*)&idummy,sizeof(int)); - idummy = val<3>(cells[c])+1; out.write((char*)&idummy,sizeof(int)); - idummy = val<4>(cells[c])+1; out.write((char*)&idummy,sizeof(int)); - } - - //coords - //x1-coords - for(int n=0; n<nofNodes; n++) - { fdummy = (float)( val<1>(nodes[n]) ); out.write((char*)&fdummy ,sizeof(float)); } - //x2-coords - for(int n=0; n<nofNodes; n++) - { fdummy = (float)( val<2>(nodes[n]) ); out.write((char*)&fdummy ,sizeof(float)); } - //x3-coords - for(int n=0; n<nofNodes; n++) - { fdummy = (float)( val<3>(nodes[n]) ); out.write((char*)&fdummy ,sizeof(float)); } - //out<<"\n"; - - out.close(); - UBLOG(logDEBUG1,"WbWriterAvsASCII::writeQuads to "<<avsfilename<<" - end"); - - return avsfilename; + string avsfilename = filename + getFileExtension(); + UBLOG(logDEBUG1, "WbWriterAvsASCII::writeQuads to " << avsfilename << " - start"); + + ofstream out(avsfilename.c_str(), ios::out | ios::binary); + if (!out) { + out.clear(); // flags ruecksetzen (ansonsten liefert utern if(!outfile) weiterhin true!!! + string path = UbSystem::getPathFromString(avsfilename); + if (path.size() > 0) { + UbSystem::makeDirectory(path); + out.open(avsfilename.c_str(), ios::out | ios::binary); + } + if (!out) + throw UbException(UB_EXARGS, "couldn't open file " + avsfilename); + } + char magic = (char)7; + int idummy; + float fdummy; + + int nofNodes = (int)nodes.size(); + int nofCells = (int)cells.size(); + + int nofNodeData = 0; + int nofCellData = 0; + int nofModelData = 0; + int cellType = 3; //=quad + int nofNodesPerCell = 4; + + out.write((char *)&magic, sizeof(char)); + out.write((char *)&nofNodes, sizeof(int)); + out.write((char *)&nofCells, sizeof(int)); + out.write((char *)&nofNodeData, sizeof(int)); + out.write((char *)&nofCellData, sizeof(int)); + out.write((char *)&nofModelData, sizeof(int)); + + idummy = (int)nofCells * nofNodesPerCell; + out.write((char *)&idummy, sizeof(int)); //(nof nodes) * (nodes per cell) + for (int c = 0; c < nofCells; c++) { + idummy = c + 1; + out.write((char *)&idummy, sizeof(int)); // cell id + idummy = 1; + out.write((char *)&idummy, sizeof(int)); // mat + idummy = nofNodesPerCell; + out.write((char *)&idummy, sizeof(int)); // nodes per cell + idummy = cellType; + out.write((char *)&idummy, sizeof(int)); // cell type + } + // knotennummern der einzelnen zellen + for (int c = 0; c < nofCells; c++) { + idummy = val<1>(cells[c]) + 1; + out.write((char *)&idummy, sizeof(int)); + idummy = val<2>(cells[c]) + 1; + out.write((char *)&idummy, sizeof(int)); + idummy = val<3>(cells[c]) + 1; + out.write((char *)&idummy, sizeof(int)); + idummy = val<4>(cells[c]) + 1; + out.write((char *)&idummy, sizeof(int)); + } + + // coords + // x1-coords + for (int n = 0; n < nofNodes; n++) { + fdummy = (float)(val<1>(nodes[n])); + out.write((char *)&fdummy, sizeof(float)); + } + // x2-coords + for (int n = 0; n < nofNodes; n++) { + fdummy = (float)(val<2>(nodes[n])); + out.write((char *)&fdummy, sizeof(float)); + } + // x3-coords + for (int n = 0; n < nofNodes; n++) { + fdummy = (float)(val<3>(nodes[n])); + out.write((char *)&fdummy, sizeof(float)); + } + // out<<"\n"; + + out.close(); + UBLOG(logDEBUG1, "WbWriterAvsASCII::writeQuads to " << avsfilename << " - end"); + + return avsfilename; } /*===============================================================================*/ -std::string WbWriterAvsASCII::writeOcts(const std::string& filename,std::vector< UbTupleFloat3 >& nodes, std::vector< UbTupleInt8 >& cells) +std::string WbWriterAvsASCII::writeOcts(const std::string &filename, std::vector<UbTupleFloat3> &nodes, + std::vector<UbTupleInt8> &cells) { - string avsfilename = filename+getFileExtension(); - UBLOG(logDEBUG1,"WbWriterAvsASCII::writeOcts to "<<avsfilename<<" - start"); - - ofstream out(avsfilename.c_str(),ios::out|ios::binary); - if(!out) - { - out.clear(); //flags ruecksetzen (ansonsten liefert utern if(!outfile) weiterhin true!!! - string path = UbSystem::getPathFromString(avsfilename); - if(path.size()>0){UbSystem::makeDirectory(path);out.open(avsfilename.c_str(),ios::out|ios::binary);} - if(!out) throw UbException(UB_EXARGS,"file konnte nicht geschrieben werden "+avsfilename); - } - - char magic = (char)7; - int idummy; - float fdummy; - - int nofNodes = (int)nodes.size(); - int nofCells = (int)cells.size(); - - int nofNodeData = 0; - int nofCellData = 0; - int nofModelData = 0; - int cellType = 7; //=hex - int nofNodesPerCell = 8; - - out.write((char*)&magic,sizeof(char)); - out.write((char*)&nofNodes,sizeof(int)); - out.write((char*)&nofCells,sizeof(int)); - out.write((char*)&nofNodeData,sizeof(int)); - out.write((char*)&nofCellData,sizeof(int)); - out.write((char*)&nofModelData,sizeof(int)); - - idummy = (int)nofCells*nofNodesPerCell; - out.write((char*)&idummy,sizeof(int)); //(nof nodes) * (nodes per cell) - for(int c=0; c<nofCells; c++) - { - idummy=c+1; out.write((char*)&idummy,sizeof(int)); //cell id - idummy=1; out.write((char*)&idummy,sizeof(int)); //mat - idummy=nofNodesPerCell; out.write((char*)&idummy,sizeof(int)); //nodes per cell - idummy=cellType; out.write((char*)&idummy,sizeof(int)); //cell type - } - //knotennummern der einzelnen zellen - for(int c=0; c<nofCells; c++) - { - idummy = val<1>(cells[c])+1; out.write((char*)&idummy,sizeof(int)); - idummy = val<2>(cells[c])+1; out.write((char*)&idummy,sizeof(int)); - idummy = val<3>(cells[c])+1; out.write((char*)&idummy,sizeof(int)); - idummy = val<4>(cells[c])+1; out.write((char*)&idummy,sizeof(int)); - idummy = val<5>(cells[c])+1; out.write((char*)&idummy,sizeof(int)); - idummy = val<6>(cells[c])+1; out.write((char*)&idummy,sizeof(int)); - idummy = val<7>(cells[c])+1; out.write((char*)&idummy,sizeof(int)); - idummy = val<8>(cells[c])+1; out.write((char*)&idummy,sizeof(int)); - } - - //coords - //x1-coords - for(int n=0; n<nofNodes; n++) - { fdummy = (float)( val<1>(nodes[n]) ); out.write((char*)&fdummy ,sizeof(float)); } - //x2-coords - for(int n=0; n<nofNodes; n++) - { fdummy = (float)( val<2>(nodes[n]) ); out.write((char*)&fdummy ,sizeof(float)); } - //x3-coords - for(int n=0; n<nofNodes; n++) - { fdummy = (float)( val<3>(nodes[n]) ); out.write((char*)&fdummy ,sizeof(float)); } - //out<<"\n"; - - - out.close(); - UBLOG(logDEBUG1,"WbWriterAvsASCII::writeOcts to "<<avsfilename<<" - end"); - - return avsfilename; + string avsfilename = filename + getFileExtension(); + UBLOG(logDEBUG1, "WbWriterAvsASCII::writeOcts to " << avsfilename << " - start"); + + ofstream out(avsfilename.c_str(), ios::out | ios::binary); + if (!out) { + out.clear(); // flags ruecksetzen (ansonsten liefert utern if(!outfile) weiterhin true!!! + string path = UbSystem::getPathFromString(avsfilename); + if (path.size() > 0) { + UbSystem::makeDirectory(path); + out.open(avsfilename.c_str(), ios::out | ios::binary); + } + if (!out) + throw UbException(UB_EXARGS, "file konnte nicht geschrieben werden " + avsfilename); + } + + char magic = (char)7; + int idummy; + float fdummy; + + int nofNodes = (int)nodes.size(); + int nofCells = (int)cells.size(); + + int nofNodeData = 0; + int nofCellData = 0; + int nofModelData = 0; + int cellType = 7; //=hex + int nofNodesPerCell = 8; + + out.write((char *)&magic, sizeof(char)); + out.write((char *)&nofNodes, sizeof(int)); + out.write((char *)&nofCells, sizeof(int)); + out.write((char *)&nofNodeData, sizeof(int)); + out.write((char *)&nofCellData, sizeof(int)); + out.write((char *)&nofModelData, sizeof(int)); + + idummy = (int)nofCells * nofNodesPerCell; + out.write((char *)&idummy, sizeof(int)); //(nof nodes) * (nodes per cell) + for (int c = 0; c < nofCells; c++) { + idummy = c + 1; + out.write((char *)&idummy, sizeof(int)); // cell id + idummy = 1; + out.write((char *)&idummy, sizeof(int)); // mat + idummy = nofNodesPerCell; + out.write((char *)&idummy, sizeof(int)); // nodes per cell + idummy = cellType; + out.write((char *)&idummy, sizeof(int)); // cell type + } + // knotennummern der einzelnen zellen + for (int c = 0; c < nofCells; c++) { + idummy = val<1>(cells[c]) + 1; + out.write((char *)&idummy, sizeof(int)); + idummy = val<2>(cells[c]) + 1; + out.write((char *)&idummy, sizeof(int)); + idummy = val<3>(cells[c]) + 1; + out.write((char *)&idummy, sizeof(int)); + idummy = val<4>(cells[c]) + 1; + out.write((char *)&idummy, sizeof(int)); + idummy = val<5>(cells[c]) + 1; + out.write((char *)&idummy, sizeof(int)); + idummy = val<6>(cells[c]) + 1; + out.write((char *)&idummy, sizeof(int)); + idummy = val<7>(cells[c]) + 1; + out.write((char *)&idummy, sizeof(int)); + idummy = val<8>(cells[c]) + 1; + out.write((char *)&idummy, sizeof(int)); + } + + // coords + // x1-coords + for (int n = 0; n < nofNodes; n++) { + fdummy = (float)(val<1>(nodes[n])); + out.write((char *)&fdummy, sizeof(float)); + } + // x2-coords + for (int n = 0; n < nofNodes; n++) { + fdummy = (float)(val<2>(nodes[n])); + out.write((char *)&fdummy, sizeof(float)); + } + // x3-coords + for (int n = 0; n < nofNodes; n++) { + fdummy = (float)(val<3>(nodes[n])); + out.write((char *)&fdummy, sizeof(float)); + } + // out<<"\n"; + + out.close(); + UBLOG(logDEBUG1, "WbWriterAvsASCII::writeOcts to " << avsfilename << " - end"); + + return avsfilename; } /*===============================================================================*/ -std::string WbWriterAvsASCII::writeQuadsWithNodeData(const string& filename,vector< UbTupleFloat3 >& nodes, vector< UbTupleInt4 >& cells, vector< string >& datanames, vector< vector< double > >& nodedata) +std::string WbWriterAvsASCII::writeQuadsWithNodeData(const string &filename, vector<UbTupleFloat3> &nodes, + vector<UbTupleInt4> &cells, vector<string> &datanames, + vector<vector<double>> &nodedata) { - string avsfilename = filename+getFileExtension(); - UBLOG(logDEBUG1,"WbWriterAvsASCII::writeQuadsWithNodeData to "<<avsfilename<<" - start"); - - ofstream out(avsfilename.c_str(),ios::out|ios::binary); - if(!out) - { - out.clear(); //flags ruecksetzen (ansonsten liefert utern if(!outfile) weiterhin true!!! - string path = UbSystem::getPathFromString(avsfilename); - if(path.size()>0){UbSystem::makeDirectory(path);out.open(avsfilename.c_str(),ios::out|ios::binary);} - if(!out) throw UbException(UB_EXARGS,"write UCD File "+avsfilename+" konnte nicht geschrieben werden"); - } - char magic = (char)7; - int idummy; - float fdummy; - - int nofNodes = (int)nodes.size(); - int nofCells = (int)cells.size(); - - int nofNodeData = (int)datanames.size(); - int nofCellData = 0; - int nofModelData = 0; - int cellType = 3; //=quad - int nofNodesPerCell = 4; - - out.write((char*)&magic,sizeof(char)); - out.write((char*)&nofNodes,sizeof(int)); - out.write((char*)&nofCells,sizeof(int)); - out.write((char*)&nofNodeData,sizeof(int)); - out.write((char*)&nofCellData,sizeof(int)); - out.write((char*)&nofModelData,sizeof(int)); - - idummy = (int)nofCells*nofNodesPerCell; - out.write((char*)&idummy,sizeof(int)); //(nof nodes) * (nodes per cell) - for(int c=0; c<nofCells; c++) - { - idummy=c+1; out.write((char*)&idummy,sizeof(int)); //cell id - idummy=1; out.write((char*)&idummy,sizeof(int)); //mat - idummy=nofNodesPerCell; out.write((char*)&idummy,sizeof(int)); //nodes per cell - idummy=cellType; out.write((char*)&idummy,sizeof(int)); //cell type - } - //knotennummern der einzelnen zellen - for(int c=0; c<nofCells; c++) - { - idummy = val<1>(cells[c])+1; out.write((char*)&idummy,sizeof(int)); - idummy = val<2>(cells[c])+1; out.write((char*)&idummy,sizeof(int)); - idummy = val<3>(cells[c])+1; out.write((char*)&idummy,sizeof(int)); - idummy = val<4>(cells[c])+1; out.write((char*)&idummy,sizeof(int)); - } - - //coords - //x1-coords - for(int n=0; n<nofNodes; n++) - { fdummy = (float)( val<1>(nodes[n]) ); out.write((char*)&fdummy ,sizeof(float)); } - //x2-coords - for(int n=0; n<nofNodes; n++) - { fdummy = (float)( val<2>(nodes[n]) ); out.write((char*)&fdummy ,sizeof(float)); } - //x3-coords - for(int n=0; n<nofNodes; n++) - { fdummy = (float)( val<3>(nodes[n]) ); out.write((char*)&fdummy ,sizeof(float)); } - //out<<"\n"; - - //NODE DATA - char labels[1024]; - char units[1024]; - strcpy(labels, ""); - strcpy(units, ""); - - for(int d=0; d<nofNodeData-1; ++d) - { strcat(labels, datanames[d].c_str() ); strcat(labels,"."); } - strcat(labels, datanames[nofNodeData-1].c_str()); - - for(int i=0;i<(nofNodeData-1);i++) strcat(units, "no_unit."); - strcat(units, "no_unit"); - - out.write((char*)&labels,sizeof(labels)); - out.write((char*)&units,sizeof(units)); - - //nof and type of data - idummy = nofNodeData; - out.write((char*)&idummy,sizeof(int)); //Datentypen pro knoten (hier = nof_node_data, da NUR skalare) - - idummy = 1; - for(int i=0;i<nofNodeData;i++) out.write((char*)&idummy,sizeof(int)); //jeder Datentyp ist ein skalarer Wert - - //min and max of data - fdummy = 0.0; - for(int i=0;i<nofNodeData;i++) out.write((char*)&fdummy,sizeof(float)); //min Wert pro Datentyp - fdummy = 1.0; - for(int i=0;i<nofNodeData;i++) out.write((char*)&fdummy,sizeof(float)); //max Wert pro Datentyp - - //daten ins file schreiben - for(int d=0; d<nofNodeData; ++d) - for(int n=0; n<(int)nodedata[d].size(); n++) - { fdummy=(float)nodedata[d][n]; out.write((char*)&fdummy,sizeof(float)); } - - fdummy = 1.; - for(int i=0;i<nofNodeData;i++) out.write((char*)&fdummy,sizeof(float)); //max Wert pro Datentyp - - out.close(); - UBLOG(logDEBUG1,"WbWriterAvsASCII::writeQuadsWithNodeData to "<<avsfilename<<" - end"); - - return avsfilename; + string avsfilename = filename + getFileExtension(); + UBLOG(logDEBUG1, "WbWriterAvsASCII::writeQuadsWithNodeData to " << avsfilename << " - start"); + + ofstream out(avsfilename.c_str(), ios::out | ios::binary); + if (!out) { + out.clear(); // flags ruecksetzen (ansonsten liefert utern if(!outfile) weiterhin true!!! + string path = UbSystem::getPathFromString(avsfilename); + if (path.size() > 0) { + UbSystem::makeDirectory(path); + out.open(avsfilename.c_str(), ios::out | ios::binary); + } + if (!out) + throw UbException(UB_EXARGS, "write UCD File " + avsfilename + " konnte nicht geschrieben werden"); + } + char magic = (char)7; + int idummy; + float fdummy; + + int nofNodes = (int)nodes.size(); + int nofCells = (int)cells.size(); + + int nofNodeData = (int)datanames.size(); + int nofCellData = 0; + int nofModelData = 0; + int cellType = 3; //=quad + int nofNodesPerCell = 4; + + out.write((char *)&magic, sizeof(char)); + out.write((char *)&nofNodes, sizeof(int)); + out.write((char *)&nofCells, sizeof(int)); + out.write((char *)&nofNodeData, sizeof(int)); + out.write((char *)&nofCellData, sizeof(int)); + out.write((char *)&nofModelData, sizeof(int)); + + idummy = (int)nofCells * nofNodesPerCell; + out.write((char *)&idummy, sizeof(int)); //(nof nodes) * (nodes per cell) + for (int c = 0; c < nofCells; c++) { + idummy = c + 1; + out.write((char *)&idummy, sizeof(int)); // cell id + idummy = 1; + out.write((char *)&idummy, sizeof(int)); // mat + idummy = nofNodesPerCell; + out.write((char *)&idummy, sizeof(int)); // nodes per cell + idummy = cellType; + out.write((char *)&idummy, sizeof(int)); // cell type + } + // knotennummern der einzelnen zellen + for (int c = 0; c < nofCells; c++) { + idummy = val<1>(cells[c]) + 1; + out.write((char *)&idummy, sizeof(int)); + idummy = val<2>(cells[c]) + 1; + out.write((char *)&idummy, sizeof(int)); + idummy = val<3>(cells[c]) + 1; + out.write((char *)&idummy, sizeof(int)); + idummy = val<4>(cells[c]) + 1; + out.write((char *)&idummy, sizeof(int)); + } + + // coords + // x1-coords + for (int n = 0; n < nofNodes; n++) { + fdummy = (float)(val<1>(nodes[n])); + out.write((char *)&fdummy, sizeof(float)); + } + // x2-coords + for (int n = 0; n < nofNodes; n++) { + fdummy = (float)(val<2>(nodes[n])); + out.write((char *)&fdummy, sizeof(float)); + } + // x3-coords + for (int n = 0; n < nofNodes; n++) { + fdummy = (float)(val<3>(nodes[n])); + out.write((char *)&fdummy, sizeof(float)); + } + // out<<"\n"; + + // NODE DATA + char labels[1024]; + char units[1024]; + strcpy(labels, ""); + strcpy(units, ""); + + for (int d = 0; d < nofNodeData - 1; ++d) { + strcat(labels, datanames[d].c_str()); + strcat(labels, "."); + } + strcat(labels, datanames[nofNodeData - 1].c_str()); + + for (int i = 0; i < (nofNodeData - 1); i++) + strcat(units, "no_unit."); + strcat(units, "no_unit"); + + out.write((char *)&labels, sizeof(labels)); + out.write((char *)&units, sizeof(units)); + + // nof and type of data + idummy = nofNodeData; + out.write((char *)&idummy, sizeof(int)); // Datentypen pro knoten (hier = nof_node_data, da NUR skalare) + + idummy = 1; + for (int i = 0; i < nofNodeData; i++) + out.write((char *)&idummy, sizeof(int)); // jeder Datentyp ist ein skalarer Wert + + // min and max of data + fdummy = 0.0; + for (int i = 0; i < nofNodeData; i++) + out.write((char *)&fdummy, sizeof(float)); // min Wert pro Datentyp + fdummy = 1.0; + for (int i = 0; i < nofNodeData; i++) + out.write((char *)&fdummy, sizeof(float)); // max Wert pro Datentyp + + // daten ins file schreiben + for (int d = 0; d < nofNodeData; ++d) + for (int n = 0; n < (int)nodedata[d].size(); n++) { + fdummy = (float)nodedata[d][n]; + out.write((char *)&fdummy, sizeof(float)); + } + + fdummy = 1.; + for (int i = 0; i < nofNodeData; i++) + out.write((char *)&fdummy, sizeof(float)); // max Wert pro Datentyp + + out.close(); + UBLOG(logDEBUG1, "WbWriterAvsASCII::writeQuadsWithNodeData to " << avsfilename << " - end"); + + return avsfilename; } /*===============================================================================*/ -std::string WbWriterAvsASCII::writeQuadsWithCellData(const string& filename,vector< UbTupleFloat3 >& nodes, vector< UbTupleInt4 >& cells, vector< string >& datanames, vector< vector< double > >& celldata) +std::string WbWriterAvsASCII::writeQuadsWithCellData(const string &filename, vector<UbTupleFloat3> &nodes, + vector<UbTupleInt4> &cells, vector<string> &datanames, + vector<vector<double>> &celldata) { - string avsfilename = filename+getFileExtension(); - UBLOG(logDEBUG1,"WbWriterAvsASCII::writeQuadsWithCellData to "<<avsfilename<<" - start"); - - ofstream out(avsfilename.c_str(),ios::out|ios::binary); - if(!out) - { - out.clear(); //flags ruecksetzen (ansonsten liefert utern if(!outfile) weiterhin true!!! - string path = UbSystem::getPathFromString(avsfilename); - if(path.size()>0){UbSystem::makeDirectory(path);out.open(avsfilename.c_str(),ios::out|ios::binary);} - if(!out) throw UbException(UB_EXARGS,"write_OutputFile-UCD File "+avsfilename+" konnte nicht geschrieben werden"); - } - - char magic = (char)7; - int idummy; - float fdummy; - - int nofNodes = (int)nodes.size(); - int nofCells = (int)cells.size(); - - int nofNodeData = 0; - int nofCellData = (int)datanames.size(); - int nofModelData = 0; - int cellType = 3; //=quad - int nofNodesPerCell = 4; - - out.write((char*)&magic,sizeof(char)); - out.write((char*)&nofNodes,sizeof(int)); - out.write((char*)&nofCells,sizeof(int)); - out.write((char*)&nofNodeData,sizeof(int)); - out.write((char*)&nofCellData,sizeof(int)); - out.write((char*)&nofModelData,sizeof(int)); - - idummy = (int)nofCells*nofNodesPerCell; - out.write((char*)&idummy,sizeof(int)); //(nof nodes) * (nodes per cell) - for(int c=0; c<nofCells; c++) - { - idummy=c+1; out.write((char*)&idummy,sizeof(int)); //cell id - idummy=1; out.write((char*)&idummy,sizeof(int)); //mat - idummy=nofNodesPerCell; out.write((char*)&idummy,sizeof(int)); //nodes per cell - idummy=cellType; out.write((char*)&idummy,sizeof(int)); //cell type - } - //knotennummern der einzelnen zellen - for(int c=0; c<nofCells; c++) - { - idummy = val<1>(cells[c])+1; out.write((char*)&idummy,sizeof(int)); - idummy = val<2>(cells[c])+1; out.write((char*)&idummy,sizeof(int)); - idummy = val<3>(cells[c])+1; out.write((char*)&idummy,sizeof(int)); - idummy = val<4>(cells[c])+1; out.write((char*)&idummy,sizeof(int)); - } - - //coords - //x1-coords - for(int n=0; n<nofNodes; n++) - { fdummy = (float)( val<1>(nodes[n]) ); out.write((char*)&fdummy ,sizeof(float)); } - //x2-coords - for(int n=0; n<nofNodes; n++) - { fdummy = (float)( val<2>(nodes[n]) ); out.write((char*)&fdummy ,sizeof(float)); } - //x3-coords - fdummy=0.0; - for(int n=0; n<nofNodes; n++) - { fdummy = (float)( val<3>(nodes[n]) ); out.write((char*)&fdummy ,sizeof(float)); } - //out<<"\n"; - - //CELL DATA - char labels[1024]; - char units[1024]; - strcpy(labels, ""); - strcpy(units, ""); - - for(int d=0; d<nofCellData-1; ++d) { strcat(labels, datanames[d].c_str() ); strcat(labels,"."); } - strcat(labels, datanames[nofCellData-1].c_str()); - - for(int d=0; d<nofCellData-1; ++d) strcat(units, "no_unit."); - strcat(units, "no_unit"); - - out.write((char*)&labels,sizeof(labels)); - out.write((char*)&units,sizeof(units)); - - //nof and type of data - idummy = nofCellData; - out.write((char*)&idummy,sizeof(int)); //Datentypen pro knoten (hier = nof_node_data, da NUR skalare) - - idummy = 1; - for(int i=0;i<nofCellData;i++) out.write((char*)&idummy,sizeof(int)); //jeder Datentyp ist ein skalarer Wert - - //min and max of data - fdummy = 0.0; - for(int i=0;i<nofCellData;i++) out.write((char*)&fdummy,sizeof(float)); //min Wert pro Datentyp - fdummy = 1.0; - for(int i=0;i<nofCellData;i++) out.write((char*)&fdummy,sizeof(float)); //max Wert pro Datentyp - - //daten ins file schreiben - for(int d=0; d<nofCellData; ++d) - for(int n=0; n<(int)celldata[d].size(); n++) - { fdummy=(float)celldata[d][n]; out.write((char*)&fdummy,sizeof(float)); } - - fdummy = 1.; - for(int i=0;i<nofCellData;i++) out.write((char*)&fdummy,sizeof(float)); //max Wert pro Datentyp - - out.close(); - UBLOG(logDEBUG1,"WbWriterAvsASCII::writeQuadsWithCellData to "<<avsfilename<<" - end"); - - return avsfilename; + string avsfilename = filename + getFileExtension(); + UBLOG(logDEBUG1, "WbWriterAvsASCII::writeQuadsWithCellData to " << avsfilename << " - start"); + + ofstream out(avsfilename.c_str(), ios::out | ios::binary); + if (!out) { + out.clear(); // flags ruecksetzen (ansonsten liefert utern if(!outfile) weiterhin true!!! + string path = UbSystem::getPathFromString(avsfilename); + if (path.size() > 0) { + UbSystem::makeDirectory(path); + out.open(avsfilename.c_str(), ios::out | ios::binary); + } + if (!out) + throw UbException(UB_EXARGS, + "write_OutputFile-UCD File " + avsfilename + " konnte nicht geschrieben werden"); + } + + char magic = (char)7; + int idummy; + float fdummy; + + int nofNodes = (int)nodes.size(); + int nofCells = (int)cells.size(); + + int nofNodeData = 0; + int nofCellData = (int)datanames.size(); + int nofModelData = 0; + int cellType = 3; //=quad + int nofNodesPerCell = 4; + + out.write((char *)&magic, sizeof(char)); + out.write((char *)&nofNodes, sizeof(int)); + out.write((char *)&nofCells, sizeof(int)); + out.write((char *)&nofNodeData, sizeof(int)); + out.write((char *)&nofCellData, sizeof(int)); + out.write((char *)&nofModelData, sizeof(int)); + + idummy = (int)nofCells * nofNodesPerCell; + out.write((char *)&idummy, sizeof(int)); //(nof nodes) * (nodes per cell) + for (int c = 0; c < nofCells; c++) { + idummy = c + 1; + out.write((char *)&idummy, sizeof(int)); // cell id + idummy = 1; + out.write((char *)&idummy, sizeof(int)); // mat + idummy = nofNodesPerCell; + out.write((char *)&idummy, sizeof(int)); // nodes per cell + idummy = cellType; + out.write((char *)&idummy, sizeof(int)); // cell type + } + // knotennummern der einzelnen zellen + for (int c = 0; c < nofCells; c++) { + idummy = val<1>(cells[c]) + 1; + out.write((char *)&idummy, sizeof(int)); + idummy = val<2>(cells[c]) + 1; + out.write((char *)&idummy, sizeof(int)); + idummy = val<3>(cells[c]) + 1; + out.write((char *)&idummy, sizeof(int)); + idummy = val<4>(cells[c]) + 1; + out.write((char *)&idummy, sizeof(int)); + } + + // coords + // x1-coords + for (int n = 0; n < nofNodes; n++) { + fdummy = (float)(val<1>(nodes[n])); + out.write((char *)&fdummy, sizeof(float)); + } + // x2-coords + for (int n = 0; n < nofNodes; n++) { + fdummy = (float)(val<2>(nodes[n])); + out.write((char *)&fdummy, sizeof(float)); + } + // x3-coords + fdummy = 0.0; + for (int n = 0; n < nofNodes; n++) { + fdummy = (float)(val<3>(nodes[n])); + out.write((char *)&fdummy, sizeof(float)); + } + // out<<"\n"; + + // CELL DATA + char labels[1024]; + char units[1024]; + strcpy(labels, ""); + strcpy(units, ""); + + for (int d = 0; d < nofCellData - 1; ++d) { + strcat(labels, datanames[d].c_str()); + strcat(labels, "."); + } + strcat(labels, datanames[nofCellData - 1].c_str()); + + for (int d = 0; d < nofCellData - 1; ++d) + strcat(units, "no_unit."); + strcat(units, "no_unit"); + + out.write((char *)&labels, sizeof(labels)); + out.write((char *)&units, sizeof(units)); + + // nof and type of data + idummy = nofCellData; + out.write((char *)&idummy, sizeof(int)); // Datentypen pro knoten (hier = nof_node_data, da NUR skalare) + + idummy = 1; + for (int i = 0; i < nofCellData; i++) + out.write((char *)&idummy, sizeof(int)); // jeder Datentyp ist ein skalarer Wert + + // min and max of data + fdummy = 0.0; + for (int i = 0; i < nofCellData; i++) + out.write((char *)&fdummy, sizeof(float)); // min Wert pro Datentyp + fdummy = 1.0; + for (int i = 0; i < nofCellData; i++) + out.write((char *)&fdummy, sizeof(float)); // max Wert pro Datentyp + + // daten ins file schreiben + for (int d = 0; d < nofCellData; ++d) + for (int n = 0; n < (int)celldata[d].size(); n++) { + fdummy = (float)celldata[d][n]; + out.write((char *)&fdummy, sizeof(float)); + } + + fdummy = 1.; + for (int i = 0; i < nofCellData; i++) + out.write((char *)&fdummy, sizeof(float)); // max Wert pro Datentyp + + out.close(); + UBLOG(logDEBUG1, "WbWriterAvsASCII::writeQuadsWithCellData to " << avsfilename << " - end"); + + return avsfilename; } /*===============================================================================*/ -std::string WbWriterAvsASCII::writeQuadsWithNodeAndCellData(const string& filename,vector< UbTupleFloat3 >& nodes, vector< UbTupleInt4 >& cells, vector< string >& nodedatanames, vector< vector< double > >& nodedata, vector< string >& celldatanames, vector< vector< double > >& celldata) +std::string WbWriterAvsASCII::writeQuadsWithNodeAndCellData(const string &filename, vector<UbTupleFloat3> &nodes, + vector<UbTupleInt4> &cells, vector<string> &nodedatanames, + vector<vector<double>> &nodedata, + vector<string> &celldatanames, + vector<vector<double>> &celldata) { - string avsfilename = filename+getFileExtension(); - UBLOG(logDEBUG1,"WbWriterAvsASCII::writeQuadsWithNodeAndCellData to "<<avsfilename<<" - start"); - - ofstream out(avsfilename.c_str(),ios::out|ios::binary); - if(!out) - { - out.clear(); //flags ruecksetzen (ansonsten liefert utern if(!outfile) weiterhin true!!! - string path = UbSystem::getPathFromString(avsfilename); - if(path.size()>0){UbSystem::makeDirectory(path);out.open(avsfilename.c_str(),ios::out|ios::binary);} - if(!out) throw UbException(UB_EXARGS,"write_OutputFile-UCD File "+avsfilename+" konnte nicht geschrieben werden"); - } - - char magic = (char)7; - int idummy; - float fdummy; - - int nofNodes = (int)nodes.size(); - int nofCells = (int)cells.size(); - - int nofNodeData = (int)nodedatanames.size(); - int nofCellData = (int)celldatanames.size(); - int nofModelData = 0; - int cellType = 3; //=quad - int nofNodesPerCell = 4; - - out.write((char*)&magic,sizeof(char)); - out.write((char*)&nofNodes,sizeof(int)); - out.write((char*)&nofCells,sizeof(int)); - out.write((char*)&nofNodeData,sizeof(int)); - out.write((char*)&nofCellData,sizeof(int)); - out.write((char*)&nofModelData,sizeof(int)); - - idummy = (int)nofCells*nofNodesPerCell; - out.write((char*)&idummy,sizeof(int)); //(nof nodes) * (nodes per cell) - for(int c=0; c<nofCells; c++) - { - idummy=c+1; out.write((char*)&idummy,sizeof(int)); //cell id - idummy=1; out.write((char*)&idummy,sizeof(int)); //mat - idummy=nofNodesPerCell; out.write((char*)&idummy,sizeof(int)); //nodes per cell - idummy=cellType; out.write((char*)&idummy,sizeof(int)); //cell type - } - //knotennummern der einzelnen zellen - for(int c=0; c<nofCells; c++) - { - idummy = val<1>(cells[c])+1; out.write((char*)&idummy,sizeof(int)); - idummy = val<2>(cells[c])+1; out.write((char*)&idummy,sizeof(int)); - idummy = val<3>(cells[c])+1; out.write((char*)&idummy,sizeof(int)); - idummy = val<4>(cells[c])+1; out.write((char*)&idummy,sizeof(int)); - } - - //coords - //x1-coords - for(int n=0; n<nofNodes; n++) - { fdummy = (float)( val<1>(nodes[n]) ); out.write((char*)&fdummy ,sizeof(float)); } - //x2-coords - for(int n=0; n<nofNodes; n++) - { fdummy = (float)( val<2>(nodes[n]) ); out.write((char*)&fdummy ,sizeof(float)); } - //x3-coords - for(int n=0; n<nofNodes; n++) - { fdummy = (float)( val<3>(nodes[n]) ); out.write((char*)&fdummy ,sizeof(float)); } - //out<<"\n"; - - //NODE DATA - char nodelabels[1024]; - char nodeunits[1024]; - strcpy(nodelabels, ""); - strcpy(nodeunits, ""); - - for(int d=0; d<nofNodeData-1; ++d) { strcat(nodelabels, nodedatanames[d].c_str() ); strcat(nodelabels,"."); } - strcat(nodelabels, nodedatanames[nofNodeData-1].c_str()); - - for(int i=0;i<(nofNodeData-1);i++) strcat(nodeunits, "no_unit."); - strcat(nodeunits, "no_unit"); - - out.write((char*)&nodelabels,sizeof(nodelabels)); - out.write((char*)&nodeunits,sizeof(nodeunits)); - - //nof and type of data - idummy = nofNodeData; - out.write((char*)&idummy,sizeof(int)); //Datentypen pro knoten (hier = nof_node_data, da NUR skalare) - - idummy = 1; - for(int i=0;i<nofNodeData;i++) out.write((char*)&idummy,sizeof(int)); //jeder Datentyp ist ein skalarer Wert - - //min and max of data - fdummy = 0.0; - for(int i=0;i<nofNodeData;i++) out.write((char*)&fdummy,sizeof(float)); //min Wert pro Datentyp - fdummy = 1.0; - for(int i=0;i<nofNodeData;i++) out.write((char*)&fdummy,sizeof(float)); //max Wert pro Datentyp - - //daten ins file schreiben - for(int d=0; d<nofNodeData; ++d) - for(int n=0; n<(int)nodedata[d].size(); n++) - { fdummy=(float)nodedata[d][n]; out.write((char*)&fdummy,sizeof(float)); } - - fdummy = 1.; - for(int i=0;i<nofNodeData;i++) out.write((char*)&fdummy,sizeof(float)); //max Wert pro Datentyp - - //CELL DATA - char celllabels[1024]; - char cellunits[1024]; - strcpy(celllabels, ""); - strcpy(cellunits, ""); - - for(int d=0; d<nofCellData-1; ++d) { strcat(celllabels, celldatanames[d].c_str() ); strcat(celllabels,"."); } - strcat(celllabels, celldatanames[nofCellData-1].c_str()); - - for(int d=0; d<nofCellData-1; ++d) strcat(cellunits, "no_unit."); - strcat(cellunits, "no_unit"); - - out.write((char*)&celllabels,sizeof(celllabels)); - out.write((char*)&cellunits,sizeof(cellunits)); - - //nof and type of data - idummy = nofCellData; - out.write((char*)&idummy,sizeof(int)); //Datentypen pro knoten (hier = nof_node_data, da NUR skalare) - - idummy = 1; - for(int i=0;i<nofCellData;i++) out.write((char*)&idummy,sizeof(int)); //jeder Datentyp ist ein skalarer Wert - - //min and max of data - fdummy = 0.0; - for(int i=0;i<nofCellData;i++) out.write((char*)&fdummy,sizeof(float)); //min Wert pro Datentyp - fdummy = 1.0; - for(int i=0;i<nofCellData;i++) out.write((char*)&fdummy,sizeof(float)); //max Wert pro Datentyp - - //daten ins file schreiben - for(int d=0; d<nofCellData; ++d) - for(int n=0; n<(int)celldata[d].size(); n++) - { fdummy=(float)celldata[d][n]; out.write((char*)&fdummy,sizeof(float)); } - - fdummy = 1.; - for(int i=0;i<nofCellData;i++) out.write((char*)&fdummy,sizeof(float)); //max Wert pro Datentyp - - out.close(); - UBLOG(logDEBUG1,"WbWriterAvsASCII::writeQuadsWithNodeAndCellData to "<<avsfilename<<" - end"); - - return avsfilename; + string avsfilename = filename + getFileExtension(); + UBLOG(logDEBUG1, "WbWriterAvsASCII::writeQuadsWithNodeAndCellData to " << avsfilename << " - start"); + + ofstream out(avsfilename.c_str(), ios::out | ios::binary); + if (!out) { + out.clear(); // flags ruecksetzen (ansonsten liefert utern if(!outfile) weiterhin true!!! + string path = UbSystem::getPathFromString(avsfilename); + if (path.size() > 0) { + UbSystem::makeDirectory(path); + out.open(avsfilename.c_str(), ios::out | ios::binary); + } + if (!out) + throw UbException(UB_EXARGS, + "write_OutputFile-UCD File " + avsfilename + " konnte nicht geschrieben werden"); + } + + char magic = (char)7; + int idummy; + float fdummy; + + int nofNodes = (int)nodes.size(); + int nofCells = (int)cells.size(); + + int nofNodeData = (int)nodedatanames.size(); + int nofCellData = (int)celldatanames.size(); + int nofModelData = 0; + int cellType = 3; //=quad + int nofNodesPerCell = 4; + + out.write((char *)&magic, sizeof(char)); + out.write((char *)&nofNodes, sizeof(int)); + out.write((char *)&nofCells, sizeof(int)); + out.write((char *)&nofNodeData, sizeof(int)); + out.write((char *)&nofCellData, sizeof(int)); + out.write((char *)&nofModelData, sizeof(int)); + + idummy = (int)nofCells * nofNodesPerCell; + out.write((char *)&idummy, sizeof(int)); //(nof nodes) * (nodes per cell) + for (int c = 0; c < nofCells; c++) { + idummy = c + 1; + out.write((char *)&idummy, sizeof(int)); // cell id + idummy = 1; + out.write((char *)&idummy, sizeof(int)); // mat + idummy = nofNodesPerCell; + out.write((char *)&idummy, sizeof(int)); // nodes per cell + idummy = cellType; + out.write((char *)&idummy, sizeof(int)); // cell type + } + // knotennummern der einzelnen zellen + for (int c = 0; c < nofCells; c++) { + idummy = val<1>(cells[c]) + 1; + out.write((char *)&idummy, sizeof(int)); + idummy = val<2>(cells[c]) + 1; + out.write((char *)&idummy, sizeof(int)); + idummy = val<3>(cells[c]) + 1; + out.write((char *)&idummy, sizeof(int)); + idummy = val<4>(cells[c]) + 1; + out.write((char *)&idummy, sizeof(int)); + } + + // coords + // x1-coords + for (int n = 0; n < nofNodes; n++) { + fdummy = (float)(val<1>(nodes[n])); + out.write((char *)&fdummy, sizeof(float)); + } + // x2-coords + for (int n = 0; n < nofNodes; n++) { + fdummy = (float)(val<2>(nodes[n])); + out.write((char *)&fdummy, sizeof(float)); + } + // x3-coords + for (int n = 0; n < nofNodes; n++) { + fdummy = (float)(val<3>(nodes[n])); + out.write((char *)&fdummy, sizeof(float)); + } + // out<<"\n"; + + // NODE DATA + char nodelabels[1024]; + char nodeunits[1024]; + strcpy(nodelabels, ""); + strcpy(nodeunits, ""); + + for (int d = 0; d < nofNodeData - 1; ++d) { + strcat(nodelabels, nodedatanames[d].c_str()); + strcat(nodelabels, "."); + } + strcat(nodelabels, nodedatanames[nofNodeData - 1].c_str()); + + for (int i = 0; i < (nofNodeData - 1); i++) + strcat(nodeunits, "no_unit."); + strcat(nodeunits, "no_unit"); + + out.write((char *)&nodelabels, sizeof(nodelabels)); + out.write((char *)&nodeunits, sizeof(nodeunits)); + + // nof and type of data + idummy = nofNodeData; + out.write((char *)&idummy, sizeof(int)); // Datentypen pro knoten (hier = nof_node_data, da NUR skalare) + + idummy = 1; + for (int i = 0; i < nofNodeData; i++) + out.write((char *)&idummy, sizeof(int)); // jeder Datentyp ist ein skalarer Wert + + // min and max of data + fdummy = 0.0; + for (int i = 0; i < nofNodeData; i++) + out.write((char *)&fdummy, sizeof(float)); // min Wert pro Datentyp + fdummy = 1.0; + for (int i = 0; i < nofNodeData; i++) + out.write((char *)&fdummy, sizeof(float)); // max Wert pro Datentyp + + // daten ins file schreiben + for (int d = 0; d < nofNodeData; ++d) + for (int n = 0; n < (int)nodedata[d].size(); n++) { + fdummy = (float)nodedata[d][n]; + out.write((char *)&fdummy, sizeof(float)); + } + + fdummy = 1.; + for (int i = 0; i < nofNodeData; i++) + out.write((char *)&fdummy, sizeof(float)); // max Wert pro Datentyp + + // CELL DATA + char celllabels[1024]; + char cellunits[1024]; + strcpy(celllabels, ""); + strcpy(cellunits, ""); + + for (int d = 0; d < nofCellData - 1; ++d) { + strcat(celllabels, celldatanames[d].c_str()); + strcat(celllabels, "."); + } + strcat(celllabels, celldatanames[nofCellData - 1].c_str()); + + for (int d = 0; d < nofCellData - 1; ++d) + strcat(cellunits, "no_unit."); + strcat(cellunits, "no_unit"); + + out.write((char *)&celllabels, sizeof(celllabels)); + out.write((char *)&cellunits, sizeof(cellunits)); + + // nof and type of data + idummy = nofCellData; + out.write((char *)&idummy, sizeof(int)); // Datentypen pro knoten (hier = nof_node_data, da NUR skalare) + + idummy = 1; + for (int i = 0; i < nofCellData; i++) + out.write((char *)&idummy, sizeof(int)); // jeder Datentyp ist ein skalarer Wert + + // min and max of data + fdummy = 0.0; + for (int i = 0; i < nofCellData; i++) + out.write((char *)&fdummy, sizeof(float)); // min Wert pro Datentyp + fdummy = 1.0; + for (int i = 0; i < nofCellData; i++) + out.write((char *)&fdummy, sizeof(float)); // max Wert pro Datentyp + + // daten ins file schreiben + for (int d = 0; d < nofCellData; ++d) + for (int n = 0; n < (int)celldata[d].size(); n++) { + fdummy = (float)celldata[d][n]; + out.write((char *)&fdummy, sizeof(float)); + } + + fdummy = 1.; + for (int i = 0; i < nofCellData; i++) + out.write((char *)&fdummy, sizeof(float)); // max Wert pro Datentyp + + out.close(); + UBLOG(logDEBUG1, "WbWriterAvsASCII::writeQuadsWithNodeAndCellData to " << avsfilename << " - end"); + + return avsfilename; } /*===============================================================================*/ -std::string WbWriterAvsASCII::writeLines(const string& filename,vector<UbTupleFloat3 >& nodes, vector<UbTupleInt2 >& lines) +std::string WbWriterAvsASCII::writeLines(const string &filename, vector<UbTupleFloat3> &nodes, + vector<UbTupleInt2> &lines) { - string avsfilename = filename+getFileExtension(); - UBLOG(logDEBUG1,"WbWriterAvsASCII::writeLines to "<<avsfilename<<" - start"); - - ofstream out(avsfilename.c_str(),ios::out); - if(!out) - { - out.clear(); //flags ruecksetzen (ansonsten liefert utern if(!outfile) weiterhin true!!! - string path = UbSystem::getPathFromString(avsfilename); - if(path.size()>0){UbSystem::makeDirectory(path);out.open(avsfilename.c_str(),ios::out);} - if(!out) throw UbException(UB_EXARGS,avsfilename+" konnte nicht geschrieben werden"); - } - - int nofNodes = (int)nodes.size(); - int nofLines = (int)lines.size(); - - out<<"# UCD-File created by WbWriterAvsASCII\n"; - out<<nofNodes<<" "<<nofLines<<" 0 0 0 "<<endl; - - for(int n=0; n<nofNodes; n++) - out<<n+1<<" "<< val<1>(nodes[n]) <<" "<< val<2>(nodes[n]) <<" "<< val<3>(nodes[n])<<" \n"; - - for(int l=0; l<nofLines; l++) - out<<l+1<<" 2 line "<< val<1>(lines[l])+1 <<" "<< val<2>(lines[l])+1 <<" "<<endl; - - out.close(); - UBLOG(logDEBUG1,"WbWriterAvsASCII::writeLines to "<<avsfilename<<" - end"); - - return avsfilename; + string avsfilename = filename + getFileExtension(); + UBLOG(logDEBUG1, "WbWriterAvsASCII::writeLines to " << avsfilename << " - start"); + + ofstream out(avsfilename.c_str(), ios::out); + if (!out) { + out.clear(); // flags ruecksetzen (ansonsten liefert utern if(!outfile) weiterhin true!!! + string path = UbSystem::getPathFromString(avsfilename); + if (path.size() > 0) { + UbSystem::makeDirectory(path); + out.open(avsfilename.c_str(), ios::out); + } + if (!out) + throw UbException(UB_EXARGS, avsfilename + " konnte nicht geschrieben werden"); + } + + int nofNodes = (int)nodes.size(); + int nofLines = (int)lines.size(); + + out << "# UCD-File created by WbWriterAvsASCII\n"; + out << nofNodes << " " << nofLines << " 0 0 0 " << endl; + + for (int n = 0; n < nofNodes; n++) + out << n + 1 << " " << val<1>(nodes[n]) << " " << val<2>(nodes[n]) << " " << val<3>(nodes[n]) << " \n"; + + for (int l = 0; l < nofLines; l++) + out << l + 1 << " 2 line " << val<1>(lines[l]) + 1 << " " << val<2>(lines[l]) + 1 << " " << endl; + + out.close(); + UBLOG(logDEBUG1, "WbWriterAvsASCII::writeLines to " << avsfilename << " - end"); + + return avsfilename; } /*===============================================================================*/ -std::string WbWriterAvsASCII::writeTriangles(const string& filename,vector<UbTupleFloat3 >& nodes, vector<UbTupleInt3 >& triangles) +std::string WbWriterAvsASCII::writeTriangles(const string &filename, vector<UbTupleFloat3> &nodes, + vector<UbTupleInt3> &triangles) { - string avsfilename = filename+getFileExtension(); - UBLOG(logDEBUG1,"WbWriterAvsASCII::writeTriangles to "<<avsfilename<<" - start"); - - ofstream out(avsfilename.c_str(),ios::out); - if(!out) - { - out.clear(); //flags ruecksetzen (ansonsten liefert utern if(!outfile) weiterhin true!!! - string path = UbSystem::getPathFromString(avsfilename); - if(path.size()>0){UbSystem::makeDirectory(path);out.open(avsfilename.c_str(),ios::out);} - if(!out) throw UbException(UB_EXARGS,"file konnte nicht geschrieben werden "+avsfilename); - } + string avsfilename = filename + getFileExtension(); + UBLOG(logDEBUG1, "WbWriterAvsASCII::writeTriangles to " << avsfilename << " - start"); + + ofstream out(avsfilename.c_str(), ios::out); + if (!out) { + out.clear(); // flags ruecksetzen (ansonsten liefert utern if(!outfile) weiterhin true!!! + string path = UbSystem::getPathFromString(avsfilename); + if (path.size() > 0) { + UbSystem::makeDirectory(path); + out.open(avsfilename.c_str(), ios::out); + } + if (!out) + throw UbException(UB_EXARGS, "file konnte nicht geschrieben werden " + avsfilename); + } - int nofNodes = (int)nodes.size(); - int nofTrian = (int)triangles.size(); + int nofNodes = (int)nodes.size(); + int nofTrian = (int)triangles.size(); - out<<"# UCD-File created by WbWriterAvsASCII\n"; - out<<nofNodes<<" "<<nofTrian<<" 0 0 0 "<<endl; + out << "# UCD-File created by WbWriterAvsASCII\n"; + out << nofNodes << " " << nofTrian << " 0 0 0 " << endl; - for(int n=0; n<nofNodes; n++) - out<<n+1<<" "<< val<1>(nodes[n]) <<" "<< val<2>(nodes[n]) <<" "<< val<3>(nodes[n])<<" \n"; + for (int n = 0; n < nofNodes; n++) + out << n + 1 << " " << val<1>(nodes[n]) << " " << val<2>(nodes[n]) << " " << val<3>(nodes[n]) << " \n"; - for(int l=0; l<nofTrian; l++) - out<<l+1<<" 2 tri "<< val<1>(triangles[l])+1 <<" "<< val<2>(triangles[l])+1 <<" "<< val<3>(triangles[l])+1 <<" "<<endl; + for (int l = 0; l < nofTrian; l++) + out << l + 1 << " 2 tri " << val<1>(triangles[l]) + 1 << " " << val<2>(triangles[l]) + 1 << " " + << val<3>(triangles[l]) + 1 << " " << endl; - out.close(); - UBLOG(logDEBUG1,"WbWriterAvsASCII::writeTriangles to "<<avsfilename<<" - end"); + out.close(); + UBLOG(logDEBUG1, "WbWriterAvsASCII::writeTriangles to " << avsfilename << " - end"); - return avsfilename; + return avsfilename; } /*===============================================================================*/ -std::string WbWriterAvsASCII::writeTrianglesWithNodeData(const std::string& filename,std::vector< UbTupleFloat3 >& nodes, std::vector< UbTupleInt3 >& cells, std::vector< std::string >& datanames, std::vector< std::vector< double > >& nodedata) +std::string WbWriterAvsASCII::writeTrianglesWithNodeData(const std::string &filename, std::vector<UbTupleFloat3> &nodes, + std::vector<UbTupleInt3> &cells, + std::vector<std::string> &datanames, + std::vector<std::vector<double>> &nodedata) { - string avsfilename = filename+getFileExtension(); - UBLOG(logDEBUG1,"WbWriterAvsASCII::writeTrianglesWithNodeData to "<<avsfilename<<" - end"); - - ofstream out(avsfilename.c_str(),ios::out|ios::binary); - if(!out) - { - out.clear(); //flags ruecksetzen (ansonsten liefert utern if(!outfile) weiterhin true!!! - string path = UbSystem::getPathFromString(avsfilename); - if(path.size()>0){UbSystem::makeDirectory(path);out.open(avsfilename.c_str(),ios::out|ios::binary);} - if(!out) throw UbException(UB_EXARGS,"write_OutputFile-UCD File "+avsfilename+" konnte nicht geschrieben werden"); - } - char magic = (char)7; - int idummy; - float fdummy; - - int nofNodes = (int)nodes.size(); - int nofCells = (int)cells.size(); - - int nofNodeData = (int)datanames.size(); - int nofCellData = 0; - int nofModelData = 0; - int cellType = 2; //triangle - int nofNodesPerCell = 3; - - out.write((char*)&magic,sizeof(char)); - out.write((char*)&nofNodes,sizeof(int)); - out.write((char*)&nofCells,sizeof(int)); - out.write((char*)&nofNodeData,sizeof(int)); - out.write((char*)&nofCellData,sizeof(int)); - out.write((char*)&nofModelData,sizeof(int)); - - idummy = (int)nofCells*nofNodesPerCell; - out.write((char*)&idummy,sizeof(int)); //(nof nodes) * (nodes per cell) - for(int c=0; c<nofCells; c++) - { - idummy=c+1; out.write((char*)&idummy,sizeof(int)); //cell id - idummy=1; out.write((char*)&idummy,sizeof(int)); //mat - idummy=nofNodesPerCell; out.write((char*)&idummy,sizeof(int)); //nodes per cell - idummy=cellType; out.write((char*)&idummy,sizeof(int)); //cell type - } - //knotennummern der einzelnen zellen - for(int c=0; c<nofCells; c++) - { - idummy = val<1>(cells[c])+1; out.write((char*)&idummy,sizeof(int)); - idummy = val<2>(cells[c])+1; out.write((char*)&idummy,sizeof(int)); - idummy = val<3>(cells[c])+1; out.write((char*)&idummy,sizeof(int)); - } - - //coords - //x1-coords - for(int n=0; n<nofNodes; n++) - { fdummy = (float)( val<1>(nodes[n]) ); out.write((char*)&fdummy ,sizeof(float)); } - //x2-coords - for(int n=0; n<nofNodes; n++) - { fdummy = (float)( val<2>(nodes[n]) ); out.write((char*)&fdummy ,sizeof(float)); } - //x3-coords - for(int n=0; n<nofNodes; n++) - { fdummy = (float)( val<3>(nodes[n]) ); out.write((char*)&fdummy ,sizeof(float)); } - //out<<"\n"; - - //NODE DATA - char labels[1024]; - char units[1024]; - strcpy(labels, ""); - strcpy(units, ""); - - for(int d=0; d<nofNodeData-1; ++d) - { strcat(labels, datanames[d].c_str() ); strcat(labels,"."); } - strcat(labels, datanames[nofNodeData-1].c_str()); - - for(int i=0;i<(nofNodeData-1);i++) strcat(units, "no_unit."); - strcat(units, "no_unit"); - - out.write((char*)&labels,sizeof(labels)); - out.write((char*)&units,sizeof(units)); - - //nof and type of data - idummy = nofNodeData; - out.write((char*)&idummy,sizeof(int)); //Datentypen pro knoten (hier = nof_node_data, da NUR skalare) - - idummy = 1; - for(int i=0;i<nofNodeData;i++) out.write((char*)&idummy,sizeof(int)); //jeder Datentyp ist ein skalarer Wert - - //min and max of data - fdummy = 0.0; - for(int i=0;i<nofNodeData;i++) out.write((char*)&fdummy,sizeof(float)); //min Wert pro Datentyp - fdummy = 1.0; - for(int i=0;i<nofNodeData;i++) out.write((char*)&fdummy,sizeof(float)); //max Wert pro Datentyp - - //daten ins file schreiben - for(int d=0; d<nofNodeData; ++d){ - for(int n=0; n<(int)nodedata[d].size(); n++) - { - fdummy=(float)nodedata[d][n]; - out.write((char*)&fdummy,sizeof(float)); - } - } - - fdummy = 1.; - for(int i=0;i<nofNodeData;i++) - out.write((char*)&fdummy,sizeof(float)); //max Wert pro Datentyp - - out.close(); - UBLOG(logDEBUG1,"WbWriterAvsASCII::writeTrianglesWithNodeData to "<<avsfilename<<" - end"); - - return avsfilename; + string avsfilename = filename + getFileExtension(); + UBLOG(logDEBUG1, "WbWriterAvsASCII::writeTrianglesWithNodeData to " << avsfilename << " - end"); + + ofstream out(avsfilename.c_str(), ios::out | ios::binary); + if (!out) { + out.clear(); // flags ruecksetzen (ansonsten liefert utern if(!outfile) weiterhin true!!! + string path = UbSystem::getPathFromString(avsfilename); + if (path.size() > 0) { + UbSystem::makeDirectory(path); + out.open(avsfilename.c_str(), ios::out | ios::binary); + } + if (!out) + throw UbException(UB_EXARGS, + "write_OutputFile-UCD File " + avsfilename + " konnte nicht geschrieben werden"); + } + char magic = (char)7; + int idummy; + float fdummy; + + int nofNodes = (int)nodes.size(); + int nofCells = (int)cells.size(); + + int nofNodeData = (int)datanames.size(); + int nofCellData = 0; + int nofModelData = 0; + int cellType = 2; // triangle + int nofNodesPerCell = 3; + + out.write((char *)&magic, sizeof(char)); + out.write((char *)&nofNodes, sizeof(int)); + out.write((char *)&nofCells, sizeof(int)); + out.write((char *)&nofNodeData, sizeof(int)); + out.write((char *)&nofCellData, sizeof(int)); + out.write((char *)&nofModelData, sizeof(int)); + + idummy = (int)nofCells * nofNodesPerCell; + out.write((char *)&idummy, sizeof(int)); //(nof nodes) * (nodes per cell) + for (int c = 0; c < nofCells; c++) { + idummy = c + 1; + out.write((char *)&idummy, sizeof(int)); // cell id + idummy = 1; + out.write((char *)&idummy, sizeof(int)); // mat + idummy = nofNodesPerCell; + out.write((char *)&idummy, sizeof(int)); // nodes per cell + idummy = cellType; + out.write((char *)&idummy, sizeof(int)); // cell type + } + // knotennummern der einzelnen zellen + for (int c = 0; c < nofCells; c++) { + idummy = val<1>(cells[c]) + 1; + out.write((char *)&idummy, sizeof(int)); + idummy = val<2>(cells[c]) + 1; + out.write((char *)&idummy, sizeof(int)); + idummy = val<3>(cells[c]) + 1; + out.write((char *)&idummy, sizeof(int)); + } + + // coords + // x1-coords + for (int n = 0; n < nofNodes; n++) { + fdummy = (float)(val<1>(nodes[n])); + out.write((char *)&fdummy, sizeof(float)); + } + // x2-coords + for (int n = 0; n < nofNodes; n++) { + fdummy = (float)(val<2>(nodes[n])); + out.write((char *)&fdummy, sizeof(float)); + } + // x3-coords + for (int n = 0; n < nofNodes; n++) { + fdummy = (float)(val<3>(nodes[n])); + out.write((char *)&fdummy, sizeof(float)); + } + // out<<"\n"; + + // NODE DATA + char labels[1024]; + char units[1024]; + strcpy(labels, ""); + strcpy(units, ""); + + for (int d = 0; d < nofNodeData - 1; ++d) { + strcat(labels, datanames[d].c_str()); + strcat(labels, "."); + } + strcat(labels, datanames[nofNodeData - 1].c_str()); + + for (int i = 0; i < (nofNodeData - 1); i++) + strcat(units, "no_unit."); + strcat(units, "no_unit"); + + out.write((char *)&labels, sizeof(labels)); + out.write((char *)&units, sizeof(units)); + + // nof and type of data + idummy = nofNodeData; + out.write((char *)&idummy, sizeof(int)); // Datentypen pro knoten (hier = nof_node_data, da NUR skalare) + + idummy = 1; + for (int i = 0; i < nofNodeData; i++) + out.write((char *)&idummy, sizeof(int)); // jeder Datentyp ist ein skalarer Wert + + // min and max of data + fdummy = 0.0; + for (int i = 0; i < nofNodeData; i++) + out.write((char *)&fdummy, sizeof(float)); // min Wert pro Datentyp + fdummy = 1.0; + for (int i = 0; i < nofNodeData; i++) + out.write((char *)&fdummy, sizeof(float)); // max Wert pro Datentyp + + // daten ins file schreiben + for (int d = 0; d < nofNodeData; ++d) { + for (int n = 0; n < (int)nodedata[d].size(); n++) { + fdummy = (float)nodedata[d][n]; + out.write((char *)&fdummy, sizeof(float)); + } + } + + fdummy = 1.; + for (int i = 0; i < nofNodeData; i++) + out.write((char *)&fdummy, sizeof(float)); // max Wert pro Datentyp + + out.close(); + UBLOG(logDEBUG1, "WbWriterAvsASCII::writeTrianglesWithNodeData to " << avsfilename << " - end"); + + return avsfilename; } /*===============================================================================*/ -std::string WbWriterAvsASCII::writeOctsWithCellData(const string& filename,vector<UbTupleFloat3 >& nodes, vector<UbTupleInt8 >& cells, vector<string >& datanames, vector<vector<double > >& celldata) +std::string WbWriterAvsASCII::writeOctsWithCellData(const string &filename, vector<UbTupleFloat3> &nodes, + vector<UbTupleInt8> &cells, vector<string> &datanames, + vector<vector<double>> &celldata) { - string avsfilename = filename+getFileExtension(); - UBLOG(logDEBUG1,"WbWriterAvsASCII::writeOctsWithCellData to "<<avsfilename<<" - start"); - - ofstream out(avsfilename.c_str(),ios::out|ios::binary); - if(!out) - { - out.clear(); //flags ruecksetzen (ansonsten liefert utern if(!outfile) weiterhin true!!! - string path = UbSystem::getPathFromString(avsfilename); - if(path.size()>0){UbSystem::makeDirectory(path);out.open(avsfilename.c_str(),ios::out|ios::binary);} - if(!out) throw UbException(UB_EXARGS,"file konnte nicht geschrieben werden "+avsfilename); + string avsfilename = filename + getFileExtension(); + UBLOG(logDEBUG1, "WbWriterAvsASCII::writeOctsWithCellData to " << avsfilename << " - start"); + + ofstream out(avsfilename.c_str(), ios::out | ios::binary); + if (!out) { + out.clear(); // flags ruecksetzen (ansonsten liefert utern if(!outfile) weiterhin true!!! + string path = UbSystem::getPathFromString(avsfilename); + if (path.size() > 0) { + UbSystem::makeDirectory(path); + out.open(avsfilename.c_str(), ios::out | ios::binary); + } + if (!out) + throw UbException(UB_EXARGS, "file konnte nicht geschrieben werden " + avsfilename); } char magic = (char)7; - int idummy; + int idummy; float fdummy; int nofNodes = (int)nodes.size(); @@ -703,110 +869,143 @@ std::string WbWriterAvsASCII::writeOctsWithCellData(const string& filename,vecto int nofCellData = (int)datanames.size(); int nofModelData = 0; int cellType = 7; //=hex - int nofNodesPerCell = 8; - - out.write((char*)&magic,sizeof(char)); - out.write((char*)&nofNodes,sizeof(int)); - out.write((char*)&nofCells,sizeof(int)); - out.write((char*)&nofNodeData,sizeof(int)); - out.write((char*)&nofCellData,sizeof(int)); - out.write((char*)&nofModelData,sizeof(int)); - - idummy = (int)nofCells*nofNodesPerCell; - out.write((char*)&idummy,sizeof(int)); //(nof nodes) * (nodes per cell) - for(int c=0; c<nofCells; c++) - { - idummy=c+1; out.write((char*)&idummy,sizeof(int)); //cell id - idummy=1; out.write((char*)&idummy,sizeof(int)); //mat - idummy=nofNodesPerCell; out.write((char*)&idummy,sizeof(int)); //nodes per cell - idummy=cellType; out.write((char*)&idummy,sizeof(int)); //cell type - } - //knotennummern der einzelnen zellen - for(int c=0; c<nofCells; c++) - { - idummy = val<1>(cells[c])+1; out.write((char*)&idummy,sizeof(int)); - idummy = val<2>(cells[c])+1; out.write((char*)&idummy,sizeof(int)); - idummy = val<3>(cells[c])+1; out.write((char*)&idummy,sizeof(int)); - idummy = val<4>(cells[c])+1; out.write((char*)&idummy,sizeof(int)); - idummy = val<5>(cells[c])+1; out.write((char*)&idummy,sizeof(int)); - idummy = val<6>(cells[c])+1; out.write((char*)&idummy,sizeof(int)); - idummy = val<7>(cells[c])+1; out.write((char*)&idummy,sizeof(int)); - idummy = val<8>(cells[c])+1; out.write((char*)&idummy,sizeof(int)); - } - - //coords - //x1-coords - for(int n=0; n<nofNodes; n++) - { fdummy = (float)( val<1>(nodes[n]) ); out.write((char*)&fdummy ,sizeof(float)); } - //x2-coords - for(int n=0; n<nofNodes; n++) - { fdummy = (float)( val<2>(nodes[n]) ); out.write((char*)&fdummy ,sizeof(float)); } - //x3-coords - for(int n=0; n<nofNodes; n++) - { fdummy = (float)( val<3>(nodes[n]) ); out.write((char*)&fdummy ,sizeof(float)); } - //out<<"\n"; - - //CELL DATA + int nofNodesPerCell = 8; + + out.write((char *)&magic, sizeof(char)); + out.write((char *)&nofNodes, sizeof(int)); + out.write((char *)&nofCells, sizeof(int)); + out.write((char *)&nofNodeData, sizeof(int)); + out.write((char *)&nofCellData, sizeof(int)); + out.write((char *)&nofModelData, sizeof(int)); + + idummy = (int)nofCells * nofNodesPerCell; + out.write((char *)&idummy, sizeof(int)); //(nof nodes) * (nodes per cell) + for (int c = 0; c < nofCells; c++) { + idummy = c + 1; + out.write((char *)&idummy, sizeof(int)); // cell id + idummy = 1; + out.write((char *)&idummy, sizeof(int)); // mat + idummy = nofNodesPerCell; + out.write((char *)&idummy, sizeof(int)); // nodes per cell + idummy = cellType; + out.write((char *)&idummy, sizeof(int)); // cell type + } + // knotennummern der einzelnen zellen + for (int c = 0; c < nofCells; c++) { + idummy = val<1>(cells[c]) + 1; + out.write((char *)&idummy, sizeof(int)); + idummy = val<2>(cells[c]) + 1; + out.write((char *)&idummy, sizeof(int)); + idummy = val<3>(cells[c]) + 1; + out.write((char *)&idummy, sizeof(int)); + idummy = val<4>(cells[c]) + 1; + out.write((char *)&idummy, sizeof(int)); + idummy = val<5>(cells[c]) + 1; + out.write((char *)&idummy, sizeof(int)); + idummy = val<6>(cells[c]) + 1; + out.write((char *)&idummy, sizeof(int)); + idummy = val<7>(cells[c]) + 1; + out.write((char *)&idummy, sizeof(int)); + idummy = val<8>(cells[c]) + 1; + out.write((char *)&idummy, sizeof(int)); + } + + // coords + // x1-coords + for (int n = 0; n < nofNodes; n++) { + fdummy = (float)(val<1>(nodes[n])); + out.write((char *)&fdummy, sizeof(float)); + } + // x2-coords + for (int n = 0; n < nofNodes; n++) { + fdummy = (float)(val<2>(nodes[n])); + out.write((char *)&fdummy, sizeof(float)); + } + // x3-coords + for (int n = 0; n < nofNodes; n++) { + fdummy = (float)(val<3>(nodes[n])); + out.write((char *)&fdummy, sizeof(float)); + } + // out<<"\n"; + + // CELL DATA char labels[1024]; char units[1024]; strcpy(labels, ""); strcpy(units, ""); - for(int d=0; d<nofCellData-1; ++d) { strcat(labels, datanames[d].c_str() ); strcat(labels,"."); } - strcat(labels, datanames[nofCellData-1].c_str()); + for (int d = 0; d < nofCellData - 1; ++d) { + strcat(labels, datanames[d].c_str()); + strcat(labels, "."); + } + strcat(labels, datanames[nofCellData - 1].c_str()); - for(int d=0; d<nofCellData-1; ++d) strcat(units, "no_unit."); + for (int d = 0; d < nofCellData - 1; ++d) + strcat(units, "no_unit."); strcat(units, "no_unit"); - out.write((char*)&labels,sizeof(labels)); - out.write((char*)&units,sizeof(units)); + out.write((char *)&labels, sizeof(labels)); + out.write((char *)&units, sizeof(units)); - //nof and type of data + // nof and type of data idummy = nofCellData; - out.write((char*)&idummy,sizeof(int)); //Datentypen pro knoten (hier = nof_node_data, da NUR skalare) + out.write((char *)&idummy, sizeof(int)); // Datentypen pro knoten (hier = nof_node_data, da NUR skalare) idummy = 1; - for(int i=0;i<nofCellData;i++) out.write((char*)&idummy,sizeof(int)); //jeder Datentyp ist ein skalarer Wert + for (int i = 0; i < nofCellData; i++) + out.write((char *)&idummy, sizeof(int)); // jeder Datentyp ist ein skalarer Wert - //min and max of data + // min and max of data fdummy = 0.0; - for(int i=0;i<nofCellData;i++) out.write((char*)&fdummy,sizeof(float)); //min Wert pro Datentyp + for (int i = 0; i < nofCellData; i++) + out.write((char *)&fdummy, sizeof(float)); // min Wert pro Datentyp fdummy = 1.0; - for(int i=0;i<nofCellData;i++) out.write((char*)&fdummy,sizeof(float)); //max Wert pro Datentyp + for (int i = 0; i < nofCellData; i++) + out.write((char *)&fdummy, sizeof(float)); // max Wert pro Datentyp - //daten ins file schreiben - for(int d=0; d<nofCellData; ++d) - for(int n=0; n<(int)celldata[d].size(); n++) - { fdummy=(float)celldata[d][n]; out.write((char*)&fdummy,sizeof(float)); } + // daten ins file schreiben + for (int d = 0; d < nofCellData; ++d) + for (int n = 0; n < (int)celldata[d].size(); n++) { + fdummy = (float)celldata[d][n]; + out.write((char *)&fdummy, sizeof(float)); + } fdummy = 1.; - for(int i=0;i<nofCellData;i++) out.write((char*)&fdummy,sizeof(float)); //max Wert pro Datentyp + for (int i = 0; i < nofCellData; i++) + out.write((char *)&fdummy, sizeof(float)); // max Wert pro Datentyp - out.close(); - UBLOG(logDEBUG1,"WbWriterAvsASCII::writeOctsWithCellData to "<<avsfilename<<" - end"); + out.close(); + UBLOG(logDEBUG1, "WbWriterAvsASCII::writeOctsWithCellData to " << avsfilename << " - end"); return avsfilename; - } +} /*===============================================================================*/ -std::string WbWriterAvsASCII::writeOctsWithNodeData(const string& filename,vector<UbTupleFloat3 >& nodes, vector<UbTupleUInt8 >& cells, vector<string >& datanames, vector<vector<double > >& nodedata) +std::string WbWriterAvsASCII::writeOctsWithNodeData(const string &filename, vector<UbTupleFloat3> &nodes, + vector<UbTupleUInt8> &cells, vector<string> &datanames, + vector<vector<double>> &nodedata) { - string avsfilename = filename+getFileExtension(); - UBLOG(logDEBUG1,"WbWriterAvsASCII::writeOctsWithNodeData to "<<avsfilename<<" - start"); - - ofstream out(avsfilename.c_str(),ios::out|ios::binary); - if(!out) - { - out.clear(); //flags ruecksetzen (ansonsten liefert utern if(!outfile) weiterhin true!!! - string path = UbSystem::getPathFromString(avsfilename); - if(path.size()>0){UbSystem::makeDirectory(path);out.open(avsfilename.c_str(),ios::out|ios::binary);} - if(!out) throw UbException(UB_EXARGS,"file konnte nicht geschrieben werden "+avsfilename); + string avsfilename = filename + getFileExtension(); + UBLOG(logDEBUG1, "WbWriterAvsASCII::writeOctsWithNodeData to " << avsfilename << " - start"); + + ofstream out(avsfilename.c_str(), ios::out | ios::binary); + if (!out) { + out.clear(); // flags ruecksetzen (ansonsten liefert utern if(!outfile) weiterhin true!!! + string path = UbSystem::getPathFromString(avsfilename); + if (path.size() > 0) { + UbSystem::makeDirectory(path); + out.open(avsfilename.c_str(), ios::out | ios::binary); + } + if (!out) + throw UbException(UB_EXARGS, "file konnte nicht geschrieben werden " + avsfilename); } - if((int)nodedata.size()==0) throw UbException(UB_EXARGS,"no nodedata!!!"); - if(nodes.size()!=nodedata[0].size()) throw UbException(UB_EXARGS,"nodedata != nofNodes!!!"); + if ((int)nodedata.size() == 0) + throw UbException(UB_EXARGS, "no nodedata!!!"); + if (nodes.size() != nodedata[0].size()) + throw UbException(UB_EXARGS, "nodedata != nofNodes!!!"); char magic = (char)7; - int idummy; + int idummy; float fdummy; int nofNodes = (int)nodes.size(); @@ -816,87 +1015,112 @@ std::string WbWriterAvsASCII::writeOctsWithNodeData(const string& filename,vecto int nofCellData = 0; int nofModelData = 0; int cellType = 7; //=hex - int nofNodesPerCell = 8; - - out.write((char*)&magic,sizeof(char)); - out.write((char*)&nofNodes,sizeof(int)); - out.write((char*)&nofCells,sizeof(int)); - out.write((char*)&nofNodeData,sizeof(int)); - out.write((char*)&nofCellData,sizeof(int)); - out.write((char*)&nofModelData,sizeof(int)); - - idummy = (int)nofCells*nofNodesPerCell; - out.write((char*)&idummy,sizeof(int)); //(nof nodes) * (nodes per cell) - for(int c=0; c<nofCells; c++) - { - idummy=c+1; out.write((char*)&idummy,sizeof(int)); //cell id - idummy=1; out.write((char*)&idummy,sizeof(int)); //mat - idummy=nofNodesPerCell; out.write((char*)&idummy,sizeof(int)); //nodes per cell - idummy=cellType; out.write((char*)&idummy,sizeof(int)); //cell type - } - //knotennummern der einzelnen zellen - for(int c=0; c<nofCells; c++) - { - idummy = val<1>(cells[c])+1; out.write((char*)&idummy,sizeof(int)); - idummy = val<2>(cells[c])+1; out.write((char*)&idummy,sizeof(int)); - idummy = val<3>(cells[c])+1; out.write((char*)&idummy,sizeof(int)); - idummy = val<4>(cells[c])+1; out.write((char*)&idummy,sizeof(int)); - idummy = val<5>(cells[c])+1; out.write((char*)&idummy,sizeof(int)); - idummy = val<6>(cells[c])+1; out.write((char*)&idummy,sizeof(int)); - idummy = val<7>(cells[c])+1; out.write((char*)&idummy,sizeof(int)); - idummy = val<8>(cells[c])+1; out.write((char*)&idummy,sizeof(int)); - } - - //coords - //x1-coords - for(int n=0; n<nofNodes; n++) - { fdummy = (float)( val<1>(nodes[n]) ); out.write((char*)&fdummy ,sizeof(float)); } - //x2-coords - for(int n=0; n<nofNodes; n++) - { fdummy = (float)( val<2>(nodes[n]) ); out.write((char*)&fdummy ,sizeof(float)); } - //x3-coords - for(int n=0; n<nofNodes; n++) - { fdummy = (float)( val<3>(nodes[n]) ); out.write((char*)&fdummy ,sizeof(float)); } - - //NODE DATA + int nofNodesPerCell = 8; + + out.write((char *)&magic, sizeof(char)); + out.write((char *)&nofNodes, sizeof(int)); + out.write((char *)&nofCells, sizeof(int)); + out.write((char *)&nofNodeData, sizeof(int)); + out.write((char *)&nofCellData, sizeof(int)); + out.write((char *)&nofModelData, sizeof(int)); + + idummy = (int)nofCells * nofNodesPerCell; + out.write((char *)&idummy, sizeof(int)); //(nof nodes) * (nodes per cell) + for (int c = 0; c < nofCells; c++) { + idummy = c + 1; + out.write((char *)&idummy, sizeof(int)); // cell id + idummy = 1; + out.write((char *)&idummy, sizeof(int)); // mat + idummy = nofNodesPerCell; + out.write((char *)&idummy, sizeof(int)); // nodes per cell + idummy = cellType; + out.write((char *)&idummy, sizeof(int)); // cell type + } + // knotennummern der einzelnen zellen + for (int c = 0; c < nofCells; c++) { + idummy = val<1>(cells[c]) + 1; + out.write((char *)&idummy, sizeof(int)); + idummy = val<2>(cells[c]) + 1; + out.write((char *)&idummy, sizeof(int)); + idummy = val<3>(cells[c]) + 1; + out.write((char *)&idummy, sizeof(int)); + idummy = val<4>(cells[c]) + 1; + out.write((char *)&idummy, sizeof(int)); + idummy = val<5>(cells[c]) + 1; + out.write((char *)&idummy, sizeof(int)); + idummy = val<6>(cells[c]) + 1; + out.write((char *)&idummy, sizeof(int)); + idummy = val<7>(cells[c]) + 1; + out.write((char *)&idummy, sizeof(int)); + idummy = val<8>(cells[c]) + 1; + out.write((char *)&idummy, sizeof(int)); + } + + // coords + // x1-coords + for (int n = 0; n < nofNodes; n++) { + fdummy = (float)(val<1>(nodes[n])); + out.write((char *)&fdummy, sizeof(float)); + } + // x2-coords + for (int n = 0; n < nofNodes; n++) { + fdummy = (float)(val<2>(nodes[n])); + out.write((char *)&fdummy, sizeof(float)); + } + // x3-coords + for (int n = 0; n < nofNodes; n++) { + fdummy = (float)(val<3>(nodes[n])); + out.write((char *)&fdummy, sizeof(float)); + } + + // NODE DATA char labels[1024]; char units[1024]; strcpy(labels, ""); strcpy(units, ""); - for(int d=0; d<nofNodeData-1; ++d) - { strcat(labels, datanames[d].c_str() ); strcat(labels,"."); } - strcat(labels, datanames[nofNodeData-1].c_str()); + for (int d = 0; d < nofNodeData - 1; ++d) { + strcat(labels, datanames[d].c_str()); + strcat(labels, "."); + } + strcat(labels, datanames[nofNodeData - 1].c_str()); - for(int i=0;i<(nofNodeData-1);i++) strcat(units, "no_unit."); + for (int i = 0; i < (nofNodeData - 1); i++) + strcat(units, "no_unit."); strcat(units, "no_unit"); - out.write((char*)&labels,sizeof(labels)); - out.write((char*)&units,sizeof(units)); + out.write((char *)&labels, sizeof(labels)); + out.write((char *)&units, sizeof(units)); - //nof and type of data + // nof and type of data idummy = nofNodeData; - out.write((char*)&idummy,sizeof(int)); //Datentypen pro knoten (hier = nof_node_data, da NUR skalare) + out.write((char *)&idummy, sizeof(int)); // Datentypen pro knoten (hier = nof_node_data, da NUR skalare) idummy = 1; - for(int i=0;i<nofNodeData;i++) out.write((char*)&idummy,sizeof(int)); //jeder Datentyp ist ein skalarer Wert + for (int i = 0; i < nofNodeData; i++) + out.write((char *)&idummy, sizeof(int)); // jeder Datentyp ist ein skalarer Wert - //min and max of data + // min and max of data fdummy = 0.0; - for(int i=0;i<nofNodeData;i++) out.write((char*)&fdummy,sizeof(float)); //min Wert pro Datentyp + for (int i = 0; i < nofNodeData; i++) + out.write((char *)&fdummy, sizeof(float)); // min Wert pro Datentyp fdummy = 1.0; - for(int i=0;i<nofNodeData;i++) out.write((char*)&fdummy,sizeof(float)); //max Wert pro Datentyp + for (int i = 0; i < nofNodeData; i++) + out.write((char *)&fdummy, sizeof(float)); // max Wert pro Datentyp - //daten ins file schreiben - for(int d=0; d<nofNodeData; ++d) - for(int n=0; n<(int)nodedata[d].size(); n++) - { fdummy=(float)nodedata[d][n]; out.write((char*)&fdummy,sizeof(float)); } + // daten ins file schreiben + for (int d = 0; d < nofNodeData; ++d) + for (int n = 0; n < (int)nodedata[d].size(); n++) { + fdummy = (float)nodedata[d][n]; + out.write((char *)&fdummy, sizeof(float)); + } fdummy = 1.; - for(int i=0;i<nofNodeData;i++) out.write((char*)&fdummy,sizeof(float)); //max Wert pro Datentyp + for (int i = 0; i < nofNodeData; i++) + out.write((char *)&fdummy, sizeof(float)); // max Wert pro Datentyp - out.close(); - UBLOG(logDEBUG1,"WbWriterAvsASCII::writeOctsWithNodeData to "<<avsfilename<<" - end"); + out.close(); + UBLOG(logDEBUG1, "WbWriterAvsASCII::writeOctsWithNodeData to " << avsfilename << " - end"); return avsfilename; - } +} diff --git a/src/basics/basics/writer/WbWriterAvsASCII.h b/src/basics/basics/writer/WbWriterAvsASCII.h index 3e382f37dd3ebcf2c4a2f2ec453b1e789768578e..493d8b1e0fa3182b9acaf4bfa3f11e436c18d678 100644 --- a/src/basics/basics/writer/WbWriterAvsASCII.h +++ b/src/basics/basics/writer/WbWriterAvsASCII.h @@ -8,65 +8,85 @@ #define WBWRITERAVSASCII_H #include <basics/writer/WbWriter.h> - + class WbWriterAvsASCII : public WbWriter { public: - static WbWriterAvsASCII* getInstance() - { - static WbWriterAvsASCII instance; - return &instance; - } + static WbWriterAvsASCII *getInstance() + { + static WbWriterAvsASCII instance; + return &instance; + } + + WbWriterAvsASCII(const WbWriterAvsASCII &) = delete; + const WbWriterAvsASCII &operator=(const WbWriterAvsASCII &) = delete; - WbWriterAvsASCII( const WbWriterAvsASCII& ) = delete; - const WbWriterAvsASCII& operator=( const WbWriterAvsASCII& ) = delete; private: - WbWriterAvsASCII() = default; + WbWriterAvsASCII() = default; public: - std::string getFileExtension() override { return ".ascii.inp"; } - - ///////////////////virtual std::string writeOcts(const std::string& filename,std::vector< UbTupleFloat3 >& nodes, std::vector< UbTupleInt8 >& cells) = 0; - /////////////////////////////////////////////////////// - //lines - // 0 ---- 1 - //nodenumbering must start with 0! - std::string writeLines(const std::string& filename,std::vector<UbTupleFloat3 >& nodes, std::vector<UbTupleInt2 >& lines) override; + std::string getFileExtension() override { return ".ascii.inp"; } + + ///////////////////virtual std::string writeOcts(const std::string& filename,std::vector< UbTupleFloat3 >& nodes, + ///std::vector< UbTupleInt8 >& cells) = 0; + /////////////////////////////////////////////////////// + // lines + // 0 ---- 1 + // nodenumbering must start with 0! + std::string writeLines(const std::string &filename, std::vector<UbTupleFloat3> &nodes, + std::vector<UbTupleInt2> &lines) override; - ////////////////////////////////////////////////////////////////////////// - //triangles - //cell numbering: - // 2 - // - // 0---1 - //nodenumbering must start with 0! - std::string writeTriangles(const std::string& filename,std::vector<UbTupleFloat3 >& nodes, std::vector<UbTuple<int,int,int> >& triangles) override; - std::string writeTrianglesWithNodeData(const std::string& filename,std::vector< UbTupleFloat3 >& nodes, std::vector< UbTupleInt3 >& cells, std::vector< std::string >& datanames, std::vector< std::vector< double > >& nodedata) override; + ////////////////////////////////////////////////////////////////////////// + // triangles + // cell numbering: + // 2 + // + // 0---1 + // nodenumbering must start with 0! + std::string writeTriangles(const std::string &filename, std::vector<UbTupleFloat3> &nodes, + std::vector<UbTuple<int, int, int>> &triangles) override; + std::string writeTrianglesWithNodeData(const std::string &filename, std::vector<UbTupleFloat3> &nodes, + std::vector<UbTupleInt3> &cells, std::vector<std::string> &datanames, + std::vector<std::vector<double>> &nodedata) override; - ////////////////////////////////////////////////////////////////////////// - //quads - //cell numbering: - // 3---2 - // | | - // 0---1 - //nodenumbering must start with 0! - std::string writeQuads(const std::string& filename,std::vector< UbTupleFloat3 >& nodes, std::vector< UbTupleInt4 >& cells) override; - std::string writeQuadsWithNodeData(const std::string& filename, std::vector< UbTupleFloat3 >& nodes, std::vector< UbTupleInt4 >& cells, std::vector< std::string >& datanames, std::vector< std::vector< double > >& nodedata) override; - std::string writeQuadsWithCellData(const std::string& filename, std::vector< UbTupleFloat3 >& nodes, std::vector< UbTupleInt4 >& cells, std::vector< std::string >& datanames, std::vector< std::vector< double > >& celldata) override; - std::string writeQuadsWithNodeAndCellData(const std::string& filename, std::vector< UbTupleFloat3 >& nodes, std::vector< UbTupleInt4 >& cells, std::vector< std::string >& nodedatanames, std::vector< std::vector< double > >& nodedata, std::vector< std::string >& celldatanames, std::vector< std::vector< double > >& celldata) override; + ////////////////////////////////////////////////////////////////////////// + // quads + // cell numbering: + // 3---2 + // | | + // 0---1 + // nodenumbering must start with 0! + std::string writeQuads(const std::string &filename, std::vector<UbTupleFloat3> &nodes, + std::vector<UbTupleInt4> &cells) override; + std::string writeQuadsWithNodeData(const std::string &filename, std::vector<UbTupleFloat3> &nodes, + std::vector<UbTupleInt4> &cells, std::vector<std::string> &datanames, + std::vector<std::vector<double>> &nodedata) override; + std::string writeQuadsWithCellData(const std::string &filename, std::vector<UbTupleFloat3> &nodes, + std::vector<UbTupleInt4> &cells, std::vector<std::string> &datanames, + std::vector<std::vector<double>> &celldata) override; + std::string writeQuadsWithNodeAndCellData(const std::string &filename, std::vector<UbTupleFloat3> &nodes, + std::vector<UbTupleInt4> &cells, std::vector<std::string> &nodedatanames, + std::vector<std::vector<double>> &nodedata, + std::vector<std::string> &celldatanames, + std::vector<std::vector<double>> &celldata) override; - ////////////////////////////////////////////////////////////////////////// - //octs - // 7 ---- 6 - // /| /| - // 4 +--- 5 | - // | | | | - // | 3 ---+ 2 - // |/ |/ - // 0 ---- 1 - std::string writeOcts(const std::string& filename,std::vector< UbTupleFloat3 >& nodes, std::vector< UbTupleInt8 >& cells) override; - std::string writeOctsWithCellData(const std::string& filename, std::vector<UbTupleFloat3 >& nodes, std::vector<UbTupleInt8 >& cells, std::vector<std::string >& datanames, std::vector< std::vector<double > >& celldata) override; - std::string writeOctsWithNodeData(const std::string& filename, std::vector<UbTupleFloat3 >& nodes, std::vector<UbTupleUInt8 >& cells, std::vector<std::string >& datanames, std::vector< std::vector<double > >& nodedata) override; + ////////////////////////////////////////////////////////////////////////// + // octs + // 7 ---- 6 + // /| /| + // 4 +--- 5 | + // | | | | + // | 3 ---+ 2 + // |/ |/ + // 0 ---- 1 + std::string writeOcts(const std::string &filename, std::vector<UbTupleFloat3> &nodes, + std::vector<UbTupleInt8> &cells) override; + std::string writeOctsWithCellData(const std::string &filename, std::vector<UbTupleFloat3> &nodes, + std::vector<UbTupleInt8> &cells, std::vector<std::string> &datanames, + std::vector<std::vector<double>> &celldata) override; + std::string writeOctsWithNodeData(const std::string &filename, std::vector<UbTupleFloat3> &nodes, + std::vector<UbTupleUInt8> &cells, std::vector<std::string> &datanames, + std::vector<std::vector<double>> &nodedata) override; }; -#endif //WBWRITERAVSASCII_H +#endif // WBWRITERAVSASCII_H diff --git a/src/basics/basics/writer/WbWriterAvsBinary.cpp b/src/basics/basics/writer/WbWriterAvsBinary.cpp index d3aa34aad278c86a9f0274017a7710055a40be00..e52b2232ad701e6c61df2b552545668c9f3d9989 100644 --- a/src/basics/basics/writer/WbWriterAvsBinary.cpp +++ b/src/basics/basics/writer/WbWriterAvsBinary.cpp @@ -1,774 +1,961 @@ -#include <basics/writer/WbWriterAvsBinary.h> -#include <basics/writer/WbWriterAvsASCII.h> #include <basics/utilities/UbLogger.h> #include <basics/utilities/UbSystem.h> +#include <basics/writer/WbWriterAvsASCII.h> +#include <basics/writer/WbWriterAvsBinary.h> #include <cstring> using namespace std; -std::string WbWriterAvsBinary::writeLines(const std::string& filename,std::vector<UbTupleFloat3 >& nodes, std::vector<UbTupleInt2 >& lines) +std::string WbWriterAvsBinary::writeLines(const std::string &filename, std::vector<UbTupleFloat3> &nodes, + std::vector<UbTupleInt2> &lines) { - string avsfilename = filename+getFileExtension(); - UBLOG(logDEBUG1,"WbWriterAvsBinary::writeLines to "<<avsfilename<<" - start"); - - ofstream out(avsfilename.c_str(),ios::out|ios::binary); - if(!out) - { - out.clear(); //flags ruecksetzen (ansonsten liefert utern if(!outfile) weiterhin true!!! - string path = UbSystem::getPathFromString(avsfilename); - if(path.size()>0){ UbSystem::makeDirectory(path);out.open(avsfilename.c_str(),ios::out|ios::binary); } - if(!out) throw UbException(UB_EXARGS,avsfilename+" konnte nicht geschrieben werden"); - } - - char magic = (char)7; - int idummy; - float fdummy; - - int nofNodes = (int)nodes.size(); - int nofCells = (int)lines.size(); - - int nofNodeData = 0; - int nofCellData = 0; - int nofModelData = 0; - int cellType = 1; //line - int nofNodesPerCell = 2; - - out.write((char*)&magic,sizeof(char)); - out.write((char*)&nofNodes,sizeof(int)); - out.write((char*)&nofCells,sizeof(int)); - out.write((char*)&nofNodeData,sizeof(int)); - out.write((char*)&nofCellData,sizeof(int)); - out.write((char*)&nofModelData,sizeof(int)); - - idummy = (int)nofCells*nofNodesPerCell; - out.write((char*)&idummy,sizeof(int)); //(nof nodes) * (nodes per cell) - for(int c=0; c<nofCells; c++) - { - idummy=c+1; out.write((char*)&idummy,sizeof(int)); //cell id - idummy=1; out.write((char*)&idummy,sizeof(int)); //mat - idummy=nofNodesPerCell; out.write((char*)&idummy,sizeof(int)); //nodes per cell - idummy=cellType; out.write((char*)&idummy,sizeof(int)); //cell type - } - //knotennummern der einzelnen zellen - for(int c=0; c<nofCells; c++) - { - idummy = val<1>(lines[c])+1; out.write((char*)&idummy,sizeof(int)); - idummy = val<2>(lines[c])+1; out.write((char*)&idummy,sizeof(int)); - - } - - //coords - //x1-coords - for(int n=0; n<nofNodes; n++) - { fdummy = (float)( val<1>(nodes[n]) ); out.write((char*)&fdummy ,sizeof(float)); } - //x2-coords - for(int n=0; n<nofNodes; n++) - { fdummy = (float)( val<2>(nodes[n]) ); out.write((char*)&fdummy ,sizeof(float)); } - //x3-coords - fdummy=0.0; - for(int n=0; n<nofNodes; n++) - { fdummy = (float)( val<3>(nodes[n]) ); out.write((char*)&fdummy ,sizeof(float)); } - //out<<"\n"; - - out.close(); - UBLOG(logDEBUG1,"WbWriterAvsBinary::writeLines to "<<avsfilename<<" - end"); - - return avsfilename; + string avsfilename = filename + getFileExtension(); + UBLOG(logDEBUG1, "WbWriterAvsBinary::writeLines to " << avsfilename << " - start"); + + ofstream out(avsfilename.c_str(), ios::out | ios::binary); + if (!out) { + out.clear(); // flags ruecksetzen (ansonsten liefert utern if(!outfile) weiterhin true!!! + string path = UbSystem::getPathFromString(avsfilename); + if (path.size() > 0) { + UbSystem::makeDirectory(path); + out.open(avsfilename.c_str(), ios::out | ios::binary); + } + if (!out) + throw UbException(UB_EXARGS, avsfilename + " konnte nicht geschrieben werden"); + } + + char magic = (char)7; + int idummy; + float fdummy; + + int nofNodes = (int)nodes.size(); + int nofCells = (int)lines.size(); + + int nofNodeData = 0; + int nofCellData = 0; + int nofModelData = 0; + int cellType = 1; // line + int nofNodesPerCell = 2; + + out.write((char *)&magic, sizeof(char)); + out.write((char *)&nofNodes, sizeof(int)); + out.write((char *)&nofCells, sizeof(int)); + out.write((char *)&nofNodeData, sizeof(int)); + out.write((char *)&nofCellData, sizeof(int)); + out.write((char *)&nofModelData, sizeof(int)); + + idummy = (int)nofCells * nofNodesPerCell; + out.write((char *)&idummy, sizeof(int)); //(nof nodes) * (nodes per cell) + for (int c = 0; c < nofCells; c++) { + idummy = c + 1; + out.write((char *)&idummy, sizeof(int)); // cell id + idummy = 1; + out.write((char *)&idummy, sizeof(int)); // mat + idummy = nofNodesPerCell; + out.write((char *)&idummy, sizeof(int)); // nodes per cell + idummy = cellType; + out.write((char *)&idummy, sizeof(int)); // cell type + } + // knotennummern der einzelnen zellen + for (int c = 0; c < nofCells; c++) { + idummy = val<1>(lines[c]) + 1; + out.write((char *)&idummy, sizeof(int)); + idummy = val<2>(lines[c]) + 1; + out.write((char *)&idummy, sizeof(int)); + } + + // coords + // x1-coords + for (int n = 0; n < nofNodes; n++) { + fdummy = (float)(val<1>(nodes[n])); + out.write((char *)&fdummy, sizeof(float)); + } + // x2-coords + for (int n = 0; n < nofNodes; n++) { + fdummy = (float)(val<2>(nodes[n])); + out.write((char *)&fdummy, sizeof(float)); + } + // x3-coords + fdummy = 0.0; + for (int n = 0; n < nofNodes; n++) { + fdummy = (float)(val<3>(nodes[n])); + out.write((char *)&fdummy, sizeof(float)); + } + // out<<"\n"; + + out.close(); + UBLOG(logDEBUG1, "WbWriterAvsBinary::writeLines to " << avsfilename << " - end"); + + return avsfilename; } /*===============================================================================*/ -std::string WbWriterAvsBinary::writeTriangles(const std::string& filename,std::vector<UbTupleFloat3 >& nodes, std::vector<UbTuple<int,int,int> >& triangles) +std::string WbWriterAvsBinary::writeTriangles(const std::string &filename, std::vector<UbTupleFloat3> &nodes, + std::vector<UbTuple<int, int, int>> &triangles) { - string avsfilename = filename+getFileExtension(); - UBLOG(logDEBUG1,"WbWriterAvsBinary::writeTriangles to "<<avsfilename<<" - start"); - - ofstream out(avsfilename.c_str(),ios::out|ios::binary); - if(!out) - { - out.clear(); //flags ruecksetzen (ansonsten liefert utern if(!outfile) weiterhin true!!! - string path = UbSystem::getPathFromString(avsfilename); - if(path.size()>0){UbSystem::makeDirectory(path);out.open(avsfilename.c_str(),ios::out|ios::binary);} - if(!out) throw UbException(UB_EXARGS,avsfilename+" konnte nicht geschrieben werden"); - } - - char magic = (char)7; - int idummy; - float fdummy; - - int nofNodes = (int)nodes.size(); - int nofCells = (int)triangles.size(); - - int nofNodeData = 0; - int nofCellData = 0; - int nofModelData = 0; - int cellType = 2; //triangle - int nofNodesPerCell = 3; - - out.write((char*)&magic,sizeof(char)); - out.write((char*)&nofNodes,sizeof(int)); - out.write((char*)&nofCells,sizeof(int)); - out.write((char*)&nofNodeData,sizeof(int)); - out.write((char*)&nofCellData,sizeof(int)); - out.write((char*)&nofModelData,sizeof(int)); - - idummy = (int)nofCells*nofNodesPerCell; - out.write((char*)&idummy,sizeof(int)); //(nof nodes) * (nodes per cell) - for(int c=0; c<nofCells; c++) - { - idummy=c+1; out.write((char*)&idummy,sizeof(int)); //cell id - idummy=1; out.write((char*)&idummy,sizeof(int)); //mat - idummy=nofNodesPerCell; out.write((char*)&idummy,sizeof(int)); //nodes per cell - idummy=cellType; out.write((char*)&idummy,sizeof(int)); //cell type - } - //knotennummern der einzelnen zellen - for(int c=0; c<nofCells; c++) - { - idummy = val<1>(triangles[c])+1; out.write((char*)&idummy,sizeof(int)); - idummy = val<2>(triangles[c])+1; out.write((char*)&idummy,sizeof(int)); - idummy = val<3>(triangles[c])+1; out.write((char*)&idummy,sizeof(int)); - - } - - //coords - //x1-coords - for(int n=0; n<nofNodes; n++) - { fdummy = (float)( val<1>(nodes[n]) ); out.write((char*)&fdummy ,sizeof(float)); } - //x2-coords - for(int n=0; n<nofNodes; n++) - { fdummy = (float)( val<2>(nodes[n]) ); out.write((char*)&fdummy ,sizeof(float)); } - //x3-coords - fdummy=0.0; - for(int n=0; n<nofNodes; n++) - { fdummy = (float)( val<3>(nodes[n]) ); out.write((char*)&fdummy ,sizeof(float)); } - //out<<"\n"; - - out.close(); - UBLOG(logDEBUG1,"WbWriterAvsBinary::writeTriangles to "<<avsfilename<<" - end"); - - return avsfilename; + string avsfilename = filename + getFileExtension(); + UBLOG(logDEBUG1, "WbWriterAvsBinary::writeTriangles to " << avsfilename << " - start"); + + ofstream out(avsfilename.c_str(), ios::out | ios::binary); + if (!out) { + out.clear(); // flags ruecksetzen (ansonsten liefert utern if(!outfile) weiterhin true!!! + string path = UbSystem::getPathFromString(avsfilename); + if (path.size() > 0) { + UbSystem::makeDirectory(path); + out.open(avsfilename.c_str(), ios::out | ios::binary); + } + if (!out) + throw UbException(UB_EXARGS, avsfilename + " konnte nicht geschrieben werden"); + } + + char magic = (char)7; + int idummy; + float fdummy; + + int nofNodes = (int)nodes.size(); + int nofCells = (int)triangles.size(); + + int nofNodeData = 0; + int nofCellData = 0; + int nofModelData = 0; + int cellType = 2; // triangle + int nofNodesPerCell = 3; + + out.write((char *)&magic, sizeof(char)); + out.write((char *)&nofNodes, sizeof(int)); + out.write((char *)&nofCells, sizeof(int)); + out.write((char *)&nofNodeData, sizeof(int)); + out.write((char *)&nofCellData, sizeof(int)); + out.write((char *)&nofModelData, sizeof(int)); + + idummy = (int)nofCells * nofNodesPerCell; + out.write((char *)&idummy, sizeof(int)); //(nof nodes) * (nodes per cell) + for (int c = 0; c < nofCells; c++) { + idummy = c + 1; + out.write((char *)&idummy, sizeof(int)); // cell id + idummy = 1; + out.write((char *)&idummy, sizeof(int)); // mat + idummy = nofNodesPerCell; + out.write((char *)&idummy, sizeof(int)); // nodes per cell + idummy = cellType; + out.write((char *)&idummy, sizeof(int)); // cell type + } + // knotennummern der einzelnen zellen + for (int c = 0; c < nofCells; c++) { + idummy = val<1>(triangles[c]) + 1; + out.write((char *)&idummy, sizeof(int)); + idummy = val<2>(triangles[c]) + 1; + out.write((char *)&idummy, sizeof(int)); + idummy = val<3>(triangles[c]) + 1; + out.write((char *)&idummy, sizeof(int)); + } + + // coords + // x1-coords + for (int n = 0; n < nofNodes; n++) { + fdummy = (float)(val<1>(nodes[n])); + out.write((char *)&fdummy, sizeof(float)); + } + // x2-coords + for (int n = 0; n < nofNodes; n++) { + fdummy = (float)(val<2>(nodes[n])); + out.write((char *)&fdummy, sizeof(float)); + } + // x3-coords + fdummy = 0.0; + for (int n = 0; n < nofNodes; n++) { + fdummy = (float)(val<3>(nodes[n])); + out.write((char *)&fdummy, sizeof(float)); + } + // out<<"\n"; + + out.close(); + UBLOG(logDEBUG1, "WbWriterAvsBinary::writeTriangles to " << avsfilename << " - end"); + + return avsfilename; } /*===============================================================================*/ -std::string WbWriterAvsBinary::writeQuads(const std::string& filename,std::vector< UbTupleFloat3 >& nodes, std::vector< UbTupleInt4 >& cells) +std::string WbWriterAvsBinary::writeQuads(const std::string &filename, std::vector<UbTupleFloat3> &nodes, + std::vector<UbTupleInt4> &cells) { - string avsfilename = filename+getFileExtension(); - UBLOG(logDEBUG1,"WbWriterAvsBinary::writeQuads to "<<avsfilename<<" - start"); - - ofstream out(avsfilename.c_str(),ios::out|ios::binary); - if(!out) - { - out.clear(); //flags ruecksetzen (ansonsten liefert utern if(!outfile) weiterhin true!!! - string path = UbSystem::getPathFromString(avsfilename); - if(path.size()>0){UbSystem::makeDirectory(path);out.open(avsfilename.c_str(),ios::out|ios::binary);} - if(!out) throw UbException(UB_EXARGS,avsfilename+" konnte nicht geschrieben werden"); - } - char magic = (char)7; - int idummy; - float fdummy; - - int nofNodes = (int)nodes.size(); - int nofCells = (int)cells.size(); - - int nofNodeData = 0; - int nofCellData = 0; - int nofModelData = 0; - int cellType = 3; //=quad - int nofNodesPerCell = 4; - - out.write((char*)&magic,sizeof(char)); - out.write((char*)&nofNodes,sizeof(int)); - out.write((char*)&nofCells,sizeof(int)); - out.write((char*)&nofNodeData,sizeof(int)); - out.write((char*)&nofCellData,sizeof(int)); - out.write((char*)&nofModelData,sizeof(int)); - - idummy = (int)nofCells*nofNodesPerCell; - out.write((char*)&idummy,sizeof(int)); //(nof nodes) * (nodes per cell) - for(int c=0; c<nofCells; c++) - { - idummy=c+1; out.write((char*)&idummy,sizeof(int)); //cell id - idummy=1; out.write((char*)&idummy,sizeof(int)); //mat - idummy=nofNodesPerCell; out.write((char*)&idummy,sizeof(int)); //nodes per cell - idummy=cellType; out.write((char*)&idummy,sizeof(int)); //cell type - } - //knotennummern der einzelnen zellen - for(int c=0; c<nofCells; c++) - { - idummy = val<1>(cells[c])+1; out.write((char*)&idummy,sizeof(int)); - idummy = val<2>(cells[c])+1; out.write((char*)&idummy,sizeof(int)); - idummy = val<3>(cells[c])+1; out.write((char*)&idummy,sizeof(int)); - idummy = val<4>(cells[c])+1; out.write((char*)&idummy,sizeof(int)); - } - - //coords - //x1-coords - for(int n=0; n<nofNodes; n++) - { fdummy = (float)( val<1>(nodes[n]) ); out.write((char*)&fdummy ,sizeof(float)); } - //x2-coords - for(int n=0; n<nofNodes; n++) - { fdummy = (float)( val<2>(nodes[n]) ); out.write((char*)&fdummy ,sizeof(float)); } - //x3-coords - for(int n=0; n<nofNodes; n++) - { fdummy = (float)( val<3>(nodes[n]) ); out.write((char*)&fdummy ,sizeof(float)); } - //out<<"\n"; - - - out.close(); - UBLOG(logDEBUG1,"WbWriterAvsBinary::writeQuads to "<<avsfilename<<" - end"); - - return avsfilename; + string avsfilename = filename + getFileExtension(); + UBLOG(logDEBUG1, "WbWriterAvsBinary::writeQuads to " << avsfilename << " - start"); + + ofstream out(avsfilename.c_str(), ios::out | ios::binary); + if (!out) { + out.clear(); // flags ruecksetzen (ansonsten liefert utern if(!outfile) weiterhin true!!! + string path = UbSystem::getPathFromString(avsfilename); + if (path.size() > 0) { + UbSystem::makeDirectory(path); + out.open(avsfilename.c_str(), ios::out | ios::binary); + } + if (!out) + throw UbException(UB_EXARGS, avsfilename + " konnte nicht geschrieben werden"); + } + char magic = (char)7; + int idummy; + float fdummy; + + int nofNodes = (int)nodes.size(); + int nofCells = (int)cells.size(); + + int nofNodeData = 0; + int nofCellData = 0; + int nofModelData = 0; + int cellType = 3; //=quad + int nofNodesPerCell = 4; + + out.write((char *)&magic, sizeof(char)); + out.write((char *)&nofNodes, sizeof(int)); + out.write((char *)&nofCells, sizeof(int)); + out.write((char *)&nofNodeData, sizeof(int)); + out.write((char *)&nofCellData, sizeof(int)); + out.write((char *)&nofModelData, sizeof(int)); + + idummy = (int)nofCells * nofNodesPerCell; + out.write((char *)&idummy, sizeof(int)); //(nof nodes) * (nodes per cell) + for (int c = 0; c < nofCells; c++) { + idummy = c + 1; + out.write((char *)&idummy, sizeof(int)); // cell id + idummy = 1; + out.write((char *)&idummy, sizeof(int)); // mat + idummy = nofNodesPerCell; + out.write((char *)&idummy, sizeof(int)); // nodes per cell + idummy = cellType; + out.write((char *)&idummy, sizeof(int)); // cell type + } + // knotennummern der einzelnen zellen + for (int c = 0; c < nofCells; c++) { + idummy = val<1>(cells[c]) + 1; + out.write((char *)&idummy, sizeof(int)); + idummy = val<2>(cells[c]) + 1; + out.write((char *)&idummy, sizeof(int)); + idummy = val<3>(cells[c]) + 1; + out.write((char *)&idummy, sizeof(int)); + idummy = val<4>(cells[c]) + 1; + out.write((char *)&idummy, sizeof(int)); + } + + // coords + // x1-coords + for (int n = 0; n < nofNodes; n++) { + fdummy = (float)(val<1>(nodes[n])); + out.write((char *)&fdummy, sizeof(float)); + } + // x2-coords + for (int n = 0; n < nofNodes; n++) { + fdummy = (float)(val<2>(nodes[n])); + out.write((char *)&fdummy, sizeof(float)); + } + // x3-coords + for (int n = 0; n < nofNodes; n++) { + fdummy = (float)(val<3>(nodes[n])); + out.write((char *)&fdummy, sizeof(float)); + } + // out<<"\n"; + + out.close(); + UBLOG(logDEBUG1, "WbWriterAvsBinary::writeQuads to " << avsfilename << " - end"); + + return avsfilename; } /*===============================================================================*/ -std::string WbWriterAvsBinary::writeOcts(const std::string& filename,std::vector< UbTupleFloat3 >& nodes, std::vector< UbTupleInt8 >& cells) +std::string WbWriterAvsBinary::writeOcts(const std::string &filename, std::vector<UbTupleFloat3> &nodes, + std::vector<UbTupleInt8> &cells) { - string avsfilename = filename+getFileExtension(); - UBLOG(logDEBUG1,"WbWriterAvsBinary::writeOcts to "<<avsfilename<<" - start"); - - ofstream out(avsfilename.c_str(),ios::out|ios::binary); - if(!out) - { - out.clear(); //flags ruecksetzen (ansonsten liefert utern if(!outfile) weiterhin true!!! - string path = UbSystem::getPathFromString(avsfilename); - if(path.size()>0){UbSystem::makeDirectory(path);out.open(avsfilename.c_str(),ios::out|ios::binary);} - if(!out) throw UbException(UB_EXARGS,"file konnte nicht geschrieben werden"); - } - - char magic = (char)7; - int idummy; - float fdummy; - - int nofNodes = (int)nodes.size(); - int nofCells = (int)cells.size(); - - int nofNodeData = 0; - int nofCellData = 0; - int nofModelData = 0; - int cellType = 7; //=hex - int nofNodesPerCell = 8; - - out.write((char*)&magic,sizeof(char)); - out.write((char*)&nofNodes,sizeof(int)); - out.write((char*)&nofCells,sizeof(int)); - out.write((char*)&nofNodeData,sizeof(int)); - out.write((char*)&nofCellData,sizeof(int)); - out.write((char*)&nofModelData,sizeof(int)); - - idummy = (int)nofCells*nofNodesPerCell; - out.write((char*)&idummy,sizeof(int)); //(nof nodes) * (nodes per cell) - for(int c=0; c<nofCells; c++) - { - idummy=c+1; out.write((char*)&idummy,sizeof(int)); //cell id - idummy=1; out.write((char*)&idummy,sizeof(int)); //mat - idummy=nofNodesPerCell; out.write((char*)&idummy,sizeof(int)); //nodes per cell - idummy=cellType; out.write((char*)&idummy,sizeof(int)); //cell type - } - //knotennummern der einzelnen zellen - for(int c=0; c<nofCells; c++) - { - idummy = val<1>(cells[c])+1; out.write((char*)&idummy,sizeof(int)); - idummy = val<2>(cells[c])+1; out.write((char*)&idummy,sizeof(int)); - idummy = val<3>(cells[c])+1; out.write((char*)&idummy,sizeof(int)); - idummy = val<4>(cells[c])+1; out.write((char*)&idummy,sizeof(int)); - idummy = val<5>(cells[c])+1; out.write((char*)&idummy,sizeof(int)); - idummy = val<6>(cells[c])+1; out.write((char*)&idummy,sizeof(int)); - idummy = val<7>(cells[c])+1; out.write((char*)&idummy,sizeof(int)); - idummy = val<8>(cells[c])+1; out.write((char*)&idummy,sizeof(int)); - } - - //coords - //x1-coords - for(int n=0; n<nofNodes; n++) - { fdummy = (float)( val<1>(nodes[n]) ); out.write((char*)&fdummy ,sizeof(float)); } - //x2-coords - for(int n=0; n<nofNodes; n++) - { fdummy = (float)( val<2>(nodes[n]) ); out.write((char*)&fdummy ,sizeof(float)); } - //x3-coords - for(int n=0; n<nofNodes; n++) - { fdummy = (float)( val<3>(nodes[n]) ); out.write((char*)&fdummy ,sizeof(float)); } - //out<<"\n"; - - - out.close(); - UBLOG(logDEBUG1,"WbWriterAvsBinary::writeOcts to "<<avsfilename<<" - end"); - - return avsfilename; + string avsfilename = filename + getFileExtension(); + UBLOG(logDEBUG1, "WbWriterAvsBinary::writeOcts to " << avsfilename << " - start"); + + ofstream out(avsfilename.c_str(), ios::out | ios::binary); + if (!out) { + out.clear(); // flags ruecksetzen (ansonsten liefert utern if(!outfile) weiterhin true!!! + string path = UbSystem::getPathFromString(avsfilename); + if (path.size() > 0) { + UbSystem::makeDirectory(path); + out.open(avsfilename.c_str(), ios::out | ios::binary); + } + if (!out) + throw UbException(UB_EXARGS, "file konnte nicht geschrieben werden"); + } + + char magic = (char)7; + int idummy; + float fdummy; + + int nofNodes = (int)nodes.size(); + int nofCells = (int)cells.size(); + + int nofNodeData = 0; + int nofCellData = 0; + int nofModelData = 0; + int cellType = 7; //=hex + int nofNodesPerCell = 8; + + out.write((char *)&magic, sizeof(char)); + out.write((char *)&nofNodes, sizeof(int)); + out.write((char *)&nofCells, sizeof(int)); + out.write((char *)&nofNodeData, sizeof(int)); + out.write((char *)&nofCellData, sizeof(int)); + out.write((char *)&nofModelData, sizeof(int)); + + idummy = (int)nofCells * nofNodesPerCell; + out.write((char *)&idummy, sizeof(int)); //(nof nodes) * (nodes per cell) + for (int c = 0; c < nofCells; c++) { + idummy = c + 1; + out.write((char *)&idummy, sizeof(int)); // cell id + idummy = 1; + out.write((char *)&idummy, sizeof(int)); // mat + idummy = nofNodesPerCell; + out.write((char *)&idummy, sizeof(int)); // nodes per cell + idummy = cellType; + out.write((char *)&idummy, sizeof(int)); // cell type + } + // knotennummern der einzelnen zellen + for (int c = 0; c < nofCells; c++) { + idummy = val<1>(cells[c]) + 1; + out.write((char *)&idummy, sizeof(int)); + idummy = val<2>(cells[c]) + 1; + out.write((char *)&idummy, sizeof(int)); + idummy = val<3>(cells[c]) + 1; + out.write((char *)&idummy, sizeof(int)); + idummy = val<4>(cells[c]) + 1; + out.write((char *)&idummy, sizeof(int)); + idummy = val<5>(cells[c]) + 1; + out.write((char *)&idummy, sizeof(int)); + idummy = val<6>(cells[c]) + 1; + out.write((char *)&idummy, sizeof(int)); + idummy = val<7>(cells[c]) + 1; + out.write((char *)&idummy, sizeof(int)); + idummy = val<8>(cells[c]) + 1; + out.write((char *)&idummy, sizeof(int)); + } + + // coords + // x1-coords + for (int n = 0; n < nofNodes; n++) { + fdummy = (float)(val<1>(nodes[n])); + out.write((char *)&fdummy, sizeof(float)); + } + // x2-coords + for (int n = 0; n < nofNodes; n++) { + fdummy = (float)(val<2>(nodes[n])); + out.write((char *)&fdummy, sizeof(float)); + } + // x3-coords + for (int n = 0; n < nofNodes; n++) { + fdummy = (float)(val<3>(nodes[n])); + out.write((char *)&fdummy, sizeof(float)); + } + // out<<"\n"; + + out.close(); + UBLOG(logDEBUG1, "WbWriterAvsBinary::writeOcts to " << avsfilename << " - end"); + + return avsfilename; } /*===============================================================================*/ -std::string WbWriterAvsBinary::writeTrianglesWithNodeData(const std::string& filename,std::vector< UbTupleFloat3 >& nodes, std::vector< UbTupleInt3 >& cells, std::vector< std::string >& datanames, std::vector< std::vector< double > >& nodedata) +std::string WbWriterAvsBinary::writeTrianglesWithNodeData(const std::string &filename, + std::vector<UbTupleFloat3> &nodes, + std::vector<UbTupleInt3> &cells, + std::vector<std::string> &datanames, + std::vector<std::vector<double>> &nodedata) { - string avsfilename = filename+getFileExtension(); - UBLOG(logDEBUG1,"WbWriterAvsBinary::writeTrianglesWithNodeData to "<<avsfilename<<" - start"); - - ofstream out(avsfilename.c_str(),ios::out|ios::binary); - if(!out) - { - out.clear(); //flags ruecksetzen (ansonsten liefert utern if(!outfile) weiterhin true!!! - string path = UbSystem::getPathFromString(avsfilename); - if(path.size()>0){UbSystem::makeDirectory(path);out.open(avsfilename.c_str(),ios::out|ios::binary);} - if(!out) throw UbException(UB_EXARGS,"write_OutputFile-UCD File "+avsfilename+" konnte nicht geschrieben werden"); - } - char magic = (char)7; - int idummy; - float fdummy; - - int nofNodes = (int)nodes.size(); - int nofCells = (int)cells.size(); - - int nofNodeData = (int)datanames.size(); - int nofCellData = 0; - int nofModelData = 0; - int cellType = 2; //triangle - int nofNodesPerCell = 3; - - out.write((char*)&magic,sizeof(char)); - out.write((char*)&nofNodes,sizeof(int)); - out.write((char*)&nofCells,sizeof(int)); - out.write((char*)&nofNodeData,sizeof(int)); - out.write((char*)&nofCellData,sizeof(int)); - out.write((char*)&nofModelData,sizeof(int)); - - idummy = (int)nofCells*nofNodesPerCell; - out.write((char*)&idummy,sizeof(int)); //(nof nodes) * (nodes per cell) - for(int c=0; c<nofCells; c++) - { - idummy=c+1; out.write((char*)&idummy,sizeof(int)); //cell id - idummy=1; out.write((char*)&idummy,sizeof(int)); //mat - idummy=nofNodesPerCell; out.write((char*)&idummy,sizeof(int)); //nodes per cell - idummy=cellType; out.write((char*)&idummy,sizeof(int)); //cell type - } - //knotennummern der einzelnen zellen - for(int c=0; c<nofCells; c++) - { - idummy = val<1>(cells[c])+1; out.write((char*)&idummy,sizeof(int)); - idummy = val<2>(cells[c])+1; out.write((char*)&idummy,sizeof(int)); - idummy = val<3>(cells[c])+1; out.write((char*)&idummy,sizeof(int)); - } - - //coords - //x1-coords - for(int n=0; n<nofNodes; n++) - { fdummy = (float)( val<1>(nodes[n]) ); out.write((char*)&fdummy ,sizeof(float)); } - //x2-coords - for(int n=0; n<nofNodes; n++) - { fdummy = (float)( val<2>(nodes[n]) ); out.write((char*)&fdummy ,sizeof(float)); } - //x3-coords - for(int n=0; n<nofNodes; n++) - { fdummy = (float)( val<3>(nodes[n]) ); out.write((char*)&fdummy ,sizeof(float)); } - //out<<"\n"; - - //NODE DATA - char labels[1024]; - char units[1024]; - strcpy(labels, ""); - strcpy(units, ""); - - for(int d=0; d<nofNodeData-1; ++d) - { strcat(labels, datanames[d].c_str() ); strcat(labels,"."); } - strcat(labels, datanames[nofNodeData-1].c_str()); - - for(int i=0;i<(nofNodeData-1);i++) strcat(units, "no_unit."); - strcat(units, "no_unit"); - - out.write((char*)&labels,sizeof(labels)); - out.write((char*)&units,sizeof(units)); - - //nof and type of data - idummy = nofNodeData; - out.write((char*)&idummy,sizeof(int)); //Datentypen pro knoten (hier = nof_node_data, da NUR skalare) - - idummy = 1; - for(int i=0;i<nofNodeData;i++) out.write((char*)&idummy,sizeof(int)); //jeder Datentyp ist ein skalarer Wert - - //min and max of data - fdummy = 0.0; - for(int i=0;i<nofNodeData;i++) out.write((char*)&fdummy,sizeof(float)); //min Wert pro Datentyp - fdummy = 1.0; - for(int i=0;i<nofNodeData;i++) out.write((char*)&fdummy,sizeof(float)); //max Wert pro Datentyp - - //daten ins file schreiben - for(int d=0; d<nofNodeData; ++d) - for(int n=0; n<(int)nodedata[d].size(); n++) - { fdummy=(float)nodedata[d][n]; out.write((char*)&fdummy,sizeof(float)); } - - fdummy = 1.; - for(int i=0;i<nofNodeData;i++) out.write((char*)&fdummy,sizeof(float)); //max Wert pro Datentyp - - out.close(); - UBLOG(logDEBUG1,"WbWriterAvsBinary::writeTrianglesWithNodeData to "<<avsfilename<<" - end"); - - return avsfilename; + string avsfilename = filename + getFileExtension(); + UBLOG(logDEBUG1, "WbWriterAvsBinary::writeTrianglesWithNodeData to " << avsfilename << " - start"); + + ofstream out(avsfilename.c_str(), ios::out | ios::binary); + if (!out) { + out.clear(); // flags ruecksetzen (ansonsten liefert utern if(!outfile) weiterhin true!!! + string path = UbSystem::getPathFromString(avsfilename); + if (path.size() > 0) { + UbSystem::makeDirectory(path); + out.open(avsfilename.c_str(), ios::out | ios::binary); + } + if (!out) + throw UbException(UB_EXARGS, + "write_OutputFile-UCD File " + avsfilename + " konnte nicht geschrieben werden"); + } + char magic = (char)7; + int idummy; + float fdummy; + + int nofNodes = (int)nodes.size(); + int nofCells = (int)cells.size(); + + int nofNodeData = (int)datanames.size(); + int nofCellData = 0; + int nofModelData = 0; + int cellType = 2; // triangle + int nofNodesPerCell = 3; + + out.write((char *)&magic, sizeof(char)); + out.write((char *)&nofNodes, sizeof(int)); + out.write((char *)&nofCells, sizeof(int)); + out.write((char *)&nofNodeData, sizeof(int)); + out.write((char *)&nofCellData, sizeof(int)); + out.write((char *)&nofModelData, sizeof(int)); + + idummy = (int)nofCells * nofNodesPerCell; + out.write((char *)&idummy, sizeof(int)); //(nof nodes) * (nodes per cell) + for (int c = 0; c < nofCells; c++) { + idummy = c + 1; + out.write((char *)&idummy, sizeof(int)); // cell id + idummy = 1; + out.write((char *)&idummy, sizeof(int)); // mat + idummy = nofNodesPerCell; + out.write((char *)&idummy, sizeof(int)); // nodes per cell + idummy = cellType; + out.write((char *)&idummy, sizeof(int)); // cell type + } + // knotennummern der einzelnen zellen + for (int c = 0; c < nofCells; c++) { + idummy = val<1>(cells[c]) + 1; + out.write((char *)&idummy, sizeof(int)); + idummy = val<2>(cells[c]) + 1; + out.write((char *)&idummy, sizeof(int)); + idummy = val<3>(cells[c]) + 1; + out.write((char *)&idummy, sizeof(int)); + } + + // coords + // x1-coords + for (int n = 0; n < nofNodes; n++) { + fdummy = (float)(val<1>(nodes[n])); + out.write((char *)&fdummy, sizeof(float)); + } + // x2-coords + for (int n = 0; n < nofNodes; n++) { + fdummy = (float)(val<2>(nodes[n])); + out.write((char *)&fdummy, sizeof(float)); + } + // x3-coords + for (int n = 0; n < nofNodes; n++) { + fdummy = (float)(val<3>(nodes[n])); + out.write((char *)&fdummy, sizeof(float)); + } + // out<<"\n"; + + // NODE DATA + char labels[1024]; + char units[1024]; + strcpy(labels, ""); + strcpy(units, ""); + + for (int d = 0; d < nofNodeData - 1; ++d) { + strcat(labels, datanames[d].c_str()); + strcat(labels, "."); + } + strcat(labels, datanames[nofNodeData - 1].c_str()); + + for (int i = 0; i < (nofNodeData - 1); i++) + strcat(units, "no_unit."); + strcat(units, "no_unit"); + + out.write((char *)&labels, sizeof(labels)); + out.write((char *)&units, sizeof(units)); + + // nof and type of data + idummy = nofNodeData; + out.write((char *)&idummy, sizeof(int)); // Datentypen pro knoten (hier = nof_node_data, da NUR skalare) + + idummy = 1; + for (int i = 0; i < nofNodeData; i++) + out.write((char *)&idummy, sizeof(int)); // jeder Datentyp ist ein skalarer Wert + + // min and max of data + fdummy = 0.0; + for (int i = 0; i < nofNodeData; i++) + out.write((char *)&fdummy, sizeof(float)); // min Wert pro Datentyp + fdummy = 1.0; + for (int i = 0; i < nofNodeData; i++) + out.write((char *)&fdummy, sizeof(float)); // max Wert pro Datentyp + + // daten ins file schreiben + for (int d = 0; d < nofNodeData; ++d) + for (int n = 0; n < (int)nodedata[d].size(); n++) { + fdummy = (float)nodedata[d][n]; + out.write((char *)&fdummy, sizeof(float)); + } + + fdummy = 1.; + for (int i = 0; i < nofNodeData; i++) + out.write((char *)&fdummy, sizeof(float)); // max Wert pro Datentyp + + out.close(); + UBLOG(logDEBUG1, "WbWriterAvsBinary::writeTrianglesWithNodeData to " << avsfilename << " - end"); + + return avsfilename; } /*===============================================================================*/ -std::string WbWriterAvsBinary::writeQuadsWithNodeData(const string& filename,vector< UbTupleFloat3 >& nodes, vector< UbTupleInt4 >& cells, vector< string >& datanames, vector< vector< double > >& nodedata) +std::string WbWriterAvsBinary::writeQuadsWithNodeData(const string &filename, vector<UbTupleFloat3> &nodes, + vector<UbTupleInt4> &cells, vector<string> &datanames, + vector<vector<double>> &nodedata) { - string avsfilename = filename+getFileExtension(); - UBLOG(logDEBUG1,"WbWriterAvsBinary::writeQuadsWithNodeData to "<<avsfilename<<" - start"); - - ofstream out(avsfilename.c_str(),ios::out|ios::binary); - if(!out) - { - out.clear(); //flags ruecksetzen (ansonsten liefert utern if(!outfile) weiterhin true!!! - string path = UbSystem::getPathFromString(avsfilename); - if(path.size()>0){UbSystem::makeDirectory(path);out.open(avsfilename.c_str(),ios::out|ios::binary);} - if(!out) throw UbException(UB_EXARGS,"write_OutputFile-UCD File "+avsfilename+" konnte nicht geschrieben werden"); - } - char magic = (char)7; - int idummy; - float fdummy; - - int nofNodes = (int)nodes.size(); - int nofCells = (int)cells.size(); - - int nofNodeData = (int)datanames.size(); - int nofCellData = 0; - int nofModelData = 0; - int cellType = 3; //=quad - int nofNodesPerCell = 4; - - out.write((char*)&magic,sizeof(char)); - out.write((char*)&nofNodes,sizeof(int)); - out.write((char*)&nofCells,sizeof(int)); - out.write((char*)&nofNodeData,sizeof(int)); - out.write((char*)&nofCellData,sizeof(int)); - out.write((char*)&nofModelData,sizeof(int)); - - idummy = (int)nofCells*nofNodesPerCell; - out.write((char*)&idummy,sizeof(int)); //(nof nodes) * (nodes per cell) - for(int c=0; c<nofCells; c++) - { - idummy=c+1; out.write((char*)&idummy,sizeof(int)); //cell id - idummy=1; out.write((char*)&idummy,sizeof(int)); //mat - idummy=nofNodesPerCell; out.write((char*)&idummy,sizeof(int)); //nodes per cell - idummy=cellType; out.write((char*)&idummy,sizeof(int)); //cell type - } - //knotennummern der einzelnen zellen - for(int c=0; c<nofCells; c++) - { - idummy = val<1>(cells[c])+1; out.write((char*)&idummy,sizeof(int)); - idummy = val<2>(cells[c])+1; out.write((char*)&idummy,sizeof(int)); - idummy = val<3>(cells[c])+1; out.write((char*)&idummy,sizeof(int)); - idummy = val<4>(cells[c])+1; out.write((char*)&idummy,sizeof(int)); - } - - //coords - //x1-coords - for(int n=0; n<nofNodes; n++) - { fdummy = (float)( val<1>(nodes[n]) ); out.write((char*)&fdummy ,sizeof(float)); } - //x2-coords - for(int n=0; n<nofNodes; n++) - { fdummy = (float)( val<2>(nodes[n]) ); out.write((char*)&fdummy ,sizeof(float)); } - //x3-coords - for(int n=0; n<nofNodes; n++) - { fdummy = (float)( val<3>(nodes[n]) ); out.write((char*)&fdummy ,sizeof(float)); } - //out<<"\n"; - - //NODE DATA - char labels[1024]; - char units[1024]; - strcpy(labels, ""); - strcpy(units, ""); - - for(int d=0; d<nofNodeData-1; ++d) - { strcat(labels, datanames[d].c_str() ); strcat(labels,"."); } - strcat(labels, datanames[nofNodeData-1].c_str()); - - for(int i=0;i<(nofNodeData-1);i++) strcat(units, "no_unit."); - strcat(units, "no_unit"); - - out.write((char*)&labels,sizeof(labels)); - out.write((char*)&units,sizeof(units)); - - //nof and type of data - idummy = nofNodeData; - out.write((char*)&idummy,sizeof(int)); //Datentypen pro knoten (hier = nof_node_data, da NUR skalare) - - idummy = 1; - for(int i=0;i<nofNodeData;i++) out.write((char*)&idummy,sizeof(int)); //jeder Datentyp ist ein skalarer Wert - - //min and max of data - fdummy = 0.0; - for(int i=0;i<nofNodeData;i++) out.write((char*)&fdummy,sizeof(float)); //min Wert pro Datentyp - fdummy = 1.0; - for(int i=0;i<nofNodeData;i++) out.write((char*)&fdummy,sizeof(float)); //max Wert pro Datentyp - - //daten ins file schreiben - for(int d=0; d<nofNodeData; ++d) - for(int n=0; n<(int)nodedata[d].size(); n++) - { fdummy=(float)nodedata[d][n]; out.write((char*)&fdummy,sizeof(float)); } - - fdummy = 1.; - for(int i=0;i<nofNodeData;i++) out.write((char*)&fdummy,sizeof(float)); //max Wert pro Datentyp - - out.close(); - UBLOG(logDEBUG1,"WbWriterAvsBinary::writeQuadsWithNodeData to "<<avsfilename<<" - end"); - - return avsfilename; + string avsfilename = filename + getFileExtension(); + UBLOG(logDEBUG1, "WbWriterAvsBinary::writeQuadsWithNodeData to " << avsfilename << " - start"); + + ofstream out(avsfilename.c_str(), ios::out | ios::binary); + if (!out) { + out.clear(); // flags ruecksetzen (ansonsten liefert utern if(!outfile) weiterhin true!!! + string path = UbSystem::getPathFromString(avsfilename); + if (path.size() > 0) { + UbSystem::makeDirectory(path); + out.open(avsfilename.c_str(), ios::out | ios::binary); + } + if (!out) + throw UbException(UB_EXARGS, + "write_OutputFile-UCD File " + avsfilename + " konnte nicht geschrieben werden"); + } + char magic = (char)7; + int idummy; + float fdummy; + + int nofNodes = (int)nodes.size(); + int nofCells = (int)cells.size(); + + int nofNodeData = (int)datanames.size(); + int nofCellData = 0; + int nofModelData = 0; + int cellType = 3; //=quad + int nofNodesPerCell = 4; + + out.write((char *)&magic, sizeof(char)); + out.write((char *)&nofNodes, sizeof(int)); + out.write((char *)&nofCells, sizeof(int)); + out.write((char *)&nofNodeData, sizeof(int)); + out.write((char *)&nofCellData, sizeof(int)); + out.write((char *)&nofModelData, sizeof(int)); + + idummy = (int)nofCells * nofNodesPerCell; + out.write((char *)&idummy, sizeof(int)); //(nof nodes) * (nodes per cell) + for (int c = 0; c < nofCells; c++) { + idummy = c + 1; + out.write((char *)&idummy, sizeof(int)); // cell id + idummy = 1; + out.write((char *)&idummy, sizeof(int)); // mat + idummy = nofNodesPerCell; + out.write((char *)&idummy, sizeof(int)); // nodes per cell + idummy = cellType; + out.write((char *)&idummy, sizeof(int)); // cell type + } + // knotennummern der einzelnen zellen + for (int c = 0; c < nofCells; c++) { + idummy = val<1>(cells[c]) + 1; + out.write((char *)&idummy, sizeof(int)); + idummy = val<2>(cells[c]) + 1; + out.write((char *)&idummy, sizeof(int)); + idummy = val<3>(cells[c]) + 1; + out.write((char *)&idummy, sizeof(int)); + idummy = val<4>(cells[c]) + 1; + out.write((char *)&idummy, sizeof(int)); + } + + // coords + // x1-coords + for (int n = 0; n < nofNodes; n++) { + fdummy = (float)(val<1>(nodes[n])); + out.write((char *)&fdummy, sizeof(float)); + } + // x2-coords + for (int n = 0; n < nofNodes; n++) { + fdummy = (float)(val<2>(nodes[n])); + out.write((char *)&fdummy, sizeof(float)); + } + // x3-coords + for (int n = 0; n < nofNodes; n++) { + fdummy = (float)(val<3>(nodes[n])); + out.write((char *)&fdummy, sizeof(float)); + } + // out<<"\n"; + + // NODE DATA + char labels[1024]; + char units[1024]; + strcpy(labels, ""); + strcpy(units, ""); + + for (int d = 0; d < nofNodeData - 1; ++d) { + strcat(labels, datanames[d].c_str()); + strcat(labels, "."); + } + strcat(labels, datanames[nofNodeData - 1].c_str()); + + for (int i = 0; i < (nofNodeData - 1); i++) + strcat(units, "no_unit."); + strcat(units, "no_unit"); + + out.write((char *)&labels, sizeof(labels)); + out.write((char *)&units, sizeof(units)); + + // nof and type of data + idummy = nofNodeData; + out.write((char *)&idummy, sizeof(int)); // Datentypen pro knoten (hier = nof_node_data, da NUR skalare) + + idummy = 1; + for (int i = 0; i < nofNodeData; i++) + out.write((char *)&idummy, sizeof(int)); // jeder Datentyp ist ein skalarer Wert + + // min and max of data + fdummy = 0.0; + for (int i = 0; i < nofNodeData; i++) + out.write((char *)&fdummy, sizeof(float)); // min Wert pro Datentyp + fdummy = 1.0; + for (int i = 0; i < nofNodeData; i++) + out.write((char *)&fdummy, sizeof(float)); // max Wert pro Datentyp + + // daten ins file schreiben + for (int d = 0; d < nofNodeData; ++d) + for (int n = 0; n < (int)nodedata[d].size(); n++) { + fdummy = (float)nodedata[d][n]; + out.write((char *)&fdummy, sizeof(float)); + } + + fdummy = 1.; + for (int i = 0; i < nofNodeData; i++) + out.write((char *)&fdummy, sizeof(float)); // max Wert pro Datentyp + + out.close(); + UBLOG(logDEBUG1, "WbWriterAvsBinary::writeQuadsWithNodeData to " << avsfilename << " - end"); + + return avsfilename; } /*===============================================================================*/ -std::string WbWriterAvsBinary::writeQuadsWithCellData(const string& filename,vector< UbTupleFloat3 >& nodes, vector< UbTupleInt4 >& cells, vector< string >& datanames, vector< vector< double > >& celldata) +std::string WbWriterAvsBinary::writeQuadsWithCellData(const string &filename, vector<UbTupleFloat3> &nodes, + vector<UbTupleInt4> &cells, vector<string> &datanames, + vector<vector<double>> &celldata) { - string avsfilename = filename+getFileExtension(); - UBLOG(logDEBUG1,"WbWriterAvsBinary::writeQuadsWithCellData to "<<avsfilename<<" - start"); - - ofstream out(avsfilename.c_str(),ios::out|ios::binary); - if(!out) - { - out.clear(); //flags ruecksetzen (ansonsten liefert utern if(!outfile) weiterhin true!!! - string path = UbSystem::getPathFromString(avsfilename); - if(path.size()>0){UbSystem::makeDirectory(path);out.open(avsfilename.c_str(),ios::out|ios::binary);} - if(!out) throw UbException(UB_EXARGS,avsfilename+" konnte nicht geschrieben werden"); - } - - char magic = (char)7; - int idummy; - float fdummy; - - int nofNodes = (int)nodes.size(); - int nofCells = (int)cells.size(); - - int nofNodeData = 0; - int nofCellData = (int)datanames.size(); - int nofModelData = 0; - int cellType = 3; //=quad - int nofNodesPerCell = 4; - - out.write((char*)&magic,sizeof(char)); - out.write((char*)&nofNodes,sizeof(int)); - out.write((char*)&nofCells,sizeof(int)); - out.write((char*)&nofNodeData,sizeof(int)); - out.write((char*)&nofCellData,sizeof(int)); - out.write((char*)&nofModelData,sizeof(int)); - - idummy = (int)nofCells*nofNodesPerCell; - out.write((char*)&idummy,sizeof(int)); //(nof nodes) * (nodes per cell) - for(int c=0; c<nofCells; c++) - { - idummy=c+1; out.write((char*)&idummy,sizeof(int)); //cell id - idummy=1; out.write((char*)&idummy,sizeof(int)); //mat - idummy=nofNodesPerCell; out.write((char*)&idummy,sizeof(int)); //nodes per cell - idummy=cellType; out.write((char*)&idummy,sizeof(int)); //cell type - } - //knotennummern der einzelnen zellen - for(int c=0; c<nofCells; c++) - { - idummy = val<1>(cells[c])+1; out.write((char*)&idummy,sizeof(int)); - idummy = val<2>(cells[c])+1; out.write((char*)&idummy,sizeof(int)); - idummy = val<3>(cells[c])+1; out.write((char*)&idummy,sizeof(int)); - idummy = val<4>(cells[c])+1; out.write((char*)&idummy,sizeof(int)); - } - - //coords - //x1-coords - for(int n=0; n<nofNodes; n++) - { fdummy = (float)( val<1>(nodes[n]) ); out.write((char*)&fdummy ,sizeof(float)); } - //x2-coords - for(int n=0; n<nofNodes; n++) - { fdummy = (float)( val<2>(nodes[n]) ); out.write((char*)&fdummy ,sizeof(float)); } - //x3-coords - fdummy=0.0; - for(int n=0; n<nofNodes; n++) - { fdummy = (float)( val<3>(nodes[n]) ); out.write((char*)&fdummy ,sizeof(float)); } - //out<<"\n"; - - //CELL DATA - char labels[1024]; - char units[1024]; - strcpy(labels, ""); - strcpy(units, ""); - - for(int d=0; d<nofCellData-1; ++d) { strcat(labels, datanames[d].c_str() ); strcat(labels,"."); } - strcat(labels, datanames[nofCellData-1].c_str()); - - for(int d=0; d<nofCellData-1; ++d) strcat(units, "no_unit."); - strcat(units, "no_unit"); - - out.write((char*)&labels,sizeof(labels)); - out.write((char*)&units,sizeof(units)); - - //nof and type of data - idummy = nofCellData; - out.write((char*)&idummy,sizeof(int)); //Datentypen pro knoten (hier = nof_node_data, da NUR skalare) - - idummy = 1; - for(int i=0;i<nofCellData;i++) out.write((char*)&idummy,sizeof(int)); //jeder Datentyp ist ein skalarer Wert - - //min and max of data - fdummy = 0.0; - for(int i=0;i<nofCellData;i++) out.write((char*)&fdummy,sizeof(float)); //min Wert pro Datentyp - fdummy = 1.0; - for(int i=0;i<nofCellData;i++) out.write((char*)&fdummy,sizeof(float)); //max Wert pro Datentyp - - //daten ins file schreiben - for(int d=0; d<nofCellData; ++d) - for(int n=0; n<(int)celldata[d].size(); n++) - { fdummy=(float)celldata[d][n]; out.write((char*)&fdummy,sizeof(float)); } - - fdummy = 1.; - for(int i=0;i<nofCellData;i++) out.write((char*)&fdummy,sizeof(float)); //max Wert pro Datentyp - - out.close(); - UBLOG(logDEBUG1,"WbWriterAvsBinary::writeQuadsWithCellData to "<<avsfilename<<" - end"); - - return avsfilename; + string avsfilename = filename + getFileExtension(); + UBLOG(logDEBUG1, "WbWriterAvsBinary::writeQuadsWithCellData to " << avsfilename << " - start"); + + ofstream out(avsfilename.c_str(), ios::out | ios::binary); + if (!out) { + out.clear(); // flags ruecksetzen (ansonsten liefert utern if(!outfile) weiterhin true!!! + string path = UbSystem::getPathFromString(avsfilename); + if (path.size() > 0) { + UbSystem::makeDirectory(path); + out.open(avsfilename.c_str(), ios::out | ios::binary); + } + if (!out) + throw UbException(UB_EXARGS, avsfilename + " konnte nicht geschrieben werden"); + } + + char magic = (char)7; + int idummy; + float fdummy; + + int nofNodes = (int)nodes.size(); + int nofCells = (int)cells.size(); + + int nofNodeData = 0; + int nofCellData = (int)datanames.size(); + int nofModelData = 0; + int cellType = 3; //=quad + int nofNodesPerCell = 4; + + out.write((char *)&magic, sizeof(char)); + out.write((char *)&nofNodes, sizeof(int)); + out.write((char *)&nofCells, sizeof(int)); + out.write((char *)&nofNodeData, sizeof(int)); + out.write((char *)&nofCellData, sizeof(int)); + out.write((char *)&nofModelData, sizeof(int)); + + idummy = (int)nofCells * nofNodesPerCell; + out.write((char *)&idummy, sizeof(int)); //(nof nodes) * (nodes per cell) + for (int c = 0; c < nofCells; c++) { + idummy = c + 1; + out.write((char *)&idummy, sizeof(int)); // cell id + idummy = 1; + out.write((char *)&idummy, sizeof(int)); // mat + idummy = nofNodesPerCell; + out.write((char *)&idummy, sizeof(int)); // nodes per cell + idummy = cellType; + out.write((char *)&idummy, sizeof(int)); // cell type + } + // knotennummern der einzelnen zellen + for (int c = 0; c < nofCells; c++) { + idummy = val<1>(cells[c]) + 1; + out.write((char *)&idummy, sizeof(int)); + idummy = val<2>(cells[c]) + 1; + out.write((char *)&idummy, sizeof(int)); + idummy = val<3>(cells[c]) + 1; + out.write((char *)&idummy, sizeof(int)); + idummy = val<4>(cells[c]) + 1; + out.write((char *)&idummy, sizeof(int)); + } + + // coords + // x1-coords + for (int n = 0; n < nofNodes; n++) { + fdummy = (float)(val<1>(nodes[n])); + out.write((char *)&fdummy, sizeof(float)); + } + // x2-coords + for (int n = 0; n < nofNodes; n++) { + fdummy = (float)(val<2>(nodes[n])); + out.write((char *)&fdummy, sizeof(float)); + } + // x3-coords + fdummy = 0.0; + for (int n = 0; n < nofNodes; n++) { + fdummy = (float)(val<3>(nodes[n])); + out.write((char *)&fdummy, sizeof(float)); + } + // out<<"\n"; + + // CELL DATA + char labels[1024]; + char units[1024]; + strcpy(labels, ""); + strcpy(units, ""); + + for (int d = 0; d < nofCellData - 1; ++d) { + strcat(labels, datanames[d].c_str()); + strcat(labels, "."); + } + strcat(labels, datanames[nofCellData - 1].c_str()); + + for (int d = 0; d < nofCellData - 1; ++d) + strcat(units, "no_unit."); + strcat(units, "no_unit"); + + out.write((char *)&labels, sizeof(labels)); + out.write((char *)&units, sizeof(units)); + + // nof and type of data + idummy = nofCellData; + out.write((char *)&idummy, sizeof(int)); // Datentypen pro knoten (hier = nof_node_data, da NUR skalare) + + idummy = 1; + for (int i = 0; i < nofCellData; i++) + out.write((char *)&idummy, sizeof(int)); // jeder Datentyp ist ein skalarer Wert + + // min and max of data + fdummy = 0.0; + for (int i = 0; i < nofCellData; i++) + out.write((char *)&fdummy, sizeof(float)); // min Wert pro Datentyp + fdummy = 1.0; + for (int i = 0; i < nofCellData; i++) + out.write((char *)&fdummy, sizeof(float)); // max Wert pro Datentyp + + // daten ins file schreiben + for (int d = 0; d < nofCellData; ++d) + for (int n = 0; n < (int)celldata[d].size(); n++) { + fdummy = (float)celldata[d][n]; + out.write((char *)&fdummy, sizeof(float)); + } + + fdummy = 1.; + for (int i = 0; i < nofCellData; i++) + out.write((char *)&fdummy, sizeof(float)); // max Wert pro Datentyp + + out.close(); + UBLOG(logDEBUG1, "WbWriterAvsBinary::writeQuadsWithCellData to " << avsfilename << " - end"); + + return avsfilename; } /*===============================================================================*/ -std::string WbWriterAvsBinary::writeQuadsWithNodeAndCellData(const string& filename,vector< UbTupleFloat3 >& nodes, vector< UbTupleInt4 >& cells, vector< string >& nodedatanames, vector< vector< double > >& nodedata, vector< string >& celldatanames, vector< vector< double > >& celldata) +std::string WbWriterAvsBinary::writeQuadsWithNodeAndCellData(const string &filename, vector<UbTupleFloat3> &nodes, + vector<UbTupleInt4> &cells, vector<string> &nodedatanames, + vector<vector<double>> &nodedata, + vector<string> &celldatanames, + vector<vector<double>> &celldata) { - string avsfilename = filename+getFileExtension(); - UBLOG(logDEBUG1,"WbWriterAvsBinary::writeQuadsWithNodeAndCellData to "<<avsfilename<<" - start"); - - ofstream out(avsfilename.c_str(),ios::out|ios::binary); - if(!out) - { - out.clear(); //flags ruecksetzen (ansonsten liefert utern if(!outfile) weiterhin true!!! - string path = UbSystem::getPathFromString(avsfilename); - if(path.size()>0){UbSystem::makeDirectory(path);out.open(avsfilename.c_str(),ios::out|ios::binary);} - if(!out) throw UbException(UB_EXARGS,avsfilename+" konnte nicht geschrieben werden"); - } - - char magic = (char)7; - int idummy; - float fdummy; - - int nofNodes = (int)nodes.size(); - int nofCells = (int)cells.size(); - - int nofNodeData = (int)nodedatanames.size(); - int nofCellData = (int)celldatanames.size(); - int nofModelData = 0; - int cellType = 3; //=quad - int nofNodesPerCell = 4; - - out.write((char*)&magic,sizeof(char)); - out.write((char*)&nofNodes,sizeof(int)); - out.write((char*)&nofCells,sizeof(int)); - out.write((char*)&nofNodeData,sizeof(int)); - out.write((char*)&nofCellData,sizeof(int)); - out.write((char*)&nofModelData,sizeof(int)); - - idummy = (int)nofCells*nofNodesPerCell; - out.write((char*)&idummy,sizeof(int)); //(nof nodes) * (nodes per cell) - for(int c=0; c<nofCells; c++) - { - idummy=c+1; out.write((char*)&idummy,sizeof(int)); //cell id - idummy=1; out.write((char*)&idummy,sizeof(int)); //mat - idummy=nofNodesPerCell; out.write((char*)&idummy,sizeof(int)); //nodes per cell - idummy=cellType; out.write((char*)&idummy,sizeof(int)); //cell type - } - //knotennummern der einzelnen zellen - for(int c=0; c<nofCells; c++) - { - idummy = val<1>(cells[c])+1; out.write((char*)&idummy,sizeof(int)); - idummy = val<2>(cells[c])+1; out.write((char*)&idummy,sizeof(int)); - idummy = val<3>(cells[c])+1; out.write((char*)&idummy,sizeof(int)); - idummy = val<4>(cells[c])+1; out.write((char*)&idummy,sizeof(int)); - } - - //coords - //x1-coords - for(int n=0; n<nofNodes; n++) - { fdummy = (float)( val<1>(nodes[n]) ); out.write((char*)&fdummy ,sizeof(float)); } - //x2-coords - for(int n=0; n<nofNodes; n++) - { fdummy = (float)( val<2>(nodes[n]) ); out.write((char*)&fdummy ,sizeof(float)); } - //x3-coords - for(int n=0; n<nofNodes; n++) - { fdummy = (float)( val<3>(nodes[n]) ); out.write((char*)&fdummy ,sizeof(float)); } - //out<<"\n"; - - //NODE DATA - char nodelabels[1024]; - char nodeunits[1024]; - strcpy(nodelabels, ""); - strcpy(nodeunits, ""); - - for(int d=0; d<nofNodeData-1; ++d) { strcat(nodelabels, nodedatanames[d].c_str() ); strcat(nodelabels,"."); } - strcat(nodelabels, nodedatanames[nofNodeData-1].c_str()); - - for(int i=0;i<(nofNodeData-1);i++) strcat(nodeunits, "no_unit."); - strcat(nodeunits, "no_unit"); - - out.write((char*)&nodelabels,sizeof(nodelabels)); - out.write((char*)&nodeunits,sizeof(nodeunits)); - - //nof and type of data - idummy = nofNodeData; - out.write((char*)&idummy,sizeof(int)); //Datentypen pro knoten (hier = nof_node_data, da NUR skalare) - - idummy = 1; - for(int i=0;i<nofNodeData;i++) out.write((char*)&idummy,sizeof(int)); //jeder Datentyp ist ein skalarer Wert - - //min and max of data - fdummy = 0.0; - for(int i=0;i<nofNodeData;i++) out.write((char*)&fdummy,sizeof(float)); //min Wert pro Datentyp - fdummy = 1.0; - for(int i=0;i<nofNodeData;i++) out.write((char*)&fdummy,sizeof(float)); //max Wert pro Datentyp - - //daten ins file schreiben - for(int d=0; d<nofNodeData; ++d) - for(int n=0; n<(int)nodedata[d].size(); n++) - { fdummy=(float)nodedata[d][n]; out.write((char*)&fdummy,sizeof(float)); } - - fdummy = 1.; - for(int i=0;i<nofNodeData;i++) out.write((char*)&fdummy,sizeof(float)); //max Wert pro Datentyp - - //CELL DATA - char celllabels[1024]; - char cellunits[1024]; - strcpy(celllabels, ""); - strcpy(cellunits, ""); - - for(int d=0; d<nofCellData-1; ++d) { strcat(celllabels, celldatanames[d].c_str() ); strcat(celllabels,"."); } - strcat(celllabels, celldatanames[nofCellData-1].c_str()); - - for(int d=0; d<nofCellData-1; ++d) strcat(cellunits, "no_unit."); - strcat(cellunits, "no_unit"); - - out.write((char*)&celllabels,sizeof(celllabels)); - out.write((char*)&cellunits,sizeof(cellunits)); - - //nof and type of data - idummy = nofCellData; - out.write((char*)&idummy,sizeof(int)); //Datentypen pro knoten (hier = nof_node_data, da NUR skalare) - - idummy = 1; - for(int i=0;i<nofCellData;i++) out.write((char*)&idummy,sizeof(int)); //jeder Datentyp ist ein skalarer Wert - - //min and max of data - fdummy = 0.0; - for(int i=0;i<nofCellData;i++) out.write((char*)&fdummy,sizeof(float)); //min Wert pro Datentyp - fdummy = 1.0; - for(int i=0;i<nofCellData;i++) out.write((char*)&fdummy,sizeof(float)); //max Wert pro Datentyp - - //daten ins file schreiben - for(int d=0; d<nofCellData; ++d) - for(int n=0; n<(int)celldata[d].size(); n++) - { fdummy=(float)celldata[d][n]; out.write((char*)&fdummy,sizeof(float)); } - - fdummy = 1.; - for(int i=0;i<nofCellData;i++) out.write((char*)&fdummy,sizeof(float)); //max Wert pro Datentyp - - out.close(); - UBLOG(logDEBUG1,"WbWriterAvsBinary::writeQuadsWithNodeAndCellData to "<<avsfilename<<" - end"); - - return avsfilename; + string avsfilename = filename + getFileExtension(); + UBLOG(logDEBUG1, "WbWriterAvsBinary::writeQuadsWithNodeAndCellData to " << avsfilename << " - start"); + + ofstream out(avsfilename.c_str(), ios::out | ios::binary); + if (!out) { + out.clear(); // flags ruecksetzen (ansonsten liefert utern if(!outfile) weiterhin true!!! + string path = UbSystem::getPathFromString(avsfilename); + if (path.size() > 0) { + UbSystem::makeDirectory(path); + out.open(avsfilename.c_str(), ios::out | ios::binary); + } + if (!out) + throw UbException(UB_EXARGS, avsfilename + " konnte nicht geschrieben werden"); + } + + char magic = (char)7; + int idummy; + float fdummy; + + int nofNodes = (int)nodes.size(); + int nofCells = (int)cells.size(); + + int nofNodeData = (int)nodedatanames.size(); + int nofCellData = (int)celldatanames.size(); + int nofModelData = 0; + int cellType = 3; //=quad + int nofNodesPerCell = 4; + + out.write((char *)&magic, sizeof(char)); + out.write((char *)&nofNodes, sizeof(int)); + out.write((char *)&nofCells, sizeof(int)); + out.write((char *)&nofNodeData, sizeof(int)); + out.write((char *)&nofCellData, sizeof(int)); + out.write((char *)&nofModelData, sizeof(int)); + + idummy = (int)nofCells * nofNodesPerCell; + out.write((char *)&idummy, sizeof(int)); //(nof nodes) * (nodes per cell) + for (int c = 0; c < nofCells; c++) { + idummy = c + 1; + out.write((char *)&idummy, sizeof(int)); // cell id + idummy = 1; + out.write((char *)&idummy, sizeof(int)); // mat + idummy = nofNodesPerCell; + out.write((char *)&idummy, sizeof(int)); // nodes per cell + idummy = cellType; + out.write((char *)&idummy, sizeof(int)); // cell type + } + // knotennummern der einzelnen zellen + for (int c = 0; c < nofCells; c++) { + idummy = val<1>(cells[c]) + 1; + out.write((char *)&idummy, sizeof(int)); + idummy = val<2>(cells[c]) + 1; + out.write((char *)&idummy, sizeof(int)); + idummy = val<3>(cells[c]) + 1; + out.write((char *)&idummy, sizeof(int)); + idummy = val<4>(cells[c]) + 1; + out.write((char *)&idummy, sizeof(int)); + } + + // coords + // x1-coords + for (int n = 0; n < nofNodes; n++) { + fdummy = (float)(val<1>(nodes[n])); + out.write((char *)&fdummy, sizeof(float)); + } + // x2-coords + for (int n = 0; n < nofNodes; n++) { + fdummy = (float)(val<2>(nodes[n])); + out.write((char *)&fdummy, sizeof(float)); + } + // x3-coords + for (int n = 0; n < nofNodes; n++) { + fdummy = (float)(val<3>(nodes[n])); + out.write((char *)&fdummy, sizeof(float)); + } + // out<<"\n"; + + // NODE DATA + char nodelabels[1024]; + char nodeunits[1024]; + strcpy(nodelabels, ""); + strcpy(nodeunits, ""); + + for (int d = 0; d < nofNodeData - 1; ++d) { + strcat(nodelabels, nodedatanames[d].c_str()); + strcat(nodelabels, "."); + } + strcat(nodelabels, nodedatanames[nofNodeData - 1].c_str()); + + for (int i = 0; i < (nofNodeData - 1); i++) + strcat(nodeunits, "no_unit."); + strcat(nodeunits, "no_unit"); + + out.write((char *)&nodelabels, sizeof(nodelabels)); + out.write((char *)&nodeunits, sizeof(nodeunits)); + + // nof and type of data + idummy = nofNodeData; + out.write((char *)&idummy, sizeof(int)); // Datentypen pro knoten (hier = nof_node_data, da NUR skalare) + + idummy = 1; + for (int i = 0; i < nofNodeData; i++) + out.write((char *)&idummy, sizeof(int)); // jeder Datentyp ist ein skalarer Wert + + // min and max of data + fdummy = 0.0; + for (int i = 0; i < nofNodeData; i++) + out.write((char *)&fdummy, sizeof(float)); // min Wert pro Datentyp + fdummy = 1.0; + for (int i = 0; i < nofNodeData; i++) + out.write((char *)&fdummy, sizeof(float)); // max Wert pro Datentyp + + // daten ins file schreiben + for (int d = 0; d < nofNodeData; ++d) + for (int n = 0; n < (int)nodedata[d].size(); n++) { + fdummy = (float)nodedata[d][n]; + out.write((char *)&fdummy, sizeof(float)); + } + + fdummy = 1.; + for (int i = 0; i < nofNodeData; i++) + out.write((char *)&fdummy, sizeof(float)); // max Wert pro Datentyp + + // CELL DATA + char celllabels[1024]; + char cellunits[1024]; + strcpy(celllabels, ""); + strcpy(cellunits, ""); + + for (int d = 0; d < nofCellData - 1; ++d) { + strcat(celllabels, celldatanames[d].c_str()); + strcat(celllabels, "."); + } + strcat(celllabels, celldatanames[nofCellData - 1].c_str()); + + for (int d = 0; d < nofCellData - 1; ++d) + strcat(cellunits, "no_unit."); + strcat(cellunits, "no_unit"); + + out.write((char *)&celllabels, sizeof(celllabels)); + out.write((char *)&cellunits, sizeof(cellunits)); + + // nof and type of data + idummy = nofCellData; + out.write((char *)&idummy, sizeof(int)); // Datentypen pro knoten (hier = nof_node_data, da NUR skalare) + + idummy = 1; + for (int i = 0; i < nofCellData; i++) + out.write((char *)&idummy, sizeof(int)); // jeder Datentyp ist ein skalarer Wert + + // min and max of data + fdummy = 0.0; + for (int i = 0; i < nofCellData; i++) + out.write((char *)&fdummy, sizeof(float)); // min Wert pro Datentyp + fdummy = 1.0; + for (int i = 0; i < nofCellData; i++) + out.write((char *)&fdummy, sizeof(float)); // max Wert pro Datentyp + + // daten ins file schreiben + for (int d = 0; d < nofCellData; ++d) + for (int n = 0; n < (int)celldata[d].size(); n++) { + fdummy = (float)celldata[d][n]; + out.write((char *)&fdummy, sizeof(float)); + } + + fdummy = 1.; + for (int i = 0; i < nofCellData; i++) + out.write((char *)&fdummy, sizeof(float)); // max Wert pro Datentyp + + out.close(); + UBLOG(logDEBUG1, "WbWriterAvsBinary::writeQuadsWithNodeAndCellData to " << avsfilename << " - end"); + + return avsfilename; } /*===============================================================================*/ -std::string WbWriterAvsBinary::writeOctsWithCellData(const string& filename,vector<UbTupleFloat3 >& nodes, vector<UbTupleInt8 >& cells, vector<string >& datanames, vector<vector<double > >& celldata) +std::string WbWriterAvsBinary::writeOctsWithCellData(const string &filename, vector<UbTupleFloat3> &nodes, + vector<UbTupleInt8> &cells, vector<string> &datanames, + vector<vector<double>> &celldata) { - string avsfilename = filename+getFileExtension(); - UBLOG(logDEBUG1,"WbWriterAvsBinary::writeOctsWithCellData to "<<avsfilename<<" - start"); - - ofstream out(avsfilename.c_str(),ios::out|ios::binary); - if(!out) - { - out.clear(); //flags ruecksetzen (ansonsten liefert utern if(!outfile) weiterhin true!!! - string path = UbSystem::getPathFromString(avsfilename); - if(path.size()>0){UbSystem::makeDirectory(path);out.open(avsfilename.c_str(),ios::out|ios::binary);} - if(!out) throw UbException(UB_EXARGS,"file konnte nicht geschrieben werden"); + string avsfilename = filename + getFileExtension(); + UBLOG(logDEBUG1, "WbWriterAvsBinary::writeOctsWithCellData to " << avsfilename << " - start"); + + ofstream out(avsfilename.c_str(), ios::out | ios::binary); + if (!out) { + out.clear(); // flags ruecksetzen (ansonsten liefert utern if(!outfile) weiterhin true!!! + string path = UbSystem::getPathFromString(avsfilename); + if (path.size() > 0) { + UbSystem::makeDirectory(path); + out.open(avsfilename.c_str(), ios::out | ios::binary); + } + if (!out) + throw UbException(UB_EXARGS, "file konnte nicht geschrieben werden"); } char magic = (char)7; - int idummy; + int idummy; float fdummy; int nofNodes = (int)nodes.size(); @@ -778,110 +965,143 @@ std::string WbWriterAvsBinary::writeOctsWithCellData(const string& filename,vect int nofCellData = (int)datanames.size(); int nofModelData = 0; int cellType = 7; //=hex - int nofNodesPerCell = 8; - - out.write((char*)&magic,sizeof(char)); - out.write((char*)&nofNodes,sizeof(int)); - out.write((char*)&nofCells,sizeof(int)); - out.write((char*)&nofNodeData,sizeof(int)); - out.write((char*)&nofCellData,sizeof(int)); - out.write((char*)&nofModelData,sizeof(int)); - - idummy = (int)nofCells*nofNodesPerCell; - out.write((char*)&idummy,sizeof(int)); //(nof nodes) * (nodes per cell) - for(int c=0; c<nofCells; c++) - { - idummy=c+1; out.write((char*)&idummy,sizeof(int)); //cell id - idummy=1; out.write((char*)&idummy,sizeof(int)); //mat - idummy=nofNodesPerCell; out.write((char*)&idummy,sizeof(int)); //nodes per cell - idummy=cellType; out.write((char*)&idummy,sizeof(int)); //cell type - } - //knotennummern der einzelnen zellen - for(int c=0; c<nofCells; c++) - { - idummy = val<1>(cells[c])+1; out.write((char*)&idummy,sizeof(int)); - idummy = val<2>(cells[c])+1; out.write((char*)&idummy,sizeof(int)); - idummy = val<3>(cells[c])+1; out.write((char*)&idummy,sizeof(int)); - idummy = val<4>(cells[c])+1; out.write((char*)&idummy,sizeof(int)); - idummy = val<5>(cells[c])+1; out.write((char*)&idummy,sizeof(int)); - idummy = val<6>(cells[c])+1; out.write((char*)&idummy,sizeof(int)); - idummy = val<7>(cells[c])+1; out.write((char*)&idummy,sizeof(int)); - idummy = val<8>(cells[c])+1; out.write((char*)&idummy,sizeof(int)); - } - - //coords - //x1-coords - for(int n=0; n<nofNodes; n++) - { fdummy = (float)( val<1>(nodes[n]) ); out.write((char*)&fdummy ,sizeof(float)); } - //x2-coords - for(int n=0; n<nofNodes; n++) - { fdummy = (float)( val<2>(nodes[n]) ); out.write((char*)&fdummy ,sizeof(float)); } - //x3-coords - for(int n=0; n<nofNodes; n++) - { fdummy = (float)( val<3>(nodes[n]) ); out.write((char*)&fdummy ,sizeof(float)); } - //out<<"\n"; - - //CELL DATA + int nofNodesPerCell = 8; + + out.write((char *)&magic, sizeof(char)); + out.write((char *)&nofNodes, sizeof(int)); + out.write((char *)&nofCells, sizeof(int)); + out.write((char *)&nofNodeData, sizeof(int)); + out.write((char *)&nofCellData, sizeof(int)); + out.write((char *)&nofModelData, sizeof(int)); + + idummy = (int)nofCells * nofNodesPerCell; + out.write((char *)&idummy, sizeof(int)); //(nof nodes) * (nodes per cell) + for (int c = 0; c < nofCells; c++) { + idummy = c + 1; + out.write((char *)&idummy, sizeof(int)); // cell id + idummy = 1; + out.write((char *)&idummy, sizeof(int)); // mat + idummy = nofNodesPerCell; + out.write((char *)&idummy, sizeof(int)); // nodes per cell + idummy = cellType; + out.write((char *)&idummy, sizeof(int)); // cell type + } + // knotennummern der einzelnen zellen + for (int c = 0; c < nofCells; c++) { + idummy = val<1>(cells[c]) + 1; + out.write((char *)&idummy, sizeof(int)); + idummy = val<2>(cells[c]) + 1; + out.write((char *)&idummy, sizeof(int)); + idummy = val<3>(cells[c]) + 1; + out.write((char *)&idummy, sizeof(int)); + idummy = val<4>(cells[c]) + 1; + out.write((char *)&idummy, sizeof(int)); + idummy = val<5>(cells[c]) + 1; + out.write((char *)&idummy, sizeof(int)); + idummy = val<6>(cells[c]) + 1; + out.write((char *)&idummy, sizeof(int)); + idummy = val<7>(cells[c]) + 1; + out.write((char *)&idummy, sizeof(int)); + idummy = val<8>(cells[c]) + 1; + out.write((char *)&idummy, sizeof(int)); + } + + // coords + // x1-coords + for (int n = 0; n < nofNodes; n++) { + fdummy = (float)(val<1>(nodes[n])); + out.write((char *)&fdummy, sizeof(float)); + } + // x2-coords + for (int n = 0; n < nofNodes; n++) { + fdummy = (float)(val<2>(nodes[n])); + out.write((char *)&fdummy, sizeof(float)); + } + // x3-coords + for (int n = 0; n < nofNodes; n++) { + fdummy = (float)(val<3>(nodes[n])); + out.write((char *)&fdummy, sizeof(float)); + } + // out<<"\n"; + + // CELL DATA char labels[1024]; char units[1024]; strcpy(labels, ""); strcpy(units, ""); - for(int d=0; d<nofCellData-1; ++d) { strcat(labels, datanames[d].c_str() ); strcat(labels,"."); } - strcat(labels, datanames[nofCellData-1].c_str()); + for (int d = 0; d < nofCellData - 1; ++d) { + strcat(labels, datanames[d].c_str()); + strcat(labels, "."); + } + strcat(labels, datanames[nofCellData - 1].c_str()); - for(int d=0; d<nofCellData-1; ++d) strcat(units, "no_unit."); + for (int d = 0; d < nofCellData - 1; ++d) + strcat(units, "no_unit."); strcat(units, "no_unit"); - out.write((char*)&labels,sizeof(labels)); - out.write((char*)&units,sizeof(units)); + out.write((char *)&labels, sizeof(labels)); + out.write((char *)&units, sizeof(units)); - //nof and type of data + // nof and type of data idummy = nofCellData; - out.write((char*)&idummy,sizeof(int)); //Datentypen pro knoten (hier = nof_node_data, da NUR skalare) + out.write((char *)&idummy, sizeof(int)); // Datentypen pro knoten (hier = nof_node_data, da NUR skalare) idummy = 1; - for(int i=0;i<nofCellData;i++) out.write((char*)&idummy,sizeof(int)); //jeder Datentyp ist ein skalarer Wert + for (int i = 0; i < nofCellData; i++) + out.write((char *)&idummy, sizeof(int)); // jeder Datentyp ist ein skalarer Wert - //min and max of data + // min and max of data fdummy = 0.0; - for(int i=0;i<nofCellData;i++) out.write((char*)&fdummy,sizeof(float)); //min Wert pro Datentyp + for (int i = 0; i < nofCellData; i++) + out.write((char *)&fdummy, sizeof(float)); // min Wert pro Datentyp fdummy = 1.0; - for(int i=0;i<nofCellData;i++) out.write((char*)&fdummy,sizeof(float)); //max Wert pro Datentyp + for (int i = 0; i < nofCellData; i++) + out.write((char *)&fdummy, sizeof(float)); // max Wert pro Datentyp - //daten ins file schreiben - for(int d=0; d<nofCellData; ++d) - for(int n=0; n<(int)celldata[d].size(); n++) - { fdummy=(float)celldata[d][n]; out.write((char*)&fdummy,sizeof(float)); } + // daten ins file schreiben + for (int d = 0; d < nofCellData; ++d) + for (int n = 0; n < (int)celldata[d].size(); n++) { + fdummy = (float)celldata[d][n]; + out.write((char *)&fdummy, sizeof(float)); + } fdummy = 1.; - for(int i=0;i<nofCellData;i++) out.write((char*)&fdummy,sizeof(float)); //max Wert pro Datentyp + for (int i = 0; i < nofCellData; i++) + out.write((char *)&fdummy, sizeof(float)); // max Wert pro Datentyp - out.close(); - UBLOG(logDEBUG1,"WbWriterAvsBinary::writeOctsWithCellData to "<<avsfilename<<" - end"); + out.close(); + UBLOG(logDEBUG1, "WbWriterAvsBinary::writeOctsWithCellData to " << avsfilename << " - end"); return avsfilename; - } +} /*===============================================================================*/ -std::string WbWriterAvsBinary::writeOctsWithNodeData(const string& filename,vector<UbTupleFloat3 >& nodes, vector<UbTupleUInt8 >& cells, vector<string >& datanames, vector<vector<double > >& nodedata) +std::string WbWriterAvsBinary::writeOctsWithNodeData(const string &filename, vector<UbTupleFloat3> &nodes, + vector<UbTupleUInt8> &cells, vector<string> &datanames, + vector<vector<double>> &nodedata) { - string avsfilename = filename+getFileExtension(); - UBLOG(logDEBUG1,"WbWriterAvsBinary::writeOctsWithNodeData to "<<avsfilename<<" - start"); - - ofstream out(avsfilename.c_str(),ios::out|ios::binary); - if(!out) - { - out.clear(); //flags ruecksetzen (ansonsten liefert utern if(!outfile) weiterhin true!!! - string path = UbSystem::getPathFromString(avsfilename); - if(path.size()>0){UbSystem::makeDirectory(path);out.open(avsfilename.c_str(),ios::out|ios::binary);} - if(!out) throw UbException(UB_EXARGS,"file konnte nicht geschrieben werden"); + string avsfilename = filename + getFileExtension(); + UBLOG(logDEBUG1, "WbWriterAvsBinary::writeOctsWithNodeData to " << avsfilename << " - start"); + + ofstream out(avsfilename.c_str(), ios::out | ios::binary); + if (!out) { + out.clear(); // flags ruecksetzen (ansonsten liefert utern if(!outfile) weiterhin true!!! + string path = UbSystem::getPathFromString(avsfilename); + if (path.size() > 0) { + UbSystem::makeDirectory(path); + out.open(avsfilename.c_str(), ios::out | ios::binary); + } + if (!out) + throw UbException(UB_EXARGS, "file konnte nicht geschrieben werden"); } - if((int)nodedata.size()==0) throw UbException(UB_EXARGS,"no nodedata!!!"); - if(nodes.size()!=nodedata[0].size()) throw UbException(UB_EXARGS,"nodedata != nofNodes!!!"); + if ((int)nodedata.size() == 0) + throw UbException(UB_EXARGS, "no nodedata!!!"); + if (nodes.size() != nodedata[0].size()) + throw UbException(UB_EXARGS, "nodedata != nofNodes!!!"); char magic = (char)7; - int idummy; + int idummy; float fdummy; int nofNodes = (int)nodes.size(); @@ -891,87 +1111,112 @@ std::string WbWriterAvsBinary::writeOctsWithNodeData(const string& filename,vect int nofCellData = 0; int nofModelData = 0; int cellType = 7; //=hex - int nofNodesPerCell = 8; - - out.write((char*)&magic,sizeof(char)); - out.write((char*)&nofNodes,sizeof(int)); - out.write((char*)&nofCells,sizeof(int)); - out.write((char*)&nofNodeData,sizeof(int)); - out.write((char*)&nofCellData,sizeof(int)); - out.write((char*)&nofModelData,sizeof(int)); - - idummy = (int)nofCells*nofNodesPerCell; - out.write((char*)&idummy,sizeof(int)); //(nof nodes) * (nodes per cell) - for(int c=0; c<nofCells; c++) - { - idummy=c+1; out.write((char*)&idummy,sizeof(int)); //cell id - idummy=1; out.write((char*)&idummy,sizeof(int)); //mat - idummy=nofNodesPerCell; out.write((char*)&idummy,sizeof(int)); //nodes per cell - idummy=cellType; out.write((char*)&idummy,sizeof(int)); //cell type - } - //knotennummern der einzelnen zellen - for(int c=0; c<nofCells; c++) - { - idummy = val<1>(cells[c])+1; out.write((char*)&idummy,sizeof(int)); - idummy = val<2>(cells[c])+1; out.write((char*)&idummy,sizeof(int)); - idummy = val<3>(cells[c])+1; out.write((char*)&idummy,sizeof(int)); - idummy = val<4>(cells[c])+1; out.write((char*)&idummy,sizeof(int)); - idummy = val<5>(cells[c])+1; out.write((char*)&idummy,sizeof(int)); - idummy = val<6>(cells[c])+1; out.write((char*)&idummy,sizeof(int)); - idummy = val<7>(cells[c])+1; out.write((char*)&idummy,sizeof(int)); - idummy = val<8>(cells[c])+1; out.write((char*)&idummy,sizeof(int)); - } - - //coords - //x1-coords - for(int n=0; n<nofNodes; n++) - { fdummy = (float)( val<1>(nodes[n]) ); out.write((char*)&fdummy ,sizeof(float)); } - //x2-coords - for(int n=0; n<nofNodes; n++) - { fdummy = (float)( val<2>(nodes[n]) ); out.write((char*)&fdummy ,sizeof(float)); } - //x3-coords - for(int n=0; n<nofNodes; n++) - { fdummy = (float)( val<3>(nodes[n]) ); out.write((char*)&fdummy ,sizeof(float)); } - - //NODE DATA + int nofNodesPerCell = 8; + + out.write((char *)&magic, sizeof(char)); + out.write((char *)&nofNodes, sizeof(int)); + out.write((char *)&nofCells, sizeof(int)); + out.write((char *)&nofNodeData, sizeof(int)); + out.write((char *)&nofCellData, sizeof(int)); + out.write((char *)&nofModelData, sizeof(int)); + + idummy = (int)nofCells * nofNodesPerCell; + out.write((char *)&idummy, sizeof(int)); //(nof nodes) * (nodes per cell) + for (int c = 0; c < nofCells; c++) { + idummy = c + 1; + out.write((char *)&idummy, sizeof(int)); // cell id + idummy = 1; + out.write((char *)&idummy, sizeof(int)); // mat + idummy = nofNodesPerCell; + out.write((char *)&idummy, sizeof(int)); // nodes per cell + idummy = cellType; + out.write((char *)&idummy, sizeof(int)); // cell type + } + // knotennummern der einzelnen zellen + for (int c = 0; c < nofCells; c++) { + idummy = val<1>(cells[c]) + 1; + out.write((char *)&idummy, sizeof(int)); + idummy = val<2>(cells[c]) + 1; + out.write((char *)&idummy, sizeof(int)); + idummy = val<3>(cells[c]) + 1; + out.write((char *)&idummy, sizeof(int)); + idummy = val<4>(cells[c]) + 1; + out.write((char *)&idummy, sizeof(int)); + idummy = val<5>(cells[c]) + 1; + out.write((char *)&idummy, sizeof(int)); + idummy = val<6>(cells[c]) + 1; + out.write((char *)&idummy, sizeof(int)); + idummy = val<7>(cells[c]) + 1; + out.write((char *)&idummy, sizeof(int)); + idummy = val<8>(cells[c]) + 1; + out.write((char *)&idummy, sizeof(int)); + } + + // coords + // x1-coords + for (int n = 0; n < nofNodes; n++) { + fdummy = (float)(val<1>(nodes[n])); + out.write((char *)&fdummy, sizeof(float)); + } + // x2-coords + for (int n = 0; n < nofNodes; n++) { + fdummy = (float)(val<2>(nodes[n])); + out.write((char *)&fdummy, sizeof(float)); + } + // x3-coords + for (int n = 0; n < nofNodes; n++) { + fdummy = (float)(val<3>(nodes[n])); + out.write((char *)&fdummy, sizeof(float)); + } + + // NODE DATA char labels[1024]; char units[1024]; strcpy(labels, ""); strcpy(units, ""); - for(int d=0; d<nofNodeData-1; ++d) - { strcat(labels, datanames[d].c_str() ); strcat(labels,"."); } - strcat(labels, datanames[nofNodeData-1].c_str()); + for (int d = 0; d < nofNodeData - 1; ++d) { + strcat(labels, datanames[d].c_str()); + strcat(labels, "."); + } + strcat(labels, datanames[nofNodeData - 1].c_str()); - for(int i=0;i<(nofNodeData-1);i++) strcat(units, "no_unit."); + for (int i = 0; i < (nofNodeData - 1); i++) + strcat(units, "no_unit."); strcat(units, "no_unit"); - out.write((char*)&labels,sizeof(labels)); - out.write((char*)&units,sizeof(units)); + out.write((char *)&labels, sizeof(labels)); + out.write((char *)&units, sizeof(units)); - //nof and type of data + // nof and type of data idummy = nofNodeData; - out.write((char*)&idummy,sizeof(int)); //Datentypen pro knoten (hier = nof_node_data, da NUR skalare) + out.write((char *)&idummy, sizeof(int)); // Datentypen pro knoten (hier = nof_node_data, da NUR skalare) idummy = 1; - for(int i=0;i<nofNodeData;i++) out.write((char*)&idummy,sizeof(int)); //jeder Datentyp ist ein skalarer Wert + for (int i = 0; i < nofNodeData; i++) + out.write((char *)&idummy, sizeof(int)); // jeder Datentyp ist ein skalarer Wert - //min and max of data + // min and max of data fdummy = 0.0; - for(int i=0;i<nofNodeData;i++) out.write((char*)&fdummy,sizeof(float)); //min Wert pro Datentyp + for (int i = 0; i < nofNodeData; i++) + out.write((char *)&fdummy, sizeof(float)); // min Wert pro Datentyp fdummy = 1.0; - for(int i=0;i<nofNodeData;i++) out.write((char*)&fdummy,sizeof(float)); //max Wert pro Datentyp + for (int i = 0; i < nofNodeData; i++) + out.write((char *)&fdummy, sizeof(float)); // max Wert pro Datentyp - //daten ins file schreiben - for(int d=0; d<nofNodeData; ++d) - for(int n=0; n<(int)nodedata[d].size(); n++) - { fdummy=(float)nodedata[d][n]; out.write((char*)&fdummy,sizeof(float)); } + // daten ins file schreiben + for (int d = 0; d < nofNodeData; ++d) + for (int n = 0; n < (int)nodedata[d].size(); n++) { + fdummy = (float)nodedata[d][n]; + out.write((char *)&fdummy, sizeof(float)); + } fdummy = 1.; - for(int i=0;i<nofNodeData;i++) out.write((char*)&fdummy,sizeof(float)); //max Wert pro Datentyp + for (int i = 0; i < nofNodeData; i++) + out.write((char *)&fdummy, sizeof(float)); // max Wert pro Datentyp - out.close(); - UBLOG(logDEBUG1,"WbWriterAvsBinary::writeOctsWithNodeData to "<<avsfilename<<" - end"); + out.close(); + UBLOG(logDEBUG1, "WbWriterAvsBinary::writeOctsWithNodeData to " << avsfilename << " - end"); return avsfilename; - } +} diff --git a/src/basics/basics/writer/WbWriterAvsBinary.h b/src/basics/basics/writer/WbWriterAvsBinary.h index 17b44adaa4f19993c8b50b32bf707290308b8803..42e50debd8b63f877fc132d652088dfaefb1271e 100644 --- a/src/basics/basics/writer/WbWriterAvsBinary.h +++ b/src/basics/basics/writer/WbWriterAvsBinary.h @@ -12,60 +12,79 @@ class WbWriterAvsBinary : public WbWriter { public: - static WbWriterAvsBinary* getInstance() - { - static WbWriterAvsBinary instance; - return &instance; - } + static WbWriterAvsBinary *getInstance() + { + static WbWriterAvsBinary instance; + return &instance; + } + + WbWriterAvsBinary(const WbWriterAvsBinary &) = delete; + const WbWriterAvsBinary &operator=(const WbWriterAvsBinary &) = delete; - WbWriterAvsBinary( const WbWriterAvsBinary& ) = delete; - const WbWriterAvsBinary& operator=( const WbWriterAvsBinary& ) = delete; private: - WbWriterAvsBinary() = default; + WbWriterAvsBinary() = default; public: - std::string getFileExtension() override { return ".bin.inp"; } + std::string getFileExtension() override { return ".bin.inp"; } + + ////////////////////////////////////////////////////////////////////////// + // lines + // 0 ---- 1 + // nodenumbering must start with 0! + std::string writeLines(const std::string &filename, std::vector<UbTupleFloat3> &nodes, + std::vector<UbTupleInt2> &lines) override; - ////////////////////////////////////////////////////////////////////////// - //lines - // 0 ---- 1 - //nodenumbering must start with 0! - std::string writeLines(const std::string& filename,std::vector<UbTupleFloat3 >& nodes, std::vector<UbTupleInt2 >& lines) override; + ////////////////////////////////////////////////////////////////////////// + // triangles + // cell numbering: + // 2 + // + // 0---1 + // nodenumbering must start with 0! + std::string writeTriangles(const std::string &filename, std::vector<UbTupleFloat3> &nodes, + std::vector<UbTuple<int, int, int>> &triangles) override; + std::string writeTrianglesWithNodeData(const std::string &filename, std::vector<UbTupleFloat3> &nodes, + std::vector<UbTupleInt3> &cells, std::vector<std::string> &datanames, + std::vector<std::vector<double>> &nodedata) override; - ////////////////////////////////////////////////////////////////////////// - //triangles - //cell numbering: - // 2 - // - // 0---1 - //nodenumbering must start with 0! - std::string writeTriangles(const std::string& filename,std::vector<UbTupleFloat3 >& nodes, std::vector<UbTuple<int,int,int> >& triangles) override; - std::string writeTrianglesWithNodeData(const std::string& filename,std::vector< UbTupleFloat3 >& nodes, std::vector< UbTupleInt3 >& cells, std::vector< std::string >& datanames, std::vector< std::vector< double > >& nodedata) override; - - ////////////////////////////////////////////////////////////////////////// - //quads - //cell numbering: - // 3---2 - // | | - // 0---1 - //nodenumbering must start with 0! - std::string writeQuads(const std::string& filename,std::vector< UbTupleFloat3 >& nodes, std::vector< UbTupleInt4 >& cells) override; - std::string writeQuadsWithNodeData(const std::string& filename, std::vector< UbTupleFloat3 >& nodes, std::vector< UbTupleInt4 >& cells, std::vector< std::string >& datanames, std::vector< std::vector< double > >& nodedata) override; - std::string writeQuadsWithCellData(const std::string& filename, std::vector< UbTupleFloat3 >& nodes, std::vector< UbTupleInt4 >& cells, std::vector< std::string >& datanames, std::vector< std::vector< double > >& celldata) override; - std::string writeQuadsWithNodeAndCellData(const std::string& filename, std::vector< UbTupleFloat3 >& nodes, std::vector< UbTupleInt4 >& cells, std::vector< std::string >& nodedatanames, std::vector< std::vector< double > >& nodedata, std::vector< std::string >& celldatanames, std::vector< std::vector< double > >& celldata) override; + ////////////////////////////////////////////////////////////////////////// + // quads + // cell numbering: + // 3---2 + // | | + // 0---1 + // nodenumbering must start with 0! + std::string writeQuads(const std::string &filename, std::vector<UbTupleFloat3> &nodes, + std::vector<UbTupleInt4> &cells) override; + std::string writeQuadsWithNodeData(const std::string &filename, std::vector<UbTupleFloat3> &nodes, + std::vector<UbTupleInt4> &cells, std::vector<std::string> &datanames, + std::vector<std::vector<double>> &nodedata) override; + std::string writeQuadsWithCellData(const std::string &filename, std::vector<UbTupleFloat3> &nodes, + std::vector<UbTupleInt4> &cells, std::vector<std::string> &datanames, + std::vector<std::vector<double>> &celldata) override; + std::string writeQuadsWithNodeAndCellData(const std::string &filename, std::vector<UbTupleFloat3> &nodes, + std::vector<UbTupleInt4> &cells, std::vector<std::string> &nodedatanames, + std::vector<std::vector<double>> &nodedata, + std::vector<std::string> &celldatanames, + std::vector<std::vector<double>> &celldata) override; - ////////////////////////////////////////////////////////////////////////// - //octs - // 7 ---- 6 - // /| /| - // 4 +--- 5 | - // | | | | - // | 3 ---+ 2 - // |/ |/ - // 0 ---- 1 - std::string writeOcts(const std::string& filename,std::vector< UbTupleFloat3 >& nodes, std::vector< UbTupleInt8 >& cells) override; - std::string writeOctsWithCellData(const std::string& filename, std::vector<UbTupleFloat3 >& nodes, std::vector<UbTupleInt8 >& cells, std::vector<std::string >& datanames, std::vector< std::vector<double > >& celldata) override; - std::string writeOctsWithNodeData(const std::string& filename, std::vector<UbTupleFloat3 >& nodes, std::vector<UbTupleUInt8 >& cells, std::vector<std::string >& datanames, std::vector< std::vector<double > >& nodedata) override; + ////////////////////////////////////////////////////////////////////////// + // octs + // 7 ---- 6 + // /| /| + // 4 +--- 5 | + // | | | | + // | 3 ---+ 2 + // |/ |/ + // 0 ---- 1 + std::string writeOcts(const std::string &filename, std::vector<UbTupleFloat3> &nodes, + std::vector<UbTupleInt8> &cells) override; + std::string writeOctsWithCellData(const std::string &filename, std::vector<UbTupleFloat3> &nodes, + std::vector<UbTupleInt8> &cells, std::vector<std::string> &datanames, + std::vector<std::vector<double>> &celldata) override; + std::string writeOctsWithNodeData(const std::string &filename, std::vector<UbTupleFloat3> &nodes, + std::vector<UbTupleUInt8> &cells, std::vector<std::string> &datanames, + std::vector<std::vector<double>> &nodedata) override; }; -#endif //WBWRITERAVSBINARY_H +#endif // WBWRITERAVSBINARY_H diff --git a/src/basics/basics/writer/WbWriterBOBJ.cpp b/src/basics/basics/writer/WbWriterBOBJ.cpp index fa88708b2de715471fb3f04c69ab6c3c2d2d45e1..4401f25b0bd2dc0a9ac8161b901a9d53683ad941 100644 --- a/src/basics/basics/writer/WbWriterBOBJ.cpp +++ b/src/basics/basics/writer/WbWriterBOBJ.cpp @@ -1,79 +1,81 @@ #ifdef CAB_ZLIB - #include <basics/writer/WbWriterBOBJ.h> - #include <basics/utilities/UbLogger.h> - #include <cstring> +#include <basics/utilities/UbLogger.h> +#include <basics/writer/WbWriterBOBJ.h> +#include <cstring> - #include <zlib.h> +#include <zlib.h> +using namespace std; +/*===============================================================================*/ +std::string WbWriterBOBJ::writeTriangles(const std::string &filename, std::vector<UbTupleFloat3> &nodes, + std::vector<UbTupleInt3> &triangles) +{ + string bobjFilename = filename + getFileExtension(); + UBLOG(logDEBUG1, "WbWriterBOBJ::writeTriangles to " << bobjFilename << " - start"); - using namespace std; - /*===============================================================================*/ - std::string WbWriterBOBJ::writeTriangles(const std::string& filename,std::vector<UbTupleFloat3 >& nodes, std::vector<UbTupleInt3 >& triangles) - { - string bobjFilename=filename+getFileExtension(); - UBLOG(logDEBUG1,"WbWriterBOBJ::writeTriangles to "<<bobjFilename<<" - start"); + gzFile gzf = gzopen(bobjFilename.c_str(), "wb1"); - gzFile gzf = gzopen( bobjFilename.c_str(), "wb1" ); - - size_t nofNodes = nodes.size(); - size_t nofTriangles = triangles.size(); + size_t nofNodes = nodes.size(); + size_t nofTriangles = triangles.size(); - //write to file - size_t numVerts; - //double v[3]; - if(sizeof(numVerts)!=4) { throw UbException(UB_EXARGS,"danger..."); } - numVerts = nofNodes; - gzwrite(gzf, &numVerts, sizeof(numVerts)); + // write to file + size_t numVerts; + // double v[3]; + if (sizeof(numVerts) != 4) { + throw UbException(UB_EXARGS, "danger..."); + } + numVerts = nofNodes; + gzwrite(gzf, &numVerts, sizeof(numVerts)); - for(size_t k=0; k<nofNodes; k++) { - float vertp = val<1>(nodes[k]); - gzwrite(gzf, &vertp, sizeof(vertp)); - vertp = val<2>(nodes[k]); - gzwrite(gzf, &vertp, sizeof(vertp)); - vertp = val<3>(nodes[k]); - gzwrite(gzf, &vertp, sizeof(vertp)); - } + for (size_t k = 0; k < nofNodes; k++) { + float vertp = val<1>(nodes[k]); + gzwrite(gzf, &vertp, sizeof(vertp)); + vertp = val<2>(nodes[k]); + gzwrite(gzf, &vertp, sizeof(vertp)); + vertp = val<3>(nodes[k]); + gzwrite(gzf, &vertp, sizeof(vertp)); + } - //NORMAL VECTOR - //double n[3]; - gzwrite(gzf, &numVerts, sizeof(numVerts)); - for(size_t k=0; k<nofNodes; k++) { - //poly->GetPointData()->GetNormals()->GetTuple(k, n); - float normp = 0.0;//n[0]; - gzwrite(gzf, &normp, sizeof(normp)); - normp = 0.0;//n[1]; - gzwrite(gzf, &normp, sizeof(normp)); - normp = 0.0;//n[2]; - gzwrite(gzf, &normp, sizeof(normp)); - } + // NORMAL VECTOR + // double n[3]; + gzwrite(gzf, &numVerts, sizeof(numVerts)); + for (size_t k = 0; k < nofNodes; k++) { + // poly->GetPointData()->GetNormals()->GetTuple(k, n); + float normp = 0.0; // n[0]; + gzwrite(gzf, &normp, sizeof(normp)); + normp = 0.0; // n[1]; + gzwrite(gzf, &normp, sizeof(normp)); + normp = 0.0; // n[2]; + gzwrite(gzf, &normp, sizeof(normp)); + } - //vtkIdType npts = 3; - //vtkIdType* pts; - size_t numTris = nofTriangles; - gzwrite(gzf, &numTris, sizeof(numTris)); - for(size_t k=0; k<nofTriangles/*(size_t)poly->GetNumberOfPolys()*/; k++) { - //poly->GetPolys()->GetNextCell(npts, pts); - //int triIndex = *pts; - //gzwrite(gzf, &triIndex, sizeof(triIndex)); - //triIndex = *(pts+1); - //gzwrite(gzf, &triIndex, sizeof(triIndex)); - //triIndex = *(pts+2); - //gzwrite(gzf, &triIndex, sizeof(triIndex)); - //poly->GetPolys()->GetNextCell(npts, pts); - int triIndex = val<1>(triangles[k]);//*pts; - gzwrite(gzf, &triIndex, sizeof(triIndex)); - triIndex = val<2>(triangles[k]);//*(pts+1); - gzwrite(gzf, &triIndex, sizeof(triIndex)); - triIndex = val<3>(triangles[k]);//*(pts+2); - gzwrite(gzf, &triIndex, sizeof(triIndex)); - } + // vtkIdType npts = 3; + // vtkIdType* pts; + size_t numTris = nofTriangles; + gzwrite(gzf, &numTris, sizeof(numTris)); + for (size_t k = 0; k < nofTriangles /*(size_t)poly->GetNumberOfPolys()*/; k++) { + // poly->GetPolys()->GetNextCell(npts, pts); + // int triIndex = *pts; + // gzwrite(gzf, &triIndex, sizeof(triIndex)); + // triIndex = *(pts+1); + // gzwrite(gzf, &triIndex, sizeof(triIndex)); + // triIndex = *(pts+2); + // gzwrite(gzf, &triIndex, sizeof(triIndex)); + // poly->GetPolys()->GetNextCell(npts, pts); + int triIndex = val<1>(triangles[k]); //*pts; + gzwrite(gzf, &triIndex, sizeof(triIndex)); + triIndex = val<2>(triangles[k]); //*(pts+1); + gzwrite(gzf, &triIndex, sizeof(triIndex)); + triIndex = val<3>(triangles[k]); //*(pts+2); + gzwrite(gzf, &triIndex, sizeof(triIndex)); + } - gzclose( gzf ); + gzclose(gzf); - UBLOG(logDEBUG1,"WbWriterBOBJ::writeTriangles to "<<bobjFilename<<" - end"); + UBLOG(logDEBUG1, "WbWriterBOBJ::writeTriangles to " << bobjFilename << " - end"); - return bobjFilename; - } - /*===============================================================================*/ + return bobjFilename; +} +/*===============================================================================*/ -#endif //CAB_ZLIB +#endif // CAB_ZLIB diff --git a/src/basics/basics/writer/WbWriterBOBJ.h b/src/basics/basics/writer/WbWriterBOBJ.h index 1d033c952ac2db021146a8e9ee20d9398ebae45e..f5872cc3a38eed227ebcefcdcedd13a78152b060 100644 --- a/src/basics/basics/writer/WbWriterBOBJ.h +++ b/src/basics/basics/writer/WbWriterBOBJ.h @@ -1,40 +1,47 @@ #ifdef CAB_ZLIB - #ifndef WBWRITERBOBJ_H - #define WBWRITERBOBJ_H - - #include <string> - #include <basics/writer/WbWriter.h> - - class WbWriterBOBJ : public WbWriter - { - public: - OBCREATOR_EXT( WbWriterBOBJ ) - - static WbWriterBOBJ* getInstance() - { - static WbWriterBOBJ instance; - return &instance; - } - private: - WbWriterBOBJ() : WbWriter() - { - if(sizeof(unsigned char)!=1) throw UbException(UB_EXARGS,"error char type mismatch"); - if(sizeof(int) !=4) throw UbException(UB_EXARGS,"error int type mismatch"); - if(sizeof(float) !=4) throw UbException(UB_EXARGS,"error float type mismatch"); - } - WbWriterBOBJ( const WbWriterBOBJ& ); //no copy allowed - const WbWriterBOBJ& operator=( const WbWriterBOBJ& ); //no copy allowed - - static std::string pvdEndTag; - - public: - std::string getFileExtension() { return "BOBJ.gz"; } - - std::string writeTriangles(const std::string& filename,std::vector<UbTupleFloat3 >& nodes, std::vector<UbTupleInt3 >& triangles); - }; - - UB_AUTO_RUN_NAMED(ObFactory<WbWriter>::getInstance()->addObCreator(ObSingletonCreatorImpl<WbWriterBOBJ ,WbWriter>::getInstance()), CAB_WbWriterVtkXmlASCII); - - #endif //WBWRITERBOBJ_H - -#endif //CAB_ZLIB +#ifndef WBWRITERBOBJ_H +#define WBWRITERBOBJ_H + +#include <basics/writer/WbWriter.h> +#include <string> + +class WbWriterBOBJ : public WbWriter +{ +public: + OBCREATOR_EXT(WbWriterBOBJ) + + static WbWriterBOBJ *getInstance() + { + static WbWriterBOBJ instance; + return &instance; + } + +private: + WbWriterBOBJ() : WbWriter() + { + if (sizeof(unsigned char) != 1) + throw UbException(UB_EXARGS, "error char type mismatch"); + if (sizeof(int) != 4) + throw UbException(UB_EXARGS, "error int type mismatch"); + if (sizeof(float) != 4) + throw UbException(UB_EXARGS, "error float type mismatch"); + } + WbWriterBOBJ(const WbWriterBOBJ &); // no copy allowed + const WbWriterBOBJ &operator=(const WbWriterBOBJ &); // no copy allowed + + static std::string pvdEndTag; + +public: + std::string getFileExtension() { return "BOBJ.gz"; } + + std::string writeTriangles(const std::string &filename, std::vector<UbTupleFloat3> &nodes, + std::vector<UbTupleInt3> &triangles); +}; + +UB_AUTO_RUN_NAMED( + ObFactory<WbWriter>::getInstance()->addObCreator(ObSingletonCreatorImpl<WbWriterBOBJ, WbWriter>::getInstance()), + CAB_WbWriterVtkXmlASCII); + +#endif // WBWRITERBOBJ_H + +#endif // CAB_ZLIB diff --git a/src/basics/basics/writer/WbWriterSunflow.cpp b/src/basics/basics/writer/WbWriterSunflow.cpp index 6adbc274aec46f351b0d2cfc0f42340fcc6368ab..6c60fe9d0e685dd49bad71a1452b3392e4bb0938 100644 --- a/src/basics/basics/writer/WbWriterSunflow.cpp +++ b/src/basics/basics/writer/WbWriterSunflow.cpp @@ -1,112 +1,115 @@ -#include <basics/writer/WbWriterSunflow.h> #include <basics/utilities/UbLogger.h> +#include <basics/writer/WbWriterSunflow.h> #include <cstring> using namespace std; /*===============================================================================*/ -std::string WbWriterSunflow::writeTriangles(const string& filename,vector<UbTupleFloat3 >& nodes, vector<UbTupleInt3 >& triangles) +std::string WbWriterSunflow::writeTriangles(const string &filename, vector<UbTupleFloat3> &nodes, + vector<UbTupleInt3> &triangles) { - string sunflowFilename=filename+getFileExtension(); - UBLOG(logDEBUG1,"WbWriterSunflow::writeTriangles to "<<sunflowFilename<<" - start"); - - std::ofstream out(sunflowFilename.c_str()); - if(!out) - { - out.clear(); //flags ruecksetzen (ansonsten liefert utern if(!out) weiterhin true!!! - string path = UbSystem::getPathFromString(sunflowFilename); - if(path.size()>0){UbSystem::makeDirectory(path);out.open(sunflowFilename.c_str());} - if(!out) throw UbException(UB_EXARGS,"couldn't open file "+sunflowFilename); - } - - // General part - - // Image details - out<<"image {" <<endl; - out<<" resolution 640 480"<<endl; - out<<" aa 0 1" <<endl; - out<<" filter mitchell" <<endl; - out<<"}" <<endl<<endl; - - // Camera position - out<<"camera {" <<endl; - out<<" type pinhole" <<endl; - out<<" eye -0.25 -0.3 0.13"<<endl; - out<<" target -0.1 0.1 0.13" <<endl; - out<<" up 0 0 1" <<endl; - out<<" fov 60" <<endl; - out<<" aspect 1.333333" <<endl; - out<<"}" <<endl<<endl; - - // Light - out<<"light {" <<endl; - out<<" type ibl" <<endl; - out<<" image sky_small.hdr" <<endl; - out<<" center 0 -1 0" <<endl; - out<<" up 0 0 1" <<endl; - out<<" lock true" <<endl; - out<<" samples 200" <<endl; - out<<"}" <<endl<<endl; - - // Shaders - out<<"shader {" <<endl; - out<<" name default-shader" <<endl; - out<<" type diffuse" <<endl; - out<<" diff 0.25 0.25 0.25" <<endl; - out<<"}" <<endl<<endl; - - out<<"shader {" <<endl; - out<<" name Glass" <<endl; - out<<" type glass" <<endl; - out<<" eta 1.333" <<endl; - out<<" color 0.1 0.3 0.8" <<endl; - out<<"}" <<endl<<endl; - - out<<"shader {" <<endl; - out<<" name Mirror" <<endl; - out<<" type mirror" <<endl; - out<<" refl 0.7 0.7 0.7" <<endl; - out<<"}" <<endl<<endl; - - // Objects - // a) Ground plane - out<<"object {" <<endl; - out<<" shader default-shader" <<endl; - out<<" type plane" <<endl; - out<<" p 0 0 0" <<endl; - out<<" n 0 0 1" <<endl; - out<<"}" <<endl<<endl; - - // b) Mesh - out<<"object {" <<endl; - out<<" shader Glass" <<endl; - out<<" transform {" <<endl; - out<<" rotatey 270.0" <<endl; - out<<" }" <<endl; - out<<" type generic-mesh" <<endl; - out<<" name polySurfac" <<endl<<endl; - - - // POINTS SECTION - int nofNodes = (int)nodes.size(); - out<<" points "<<nofNodes<<endl; - for(int n=0; n<nofNodes; n++) - out<<" "<< val<1>(nodes[n]) <<" "<< val<2>(nodes[n]) <<" "<< val<3>(nodes[n]) <<endl; - - // TRIANGLES SECTION - int nofTriangles= (int)triangles.size(); - out<<" triangles "<<nofTriangles<<endl; - for(int c=0; c<nofTriangles; c++) - out<<" "<<val<1>(triangles[c]) <<" "<< val<2>(triangles[c])<<" "<< val<3>(triangles[c])<<endl; - - // FOOTER - out<<" normals none" << endl; - out<<" uvs none" << endl; - out<<"}" << endl; - - out.close(); - UBLOG(logDEBUG1,"WbWriterSunflow::writeTriangles to "<<sunflowFilename<<" - end"); - - return sunflowFilename; + string sunflowFilename = filename + getFileExtension(); + UBLOG(logDEBUG1, "WbWriterSunflow::writeTriangles to " << sunflowFilename << " - start"); + + std::ofstream out(sunflowFilename.c_str()); + if (!out) { + out.clear(); // flags ruecksetzen (ansonsten liefert utern if(!out) weiterhin true!!! + string path = UbSystem::getPathFromString(sunflowFilename); + if (path.size() > 0) { + UbSystem::makeDirectory(path); + out.open(sunflowFilename.c_str()); + } + if (!out) + throw UbException(UB_EXARGS, "couldn't open file " + sunflowFilename); + } + + // General part + + // Image details + out << "image {" << endl; + out << " resolution 640 480" << endl; + out << " aa 0 1" << endl; + out << " filter mitchell" << endl; + out << "}" << endl << endl; + + // Camera position + out << "camera {" << endl; + out << " type pinhole" << endl; + out << " eye -0.25 -0.3 0.13" << endl; + out << " target -0.1 0.1 0.13" << endl; + out << " up 0 0 1" << endl; + out << " fov 60" << endl; + out << " aspect 1.333333" << endl; + out << "}" << endl << endl; + + // Light + out << "light {" << endl; + out << " type ibl" << endl; + out << " image sky_small.hdr" << endl; + out << " center 0 -1 0" << endl; + out << " up 0 0 1" << endl; + out << " lock true" << endl; + out << " samples 200" << endl; + out << "}" << endl << endl; + + // Shaders + out << "shader {" << endl; + out << " name default-shader" << endl; + out << " type diffuse" << endl; + out << " diff 0.25 0.25 0.25" << endl; + out << "}" << endl << endl; + + out << "shader {" << endl; + out << " name Glass" << endl; + out << " type glass" << endl; + out << " eta 1.333" << endl; + out << " color 0.1 0.3 0.8" << endl; + out << "}" << endl << endl; + + out << "shader {" << endl; + out << " name Mirror" << endl; + out << " type mirror" << endl; + out << " refl 0.7 0.7 0.7" << endl; + out << "}" << endl << endl; + + // Objects + // a) Ground plane + out << "object {" << endl; + out << " shader default-shader" << endl; + out << " type plane" << endl; + out << " p 0 0 0" << endl; + out << " n 0 0 1" << endl; + out << "}" << endl << endl; + + // b) Mesh + out << "object {" << endl; + out << " shader Glass" << endl; + out << " transform {" << endl; + out << " rotatey 270.0" << endl; + out << " }" << endl; + out << " type generic-mesh" << endl; + out << " name polySurfac" << endl << endl; + + // POINTS SECTION + int nofNodes = (int)nodes.size(); + out << " points " << nofNodes << endl; + for (int n = 0; n < nofNodes; n++) + out << " " << val<1>(nodes[n]) << " " << val<2>(nodes[n]) << " " << val<3>(nodes[n]) << endl; + + // TRIANGLES SECTION + int nofTriangles = (int)triangles.size(); + out << " triangles " << nofTriangles << endl; + for (int c = 0; c < nofTriangles; c++) + out << " " << val<1>(triangles[c]) << " " << val<2>(triangles[c]) << " " << val<3>(triangles[c]) << endl; + + // FOOTER + out << " normals none" << endl; + out << " uvs none" << endl; + out << "}" << endl; + + out.close(); + UBLOG(logDEBUG1, "WbWriterSunflow::writeTriangles to " << sunflowFilename << " - end"); + + return sunflowFilename; } /*===============================================================================*/ diff --git a/src/basics/basics/writer/WbWriterSunflow.h b/src/basics/basics/writer/WbWriterSunflow.h index 39f71070ee6f41b7084ba902175331b257ebd030..328f9c31014dd14977e06125a1c55c6a96898529 100644 --- a/src/basics/basics/writer/WbWriterSunflow.h +++ b/src/basics/basics/writer/WbWriterSunflow.h @@ -5,31 +5,36 @@ #include <basics/writer/WbWriter.h> -class WbWriterSunflow : public WbWriter +class WbWriterSunflow : public WbWriter { public: - static WbWriterSunflow* getInstance() - { - static WbWriterSunflow instance; - return &instance; - } - - WbWriterSunflow( const WbWriterSunflow& ) = delete; - const WbWriterSunflow& operator=( const WbWriterSunflow& ) = delete; -private: - WbWriterSunflow() : WbWriter() - { - if(sizeof(unsigned char)!=1) throw UbException(UB_EXARGS,"error char type mismatch"); - if(sizeof(int) !=4) throw UbException(UB_EXARGS,"error int type mismatch"); - if(sizeof(float) !=4) throw UbException(UB_EXARGS,"error float type mismatch"); - } + static WbWriterSunflow *getInstance() + { + static WbWriterSunflow instance; + return &instance; + } + + WbWriterSunflow(const WbWriterSunflow &) = delete; + const WbWriterSunflow &operator=(const WbWriterSunflow &) = delete; - static std::string pvdEndTag; +private: + WbWriterSunflow() : WbWriter() + { + if (sizeof(unsigned char) != 1) + throw UbException(UB_EXARGS, "error char type mismatch"); + if (sizeof(int) != 4) + throw UbException(UB_EXARGS, "error int type mismatch"); + if (sizeof(float) != 4) + throw UbException(UB_EXARGS, "error float type mismatch"); + } + + static std::string pvdEndTag; public: - std::string getFileExtension() override { return "ascii.sunflow"; } + std::string getFileExtension() override { return "ascii.sunflow"; } - std::string writeTriangles(const std::string& filename,std::vector<UbTupleFloat3 >& nodes, std::vector<UbTupleInt3 >& triangles) override; + std::string writeTriangles(const std::string &filename, std::vector<UbTupleFloat3> &nodes, + std::vector<UbTupleInt3> &triangles) override; }; -#endif //WbWriterSunflow_H +#endif // WbWriterSunflow_H diff --git a/src/basics/basics/writer/WbWriterTecPlotASCII.cpp b/src/basics/basics/writer/WbWriterTecPlotASCII.cpp index 6074b805bc25e9548d690ed49670f40102e1af79..895853eb29ea8b364a1f914655cc4a5b0c7d093c 100644 --- a/src/basics/basics/writer/WbWriterTecPlotASCII.cpp +++ b/src/basics/basics/writer/WbWriterTecPlotASCII.cpp @@ -1,68 +1,64 @@ -#include <basics/writer/WbWriterTecPlotASCII.h> #include <basics/utilities/UbLogger.h> +#include <basics/writer/WbWriterTecPlotASCII.h> using namespace std; /*===============================================================================*/ -string WbWriterTecPlotASCII::writeOctsWithNodeData(const string& filename,vector<UbTupleFloat3 >& nodes, vector<UbTupleUInt8 >& cells, vector<string >& datanames, vector<vector<double > >& nodedata) +string WbWriterTecPlotASCII::writeOctsWithNodeData(const string &filename, vector<UbTupleFloat3> &nodes, + vector<UbTupleUInt8> &cells, vector<string> &datanames, + vector<vector<double>> &nodedata) { - string tecplotfilename = filename+getFileExtension(); - UBLOG(logDEBUG1,"WbWriterTecPlotASCII::writeOctsWithNodeData to "<<tecplotfilename<<" - start"); + string tecplotfilename = filename + getFileExtension(); + UBLOG(logDEBUG1, "WbWriterTecPlotASCII::writeOctsWithNodeData to " << tecplotfilename << " - start"); - ofstream out(tecplotfilename.c_str()); - if(!out) - { - out.clear(); //flags ruecksetzen (ansonsten liefert utern if(!out) weiterhin true!!! - string path = UbSystem::getPathFromString(tecplotfilename); - if(path.size()>0){ UbSystem::makeDirectory(path); out.open(tecplotfilename.c_str());} - if(!out) throw UbException(UB_EXARGS,"couldn't open file "+tecplotfilename); - } + ofstream out(tecplotfilename.c_str()); + if (!out) { + out.clear(); // flags ruecksetzen (ansonsten liefert utern if(!out) weiterhin true!!! + string path = UbSystem::getPathFromString(tecplotfilename); + if (path.size() > 0) { + UbSystem::makeDirectory(path); + out.open(tecplotfilename.c_str()); + } + if (!out) + throw UbException(UB_EXARGS, "couldn't open file " + tecplotfilename); + } - int nofNodes = (int)nodes.size(); - int nofCells = (int)cells.size(); + int nofNodes = (int)nodes.size(); + int nofCells = (int)cells.size(); - out<<"TITLE = VirtualFluids OctGrid from "<<UbSystem::getTimeStamp()<<endl; + out << "TITLE = VirtualFluids OctGrid from " << UbSystem::getTimeStamp() << endl; - out<<"VARIABLES = \"X\", \"Y\", \"Z\""; - for(size_t d=0; d<datanames.size(); d++) - out<<", \""<<datanames[d]<<"\""; - out<<endl; + out << "VARIABLES = \"X\", \"Y\", \"Z\""; + for (size_t d = 0; d < datanames.size(); d++) + out << ", \"" << datanames[d] << "\""; + out << endl; - out<<"ZONE NODES="<<nofNodes<<", ELEMENTS="<<nofCells<<", DATAPACKING=POINT, ZONETYPE=FEBRICK"<<endl; - for(size_t n=0; n<nodes.size(); n++) - { - UbTupleFloat3& coords = nodes[n]; - out<<val<1>(coords)<<" " - <<val<2>(coords)<<" " - <<val<3>(coords); - for(size_t d=0; d<datanames.size(); d++) - out<<" "<<nodedata[d][n]; - out<<endl; - } + out << "ZONE NODES=" << nofNodes << ", ELEMENTS=" << nofCells << ", DATAPACKING=POINT, ZONETYPE=FEBRICK" << endl; + for (size_t n = 0; n < nodes.size(); n++) { + UbTupleFloat3 &coords = nodes[n]; + out << val<1>(coords) << " " << val<2>(coords) << " " << val<3>(coords); + for (size_t d = 0; d < datanames.size(); d++) + out << " " << nodedata[d][n]; + out << endl; + } - for(size_t c=0; c<cells.size(); c++) - { - UbTupleUInt8& cell = cells[c]; - out<<val<1>(cell)<<" " - <<val<2>(cell)<<" " - <<val<3>(cell)<<" " - <<val<4>(cell)<<" " - <<val<5>(cell)<<" " - <<val<6>(cell)<<" " - <<val<7>(cell)<<" " - <<val<8>(cell)<<endl; - } + for (size_t c = 0; c < cells.size(); c++) { + UbTupleUInt8 &cell = cells[c]; + out << val<1>(cell) << " " << val<2>(cell) << " " << val<3>(cell) << " " << val<4>(cell) << " " << val<5>(cell) + << " " << val<6>(cell) << " " << val<7>(cell) << " " << val<8>(cell) << endl; + } - out.close(); - UBLOG(logDEBUG1,"WbWriterTecPlotASCII::writeOctsWithNodeData to "<<tecplotfilename<<" - end"); + out.close(); + UBLOG(logDEBUG1, "WbWriterTecPlotASCII::writeOctsWithNodeData to " << tecplotfilename << " - end"); - return tecplotfilename; + return tecplotfilename; } /*===============================================================================*/ -string WbWriterTecPlotASCII::writeOctsU(const string& filename,vector< UbTupleFloat3 >& nodes, vector< UbTupleUInt8 >& cells) +string WbWriterTecPlotASCII::writeOctsU(const string &filename, vector<UbTupleFloat3> &nodes, + vector<UbTupleUInt8> &cells) { - vector<string > datanames; - vector<vector<double > > nodedata; - return writeOctsWithNodeData(filename,nodes,cells,datanames,nodedata); + vector<string> datanames; + vector<vector<double>> nodedata; + return writeOctsWithNodeData(filename, nodes, cells, datanames, nodedata); } /*===============================================================================*/ diff --git a/src/basics/basics/writer/WbWriterTecPlotASCII.h b/src/basics/basics/writer/WbWriterTecPlotASCII.h index df0256765996ce6c553609eadf46bea94219dede..8869b59dedea70d7ed634244d44f9be10372c23e 100644 --- a/src/basics/basics/writer/WbWriterTecPlotASCII.h +++ b/src/basics/basics/writer/WbWriterTecPlotASCII.h @@ -5,84 +5,103 @@ #include <basics/writer/WbWriter.h> -class WbWriterTecPlotASCII : public WbWriter +class WbWriterTecPlotASCII : public WbWriter { public: - static WbWriterTecPlotASCII* getInstance() - { - static WbWriterTecPlotASCII instance; - return &instance; - } + static WbWriterTecPlotASCII *getInstance() + { + static WbWriterTecPlotASCII instance; + return &instance; + } - WbWriterTecPlotASCII( const WbWriterTecPlotASCII& ) = delete; - const WbWriterTecPlotASCII& operator=( const WbWriterTecPlotASCII& ) = delete; + WbWriterTecPlotASCII(const WbWriterTecPlotASCII &) = delete; + const WbWriterTecPlotASCII &operator=(const WbWriterTecPlotASCII &) = delete; private: - WbWriterTecPlotASCII() : WbWriter() - { - if(sizeof(unsigned char)!=1) throw UbException(UB_EXARGS,"machine error char type mismatch"); - if(sizeof(int) !=4) throw UbException(UB_EXARGS,"machine error int type mismatch"); - if(sizeof(float) !=4) throw UbException(UB_EXARGS,"machine error float type mismatch"); - } + WbWriterTecPlotASCII() : WbWriter() + { + if (sizeof(unsigned char) != 1) + throw UbException(UB_EXARGS, "machine error char type mismatch"); + if (sizeof(int) != 4) + throw UbException(UB_EXARGS, "machine error int type mismatch"); + if (sizeof(float) != 4) + throw UbException(UB_EXARGS, "machine error float type mismatch"); + } + + static std::string pvdEndTag; - static std::string pvdEndTag; public: - std::string getFileExtension() override { return ".ascii.dat"; } + std::string getFileExtension() override { return ".ascii.dat"; } + + // write a metafile + // std::string writeCollection(const std::string& filename, const std::vector<std::string>& filenames, const + // double& timestep, const bool& sepGroups); std::string addFilesToCollection(const std::string& filename, const + // std::vector<std::string>& filenames, const double& timestep, const bool& sepGroups); std::string + // writeParallelFile(const std::string& filename,std::vector<std::string>& pieceSources, + // std::vector<std::string>& pointDataNames, std::vector<std::string>& cellDataNames); - //write a metafile -// std::string writeCollection(const std::string& filename, const std::vector<std::string>& filenames, const double& timestep, const bool& sepGroups); -// std::string addFilesToCollection(const std::string& filename, const std::vector<std::string>& filenames, const double& timestep, const bool& sepGroups); -// std::string writeParallelFile(const std::string& filename,std::vector<std::string>& pieceSources, std::vector<std::string>& pointDataNames, std::vector<std::string>& cellDataNames); + ////////////////////////////////////////////////////////////////////////// + // nodes + // std::string writeNodes(const std::string& filename,std::vector< UbTupleFloat3 >& nodes); + // std::string writeNodesWithNodeData(const std::string& filename,std::vector< UbTupleFloat3 >& nodes, + // std::vector<std::string >& datanames, std::vector<std::vector<double > >& nodedata); - ////////////////////////////////////////////////////////////////////////// - //nodes -// std::string writeNodes(const std::string& filename,std::vector< UbTupleFloat3 >& nodes); -// std::string writeNodesWithNodeData(const std::string& filename,std::vector< UbTupleFloat3 >& nodes, std::vector<std::string >& datanames, std::vector<std::vector<double > >& nodedata); + ////////////////////////////////////////////////////////////////////////// + // lines + // 0 ---- 1 + // nodenumbering must start with 0! + // std::string writeLines(const std::string& filename,std::vector<UbTupleFloat3 >& nodes, std::vector<UbTupleInt2 + // >& lines); std::string writeLinesWithNodeData(const std::string& filename,std::vector<UbTupleFloat3 >& nodes, + // std::vector<UbTupleInt2 >& lines, std::vector< std::string >& datanames, std::vector< std::vector< double > >& + // nodedata); + // + ////////////////////////////////////////////////////////////////////////// + // triangles + // 2 + // + // 0---1 + // nodenumbering must start with 0! + // std::string writeTriangles(const std::string& filename,std::vector<UbTupleFloat3 >& nodes, + // std::vector<UbTupleInt3 >& triangles); std::string writeTrianglesWithNodeData(const std::string& + // filename,std::vector< UbTupleFloat3 >& nodes, std::vector< UbTupleInt3 >& cells, std::vector<std::string >& + // datanames, std::vector<std::vector<double > >& nodedata); - ////////////////////////////////////////////////////////////////////////// - //lines - // 0 ---- 1 - //nodenumbering must start with 0! -// std::string writeLines(const std::string& filename,std::vector<UbTupleFloat3 >& nodes, std::vector<UbTupleInt2 >& lines); -// std::string writeLinesWithNodeData(const std::string& filename,std::vector<UbTupleFloat3 >& nodes, std::vector<UbTupleInt2 >& lines, std::vector< std::string >& datanames, std::vector< std::vector< double > >& nodedata); -// - ////////////////////////////////////////////////////////////////////////// - //triangles - // 2 - // - // 0---1 - //nodenumbering must start with 0! -// std::string writeTriangles(const std::string& filename,std::vector<UbTupleFloat3 >& nodes, std::vector<UbTupleInt3 >& triangles); -// std::string writeTrianglesWithNodeData(const std::string& filename,std::vector< UbTupleFloat3 >& nodes, std::vector< UbTupleInt3 >& cells, std::vector<std::string >& datanames, std::vector<std::vector<double > >& nodedata); + ////////////////////////////////////////////////////////////////////////// + // 2D + // cell numbering: + // 3---2 + // | | + // 0---1 + // nodenumbering must start with 0! - ////////////////////////////////////////////////////////////////////////// - //2D - //cell numbering: - // 3---2 - // | | - // 0---1 - //nodenumbering must start with 0! + // std::string writeQuads(const std::string& filename,std::vector< UbTupleFloat3 >& nodes, std::vector< + // UbTupleInt4 >& cells); std::string writeQuadsWithNodeData(const std::string& filename,std::vector< + // UbTupleFloat3 >& nodes, std::vector< UbTupleInt4 >& cells, std::vector< std::string >& datanames, std::vector< + // std::vector< double > >& nodedata); std::string writeQuadsWithCellData(const std::string& + // filename,std::vector< UbTupleFloat3 >& nodes, std::vector< UbTupleInt4 >& cells, std::vector< std::string >& + // datanames, std::vector< std::vector< double > >& celldata); std::string writeQuadsWithNodeAndCellData(const + // std::string& filename,std::vector< UbTupleFloat3 >& nodes, std::vector< UbTupleInt4 >& cells, + // std::vector< std::string >& nodedatanames, std::vector< std::vector< + // double > >& nodedata, std::vector< std::string >& celldatanames, + // std::vector< std::vector< double > >& celldata ); -// std::string writeQuads(const std::string& filename,std::vector< UbTupleFloat3 >& nodes, std::vector< UbTupleInt4 >& cells); -// std::string writeQuadsWithNodeData(const std::string& filename,std::vector< UbTupleFloat3 >& nodes, std::vector< UbTupleInt4 >& cells, std::vector< std::string >& datanames, std::vector< std::vector< double > >& nodedata); -// std::string writeQuadsWithCellData(const std::string& filename,std::vector< UbTupleFloat3 >& nodes, std::vector< UbTupleInt4 >& cells, std::vector< std::string >& datanames, std::vector< std::vector< double > >& celldata); -// std::string writeQuadsWithNodeAndCellData(const std::string& filename,std::vector< UbTupleFloat3 >& nodes, std::vector< UbTupleInt4 >& cells, -// std::vector< std::string >& nodedatanames, std::vector< std::vector< double > >& nodedata, std::vector< std::string >& celldatanames, -// std::vector< std::vector< double > >& celldata ); - - ////////////////////////////////////////////////////////////////////////// - //octs - // 7 ---- 6 - // /| /| - // 4 +--- 5 | - // | | | | - // | 3 ---+ 2 - // |/ |/ - // 0 ---- 1 - std::string writeOctsU(const std::string& filename,std::vector< UbTupleFloat3 >& nodes, std::vector< UbTupleUInt8 >& cells); - //std::string writeOctsWithCellData(const std::string& filename,std::vector<UbTupleFloat3 >& nodes, std::vector<UbTupleInt8 >& cells, std::vector<std::string >& datanames, std::vector<std::vector<double > >& celldata); - std::string writeOctsWithNodeData(const std::string& filename,std::vector<UbTupleFloat3 >& nodes, std::vector<UbTupleUInt8 >& cells, std::vector<std::string >& datanames, std::vector<std::vector<double > >& nodedata) override; - + ////////////////////////////////////////////////////////////////////////// + // octs + // 7 ---- 6 + // /| /| + // 4 +--- 5 | + // | | | | + // | 3 ---+ 2 + // |/ |/ + // 0 ---- 1 + std::string writeOctsU(const std::string &filename, std::vector<UbTupleFloat3> &nodes, + std::vector<UbTupleUInt8> &cells); + // std::string writeOctsWithCellData(const std::string& filename,std::vector<UbTupleFloat3 >& nodes, + // std::vector<UbTupleInt8 >& cells, std::vector<std::string >& datanames, std::vector<std::vector<double > >& + // celldata); + std::string writeOctsWithNodeData(const std::string &filename, std::vector<UbTupleFloat3> &nodes, + std::vector<UbTupleUInt8> &cells, std::vector<std::string> &datanames, + std::vector<std::vector<double>> &nodedata) override; }; -#endif //WBWRITERTECPLOTASCII_H +#endif // WBWRITERTECPLOTASCII_H diff --git a/src/basics/basics/writer/WbWriterVtkASCII.cpp b/src/basics/basics/writer/WbWriterVtkASCII.cpp index 2d55989328d34cb96e9120aa64fedbeaadcb7ffe..754d6d006b80249af5495f24b5fcdbd9d637fc5a 100644 --- a/src/basics/basics/writer/WbWriterVtkASCII.cpp +++ b/src/basics/basics/writer/WbWriterVtkASCII.cpp @@ -1,601 +1,667 @@ -#include <basics/writer/WbWriterVtkASCII.h> #include <basics/utilities/UbLogger.h> +#include <basics/writer/WbWriterVtkASCII.h> #include <cstring> using namespace std; -std::string WbWriterVtkASCII::writeQuads(const string& filename,vector< UbTupleFloat3 >& nodes, vector< UbTupleInt4 >& cells) +std::string WbWriterVtkASCII::writeQuads(const string &filename, vector<UbTupleFloat3> &nodes, + vector<UbTupleInt4> &cells) { - string vtkfilename=filename+getFileExtension(); - UBLOG(logDEBUG1,"WbWriterVtkASCII::writeQuads to "<<vtkfilename<<" - start"); - - std::ofstream out(vtkfilename.c_str()); - if(!out) - { - out.clear(); //flags ruecksetzen (ansonsten liefert utern if(!out) weiterhin true!!! - string path = UbSystem::getPathFromString(vtkfilename); - if(path.size()>0){UbSystem::makeDirectory(path);out.open(vtkfilename.c_str());} - if(!out) throw UbException(UB_EXARGS,"couldn't open file "+vtkfilename); - } - - int nofNodes = (int)nodes.size(); - int nofCells = (int)cells.size(); - - //VtkASCII FILE - out<<"# vtk DataFile Version 4.0"<<"\n"; - out<<"GeoFile"<<"\n"; - out<<"ASCII"<<"\n"; - - //POINTS SECTION - out<<"DATASET UNSTRUCTURED_GRID"<<"\n"; - out<<"POINTS "<<nofNodes<<" float"<<"\n"; - for(int n=0; n<nofNodes; n++) - out<< val<1>(nodes[n]) <<" "<< val<2>(nodes[n]) <<" "<< val<3>(nodes[n]) <<" \n"; - - out<<"\n"; - - //CELLS SECTION - out<<"CELLS "<<nofCells<<" "<<5*nofCells<<"\n"; - for(int c=0; c<(int)cells.size(); c++) - out<<"4 " - << val<1>(cells[c]) <<" " - << val<2>(cells[c]) <<" " - << val<4>(cells[c]) <<" " - << val<3>(cells[c]) <<" \n"; - out<<"\n"; - - out<<"CELL_TYPES "<<nofCells<<"\n"; - for(int i=0; i<nofCells; i++) out<<"8"<<endl; - out<<endl; - - out.close(); - - UBLOG(logDEBUG1,"WbWriterVtkASCII::writeQuads to "<<vtkfilename<<" - end"); - - return vtkfilename; + string vtkfilename = filename + getFileExtension(); + UBLOG(logDEBUG1, "WbWriterVtkASCII::writeQuads to " << vtkfilename << " - start"); + + std::ofstream out(vtkfilename.c_str()); + if (!out) { + out.clear(); // flags ruecksetzen (ansonsten liefert utern if(!out) weiterhin true!!! + string path = UbSystem::getPathFromString(vtkfilename); + if (path.size() > 0) { + UbSystem::makeDirectory(path); + out.open(vtkfilename.c_str()); + } + if (!out) + throw UbException(UB_EXARGS, "couldn't open file " + vtkfilename); + } + + int nofNodes = (int)nodes.size(); + int nofCells = (int)cells.size(); + + // VtkASCII FILE + out << "# vtk DataFile Version 4.0" + << "\n"; + out << "GeoFile" + << "\n"; + out << "ASCII" + << "\n"; + + // POINTS SECTION + out << "DATASET UNSTRUCTURED_GRID" + << "\n"; + out << "POINTS " << nofNodes << " float" + << "\n"; + for (int n = 0; n < nofNodes; n++) + out << val<1>(nodes[n]) << " " << val<2>(nodes[n]) << " " << val<3>(nodes[n]) << " \n"; + + out << "\n"; + + // CELLS SECTION + out << "CELLS " << nofCells << " " << 5 * nofCells << "\n"; + for (int c = 0; c < (int)cells.size(); c++) + out << "4 " << val<1>(cells[c]) << " " << val<2>(cells[c]) << " " << val<4>(cells[c]) << " " << val<3>(cells[c]) + << " \n"; + out << "\n"; + + out << "CELL_TYPES " << nofCells << "\n"; + for (int i = 0; i < nofCells; i++) + out << "8" << endl; + out << endl; + + out.close(); + + UBLOG(logDEBUG1, "WbWriterVtkASCII::writeQuads to " << vtkfilename << " - end"); + + return vtkfilename; } /*===============================================================================*/ -std::string WbWriterVtkASCII::writeQuadsWithNodeData(const string& filename,vector< UbTupleFloat3 >& nodes, vector< UbTupleInt4 >& cells, vector< string >& datanames, vector< vector< double > >& nodedata) +std::string WbWriterVtkASCII::writeQuadsWithNodeData(const string &filename, vector<UbTupleFloat3> &nodes, + vector<UbTupleInt4> &cells, vector<string> &datanames, + vector<vector<double>> &nodedata) { - string vtkfilename=filename+getFileExtension(); - UBLOG(logDEBUG1,"WbWriterVtkASCII::writeQuadsWithNodeData to "<<vtkfilename<<" - start"); - - std::ofstream out(vtkfilename.c_str()); - if(!out) - { - out.clear(); //flags ruecksetzen (ansonsten liefert utern if(!out) weiterhin true!!! - string path = UbSystem::getPathFromString(vtkfilename); - if(path.size()>0){UbSystem::makeDirectory(path);out.open(vtkfilename.c_str());} - if(!out) throw UbException(UB_EXARGS,"couldn't open file "+vtkfilename); - } - - //write geo - int nofNodes = (int)nodes.size(); - int nofCells = (int)cells.size(); - - //VtkASCII FILE - out<<"# vtk DataFile Version 4.0"<<"\n"; - out<<"GeoFile"<<"\n"; - out<<"ASCII"<<"\n"; - - //POINTS SECTION - out<<"DATASET UNSTRUCTURED_GRID"<<"\n"; - out<<"POINTS "<<nofNodes<<" float"<<"\n"; - for(int n=0; n<nofNodes; n++) - out<< val<1>(nodes[n]) <<" "<< val<2>(nodes[n]) <<" "<< val<3>(nodes[n]) <<" \n"; - - out<<"\n"; - - //CELLS SECTION - out<<"CELLS "<<nofCells<<" "<<5*nofCells<<"\n"; - for(int c=0; c<(int)cells.size(); c++) - out<<"4 " - << val<1>(cells[c]) <<" " - << val<2>(cells[c]) <<" " - << val<4>(cells[c]) <<" " - << val<3>(cells[c]) <<" \n"; - out<<"\n"; - - out<<"CELL_TYPES "<<nofCells<<"\n"; - for(int i=0; i<nofCells; i++) out<<"8"<<endl; - out<<endl; - - //write data section - out<<"POINT_DATA "<<nofNodes<<"\n"; - for(int s=0; s<(int)datanames.size(); ++s) - { - out<<"SCALARS "<<datanames[s]<<" float 1 \n LOOKUP_TABLE default \n"; - for(int d=0; d<(int)nodedata[s].size(); d++) - out<<nodedata[s][d]<<"\n"; - - out<<endl; - } - - out.close(); - UBLOG(logDEBUG1,"WbWriterVtkASCII::writeQuadsWithNodeData to "<<vtkfilename<<" - end"); - return vtkfilename; + string vtkfilename = filename + getFileExtension(); + UBLOG(logDEBUG1, "WbWriterVtkASCII::writeQuadsWithNodeData to " << vtkfilename << " - start"); + + std::ofstream out(vtkfilename.c_str()); + if (!out) { + out.clear(); // flags ruecksetzen (ansonsten liefert utern if(!out) weiterhin true!!! + string path = UbSystem::getPathFromString(vtkfilename); + if (path.size() > 0) { + UbSystem::makeDirectory(path); + out.open(vtkfilename.c_str()); + } + if (!out) + throw UbException(UB_EXARGS, "couldn't open file " + vtkfilename); + } + + // write geo + int nofNodes = (int)nodes.size(); + int nofCells = (int)cells.size(); + + // VtkASCII FILE + out << "# vtk DataFile Version 4.0" + << "\n"; + out << "GeoFile" + << "\n"; + out << "ASCII" + << "\n"; + + // POINTS SECTION + out << "DATASET UNSTRUCTURED_GRID" + << "\n"; + out << "POINTS " << nofNodes << " float" + << "\n"; + for (int n = 0; n < nofNodes; n++) + out << val<1>(nodes[n]) << " " << val<2>(nodes[n]) << " " << val<3>(nodes[n]) << " \n"; + + out << "\n"; + + // CELLS SECTION + out << "CELLS " << nofCells << " " << 5 * nofCells << "\n"; + for (int c = 0; c < (int)cells.size(); c++) + out << "4 " << val<1>(cells[c]) << " " << val<2>(cells[c]) << " " << val<4>(cells[c]) << " " << val<3>(cells[c]) + << " \n"; + out << "\n"; + + out << "CELL_TYPES " << nofCells << "\n"; + for (int i = 0; i < nofCells; i++) + out << "8" << endl; + out << endl; + + // write data section + out << "POINT_DATA " << nofNodes << "\n"; + for (int s = 0; s < (int)datanames.size(); ++s) { + out << "SCALARS " << datanames[s] << " float 1 \n LOOKUP_TABLE default \n"; + for (int d = 0; d < (int)nodedata[s].size(); d++) + out << nodedata[s][d] << "\n"; + + out << endl; + } + + out.close(); + UBLOG(logDEBUG1, "WbWriterVtkASCII::writeQuadsWithNodeData to " << vtkfilename << " - end"); + return vtkfilename; } /*===============================================================================*/ -std::string WbWriterVtkASCII::writeQuadsWithCellData(const string& filename,vector< UbTupleFloat3 >& nodes, vector< UbTupleInt4 >& cells, vector< string >& datanames, vector< vector< double > >& celldata) +std::string WbWriterVtkASCII::writeQuadsWithCellData(const string &filename, vector<UbTupleFloat3> &nodes, + vector<UbTupleInt4> &cells, vector<string> &datanames, + vector<vector<double>> &celldata) { - string vtkfilename=filename+getFileExtension(); - UBLOG(logDEBUG1,"WbWriterVtkASCII::writeQuadsWithCellData to "<<vtkfilename<<" - start"); - - std::ofstream out(vtkfilename.c_str()); - if(!out) - { - out.clear(); //flags ruecksetzen (ansonsten liefert utern if(!out) weiterhin true!!! - string path = UbSystem::getPathFromString(vtkfilename); - if(path.size()>0){UbSystem::makeDirectory(path);out.open(vtkfilename.c_str());} - if(!out) throw UbException(UB_EXARGS,"couldn't open file "+vtkfilename); - } - - //write geo - int nofNodes = (int)nodes.size(); - int nofCells = (int)cells.size(); - - //VtkASCII FILE - out<<"# vtk DataFile Version 4.0"<<"\n"; - out<<"GeoFile"<<"\n"; - out<<"ASCII"<<"\n"; - - //POINTS SECTION - out<<"DATASET UNSTRUCTURED_GRID"<<"\n"; - out<<"POINTS "<<nofNodes<<" float"<<"\n"; - for(int n=0; n<nofNodes; n++) - out<< val<1>(nodes[n]) <<" "<< val<2>(nodes[n]) <<" "<< val<3>(nodes[n]) <<" \n"; - - out<<"\n"; - - //CELLS SECTION - out<<"CELLS "<<nofCells<<" "<<5*nofCells<<"\n"; - for(int c=0; c<(int)cells.size(); c++) - out<<"4 " - << val<1>(cells[c]) <<" " - << val<2>(cells[c]) <<" " - << val<4>(cells[c]) <<" " - << val<3>(cells[c]) <<" \n"; - out<<"\n"; - - out<<"CELL_TYPES "<<nofCells<<"\n"; - for(int i=0; i<nofCells; i++) out<<"8"<<endl; - out<<endl; - - //write data section - out<<"CELL_DATA "<<nofCells<<"\n"; - for(int s=0; s<(int)datanames.size(); ++s) - { - out<<"SCALARS "<<datanames[s]<<" float 1 \n LOOKUP_TABLE default \n"; - for(int d=0; d<(int)celldata[s].size(); d++) - out<<celldata[s][d]<<"\n"; - - out<<endl; - } - - out.close(); - UBLOG(logDEBUG1,"WbWriterVtkASCII::writeQuadsWithCellData to "<<vtkfilename<<" - end"); - return vtkfilename; + string vtkfilename = filename + getFileExtension(); + UBLOG(logDEBUG1, "WbWriterVtkASCII::writeQuadsWithCellData to " << vtkfilename << " - start"); + + std::ofstream out(vtkfilename.c_str()); + if (!out) { + out.clear(); // flags ruecksetzen (ansonsten liefert utern if(!out) weiterhin true!!! + string path = UbSystem::getPathFromString(vtkfilename); + if (path.size() > 0) { + UbSystem::makeDirectory(path); + out.open(vtkfilename.c_str()); + } + if (!out) + throw UbException(UB_EXARGS, "couldn't open file " + vtkfilename); + } + + // write geo + int nofNodes = (int)nodes.size(); + int nofCells = (int)cells.size(); + + // VtkASCII FILE + out << "# vtk DataFile Version 4.0" + << "\n"; + out << "GeoFile" + << "\n"; + out << "ASCII" + << "\n"; + + // POINTS SECTION + out << "DATASET UNSTRUCTURED_GRID" + << "\n"; + out << "POINTS " << nofNodes << " float" + << "\n"; + for (int n = 0; n < nofNodes; n++) + out << val<1>(nodes[n]) << " " << val<2>(nodes[n]) << " " << val<3>(nodes[n]) << " \n"; + + out << "\n"; + + // CELLS SECTION + out << "CELLS " << nofCells << " " << 5 * nofCells << "\n"; + for (int c = 0; c < (int)cells.size(); c++) + out << "4 " << val<1>(cells[c]) << " " << val<2>(cells[c]) << " " << val<4>(cells[c]) << " " << val<3>(cells[c]) + << " \n"; + out << "\n"; + + out << "CELL_TYPES " << nofCells << "\n"; + for (int i = 0; i < nofCells; i++) + out << "8" << endl; + out << endl; + + // write data section + out << "CELL_DATA " << nofCells << "\n"; + for (int s = 0; s < (int)datanames.size(); ++s) { + out << "SCALARS " << datanames[s] << " float 1 \n LOOKUP_TABLE default \n"; + for (int d = 0; d < (int)celldata[s].size(); d++) + out << celldata[s][d] << "\n"; + + out << endl; + } + + out.close(); + UBLOG(logDEBUG1, "WbWriterVtkASCII::writeQuadsWithCellData to " << vtkfilename << " - end"); + return vtkfilename; } /*===============================================================================*/ -std::string WbWriterVtkASCII::writeQuadsWithNodeAndCellData(const string& filename,vector< UbTupleFloat3 >& nodes, vector< UbTupleInt4 >& cells, - vector< string >& nodedatanames, vector< vector< double > >& nodedata, vector< string >& celldatanames, - vector< vector< double > >& celldata ) +std::string WbWriterVtkASCII::writeQuadsWithNodeAndCellData(const string &filename, vector<UbTupleFloat3> &nodes, + vector<UbTupleInt4> &cells, vector<string> &nodedatanames, + vector<vector<double>> &nodedata, + vector<string> &celldatanames, + vector<vector<double>> &celldata) { - string vtkfilename=filename+getFileExtension(); - UBLOG(logDEBUG1,"WbWriterVtkASCII::writeQuadsWithNodeAndCellData to "<<vtkfilename<<" - start"); - - std::ofstream out(vtkfilename.c_str()); - if(!out) - { - out.clear(); //flags ruecksetzen (ansonsten liefert utern if(!out) weiterhin true!!! - string path = UbSystem::getPathFromString(vtkfilename); - if(path.size()>0){UbSystem::makeDirectory(path);out.open(vtkfilename.c_str());} - if(!out) throw UbException(UB_EXARGS,"couldn't open file "+vtkfilename); - } - - //write geo - int nofNodes = (int)nodes.size(); - int nofCells = (int)cells.size(); - - //VtkASCII FILE - out<<"# vtk DataFile Version 4.0"<<"\n"; - out<<"GeoFile"<<"\n"; - out<<"ASCII"<<"\n"; - - //POINTS SECTION - out<<"DATASET UNSTRUCTURED_GRID"<<"\n"; - out<<"POINTS "<<nofNodes<<" float"<<"\n"; - for(int n=0; n<nofNodes; n++) - out<< val<1>(nodes[n]) <<" "<< val<2>(nodes[n]) <<" "<< val<3>(nodes[n]) <<" \n"; - - out<<"\n"; - - //CELLS SECTION - out<<"CELLS "<<nofCells<<" "<<5*nofCells<<"\n"; - for(int c=0; c<(int)cells.size(); c++) - out<<"4 " - << val<1>(cells[c]) <<" " - << val<2>(cells[c]) <<" " - << val<4>(cells[c]) <<" " - << val<3>(cells[c]) <<" \n"; - out<<"\n"; - - out<<"CELL_TYPES "<<nofCells<<"\n"; - for(int i=0; i<nofCells; i++) out<<"8"<<endl; - out<<endl; - - //write node data section - out<<"POINT_DATA "<<nofNodes<<"\n"; - for(int s=0; s<(int)nodedatanames.size(); ++s) - { - out<<"SCALARS "<<nodedatanames[s]<<" float 1 \n LOOKUP_TABLE default \n"; - for(int d=0; d<(int)nodedata[s].size(); d++) - out<<nodedata[s][d]<<"\n"; - - out<<endl; - } - - //write cell data section - out<<"CELL_DATA "<<nofCells<<"\n"; - for(int s=0; s<(int)celldatanames.size(); ++s) - { - out<<"SCALARS "<<celldatanames[s]<<" float 1 \n LOOKUP_TABLE default \n"; - for(int d=0; d<(int)celldata[s].size(); d++) - out<<celldata[s][d]<<"\n"; - - out<<endl; - } - - out.close(); - UBLOG(logDEBUG1,"WbWriterVtkASCII::writeQuadsWithNodeAndCellData to "<<vtkfilename<<" - end"); - return vtkfilename; + string vtkfilename = filename + getFileExtension(); + UBLOG(logDEBUG1, "WbWriterVtkASCII::writeQuadsWithNodeAndCellData to " << vtkfilename << " - start"); + + std::ofstream out(vtkfilename.c_str()); + if (!out) { + out.clear(); // flags ruecksetzen (ansonsten liefert utern if(!out) weiterhin true!!! + string path = UbSystem::getPathFromString(vtkfilename); + if (path.size() > 0) { + UbSystem::makeDirectory(path); + out.open(vtkfilename.c_str()); + } + if (!out) + throw UbException(UB_EXARGS, "couldn't open file " + vtkfilename); + } + + // write geo + int nofNodes = (int)nodes.size(); + int nofCells = (int)cells.size(); + + // VtkASCII FILE + out << "# vtk DataFile Version 4.0" + << "\n"; + out << "GeoFile" + << "\n"; + out << "ASCII" + << "\n"; + + // POINTS SECTION + out << "DATASET UNSTRUCTURED_GRID" + << "\n"; + out << "POINTS " << nofNodes << " float" + << "\n"; + for (int n = 0; n < nofNodes; n++) + out << val<1>(nodes[n]) << " " << val<2>(nodes[n]) << " " << val<3>(nodes[n]) << " \n"; + + out << "\n"; + + // CELLS SECTION + out << "CELLS " << nofCells << " " << 5 * nofCells << "\n"; + for (int c = 0; c < (int)cells.size(); c++) + out << "4 " << val<1>(cells[c]) << " " << val<2>(cells[c]) << " " << val<4>(cells[c]) << " " << val<3>(cells[c]) + << " \n"; + out << "\n"; + + out << "CELL_TYPES " << nofCells << "\n"; + for (int i = 0; i < nofCells; i++) + out << "8" << endl; + out << endl; + + // write node data section + out << "POINT_DATA " << nofNodes << "\n"; + for (int s = 0; s < (int)nodedatanames.size(); ++s) { + out << "SCALARS " << nodedatanames[s] << " float 1 \n LOOKUP_TABLE default \n"; + for (int d = 0; d < (int)nodedata[s].size(); d++) + out << nodedata[s][d] << "\n"; + + out << endl; + } + + // write cell data section + out << "CELL_DATA " << nofCells << "\n"; + for (int s = 0; s < (int)celldatanames.size(); ++s) { + out << "SCALARS " << celldatanames[s] << " float 1 \n LOOKUP_TABLE default \n"; + for (int d = 0; d < (int)celldata[s].size(); d++) + out << celldata[s][d] << "\n"; + + out << endl; + } + + out.close(); + UBLOG(logDEBUG1, "WbWriterVtkASCII::writeQuadsWithNodeAndCellData to " << vtkfilename << " - end"); + return vtkfilename; } /*===============================================================================*/ -std::string WbWriterVtkASCII::writeLines(const string& filename,vector<UbTupleFloat3 >& nodes, vector<UbTupleInt2 >& lines) +std::string WbWriterVtkASCII::writeLines(const string &filename, vector<UbTupleFloat3> &nodes, + vector<UbTupleInt2> &lines) { - string vtkfilename=filename+getFileExtension(); - UBLOG(logDEBUG1,"WbWriterVtkASCII::writeLines to "<<vtkfilename<<" - start"); - - std::ofstream out(vtkfilename.c_str()); - if(!out) - { - out.clear(); //flags ruecksetzen (ansonsten liefert utern if(!out) weiterhin true!!! - string path = UbSystem::getPathFromString(vtkfilename); - if(path.size()>0){UbSystem::makeDirectory(path);out.open(vtkfilename.c_str());} - if(!out) throw UbException(UB_EXARGS,"couldn't open file "+vtkfilename); - } - - int nofNodes = (int)nodes.size(); - int nofLines = (int)lines.size(); - - //VtkASCII FILE - out<<"# vtk DataFile Version 4.0"<<"\n"; - out<<"GeoFile"<<"\n"; - out<<"ASCII"<<"\n"; - - //POINTS SECTION - out<<"DATASET UNSTRUCTURED_GRID"<<"\n"; - out<<"POINTS "<<nofNodes<<" float"<<"\n"; - for(int n=0; n<nofNodes; n++) - { - out<< val<1>(nodes[n]) <<" "<< val<2>(nodes[n]) <<" "<< val<3>(nodes[n])<<" \n"; - } - out<<"\n"; - - //CELLS SECTION - out<<"CELLS "<<nofLines<<" "<<3*nofLines<<"\n"; - int nr = 0; - for(int l=0; l<nofLines; l++) - { - int el = nr+1; - out<<"2 "<< val<1>(lines[l]) <<" "<< val<2>(lines[l]) <<" "<<endl; - nr=el+1; - } - out<<"\n"; - - out<<"CELL_TYPES "<<nofLines<<"\n"; - for(int l=0; l<nofLines; l++) out<<"3"<<endl; - out<<endl; - - out.close(); - - UBLOG(logDEBUG1,"WbWriterVtkASCII::writeLines to "<<vtkfilename<<" - end"); - return vtkfilename; + string vtkfilename = filename + getFileExtension(); + UBLOG(logDEBUG1, "WbWriterVtkASCII::writeLines to " << vtkfilename << " - start"); + + std::ofstream out(vtkfilename.c_str()); + if (!out) { + out.clear(); // flags ruecksetzen (ansonsten liefert utern if(!out) weiterhin true!!! + string path = UbSystem::getPathFromString(vtkfilename); + if (path.size() > 0) { + UbSystem::makeDirectory(path); + out.open(vtkfilename.c_str()); + } + if (!out) + throw UbException(UB_EXARGS, "couldn't open file " + vtkfilename); + } + + int nofNodes = (int)nodes.size(); + int nofLines = (int)lines.size(); + + // VtkASCII FILE + out << "# vtk DataFile Version 4.0" + << "\n"; + out << "GeoFile" + << "\n"; + out << "ASCII" + << "\n"; + + // POINTS SECTION + out << "DATASET UNSTRUCTURED_GRID" + << "\n"; + out << "POINTS " << nofNodes << " float" + << "\n"; + for (int n = 0; n < nofNodes; n++) { + out << val<1>(nodes[n]) << " " << val<2>(nodes[n]) << " " << val<3>(nodes[n]) << " \n"; + } + out << "\n"; + + // CELLS SECTION + out << "CELLS " << nofLines << " " << 3 * nofLines << "\n"; + int nr = 0; + for (int l = 0; l < nofLines; l++) { + int el = nr + 1; + out << "2 " << val<1>(lines[l]) << " " << val<2>(lines[l]) << " " << endl; + nr = el + 1; + } + out << "\n"; + + out << "CELL_TYPES " << nofLines << "\n"; + for (int l = 0; l < nofLines; l++) + out << "3" << endl; + out << endl; + + out.close(); + + UBLOG(logDEBUG1, "WbWriterVtkASCII::writeLines to " << vtkfilename << " - end"); + return vtkfilename; } /*===============================================================================*/ -std::string WbWriterVtkASCII::writeTriangles(const string& filename,vector<UbTupleFloat3 >& nodes, vector<UbTupleInt3 >& triangles) +std::string WbWriterVtkASCII::writeTriangles(const string &filename, vector<UbTupleFloat3> &nodes, + vector<UbTupleInt3> &triangles) { - string vtkfilename=filename+getFileExtension(); - UBLOG(logDEBUG1,"WbWriterVtkASCII::writeTriangles to "<<vtkfilename<<" - start"); - - std::ofstream out(vtkfilename.c_str()); - if(!out) - { - out.clear(); //flags ruecksetzen (ansonsten liefert utern if(!out) weiterhin true!!! - string path = UbSystem::getPathFromString(vtkfilename); - if(path.size()>0){UbSystem::makeDirectory(path);out.open(vtkfilename.c_str());} - if(!out) throw UbException(UB_EXARGS,"couldn't open file "+vtkfilename); - } - - int nofNodes = (int)nodes.size(); - int nofTriangles = (int)triangles.size(); - - //VtkASCII FILE - out<<"# vtk DataFile Version 4.0"<<"\n"; - out<<"GeoFile"<<"\n"; - out<<"ASCII"<<"\n"; - - //POINTS SECTION - out<<"DATASET UNSTRUCTURED_GRID"<<"\n"; - out<<"POINTS "<<nofNodes<<" float"<<"\n"; - for(int n=0; n<nofNodes; n++) - { - out<< val<1>(nodes[n]) <<" "<< val<2>(nodes[n]) <<" "<< val<3>(nodes[n])<<" \n"; - } - out<<"\n"; - - //CELLS SECTION - out<<"CELLS "<<nofTriangles<<" "<<4*nofTriangles<<"\n"; - int nr = 0; - for(int t=0; t<nofTriangles; t++) - { - int el = nr+1; - out<<"3 "<< val<1>(triangles[t]) <<" "<< val<2>(triangles[t]) <<" "<< val<3>(triangles[t]) <<" "<<endl; - nr=el+1; - } - out<<"\n"; - - out<<"CELL_TYPES "<<nofTriangles<<"\n"; - for(int l=0; l<nofTriangles; l++) out<<"5"<<endl; - out<<endl; - - out.close(); - - UBLOG(logDEBUG1,"WbWriterVtkASCII::writeTriangles to "<<vtkfilename<<" - end"); - return vtkfilename; + string vtkfilename = filename + getFileExtension(); + UBLOG(logDEBUG1, "WbWriterVtkASCII::writeTriangles to " << vtkfilename << " - start"); + + std::ofstream out(vtkfilename.c_str()); + if (!out) { + out.clear(); // flags ruecksetzen (ansonsten liefert utern if(!out) weiterhin true!!! + string path = UbSystem::getPathFromString(vtkfilename); + if (path.size() > 0) { + UbSystem::makeDirectory(path); + out.open(vtkfilename.c_str()); + } + if (!out) + throw UbException(UB_EXARGS, "couldn't open file " + vtkfilename); + } + + int nofNodes = (int)nodes.size(); + int nofTriangles = (int)triangles.size(); + + // VtkASCII FILE + out << "# vtk DataFile Version 4.0" + << "\n"; + out << "GeoFile" + << "\n"; + out << "ASCII" + << "\n"; + + // POINTS SECTION + out << "DATASET UNSTRUCTURED_GRID" + << "\n"; + out << "POINTS " << nofNodes << " float" + << "\n"; + for (int n = 0; n < nofNodes; n++) { + out << val<1>(nodes[n]) << " " << val<2>(nodes[n]) << " " << val<3>(nodes[n]) << " \n"; + } + out << "\n"; + + // CELLS SECTION + out << "CELLS " << nofTriangles << " " << 4 * nofTriangles << "\n"; + int nr = 0; + for (int t = 0; t < nofTriangles; t++) { + int el = nr + 1; + out << "3 " << val<1>(triangles[t]) << " " << val<2>(triangles[t]) << " " << val<3>(triangles[t]) << " " + << endl; + nr = el + 1; + } + out << "\n"; + + out << "CELL_TYPES " << nofTriangles << "\n"; + for (int l = 0; l < nofTriangles; l++) + out << "5" << endl; + out << endl; + + out.close(); + + UBLOG(logDEBUG1, "WbWriterVtkASCII::writeTriangles to " << vtkfilename << " - end"); + return vtkfilename; } /*===============================================================================*/ -std::string WbWriterVtkASCII::writeTrianglesWithNodeData(const string& filename,vector< UbTupleFloat3 >& nodes, vector< UbTupleInt3 >& cells, vector< string >& datanames, vector< vector< double > >& nodedata) +std::string WbWriterVtkASCII::writeTrianglesWithNodeData(const string &filename, vector<UbTupleFloat3> &nodes, + vector<UbTupleInt3> &cells, vector<string> &datanames, + vector<vector<double>> &nodedata) { - string vtkfilename=filename+getFileExtension(); - UBLOG(logDEBUG1,"WbWriterVtkASCII::writeTrianglesWithNodeData to "<<vtkfilename<<" - start"); - - std::ofstream out(vtkfilename.c_str()); - if(!out) - { - out.clear(); //flags ruecksetzen (ansonsten liefert utern if(!out) weiterhin true!!! - string path = UbSystem::getPathFromString(vtkfilename); - if(path.size()>0){UbSystem::makeDirectory(path);out.open(vtkfilename.c_str());} - if(!out) throw UbException(UB_EXARGS,"couldn't open file "+vtkfilename); - } - - //write geo - int nofNodes = (int)nodes.size(); - int nofCells = (int)cells.size(); - - //VtkASCII FILE - out<<"# vtk DataFile Version 4.0"<<"\n"; - out<<"GeoFile"<<"\n"; - out<<"ASCII"<<"\n"; - - //POINTS SECTION - out<<"DATASET UNSTRUCTURED_GRID"<<"\n"; - out<<"POINTS "<<nofNodes<<" float"<<"\n"; - for(int n=0; n<nofNodes; n++) - out<< val<1>(nodes[n]) <<" "<< val<2>(nodes[n]) <<" "<< val<3>(nodes[n]) <<" \n"; - - out<<"\n"; - - //CELLS SECTION - out<<"CELLS "<<nofCells<<" "<<4*nofCells<<"\n"; - for(int c=0; c<(int)cells.size(); c++) - out<<"3 "<< val<1>(cells[c]) <<" "<< val<2>(cells[c]) <<" "<< val<3>(cells[c]) <<" \n"; - out<<"\n"; - - out<<"CELL_TYPES "<<nofCells<<"\n"; - for(int i=0; i<nofCells; i++) out<<"5"<<endl; - out<<endl; - - //write data section - out<<"POINT_DATA "<<nofNodes<<"\n"; - for(int s=0; s<(int)datanames.size(); ++s) - { - out<<"SCALARS "<<datanames[s]<<" float 1 \n LOOKUP_TABLE default \n"; - for(int d=0; d<(int)nodedata[s].size(); d++) - out<<nodedata[s][d]<<"\n"; - - out<<endl; - } - - out.close(); - UBLOG(logDEBUG1,"WbWriterVtkASCII::writeTrianglesWithNodeData to "<<vtkfilename<<" - end"); - return vtkfilename; + string vtkfilename = filename + getFileExtension(); + UBLOG(logDEBUG1, "WbWriterVtkASCII::writeTrianglesWithNodeData to " << vtkfilename << " - start"); + + std::ofstream out(vtkfilename.c_str()); + if (!out) { + out.clear(); // flags ruecksetzen (ansonsten liefert utern if(!out) weiterhin true!!! + string path = UbSystem::getPathFromString(vtkfilename); + if (path.size() > 0) { + UbSystem::makeDirectory(path); + out.open(vtkfilename.c_str()); + } + if (!out) + throw UbException(UB_EXARGS, "couldn't open file " + vtkfilename); + } + + // write geo + int nofNodes = (int)nodes.size(); + int nofCells = (int)cells.size(); + + // VtkASCII FILE + out << "# vtk DataFile Version 4.0" + << "\n"; + out << "GeoFile" + << "\n"; + out << "ASCII" + << "\n"; + + // POINTS SECTION + out << "DATASET UNSTRUCTURED_GRID" + << "\n"; + out << "POINTS " << nofNodes << " float" + << "\n"; + for (int n = 0; n < nofNodes; n++) + out << val<1>(nodes[n]) << " " << val<2>(nodes[n]) << " " << val<3>(nodes[n]) << " \n"; + + out << "\n"; + + // CELLS SECTION + out << "CELLS " << nofCells << " " << 4 * nofCells << "\n"; + for (int c = 0; c < (int)cells.size(); c++) + out << "3 " << val<1>(cells[c]) << " " << val<2>(cells[c]) << " " << val<3>(cells[c]) << " \n"; + out << "\n"; + + out << "CELL_TYPES " << nofCells << "\n"; + for (int i = 0; i < nofCells; i++) + out << "5" << endl; + out << endl; + + // write data section + out << "POINT_DATA " << nofNodes << "\n"; + for (int s = 0; s < (int)datanames.size(); ++s) { + out << "SCALARS " << datanames[s] << " float 1 \n LOOKUP_TABLE default \n"; + for (int d = 0; d < (int)nodedata[s].size(); d++) + out << nodedata[s][d] << "\n"; + + out << endl; + } + + out.close(); + UBLOG(logDEBUG1, "WbWriterVtkASCII::writeTrianglesWithNodeData to " << vtkfilename << " - end"); + return vtkfilename; } /*===============================================================================*/ -std::string WbWriterVtkASCII::writeOctsWithCellData(const string& filename,vector< UbTupleFloat3 >& nodes, vector< UbTupleInt8 >& cells, vector< string >& datanames, vector< vector< double > >& celldata) +std::string WbWriterVtkASCII::writeOctsWithCellData(const string &filename, vector<UbTupleFloat3> &nodes, + vector<UbTupleInt8> &cells, vector<string> &datanames, + vector<vector<double>> &celldata) { - string vtkfilename=filename+getFileExtension(); - UBLOG(logDEBUG1,"WbWriterVtkASCII::writeOctsWithCellData to "<<vtkfilename<<" - start"); - - std::ofstream out(vtkfilename.c_str()); - if(!out) - { - out.clear(); //flags ruecksetzen (ansonsten liefert utern if(!out) weiterhin true!!! - string path = UbSystem::getPathFromString(vtkfilename); - if(path.size()>0){UbSystem::makeDirectory(path);out.open(vtkfilename.c_str());} - if(!out) throw UbException(UB_EXARGS,"couldn't open file "+vtkfilename); - } - - //write geo - int nofNodes = (int)nodes.size(); - int nofCells = (int)cells.size(); - - //VtkASCII FILE - out<<"# vtk DataFile Version 4.0"<<"\n"; - out<<"GeoFile"<<"\n"; - out<<"ASCII"<<"\n"; - - //POINTS SECTION - out<<"DATASET UNSTRUCTURED_GRID"<<"\n"; - out<<"POINTS "<<nofNodes<<" float"<<"\n"; - for(int n=0; n<nofNodes; n++) - out<< val<1>(nodes[n]) <<" "<< val<2>(nodes[n]) <<" "<< val<3>(nodes[n]) <<" \n"; - - out<<"\n"; - - //CELLS SECTION - out<<"CELLS "<<nofCells<<" "<<9*nofCells<<"\n"; - for(int c=0; c<(int)cells.size(); c++) - { out<<"8 " - << val<1>(cells[c]) <<" " - << val<2>(cells[c]) <<" " - << val<4>(cells[c]) <<" " - << val<3>(cells[c]) <<" " - << val<5>(cells[c]) <<" " - << val<6>(cells[c]) <<" " - << val<8>(cells[c]) <<" " - << val<7>(cells[c]) <<" \n"; - } - - out<<"\n"; - - out<<"CELL_TYPES "<<nofCells<<"\n"; - for(int i=0; i<nofCells; i++) out<<"11 "<<endl; - out<<endl; - - //write data section - out<<"CELL_DATA "<<nofCells<<"\n"; - for(int s=0; s<(int)datanames.size(); ++s) - { - out<<"SCALARS "<<datanames[s]<<" float 1 \n LOOKUP_TABLE default \n"; - for(int d=0; d<(int)celldata[s].size(); d++) - out<<celldata[s][d]<<"\n"; - - out<<endl; - } - - out.close(); - UBLOG(logDEBUG1,"WbWriterVtkASCII::writeOctsWithCellData to "<<vtkfilename<<" - end"); - - return vtkfilename; + string vtkfilename = filename + getFileExtension(); + UBLOG(logDEBUG1, "WbWriterVtkASCII::writeOctsWithCellData to " << vtkfilename << " - start"); + + std::ofstream out(vtkfilename.c_str()); + if (!out) { + out.clear(); // flags ruecksetzen (ansonsten liefert utern if(!out) weiterhin true!!! + string path = UbSystem::getPathFromString(vtkfilename); + if (path.size() > 0) { + UbSystem::makeDirectory(path); + out.open(vtkfilename.c_str()); + } + if (!out) + throw UbException(UB_EXARGS, "couldn't open file " + vtkfilename); + } + + // write geo + int nofNodes = (int)nodes.size(); + int nofCells = (int)cells.size(); + + // VtkASCII FILE + out << "# vtk DataFile Version 4.0" + << "\n"; + out << "GeoFile" + << "\n"; + out << "ASCII" + << "\n"; + + // POINTS SECTION + out << "DATASET UNSTRUCTURED_GRID" + << "\n"; + out << "POINTS " << nofNodes << " float" + << "\n"; + for (int n = 0; n < nofNodes; n++) + out << val<1>(nodes[n]) << " " << val<2>(nodes[n]) << " " << val<3>(nodes[n]) << " \n"; + + out << "\n"; + + // CELLS SECTION + out << "CELLS " << nofCells << " " << 9 * nofCells << "\n"; + for (int c = 0; c < (int)cells.size(); c++) { + out << "8 " << val<1>(cells[c]) << " " << val<2>(cells[c]) << " " << val<4>(cells[c]) << " " << val<3>(cells[c]) + << " " << val<5>(cells[c]) << " " << val<6>(cells[c]) << " " << val<8>(cells[c]) << " " << val<7>(cells[c]) + << " \n"; + } + + out << "\n"; + + out << "CELL_TYPES " << nofCells << "\n"; + for (int i = 0; i < nofCells; i++) + out << "11 " << endl; + out << endl; + + // write data section + out << "CELL_DATA " << nofCells << "\n"; + for (int s = 0; s < (int)datanames.size(); ++s) { + out << "SCALARS " << datanames[s] << " float 1 \n LOOKUP_TABLE default \n"; + for (int d = 0; d < (int)celldata[s].size(); d++) + out << celldata[s][d] << "\n"; + + out << endl; + } + + out.close(); + UBLOG(logDEBUG1, "WbWriterVtkASCII::writeOctsWithCellData to " << vtkfilename << " - end"); + + return vtkfilename; } /*===============================================================================*/ -std::string WbWriterVtkASCII::writeOctsWithNodeData(const string& filename,vector< UbTupleFloat3 >& nodes, vector< UbTupleUInt8 >& cells, vector< string >& datanames, vector< vector< double > >& nodedata) +std::string WbWriterVtkASCII::writeOctsWithNodeData(const string &filename, vector<UbTupleFloat3> &nodes, + vector<UbTupleUInt8> &cells, vector<string> &datanames, + vector<vector<double>> &nodedata) { - string vtkfilename=filename+getFileExtension(); - UBLOG(logDEBUG1,"WbWriterVtkASCII::writeOctsWithNodeData to "<<vtkfilename<<" - start"); - - std::ofstream out(vtkfilename.c_str()); - if(!out) - { - out.clear(); //flags ruecksetzen (ansonsten liefert utern if(!out) weiterhin true!!! - string path = UbSystem::getPathFromString(vtkfilename); - if(path.size()>0){UbSystem::makeDirectory(path);out.open(vtkfilename.c_str());} - if(!out) throw UbException(UB_EXARGS,"couldn't open file "+vtkfilename); - } - - //write geo - int nofNodes = (int)nodes.size(); - int nofCells = (int)cells.size(); - - //VtkASCII FILE - out<<"# vtk DataFile Version 4.0"<<"\n"; - out<<"GeoFile"<<"\n"; - out<<"ASCII"<<"\n"; - - //POINTS SECTION - out<<"DATASET UNSTRUCTURED_GRID"<<"\n"; - out<<"POINTS "<<nofNodes<<" float"<<"\n"; - for(int n=0; n<nofNodes; n++) - out<< val<1>(nodes[n]) <<" "<< val<2>(nodes[n]) <<" "<< val<3>(nodes[n]) <<" \n"; - - out<<"\n"; - - //CELLS SECTION - out<<"CELLS "<<nofCells<<" "<<9*nofCells<<"\n"; - for(int c=0; c<(int)cells.size(); c++) - { out<<"8 " - << val<1>(cells[c]) <<" " - << val<2>(cells[c]) <<" " - << val<4>(cells[c]) <<" " - << val<3>(cells[c]) <<" " - << val<5>(cells[c]) <<" " - << val<6>(cells[c]) <<" " - << val<8>(cells[c]) <<" " - << val<7>(cells[c]) <<" \n"; - } - out<<"\n"; - - out<<"CELL_TYPES "<<nofCells<<"\n"; - for(int i=0; i<nofCells; i++) out<<"11"<<endl; - out<<endl; - - //write data section - out<<"POINT_DATA "<<nofNodes<<"\n"; - for(int s=0; s<(int)datanames.size(); ++s) - { - out<<"SCALARS "<<datanames[s]<<" float 1 \n LOOKUP_TABLE default \n"; - for(int d=0; d<(int)nodedata[s].size(); d++) - out<<nodedata[s][d]<<"\n"; - - out<<endl; - } - - out.close(); - UBLOG(logDEBUG1,"WbWriterVtkASCII::writeOctsWithNodeData to "<<vtkfilename<<" - end"); - return vtkfilename; + string vtkfilename = filename + getFileExtension(); + UBLOG(logDEBUG1, "WbWriterVtkASCII::writeOctsWithNodeData to " << vtkfilename << " - start"); + + std::ofstream out(vtkfilename.c_str()); + if (!out) { + out.clear(); // flags ruecksetzen (ansonsten liefert utern if(!out) weiterhin true!!! + string path = UbSystem::getPathFromString(vtkfilename); + if (path.size() > 0) { + UbSystem::makeDirectory(path); + out.open(vtkfilename.c_str()); + } + if (!out) + throw UbException(UB_EXARGS, "couldn't open file " + vtkfilename); + } + + // write geo + int nofNodes = (int)nodes.size(); + int nofCells = (int)cells.size(); + + // VtkASCII FILE + out << "# vtk DataFile Version 4.0" + << "\n"; + out << "GeoFile" + << "\n"; + out << "ASCII" + << "\n"; + + // POINTS SECTION + out << "DATASET UNSTRUCTURED_GRID" + << "\n"; + out << "POINTS " << nofNodes << " float" + << "\n"; + for (int n = 0; n < nofNodes; n++) + out << val<1>(nodes[n]) << " " << val<2>(nodes[n]) << " " << val<3>(nodes[n]) << " \n"; + + out << "\n"; + + // CELLS SECTION + out << "CELLS " << nofCells << " " << 9 * nofCells << "\n"; + for (int c = 0; c < (int)cells.size(); c++) { + out << "8 " << val<1>(cells[c]) << " " << val<2>(cells[c]) << " " << val<4>(cells[c]) << " " << val<3>(cells[c]) + << " " << val<5>(cells[c]) << " " << val<6>(cells[c]) << " " << val<8>(cells[c]) << " " << val<7>(cells[c]) + << " \n"; + } + out << "\n"; + + out << "CELL_TYPES " << nofCells << "\n"; + for (int i = 0; i < nofCells; i++) + out << "11" << endl; + out << endl; + + // write data section + out << "POINT_DATA " << nofNodes << "\n"; + for (int s = 0; s < (int)datanames.size(); ++s) { + out << "SCALARS " << datanames[s] << " float 1 \n LOOKUP_TABLE default \n"; + for (int d = 0; d < (int)nodedata[s].size(); d++) + out << nodedata[s][d] << "\n"; + + out << endl; + } + + out.close(); + UBLOG(logDEBUG1, "WbWriterVtkASCII::writeOctsWithNodeData to " << vtkfilename << " - end"); + return vtkfilename; } /*===============================================================================*/ -std::string WbWriterVtkASCII::writeOcts(const string& filename,vector< UbTupleFloat3 >& nodes, vector< UbTupleInt8 >& cells) +std::string WbWriterVtkASCII::writeOcts(const string &filename, vector<UbTupleFloat3> &nodes, + vector<UbTupleInt8> &cells) { - string vtkfilename=filename+getFileExtension(); - UBLOG(logDEBUG1,"WbWriterVtkASCII::writeOcts to "<<vtkfilename<<" - start"); - - std::ofstream out(vtkfilename.c_str()); - if(!out) - { - out.clear(); //flags ruecksetzen (ansonsten liefert utern if(!out) weiterhin true!!! - string path = UbSystem::getPathFromString(vtkfilename); - if(path.size()>0){UbSystem::makeDirectory(path);out.open(vtkfilename.c_str());} - if(!out) throw UbException(UB_EXARGS,"couldn't open file "+vtkfilename); - } - - int nofNodes = (int)nodes.size(); - int nofCells = (int)cells.size(); - - //VtkASCII FILE - out<<"# vtk DataFile Version 4.0"<<"\n"; - out<<"GeoFile"<<"\n"; - out<<"ASCII"<<"\n"; - - //POINTS SECTION - out<<"DATASET UNSTRUCTURED_GRID"<<"\n"; - out<<"POINTS "<<nofNodes<<" float"<<"\n"; - for(int n=0; n<nofNodes; n++) - out<< val<1>(nodes[n]) <<" "<< val<2>(nodes[n]) <<" "<< val<3>(nodes[n]) <<" \n"; - - out<<"\n"; - - //CELLS SECTION - out<<"CELLS "<<nofCells<<" "<<9*nofCells<<"\n"; - for(int c=0; c<(int)cells.size(); c++) - out<<"8 " - << val<1>(cells[c]) <<" " - << val<2>(cells[c]) <<" " - << val<4>(cells[c]) <<" " - << val<3>(cells[c]) <<" " - << val<5>(cells[c]) <<" " - << val<6>(cells[c]) <<" " - << val<8>(cells[c]) <<" " - << val<7>(cells[c]) <<" \n"; - out<<"\n"; - - out<<"CELL_TYPES "<<nofCells<<"\n"; - for(int i=0; i<nofCells; i++) out<<"11"<<endl; - out<<endl; - - out.close(); - - UBLOG(logDEBUG1,"WbWriterVtkASCII::writeOcts to "<<vtkfilename<<" - end"); - return vtkfilename; + string vtkfilename = filename + getFileExtension(); + UBLOG(logDEBUG1, "WbWriterVtkASCII::writeOcts to " << vtkfilename << " - start"); + + std::ofstream out(vtkfilename.c_str()); + if (!out) { + out.clear(); // flags ruecksetzen (ansonsten liefert utern if(!out) weiterhin true!!! + string path = UbSystem::getPathFromString(vtkfilename); + if (path.size() > 0) { + UbSystem::makeDirectory(path); + out.open(vtkfilename.c_str()); + } + if (!out) + throw UbException(UB_EXARGS, "couldn't open file " + vtkfilename); + } + + int nofNodes = (int)nodes.size(); + int nofCells = (int)cells.size(); + + // VtkASCII FILE + out << "# vtk DataFile Version 4.0" + << "\n"; + out << "GeoFile" + << "\n"; + out << "ASCII" + << "\n"; + + // POINTS SECTION + out << "DATASET UNSTRUCTURED_GRID" + << "\n"; + out << "POINTS " << nofNodes << " float" + << "\n"; + for (int n = 0; n < nofNodes; n++) + out << val<1>(nodes[n]) << " " << val<2>(nodes[n]) << " " << val<3>(nodes[n]) << " \n"; + + out << "\n"; + + // CELLS SECTION + out << "CELLS " << nofCells << " " << 9 * nofCells << "\n"; + for (int c = 0; c < (int)cells.size(); c++) + out << "8 " << val<1>(cells[c]) << " " << val<2>(cells[c]) << " " << val<4>(cells[c]) << " " << val<3>(cells[c]) + << " " << val<5>(cells[c]) << " " << val<6>(cells[c]) << " " << val<8>(cells[c]) << " " << val<7>(cells[c]) + << " \n"; + out << "\n"; + + out << "CELL_TYPES " << nofCells << "\n"; + for (int i = 0; i < nofCells; i++) + out << "11" << endl; + out << endl; + + out.close(); + + UBLOG(logDEBUG1, "WbWriterVtkASCII::writeOcts to " << vtkfilename << " - end"); + return vtkfilename; } diff --git a/src/basics/basics/writer/WbWriterVtkASCII.h b/src/basics/basics/writer/WbWriterVtkASCII.h index 6d422ebd1d243a3df6e4b112bbc8788a486890a2..cce49c5fdf6a8b16724006022828854383abdb51 100644 --- a/src/basics/basics/writer/WbWriterVtkASCII.h +++ b/src/basics/basics/writer/WbWriterVtkASCII.h @@ -12,63 +12,80 @@ class WbWriterVtkASCII : public WbWriter { public: - static WbWriterVtkASCII* getInstance() - { - static WbWriterVtkASCII instance; - return &instance; - } + static WbWriterVtkASCII *getInstance() + { + static WbWriterVtkASCII instance; + return &instance; + } + private: - WbWriterVtkASCII() : WbWriter() {} - WbWriterVtkASCII( const WbWriterVtkASCII& ); //no copy allowed - const WbWriterVtkASCII& operator=( const WbWriterVtkASCII& ); //no copy allowed + WbWriterVtkASCII() : WbWriter() {} + WbWriterVtkASCII(const WbWriterVtkASCII &); // no copy allowed + const WbWriterVtkASCII &operator=(const WbWriterVtkASCII &); // no copy allowed public: - std::string getFileExtension() override { return ".ascii.vtk"; } + std::string getFileExtension() override { return ".ascii.vtk"; } - ////////////////////////////////////////////////////////////////////////// - //lines - // 0 ---- 1 - //nodenumbering must start with 0! - std::string writeLines(const std::string& filename, std::vector<UbTupleFloat3 >& nodes, std::vector<UbTupleInt2 >& lines) override; + ////////////////////////////////////////////////////////////////////////// + // lines + // 0 ---- 1 + // nodenumbering must start with 0! + std::string writeLines(const std::string &filename, std::vector<UbTupleFloat3> &nodes, + std::vector<UbTupleInt2> &lines) override; - ////////////////////////////////////////////////////////////////////////// - //triangles - //cell numbering: - // 2 - // - // 0---1 - //nodenumbering must start with 0! - std::string writeTriangles(const std::string& filename,std::vector< UbTupleFloat3 >& nodes, std::vector< UbTupleInt3 >& cells) override; - std::string writeTrianglesWithNodeData(const std::string& filename,std::vector< UbTupleFloat3 >& nodes, std::vector< UbTupleInt3 >& cells, std::vector< std::string >& datanames, std::vector< std::vector< double > >& nodedata) override; + ////////////////////////////////////////////////////////////////////////// + // triangles + // cell numbering: + // 2 + // + // 0---1 + // nodenumbering must start with 0! + std::string writeTriangles(const std::string &filename, std::vector<UbTupleFloat3> &nodes, + std::vector<UbTupleInt3> &cells) override; + std::string writeTrianglesWithNodeData(const std::string &filename, std::vector<UbTupleFloat3> &nodes, + std::vector<UbTupleInt3> &cells, std::vector<std::string> &datanames, + std::vector<std::vector<double>> &nodedata) override; - ////////////////////////////////////////////////////////////////////////// - //2D - //cell numbering: - // 3---2 - // | | - // 0---1 - //nodenumbering must start with 0! - std::string writeQuads(const std::string& filename,std::vector< UbTupleFloat3 >& nodes, std::vector< UbTupleInt4 >& cells) override; - std::string writeQuadsWithNodeData(const std::string& filename,std::vector< UbTupleFloat3 >& nodes, std::vector< UbTupleInt4 >& cells, std::vector< std::string >& datanames, std::vector< std::vector< double > >& nodedata) override; - std::string writeQuadsWithCellData(const std::string& filename,std::vector< UbTupleFloat3 >& nodes, std::vector< UbTupleInt4 >& cells, std::vector< std::string >& datanames, std::vector< std::vector< double > >& celldata) override; - std::string writeQuadsWithNodeAndCellData(const std::string& filename,std::vector< UbTupleFloat3 >& nodes, std::vector< UbTupleInt4 >& cells, - std::vector< std::string >& nodedatanames, std::vector< std::vector< double > >& nodedata, std::vector< std::string >& celldatanames, - std::vector< std::vector< double > >& celldata ) override; - - ////////////////////////////////////////////////////////////////////////// - //octs - // 7 ---- 6 - // /| /| - // 4 +--- 5 | - // | | | | - // | 3 ---+ 2 - // |/ |/ - // 0 ---- 1 - std::string writeOcts(const std::string& filename,std::vector< UbTupleFloat3 >& nodes, std::vector< UbTupleInt8 >& cells) override; - std::string writeOctsBinary(const std::string& filename,std::vector< UbTupleFloat3 >& nodes, std::vector< UbTupleInt8 >& cells); - std::string writeOctsWithCellData(const std::string& filename,std::vector< UbTupleFloat3 >& nodes, std::vector< UbTupleInt8 >& cells, std::vector<std::string >& datanames, std::vector<std::vector<double > >& celldata) override; - std::string writeOctsWithNodeData(const std::string& filename,std::vector< UbTupleFloat3 >& nodes, std::vector< UbTupleUInt8 >& cells, std::vector<std::string >& datanames, std::vector<std::vector<double > >& nodedata) override; + ////////////////////////////////////////////////////////////////////////// + // 2D + // cell numbering: + // 3---2 + // | | + // 0---1 + // nodenumbering must start with 0! + std::string writeQuads(const std::string &filename, std::vector<UbTupleFloat3> &nodes, + std::vector<UbTupleInt4> &cells) override; + std::string writeQuadsWithNodeData(const std::string &filename, std::vector<UbTupleFloat3> &nodes, + std::vector<UbTupleInt4> &cells, std::vector<std::string> &datanames, + std::vector<std::vector<double>> &nodedata) override; + std::string writeQuadsWithCellData(const std::string &filename, std::vector<UbTupleFloat3> &nodes, + std::vector<UbTupleInt4> &cells, std::vector<std::string> &datanames, + std::vector<std::vector<double>> &celldata) override; + std::string writeQuadsWithNodeAndCellData(const std::string &filename, std::vector<UbTupleFloat3> &nodes, + std::vector<UbTupleInt4> &cells, std::vector<std::string> &nodedatanames, + std::vector<std::vector<double>> &nodedata, + std::vector<std::string> &celldatanames, + std::vector<std::vector<double>> &celldata) override; + ////////////////////////////////////////////////////////////////////////// + // octs + // 7 ---- 6 + // /| /| + // 4 +--- 5 | + // | | | | + // | 3 ---+ 2 + // |/ |/ + // 0 ---- 1 + std::string writeOcts(const std::string &filename, std::vector<UbTupleFloat3> &nodes, + std::vector<UbTupleInt8> &cells) override; + std::string writeOctsBinary(const std::string &filename, std::vector<UbTupleFloat3> &nodes, + std::vector<UbTupleInt8> &cells); + std::string writeOctsWithCellData(const std::string &filename, std::vector<UbTupleFloat3> &nodes, + std::vector<UbTupleInt8> &cells, std::vector<std::string> &datanames, + std::vector<std::vector<double>> &celldata) override; + std::string writeOctsWithNodeData(const std::string &filename, std::vector<UbTupleFloat3> &nodes, + std::vector<UbTupleUInt8> &cells, std::vector<std::string> &datanames, + std::vector<std::vector<double>> &nodedata) override; }; -#endif //WBWRITERVTKASCII_H +#endif // WBWRITERVTKASCII_H diff --git a/src/basics/basics/writer/WbWriterVtkBinary.cpp b/src/basics/basics/writer/WbWriterVtkBinary.cpp index b440986f492ad8875a84524b18b3885f05a89299..2f0a203dacb1b335ede29564f3386a0cf3b8acc8 100644 --- a/src/basics/basics/writer/WbWriterVtkBinary.cpp +++ b/src/basics/basics/writer/WbWriterVtkBinary.cpp @@ -1,747 +1,818 @@ -#include <basics/writer/WbWriterVtkBinary.h> -#include <basics/writer/WbWriterVtkASCII.h> #include <basics/utilities/UbLogger.h> +#include <basics/writer/WbWriterVtkASCII.h> +#include <basics/writer/WbWriterVtkBinary.h> #include <cstring> using namespace std; -std::string WbWriterVtkBinary::writeLines(const std::string& filename, std::vector<UbTupleFloat3 >& nodes, std::vector<UbTupleInt2 >& lines) +std::string WbWriterVtkBinary::writeLines(const std::string &filename, std::vector<UbTupleFloat3> &nodes, + std::vector<UbTupleInt2> &lines) { - return WbWriterVtkASCII::getInstance()->writeLines(filename,nodes,lines); + return WbWriterVtkASCII::getInstance()->writeLines(filename, nodes, lines); } /*===============================================================================*/ -std::string WbWriterVtkBinary::writeTriangles(const std::string& filename,std::vector< UbTupleFloat3 >& nodes, std::vector< UbTupleInt3 >& cells) +std::string WbWriterVtkBinary::writeTriangles(const std::string &filename, std::vector<UbTupleFloat3> &nodes, + std::vector<UbTupleInt3> &cells) { - return WbWriterVtkASCII::getInstance()->writeTriangles(filename,nodes,cells); + return WbWriterVtkASCII::getInstance()->writeTriangles(filename, nodes, cells); } /*===============================================================================*/ -std::string WbWriterVtkBinary::writeTrianglesWithNodeData(const std::string& filename,std::vector< UbTupleFloat3 >& nodes, std::vector< UbTupleInt3 >& cells, std::vector< std::string >& datanames, std::vector< std::vector< double > >& nodedata) +std::string WbWriterVtkBinary::writeTrianglesWithNodeData(const std::string &filename, + std::vector<UbTupleFloat3> &nodes, + std::vector<UbTupleInt3> &cells, + std::vector<std::string> &datanames, + std::vector<std::vector<double>> &nodedata) { - return WbWriterVtkASCII::getInstance()->writeTrianglesWithNodeData(filename,nodes,cells,datanames,nodedata); + return WbWriterVtkASCII::getInstance()->writeTrianglesWithNodeData(filename, nodes, cells, datanames, nodedata); } /*===============================================================================*/ -std::string WbWriterVtkBinary::writeQuads(const string& filename,vector< UbTupleFloat3 >& nodes, vector< UbTupleInt4 >& cells) +std::string WbWriterVtkBinary::writeQuads(const string &filename, vector<UbTupleFloat3> &nodes, + vector<UbTupleInt4> &cells) { - string vtkfilename = filename + getFileExtension(); - UBLOG(logDEBUG1,"WbWriterVtkBinary::writeQuads to "<<vtkfilename<<" - start"); - - ofstream out(vtkfilename.c_str(),ofstream::out | ofstream::binary); - if(!out) - { - out.clear(); //flags ruecksetzen (ansonsten liefert utern if(!out) weiterhin true!!! - string path = UbSystem::getPathFromString(vtkfilename); - if(path.size()>0){ UbSystem::makeDirectory(path); out.open(vtkfilename.c_str(),ios::out | ios::binary);} - if(!out) throw UbException(UB_EXARGS,"couldn't open file "+vtkfilename); - } - - //HEADER-SECTION - //WRITE BIGENDIAN VtkBinary FILE - bool swapByte = UbSystem::isLittleEndian(); - int nofNodes = (int)nodes.size(); - int nofCells = (int)cells.size(); - - out<<"# vtk DataFile Version 4.0"<<"\n"; - out<<"D3Q19MasterNodeGrid"<<"\n"; - out<<""<<"\n"; - - //POINTS SECTION - out<<"DATASET UNSTRUCTURED_GRID"<<"\n"; - out<<"POINTS "<<nofNodes<<" float"<<"\n"; - for(int n=0; n<nofNodes; n++) - { - float x1 = (float)val<1>(nodes[n]); - float x2 = (float)val<2>(nodes[n]); - float x3 = (float)val<3>(nodes[n]); - - if(swapByte) - { - UbSystem::swapByteOrder((unsigned char*)&x1,sizeof(float)); - UbSystem::swapByteOrder((unsigned char*)&x2,sizeof(float)); - UbSystem::swapByteOrder((unsigned char*)&x3,sizeof(float)); - } - - out.write((char*)&x1,sizeof(float)); - out.write((char*)&x2,sizeof(float)); - out.write((char*)&x3,sizeof(float)); - } - out<<"\n"; - - //CELLS SECTION - out<<"CELLS "<<nofCells<<" "<<nofCells*5<<"\n"; - - int nodesPerCellDummy = 4; //nofNodesPerCell - if(swapByte) UbSystem::swapByteOrder((unsigned char*)&nodesPerCellDummy,sizeof(int)); - for(int c=0; c<(int)cells.size(); c++) - { - int SW = val<1>(cells[c]); - int SE = val<2>(cells[c]); - int NE = val<3>(cells[c]); - int NW = val<4>(cells[c]); - if(swapByte) - { - UbSystem::swapByteOrder((unsigned char*)&SW,sizeof(int)); - UbSystem::swapByteOrder((unsigned char*)&SE,sizeof(int)); - UbSystem::swapByteOrder((unsigned char*)&NW,sizeof(int)); - UbSystem::swapByteOrder((unsigned char*)&NE,sizeof(int)); - } - - out.write((char*)&nodesPerCellDummy,sizeof(int)); - out.write((char*)&SW,sizeof(int)); - out.write((char*)&SE,sizeof(int)); - out.write((char*)&NW,sizeof(int)); - out.write((char*)&NE,sizeof(int)); - } - out<<"\n"; - - out<<"CELL_TYPES "<<(int)cells.size()<<"\n"; - int celltype = 8; - if(swapByte) UbSystem::swapByteOrder((unsigned char*)&celltype,sizeof(int)); - for(int c=0; c<nofCells; c++) - out.write((char*)&celltype,sizeof(int)); - - out<<endl; - out.close(); - - UBLOG(logDEBUG1,"WbWriterVtkBinary::writeQuads to "<<vtkfilename<<" - end"); - return vtkfilename; + string vtkfilename = filename + getFileExtension(); + UBLOG(logDEBUG1, "WbWriterVtkBinary::writeQuads to " << vtkfilename << " - start"); + + ofstream out(vtkfilename.c_str(), ofstream::out | ofstream::binary); + if (!out) { + out.clear(); // flags ruecksetzen (ansonsten liefert utern if(!out) weiterhin true!!! + string path = UbSystem::getPathFromString(vtkfilename); + if (path.size() > 0) { + UbSystem::makeDirectory(path); + out.open(vtkfilename.c_str(), ios::out | ios::binary); + } + if (!out) + throw UbException(UB_EXARGS, "couldn't open file " + vtkfilename); + } + + // HEADER-SECTION + // WRITE BIGENDIAN VtkBinary FILE + bool swapByte = UbSystem::isLittleEndian(); + int nofNodes = (int)nodes.size(); + int nofCells = (int)cells.size(); + + out << "# vtk DataFile Version 4.0" + << "\n"; + out << "D3Q19MasterNodeGrid" + << "\n"; + out << "" + << "\n"; + + // POINTS SECTION + out << "DATASET UNSTRUCTURED_GRID" + << "\n"; + out << "POINTS " << nofNodes << " float" + << "\n"; + for (int n = 0; n < nofNodes; n++) { + float x1 = (float)val<1>(nodes[n]); + float x2 = (float)val<2>(nodes[n]); + float x3 = (float)val<3>(nodes[n]); + + if (swapByte) { + UbSystem::swapByteOrder((unsigned char *)&x1, sizeof(float)); + UbSystem::swapByteOrder((unsigned char *)&x2, sizeof(float)); + UbSystem::swapByteOrder((unsigned char *)&x3, sizeof(float)); + } + + out.write((char *)&x1, sizeof(float)); + out.write((char *)&x2, sizeof(float)); + out.write((char *)&x3, sizeof(float)); + } + out << "\n"; + + // CELLS SECTION + out << "CELLS " << nofCells << " " << nofCells * 5 << "\n"; + + int nodesPerCellDummy = 4; // nofNodesPerCell + if (swapByte) + UbSystem::swapByteOrder((unsigned char *)&nodesPerCellDummy, sizeof(int)); + for (int c = 0; c < (int)cells.size(); c++) { + int SW = val<1>(cells[c]); + int SE = val<2>(cells[c]); + int NE = val<3>(cells[c]); + int NW = val<4>(cells[c]); + if (swapByte) { + UbSystem::swapByteOrder((unsigned char *)&SW, sizeof(int)); + UbSystem::swapByteOrder((unsigned char *)&SE, sizeof(int)); + UbSystem::swapByteOrder((unsigned char *)&NW, sizeof(int)); + UbSystem::swapByteOrder((unsigned char *)&NE, sizeof(int)); + } + + out.write((char *)&nodesPerCellDummy, sizeof(int)); + out.write((char *)&SW, sizeof(int)); + out.write((char *)&SE, sizeof(int)); + out.write((char *)&NW, sizeof(int)); + out.write((char *)&NE, sizeof(int)); + } + out << "\n"; + + out << "CELL_TYPES " << (int)cells.size() << "\n"; + int celltype = 8; + if (swapByte) + UbSystem::swapByteOrder((unsigned char *)&celltype, sizeof(int)); + for (int c = 0; c < nofCells; c++) + out.write((char *)&celltype, sizeof(int)); + + out << endl; + out.close(); + + UBLOG(logDEBUG1, "WbWriterVtkBinary::writeQuads to " << vtkfilename << " - end"); + return vtkfilename; } /*===============================================================================*/ -std::string WbWriterVtkBinary::writeQuadsWithNodeData(const string& filename,vector< UbTupleFloat3 >& nodes, vector< UbTupleInt4 >& cells, vector< string >& datanames, vector< vector< double > >& nodedata) +std::string WbWriterVtkBinary::writeQuadsWithNodeData(const string &filename, vector<UbTupleFloat3> &nodes, + vector<UbTupleInt4> &cells, vector<string> &datanames, + vector<vector<double>> &nodedata) { - string vtkfilename = filename + getFileExtension(); - UBLOG(logDEBUG1,"WbWriterVtkBinary::writeQuadsWithNodeData to "<<vtkfilename<<" - start"); - - ofstream out(vtkfilename.c_str(),ofstream::out | ofstream::binary); - if(!out) - { - out.clear(); //flags ruecksetzen (ansonsten liefert utern if(!out) weiterhin true!!! - string path = UbSystem::getPathFromString(vtkfilename); - if(path.size()>0){ UbSystem::makeDirectory(path); out.open(vtkfilename.c_str(),ios::out | ios::binary);} - if(!out) throw UbException(UB_EXARGS,"couldn't open file "+vtkfilename); - } - - //WRITE BIGENDIAN VtkBinary FILE - bool swapByte = UbSystem::isLittleEndian(); - int nofNodes = (int)nodes.size(); - int nofCells = (int)cells.size(); - - out<<"# vtk DataFile Version 4.0"<<"\n"; - out<<"D3Q19MasterNodeGrid"<<"\n"; - out<<""<<"\n"; - - //POINTS SECTION - out<<"DATASET UNSTRUCTURED_GRID"<<"\n"; - out<<"POINTS "<<nofNodes<<" float"<<"\n"; - for(int n=0; n<nofNodes; n++) - { - float x1 = (float)val<1>(nodes[n]); - float x2 = (float)val<2>(nodes[n]); - float x3 = (float)val<3>(nodes[n]); - - if(swapByte) - { - UbSystem::swapByteOrder((unsigned char*)&x1,sizeof(float)); - UbSystem::swapByteOrder((unsigned char*)&x2,sizeof(float)); - UbSystem::swapByteOrder((unsigned char*)&x3,sizeof(float)); - } - - out.write((char*)&x1,sizeof(float)); - out.write((char*)&x2,sizeof(float)); - out.write((char*)&x3,sizeof(float)); - } - out<<"\n"; - - //CELLS SECTION - out<<"CELLS "<<nofCells<<" "<<nofCells*5<<"\n"; - - int nodesPerCellDummy = 4; //nofNodesPerCell - if(swapByte) UbSystem::swapByteOrder((unsigned char*)&nodesPerCellDummy,sizeof(int)); - for(int c=0; c<(int)cells.size(); c++) - { - int SW = val<1>(cells[c]); - int SE = val<2>(cells[c]); - int NE = val<3>(cells[c]); - int NW = val<4>(cells[c]); - if(swapByte) - { - UbSystem::swapByteOrder((unsigned char*)&SW,sizeof(int)); - UbSystem::swapByteOrder((unsigned char*)&SE,sizeof(int)); - UbSystem::swapByteOrder((unsigned char*)&NW,sizeof(int)); - UbSystem::swapByteOrder((unsigned char*)&NE,sizeof(int)); - } - - out.write((char*)&nodesPerCellDummy,sizeof(int)); - out.write((char*)&SW,sizeof(int)); - out.write((char*)&SE,sizeof(int)); - out.write((char*)&NW,sizeof(int)); - out.write((char*)&NE,sizeof(int)); - } - out<<"\n"; - - out<<"CELL_TYPES "<<(int)cells.size()<<"\n"; - int celltype = 8; - if(swapByte) UbSystem::swapByteOrder((unsigned char*)&celltype,sizeof(int)); - for(int c=0; c<nofCells; c++) - out.write((char*)&celltype,sizeof(int)); - - out<<endl; - - //DATA SECTION - //write data section - out<<"POINT_DATA "<<nofNodes<<"\n"; - for(int s=0; s<(int)datanames.size(); ++s) - { - if((int)nodedata[s].size() != nofNodes) throw UbException(UB_EXARGS,"datasetsize must be equal to nofNodes"); - out<<"SCALARS "<<datanames[s]<<" float 1 \n LOOKUP_TABLE default \n"; - for(int d=0; d<(int)nodedata[s].size(); d++) - { - float dummy = (float)nodedata[s][d]; - if(swapByte) UbSystem::swapByteOrder((unsigned char*)&dummy,sizeof(float)); - out.write((const char*)&dummy,sizeof(float)); - } - out<<endl; - } - out.close(); - - UBLOG(logDEBUG1,"WbWriterVtkBinary::writeQuadsWithNodeData to "<<vtkfilename<<" - end"); - return vtkfilename; + string vtkfilename = filename + getFileExtension(); + UBLOG(logDEBUG1, "WbWriterVtkBinary::writeQuadsWithNodeData to " << vtkfilename << " - start"); + + ofstream out(vtkfilename.c_str(), ofstream::out | ofstream::binary); + if (!out) { + out.clear(); // flags ruecksetzen (ansonsten liefert utern if(!out) weiterhin true!!! + string path = UbSystem::getPathFromString(vtkfilename); + if (path.size() > 0) { + UbSystem::makeDirectory(path); + out.open(vtkfilename.c_str(), ios::out | ios::binary); + } + if (!out) + throw UbException(UB_EXARGS, "couldn't open file " + vtkfilename); + } + + // WRITE BIGENDIAN VtkBinary FILE + bool swapByte = UbSystem::isLittleEndian(); + int nofNodes = (int)nodes.size(); + int nofCells = (int)cells.size(); + + out << "# vtk DataFile Version 4.0" + << "\n"; + out << "D3Q19MasterNodeGrid" + << "\n"; + out << "" + << "\n"; + + // POINTS SECTION + out << "DATASET UNSTRUCTURED_GRID" + << "\n"; + out << "POINTS " << nofNodes << " float" + << "\n"; + for (int n = 0; n < nofNodes; n++) { + float x1 = (float)val<1>(nodes[n]); + float x2 = (float)val<2>(nodes[n]); + float x3 = (float)val<3>(nodes[n]); + + if (swapByte) { + UbSystem::swapByteOrder((unsigned char *)&x1, sizeof(float)); + UbSystem::swapByteOrder((unsigned char *)&x2, sizeof(float)); + UbSystem::swapByteOrder((unsigned char *)&x3, sizeof(float)); + } + + out.write((char *)&x1, sizeof(float)); + out.write((char *)&x2, sizeof(float)); + out.write((char *)&x3, sizeof(float)); + } + out << "\n"; + + // CELLS SECTION + out << "CELLS " << nofCells << " " << nofCells * 5 << "\n"; + + int nodesPerCellDummy = 4; // nofNodesPerCell + if (swapByte) + UbSystem::swapByteOrder((unsigned char *)&nodesPerCellDummy, sizeof(int)); + for (int c = 0; c < (int)cells.size(); c++) { + int SW = val<1>(cells[c]); + int SE = val<2>(cells[c]); + int NE = val<3>(cells[c]); + int NW = val<4>(cells[c]); + if (swapByte) { + UbSystem::swapByteOrder((unsigned char *)&SW, sizeof(int)); + UbSystem::swapByteOrder((unsigned char *)&SE, sizeof(int)); + UbSystem::swapByteOrder((unsigned char *)&NW, sizeof(int)); + UbSystem::swapByteOrder((unsigned char *)&NE, sizeof(int)); + } + + out.write((char *)&nodesPerCellDummy, sizeof(int)); + out.write((char *)&SW, sizeof(int)); + out.write((char *)&SE, sizeof(int)); + out.write((char *)&NW, sizeof(int)); + out.write((char *)&NE, sizeof(int)); + } + out << "\n"; + + out << "CELL_TYPES " << (int)cells.size() << "\n"; + int celltype = 8; + if (swapByte) + UbSystem::swapByteOrder((unsigned char *)&celltype, sizeof(int)); + for (int c = 0; c < nofCells; c++) + out.write((char *)&celltype, sizeof(int)); + + out << endl; + + // DATA SECTION + // write data section + out << "POINT_DATA " << nofNodes << "\n"; + for (int s = 0; s < (int)datanames.size(); ++s) { + if ((int)nodedata[s].size() != nofNodes) + throw UbException(UB_EXARGS, "datasetsize must be equal to nofNodes"); + out << "SCALARS " << datanames[s] << " float 1 \n LOOKUP_TABLE default \n"; + for (int d = 0; d < (int)nodedata[s].size(); d++) { + float dummy = (float)nodedata[s][d]; + if (swapByte) + UbSystem::swapByteOrder((unsigned char *)&dummy, sizeof(float)); + out.write((const char *)&dummy, sizeof(float)); + } + out << endl; + } + out.close(); + + UBLOG(logDEBUG1, "WbWriterVtkBinary::writeQuadsWithNodeData to " << vtkfilename << " - end"); + return vtkfilename; } /*===============================================================================*/ -std::string WbWriterVtkBinary::writeQuadsWithCellData(const string& filename,vector< UbTupleFloat3 >& nodes, vector< UbTupleInt4 >& cells, vector< string >& datanames, vector< vector< double > >& celldata) +std::string WbWriterVtkBinary::writeQuadsWithCellData(const string &filename, vector<UbTupleFloat3> &nodes, + vector<UbTupleInt4> &cells, vector<string> &datanames, + vector<vector<double>> &celldata) { - //HEADER-SECTION - string vtkfilename = filename + getFileExtension(); - UBLOG(logDEBUG1,"WbWriterVtkBinary::writeQuadsWithCellData to "<<vtkfilename<<" - start"); - - ofstream out(vtkfilename.c_str(),ofstream::out | ofstream::binary); - if(!out) - { - out.clear(); //flags ruecksetzen (ansonsten liefert utern if(!out) weiterhin true!!! - string path = UbSystem::getPathFromString(vtkfilename); - if(path.size()>0){ UbSystem::makeDirectory(path); out.open(vtkfilename.c_str(),ios::out | ios::binary);} - if(!out) throw UbException(UB_EXARGS,"couldn't open file "+vtkfilename); - } - - //WRITE BIGENDIAN VtkBinary FILE - bool swapByte = UbSystem::isLittleEndian(); - int nofNodes = (int)nodes.size(); - int nofCells = (int)cells.size(); - - out<<"# vtk DataFile Version 4.0"<<"\n"; - out<<"D3Q19MasterNodeGrid"<<"\n"; - out<<""<<"\n"; - - //POINTS SECTION - out<<"DATASET UNSTRUCTURED_GRID"<<"\n"; - out<<"POINTS "<<nofNodes<<" float"<<"\n"; - for(int n=0; n<nofNodes; n++) - { - float x1 = (float)val<1>(nodes[n]); - float x2 = (float)val<2>(nodes[n]); - float x3 = (float)val<3>(nodes[n]); - - if(swapByte) - { - UbSystem::swapByteOrder((unsigned char*)&x1,sizeof(float)); - UbSystem::swapByteOrder((unsigned char*)&x2,sizeof(float)); - UbSystem::swapByteOrder((unsigned char*)&x3,sizeof(float)); - } - - out.write((char*)&x1,sizeof(float)); - out.write((char*)&x2,sizeof(float)); - out.write((char*)&x3,sizeof(float)); - } - out<<"\n"; - - //CELLS SECTION - out<<"CELLS "<<nofCells<<" "<<nofCells*5<<"\n"; - - int nodesPerCellDummy = 4; //nofNodesPerCell - if(swapByte) UbSystem::swapByteOrder((unsigned char*)&nodesPerCellDummy,sizeof(int)); - for(int c=0; c<(int)cells.size(); c++) - { - int SW = val<1>(cells[c]); - int SE = val<2>(cells[c]); - int NE = val<3>(cells[c]); - int NW = val<4>(cells[c]); - if(swapByte) - { - UbSystem::swapByteOrder((unsigned char*)&SW,sizeof(int)); - UbSystem::swapByteOrder((unsigned char*)&SE,sizeof(int)); - UbSystem::swapByteOrder((unsigned char*)&NW,sizeof(int)); - UbSystem::swapByteOrder((unsigned char*)&NE,sizeof(int)); - } - - out.write((char*)&nodesPerCellDummy,sizeof(int)); - out.write((char*)&SW,sizeof(int)); - out.write((char*)&SE,sizeof(int)); - out.write((char*)&NW,sizeof(int)); - out.write((char*)&NE,sizeof(int)); - } - out<<"\n"; - - out<<"CELL_TYPES "<<(int)cells.size()<<"\n"; - int celltype = 8; - if(swapByte) UbSystem::swapByteOrder((unsigned char*)&celltype,sizeof(int)); - for(int c=0; c<nofCells; c++) - out.write((char*)&celltype,sizeof(int)); - - out<<endl; - - //DATA SECTION - //write data section - out<<"CELL_DATA "<<nofCells<<"\n"; - for(int s=0; s<(int)datanames.size(); ++s) - { - if((int)celldata[s].size() != nofCells) throw UbException(UB_EXARGS,"datasetsize must be equal to nofNodes"); - out<<"SCALARS "<<datanames[s]<<" float 1 \n LOOKUP_TABLE default \n"; - for(int d=0; d<(int)celldata[s].size(); d++) - { - float dummy = (float)celldata[s][d]; - if(swapByte) UbSystem::swapByteOrder((unsigned char*)&dummy,sizeof(float)); - out.write((const char*)&dummy,sizeof(float)); - } - out<<endl; - } - out.close(); - - UBLOG(logDEBUG1,"WbWriterVtkBinary::writeQuadsWithCellData to "<<vtkfilename<<" - end"); - return vtkfilename; + // HEADER-SECTION + string vtkfilename = filename + getFileExtension(); + UBLOG(logDEBUG1, "WbWriterVtkBinary::writeQuadsWithCellData to " << vtkfilename << " - start"); + + ofstream out(vtkfilename.c_str(), ofstream::out | ofstream::binary); + if (!out) { + out.clear(); // flags ruecksetzen (ansonsten liefert utern if(!out) weiterhin true!!! + string path = UbSystem::getPathFromString(vtkfilename); + if (path.size() > 0) { + UbSystem::makeDirectory(path); + out.open(vtkfilename.c_str(), ios::out | ios::binary); + } + if (!out) + throw UbException(UB_EXARGS, "couldn't open file " + vtkfilename); + } + + // WRITE BIGENDIAN VtkBinary FILE + bool swapByte = UbSystem::isLittleEndian(); + int nofNodes = (int)nodes.size(); + int nofCells = (int)cells.size(); + + out << "# vtk DataFile Version 4.0" + << "\n"; + out << "D3Q19MasterNodeGrid" + << "\n"; + out << "" + << "\n"; + + // POINTS SECTION + out << "DATASET UNSTRUCTURED_GRID" + << "\n"; + out << "POINTS " << nofNodes << " float" + << "\n"; + for (int n = 0; n < nofNodes; n++) { + float x1 = (float)val<1>(nodes[n]); + float x2 = (float)val<2>(nodes[n]); + float x3 = (float)val<3>(nodes[n]); + + if (swapByte) { + UbSystem::swapByteOrder((unsigned char *)&x1, sizeof(float)); + UbSystem::swapByteOrder((unsigned char *)&x2, sizeof(float)); + UbSystem::swapByteOrder((unsigned char *)&x3, sizeof(float)); + } + + out.write((char *)&x1, sizeof(float)); + out.write((char *)&x2, sizeof(float)); + out.write((char *)&x3, sizeof(float)); + } + out << "\n"; + + // CELLS SECTION + out << "CELLS " << nofCells << " " << nofCells * 5 << "\n"; + + int nodesPerCellDummy = 4; // nofNodesPerCell + if (swapByte) + UbSystem::swapByteOrder((unsigned char *)&nodesPerCellDummy, sizeof(int)); + for (int c = 0; c < (int)cells.size(); c++) { + int SW = val<1>(cells[c]); + int SE = val<2>(cells[c]); + int NE = val<3>(cells[c]); + int NW = val<4>(cells[c]); + if (swapByte) { + UbSystem::swapByteOrder((unsigned char *)&SW, sizeof(int)); + UbSystem::swapByteOrder((unsigned char *)&SE, sizeof(int)); + UbSystem::swapByteOrder((unsigned char *)&NW, sizeof(int)); + UbSystem::swapByteOrder((unsigned char *)&NE, sizeof(int)); + } + + out.write((char *)&nodesPerCellDummy, sizeof(int)); + out.write((char *)&SW, sizeof(int)); + out.write((char *)&SE, sizeof(int)); + out.write((char *)&NW, sizeof(int)); + out.write((char *)&NE, sizeof(int)); + } + out << "\n"; + + out << "CELL_TYPES " << (int)cells.size() << "\n"; + int celltype = 8; + if (swapByte) + UbSystem::swapByteOrder((unsigned char *)&celltype, sizeof(int)); + for (int c = 0; c < nofCells; c++) + out.write((char *)&celltype, sizeof(int)); + + out << endl; + + // DATA SECTION + // write data section + out << "CELL_DATA " << nofCells << "\n"; + for (int s = 0; s < (int)datanames.size(); ++s) { + if ((int)celldata[s].size() != nofCells) + throw UbException(UB_EXARGS, "datasetsize must be equal to nofNodes"); + out << "SCALARS " << datanames[s] << " float 1 \n LOOKUP_TABLE default \n"; + for (int d = 0; d < (int)celldata[s].size(); d++) { + float dummy = (float)celldata[s][d]; + if (swapByte) + UbSystem::swapByteOrder((unsigned char *)&dummy, sizeof(float)); + out.write((const char *)&dummy, sizeof(float)); + } + out << endl; + } + out.close(); + + UBLOG(logDEBUG1, "WbWriterVtkBinary::writeQuadsWithCellData to " << vtkfilename << " - end"); + return vtkfilename; } /*===============================================================================*/ -std::string WbWriterVtkBinary::writeQuadsWithNodeAndCellData(const string& filename,vector< UbTupleFloat3 >& nodes, vector< UbTupleInt4 >& cells, - vector< string >& nodedatanames, vector< vector< double > >& nodedata, vector< string >& celldatanames, - vector< vector< double > >& celldata ) +std::string WbWriterVtkBinary::writeQuadsWithNodeAndCellData(const string &filename, vector<UbTupleFloat3> &nodes, + vector<UbTupleInt4> &cells, vector<string> &nodedatanames, + vector<vector<double>> &nodedata, + vector<string> &celldatanames, + vector<vector<double>> &celldata) { - string vtkfilename = filename + getFileExtension(); - UBLOG(logDEBUG1,"WbWriterVtkBinary::writeQuadsWithNodeAndCellData to "<<vtkfilename<<" - start"); - - ofstream out(vtkfilename.c_str(),ofstream::out | ofstream::binary); - if(!out) - { - out.clear(); //flags ruecksetzen (ansonsten liefert utern if(!out) weiterhin true!!! - string path = UbSystem::getPathFromString(vtkfilename); - if(path.size()>0){ UbSystem::makeDirectory(path); out.open(vtkfilename.c_str(),ios::out | ios::binary);} - if(!out) throw UbException(UB_EXARGS,"couldn't open file "+vtkfilename); - } - - //HEADER-SECTION - //WRITE BIGENDIAN VtkBinary FILE - bool swapByte = UbSystem::isLittleEndian(); - int nofNodes = (int)nodes.size(); - int nofCells = (int)cells.size(); - - out<<"# vtk DataFile Version 4.0"<<"\n"; - out<<"D3Q19MasterNodeGrid"<<"\n"; - out<<""<<"\n"; - - //POINTS SECTION - out<<"DATASET UNSTRUCTURED_GRID"<<"\n"; - out<<"POINTS "<<nofNodes<<" float"<<"\n"; - for(int n=0; n<nofNodes; n++) - { - float x1 = (float)val<1>(nodes[n]); - float x2 = (float)val<2>(nodes[n]); - float x3 = (float)val<3>(nodes[n]); - - if(swapByte) - { - UbSystem::swapByteOrder((unsigned char*)&x1,sizeof(float)); - UbSystem::swapByteOrder((unsigned char*)&x2,sizeof(float)); - UbSystem::swapByteOrder((unsigned char*)&x3,sizeof(float)); - } - - out.write((char*)&x1,sizeof(float)); - out.write((char*)&x2,sizeof(float)); - out.write((char*)&x3,sizeof(float)); - } - out<<"\n"; - - //CELLS SECTION - out<<"CELLS "<<nofCells<<" "<<nofCells*5<<"\n"; - - int nodesPerCellDummy = 4; //nofNodesPerCell - if(swapByte) UbSystem::swapByteOrder((unsigned char*)&nodesPerCellDummy,sizeof(int)); - for(int c=0; c<(int)cells.size(); c++) - { - int SW = val<1>(cells[c]); - int SE = val<2>(cells[c]); - int NE = val<3>(cells[c]); - int NW = val<4>(cells[c]); - if(swapByte) - { - UbSystem::swapByteOrder((unsigned char*)&SW,sizeof(int)); - UbSystem::swapByteOrder((unsigned char*)&SE,sizeof(int)); - UbSystem::swapByteOrder((unsigned char*)&NW,sizeof(int)); - UbSystem::swapByteOrder((unsigned char*)&NE,sizeof(int)); - } - - out.write((char*)&nodesPerCellDummy,sizeof(int)); - out.write((char*)&SW,sizeof(int)); - out.write((char*)&SE,sizeof(int)); - out.write((char*)&NW,sizeof(int)); - out.write((char*)&NE,sizeof(int)); - } - out<<"\n"; - - out<<"CELL_TYPES "<<(int)cells.size()<<"\n"; - int celltype = 8; - if(swapByte) UbSystem::swapByteOrder((unsigned char*)&celltype,sizeof(int)); - for(int c=0; c<nofCells; c++) - out.write((char*)&celltype,sizeof(int)); - - out<<endl; - - //NODE DATA SECTION - //write data section - out<<"POINT_DATA "<<nofNodes<<"\n"; - for(int s=0; s<(int)nodedatanames.size(); ++s) - { - if((int)nodedata[s].size() != nofNodes) throw UbException(UB_EXARGS,"datasetsize must be equal to nofNodes"); - out<<"SCALARS "<<nodedatanames[s]<<" float 1 \n LOOKUP_TABLE default \n"; - for(int d=0; d<(int)nodedata[s].size(); d++) - { - float dummy = (float)nodedata[s][d]; - if(swapByte) UbSystem::swapByteOrder((unsigned char*)&dummy,sizeof(float)); - out.write((const char*)&dummy,sizeof(float)); - } - out<<endl; - } - - //CELL DATA SECTION - //write data section - out<<"CELL_DATA "<<nofCells<<"\n"; - for(int s=0; s<(int)celldatanames.size(); ++s) - { - if((int)celldata[s].size() != nofCells) throw UbException(UB_EXARGS,"datasetsize must be equal to nofNodes"); - out<<"SCALARS "<<celldatanames[s]<<" float 1 \n LOOKUP_TABLE default \n"; - for(int d=0; d<(int)celldata[s].size(); d++) - { - float dummy = (float)celldata[s][d]; - if(swapByte) UbSystem::swapByteOrder((unsigned char*)&dummy,sizeof(float)); - out.write((const char*)&dummy,sizeof(float)); - } - out<<endl; - } - - out.close(); - - UBLOG(logDEBUG1,"WbWriterVtkBinary::writeQuadsWithNodeAndCellData to "<<vtkfilename<<" - end"); - return vtkfilename; + string vtkfilename = filename + getFileExtension(); + UBLOG(logDEBUG1, "WbWriterVtkBinary::writeQuadsWithNodeAndCellData to " << vtkfilename << " - start"); + + ofstream out(vtkfilename.c_str(), ofstream::out | ofstream::binary); + if (!out) { + out.clear(); // flags ruecksetzen (ansonsten liefert utern if(!out) weiterhin true!!! + string path = UbSystem::getPathFromString(vtkfilename); + if (path.size() > 0) { + UbSystem::makeDirectory(path); + out.open(vtkfilename.c_str(), ios::out | ios::binary); + } + if (!out) + throw UbException(UB_EXARGS, "couldn't open file " + vtkfilename); + } + + // HEADER-SECTION + // WRITE BIGENDIAN VtkBinary FILE + bool swapByte = UbSystem::isLittleEndian(); + int nofNodes = (int)nodes.size(); + int nofCells = (int)cells.size(); + + out << "# vtk DataFile Version 4.0" + << "\n"; + out << "D3Q19MasterNodeGrid" + << "\n"; + out << "" + << "\n"; + + // POINTS SECTION + out << "DATASET UNSTRUCTURED_GRID" + << "\n"; + out << "POINTS " << nofNodes << " float" + << "\n"; + for (int n = 0; n < nofNodes; n++) { + float x1 = (float)val<1>(nodes[n]); + float x2 = (float)val<2>(nodes[n]); + float x3 = (float)val<3>(nodes[n]); + + if (swapByte) { + UbSystem::swapByteOrder((unsigned char *)&x1, sizeof(float)); + UbSystem::swapByteOrder((unsigned char *)&x2, sizeof(float)); + UbSystem::swapByteOrder((unsigned char *)&x3, sizeof(float)); + } + + out.write((char *)&x1, sizeof(float)); + out.write((char *)&x2, sizeof(float)); + out.write((char *)&x3, sizeof(float)); + } + out << "\n"; + + // CELLS SECTION + out << "CELLS " << nofCells << " " << nofCells * 5 << "\n"; + + int nodesPerCellDummy = 4; // nofNodesPerCell + if (swapByte) + UbSystem::swapByteOrder((unsigned char *)&nodesPerCellDummy, sizeof(int)); + for (int c = 0; c < (int)cells.size(); c++) { + int SW = val<1>(cells[c]); + int SE = val<2>(cells[c]); + int NE = val<3>(cells[c]); + int NW = val<4>(cells[c]); + if (swapByte) { + UbSystem::swapByteOrder((unsigned char *)&SW, sizeof(int)); + UbSystem::swapByteOrder((unsigned char *)&SE, sizeof(int)); + UbSystem::swapByteOrder((unsigned char *)&NW, sizeof(int)); + UbSystem::swapByteOrder((unsigned char *)&NE, sizeof(int)); + } + + out.write((char *)&nodesPerCellDummy, sizeof(int)); + out.write((char *)&SW, sizeof(int)); + out.write((char *)&SE, sizeof(int)); + out.write((char *)&NW, sizeof(int)); + out.write((char *)&NE, sizeof(int)); + } + out << "\n"; + + out << "CELL_TYPES " << (int)cells.size() << "\n"; + int celltype = 8; + if (swapByte) + UbSystem::swapByteOrder((unsigned char *)&celltype, sizeof(int)); + for (int c = 0; c < nofCells; c++) + out.write((char *)&celltype, sizeof(int)); + + out << endl; + + // NODE DATA SECTION + // write data section + out << "POINT_DATA " << nofNodes << "\n"; + for (int s = 0; s < (int)nodedatanames.size(); ++s) { + if ((int)nodedata[s].size() != nofNodes) + throw UbException(UB_EXARGS, "datasetsize must be equal to nofNodes"); + out << "SCALARS " << nodedatanames[s] << " float 1 \n LOOKUP_TABLE default \n"; + for (int d = 0; d < (int)nodedata[s].size(); d++) { + float dummy = (float)nodedata[s][d]; + if (swapByte) + UbSystem::swapByteOrder((unsigned char *)&dummy, sizeof(float)); + out.write((const char *)&dummy, sizeof(float)); + } + out << endl; + } + + // CELL DATA SECTION + // write data section + out << "CELL_DATA " << nofCells << "\n"; + for (int s = 0; s < (int)celldatanames.size(); ++s) { + if ((int)celldata[s].size() != nofCells) + throw UbException(UB_EXARGS, "datasetsize must be equal to nofNodes"); + out << "SCALARS " << celldatanames[s] << " float 1 \n LOOKUP_TABLE default \n"; + for (int d = 0; d < (int)celldata[s].size(); d++) { + float dummy = (float)celldata[s][d]; + if (swapByte) + UbSystem::swapByteOrder((unsigned char *)&dummy, sizeof(float)); + out.write((const char *)&dummy, sizeof(float)); + } + out << endl; + } + + out.close(); + + UBLOG(logDEBUG1, "WbWriterVtkBinary::writeQuadsWithNodeAndCellData to " << vtkfilename << " - end"); + return vtkfilename; } /*===============================================================================*/ -std::string WbWriterVtkBinary::writeOctsWithCellData(const string& filename,vector<UbTupleFloat3 >& nodes, vector<UbTupleInt8 >& cells, vector<string >& datanames, vector<vector<double > >& celldata) +std::string WbWriterVtkBinary::writeOctsWithCellData(const string &filename, vector<UbTupleFloat3> &nodes, + vector<UbTupleInt8> &cells, vector<string> &datanames, + vector<vector<double>> &celldata) { - string vtkfilename = filename + getFileExtension(); - UBLOG(logDEBUG1,"WbWriterVtkBinary::writeOctsWithCellData to "<<vtkfilename<<" - start"); - - ofstream out(vtkfilename.c_str(),ofstream::out | ofstream::binary); - if(!out) - { - out.clear(); //flags ruecksetzen (ansonsten liefert utern if(!out) weiterhin true!!! - string path = UbSystem::getPathFromString(vtkfilename); - if(path.size()>0){ UbSystem::makeDirectory(path); out.open(vtkfilename.c_str(),ios::out | ios::binary);} - if(!out) throw UbException(UB_EXARGS,"couldn't open file "+vtkfilename); - } - - //HEADER-SECTION - //WRITE BIGENDIAN VtkBinary FILE - bool swapByte = UbSystem::isLittleEndian(); - int nofNodes = (int)nodes.size(); - int nofCells = (int)cells.size(); - - out<<"# vtk DataFile Version 4.0"<<"\n"; - out<<"D3Q19MasterNodeGrid"<<"\n"; - out<<""<<"\n"; - - //POINTS SECTION - out<<"DATASET UNSTRUCTURED_GRID"<<"\n"; - out<<"POINTS "<<nofNodes<<" float"<<"\n"; - for(int n=0; n<nofNodes; n++) - { - float x1 = (float)val<1>(nodes[n]); - float x2 = (float)val<2>(nodes[n]); - float x3 = (float)val<3>(nodes[n]); - - if(swapByte) - { - UbSystem::swapByteOrder((unsigned char*)&x1,sizeof(float)); - UbSystem::swapByteOrder((unsigned char*)&x2,sizeof(float)); - UbSystem::swapByteOrder((unsigned char*)&x3,sizeof(float)); - } - - out.write((char*)&x1,sizeof(float)); - out.write((char*)&x2,sizeof(float)); - out.write((char*)&x3,sizeof(float)); - } - out<<"\n"; - - //CELLS SECTION - out<<"CELLS "<<nofCells<<" "<<nofCells*9<<"\n"; - - int nodesPerCellDummy = 8; //nofNodesPerCell - if(swapByte) UbSystem::swapByteOrder((unsigned char*)&nodesPerCellDummy,sizeof(int)); - for(int c=0; c<(int)cells.size(); c++) - { - int BSW = val<1>(cells[c]); int TSW = val<5>(cells[c]); - int BSE = val<2>(cells[c]); int TSE = val<6>(cells[c]); - int BNW = val<3>(cells[c]); int TNW = val<7>(cells[c]); - int BNE = val<4>(cells[c]); int TNE = val<8>(cells[c]); - if(swapByte) - { - UbSystem::swapByteOrder((unsigned char*)&BSW,sizeof(int)); - UbSystem::swapByteOrder((unsigned char*)&BSE,sizeof(int)); - UbSystem::swapByteOrder((unsigned char*)&BNW,sizeof(int)); - UbSystem::swapByteOrder((unsigned char*)&BNE,sizeof(int)); - UbSystem::swapByteOrder((unsigned char*)&TSW,sizeof(int)); - UbSystem::swapByteOrder((unsigned char*)&TSE,sizeof(int)); - UbSystem::swapByteOrder((unsigned char*)&TNW,sizeof(int)); - UbSystem::swapByteOrder((unsigned char*)&TNE,sizeof(int)); - } - - out.write((char*)&nodesPerCellDummy,sizeof(int)); - out.write((char*)&BSW,sizeof(int)); - out.write((char*)&BSE,sizeof(int)); - out.write((char*)&BNE,sizeof(int)); - out.write((char*)&BNW,sizeof(int)); - out.write((char*)&TSW,sizeof(int)); - out.write((char*)&TSE,sizeof(int)); - out.write((char*)&TNE,sizeof(int)); - out.write((char*)&TNW,sizeof(int)); - } - out<<"\n"; - - out<<"CELL_TYPES "<<(int)cells.size()<<"\n"; - int celltype = 11; - if(swapByte) UbSystem::swapByteOrder((unsigned char*)&celltype,sizeof(int)); - for(int c=0; c<nofCells; c++) - out.write((char*)&celltype,sizeof(int)); - - out<<endl; - - //CELL DATA SECTION - //write data section - out<<"CELL_DATA "<<nofCells<<"\n"; - for(int s=0; s<(int)datanames.size(); ++s) - { - if((int)celldata[s].size() != nofCells) throw UbException(UB_EXARGS,"datasetsize must be equal to nofNodes"); - out<<"SCALARS "<<datanames[s]<<" float 1 \n LOOKUP_TABLE default \n"; - for(int d=0; d<(int)celldata[s].size(); d++) - { - float dummy = (float)celldata[s][d]; - if(swapByte) UbSystem::swapByteOrder((unsigned char*)&dummy,sizeof(float)); - out.write((const char*)&dummy,sizeof(float)); - } - out<<endl; - } - out.close(); - - UBLOG(logDEBUG1,"WbWriterVtkBinary::writeOctsWithCellData to "<<vtkfilename<<" - end"); - return vtkfilename; + string vtkfilename = filename + getFileExtension(); + UBLOG(logDEBUG1, "WbWriterVtkBinary::writeOctsWithCellData to " << vtkfilename << " - start"); + + ofstream out(vtkfilename.c_str(), ofstream::out | ofstream::binary); + if (!out) { + out.clear(); // flags ruecksetzen (ansonsten liefert utern if(!out) weiterhin true!!! + string path = UbSystem::getPathFromString(vtkfilename); + if (path.size() > 0) { + UbSystem::makeDirectory(path); + out.open(vtkfilename.c_str(), ios::out | ios::binary); + } + if (!out) + throw UbException(UB_EXARGS, "couldn't open file " + vtkfilename); + } + + // HEADER-SECTION + // WRITE BIGENDIAN VtkBinary FILE + bool swapByte = UbSystem::isLittleEndian(); + int nofNodes = (int)nodes.size(); + int nofCells = (int)cells.size(); + + out << "# vtk DataFile Version 4.0" + << "\n"; + out << "D3Q19MasterNodeGrid" + << "\n"; + out << "" + << "\n"; + + // POINTS SECTION + out << "DATASET UNSTRUCTURED_GRID" + << "\n"; + out << "POINTS " << nofNodes << " float" + << "\n"; + for (int n = 0; n < nofNodes; n++) { + float x1 = (float)val<1>(nodes[n]); + float x2 = (float)val<2>(nodes[n]); + float x3 = (float)val<3>(nodes[n]); + + if (swapByte) { + UbSystem::swapByteOrder((unsigned char *)&x1, sizeof(float)); + UbSystem::swapByteOrder((unsigned char *)&x2, sizeof(float)); + UbSystem::swapByteOrder((unsigned char *)&x3, sizeof(float)); + } + + out.write((char *)&x1, sizeof(float)); + out.write((char *)&x2, sizeof(float)); + out.write((char *)&x3, sizeof(float)); + } + out << "\n"; + + // CELLS SECTION + out << "CELLS " << nofCells << " " << nofCells * 9 << "\n"; + + int nodesPerCellDummy = 8; // nofNodesPerCell + if (swapByte) + UbSystem::swapByteOrder((unsigned char *)&nodesPerCellDummy, sizeof(int)); + for (int c = 0; c < (int)cells.size(); c++) { + int BSW = val<1>(cells[c]); + int TSW = val<5>(cells[c]); + int BSE = val<2>(cells[c]); + int TSE = val<6>(cells[c]); + int BNW = val<3>(cells[c]); + int TNW = val<7>(cells[c]); + int BNE = val<4>(cells[c]); + int TNE = val<8>(cells[c]); + if (swapByte) { + UbSystem::swapByteOrder((unsigned char *)&BSW, sizeof(int)); + UbSystem::swapByteOrder((unsigned char *)&BSE, sizeof(int)); + UbSystem::swapByteOrder((unsigned char *)&BNW, sizeof(int)); + UbSystem::swapByteOrder((unsigned char *)&BNE, sizeof(int)); + UbSystem::swapByteOrder((unsigned char *)&TSW, sizeof(int)); + UbSystem::swapByteOrder((unsigned char *)&TSE, sizeof(int)); + UbSystem::swapByteOrder((unsigned char *)&TNW, sizeof(int)); + UbSystem::swapByteOrder((unsigned char *)&TNE, sizeof(int)); + } + + out.write((char *)&nodesPerCellDummy, sizeof(int)); + out.write((char *)&BSW, sizeof(int)); + out.write((char *)&BSE, sizeof(int)); + out.write((char *)&BNE, sizeof(int)); + out.write((char *)&BNW, sizeof(int)); + out.write((char *)&TSW, sizeof(int)); + out.write((char *)&TSE, sizeof(int)); + out.write((char *)&TNE, sizeof(int)); + out.write((char *)&TNW, sizeof(int)); + } + out << "\n"; + + out << "CELL_TYPES " << (int)cells.size() << "\n"; + int celltype = 11; + if (swapByte) + UbSystem::swapByteOrder((unsigned char *)&celltype, sizeof(int)); + for (int c = 0; c < nofCells; c++) + out.write((char *)&celltype, sizeof(int)); + + out << endl; + + // CELL DATA SECTION + // write data section + out << "CELL_DATA " << nofCells << "\n"; + for (int s = 0; s < (int)datanames.size(); ++s) { + if ((int)celldata[s].size() != nofCells) + throw UbException(UB_EXARGS, "datasetsize must be equal to nofNodes"); + out << "SCALARS " << datanames[s] << " float 1 \n LOOKUP_TABLE default \n"; + for (int d = 0; d < (int)celldata[s].size(); d++) { + float dummy = (float)celldata[s][d]; + if (swapByte) + UbSystem::swapByteOrder((unsigned char *)&dummy, sizeof(float)); + out.write((const char *)&dummy, sizeof(float)); + } + out << endl; + } + out.close(); + + UBLOG(logDEBUG1, "WbWriterVtkBinary::writeOctsWithCellData to " << vtkfilename << " - end"); + return vtkfilename; } /*===============================================================================*/ -std::string WbWriterVtkBinary::writeOctsWithNodeData(const string& filename,vector<UbTupleFloat3 >& nodes, vector<UbTupleUInt8 >& cells, vector<string >& datanames, vector<vector<double > >& nodedata) +std::string WbWriterVtkBinary::writeOctsWithNodeData(const string &filename, vector<UbTupleFloat3> &nodes, + vector<UbTupleUInt8> &cells, vector<string> &datanames, + vector<vector<double>> &nodedata) { - //HEADER-SECTION - string vtkfilename = filename + getFileExtension(); - UBLOG(logDEBUG1,"WbWriterVtkBinary::writeOctsWithNodeData to "<<vtkfilename<<" - start"); - - ofstream out(vtkfilename.c_str(),ofstream::out | ofstream::binary); - if(!out) - { - out.clear(); //flags ruecksetzen (ansonsten liefert utern if(!out) weiterhin true!!! - string path = UbSystem::getPathFromString(vtkfilename); - if(path.size()>0){ UbSystem::makeDirectory(path); out.open(vtkfilename.c_str(),ios::out | ios::binary);} - if(!out) throw UbException(UB_EXARGS,"couldn't open file "+vtkfilename); - } - - //WRITE BIGENDIAN VtkBinary FILE - bool swapByte = UbSystem::isLittleEndian(); - int nofNodes = (int)nodes.size(); - int nofCells = (int)cells.size(); - - out<<"# vtk DataFile Version 4.0"<<"\n"; - out<<"D3Q19MasterNodeGrid"<<"\n"; - out<<""<<"\n"; - - //POINTS SECTION - out<<"DATASET UNSTRUCTURED_GRID"<<"\n"; - out<<"POINTS "<<nofNodes<<" float"<<"\n"; - for(int n=0; n<nofNodes; n++) - { - float x1 = val<1>(nodes[n]); - float x2 = val<2>(nodes[n]); - float x3 = val<3>(nodes[n]); - - if(swapByte) - { - UbSystem::swapByteOrder((unsigned char*)&x1,sizeof(float)); - UbSystem::swapByteOrder((unsigned char*)&x2,sizeof(float)); - UbSystem::swapByteOrder((unsigned char*)&x3,sizeof(float)); - } - - out.write((char*)&x1,sizeof(float)); - out.write((char*)&x2,sizeof(float)); - out.write((char*)&x3,sizeof(float)); - } - out<<"\n"; - - //CELLS SECTION - out<<"CELLS "<<nofCells<<" "<<nofCells*9<<"\n"; - - int nodesPerCellDummy = 8; //nofNodesPerCell - if(swapByte) UbSystem::swapByteOrder((unsigned char*)&nodesPerCellDummy,sizeof(int)); - for(int c=0; c<(int)cells.size(); c++) - { - int BSW = val<1>(cells[c]); int TSW = val<5>(cells[c]); - int BSE = val<2>(cells[c]); int TSE = val<6>(cells[c]); - int BNW = val<3>(cells[c]); int TNW = val<7>(cells[c]); - int BNE = val<4>(cells[c]); int TNE = val<8>(cells[c]); - if(swapByte) - { - UbSystem::swapByteOrder((unsigned char*)&BSW,sizeof(int)); - UbSystem::swapByteOrder((unsigned char*)&BSE,sizeof(int)); - UbSystem::swapByteOrder((unsigned char*)&BNW,sizeof(int)); - UbSystem::swapByteOrder((unsigned char*)&BNE,sizeof(int)); - UbSystem::swapByteOrder((unsigned char*)&TSW,sizeof(int)); - UbSystem::swapByteOrder((unsigned char*)&TSE,sizeof(int)); - UbSystem::swapByteOrder((unsigned char*)&TNW,sizeof(int)); - UbSystem::swapByteOrder((unsigned char*)&TNE,sizeof(int)); - } - - out.write((char*)&nodesPerCellDummy,sizeof(int)); - out.write((char*)&BSW,sizeof(int)); - out.write((char*)&BSE,sizeof(int)); - out.write((char*)&BNE,sizeof(int)); - out.write((char*)&BNW,sizeof(int)); - out.write((char*)&TSW,sizeof(int)); - out.write((char*)&TSE,sizeof(int)); - out.write((char*)&TNE,sizeof(int)); - out.write((char*)&TNW,sizeof(int)); - } - out<<"\n"; - - out<<"CELL_TYPES "<<(int)cells.size()<<"\n"; - int celltype = 11; - if(swapByte) UbSystem::swapByteOrder((unsigned char*)&celltype,sizeof(int)); - for(int c=0; c<nofCells; c++) - out.write((char*)&celltype,sizeof(int)); - - out<<endl; - - //NODE DATA SECTION - //write data section - out<<"POINT_DATA "<<nofNodes<<"\n"; - for(int s=0; s<(int)datanames.size(); ++s) - { - if((int)nodedata[s].size() != nofNodes) throw UbException(UB_EXARGS,"datasetsize must be equal to nofNodes"); - out<<"SCALARS "<<datanames[s]<<" float 1 \n LOOKUP_TABLE default \n"; - for(int d=0; d<(int)nodedata[s].size(); d++) - { - float dummy = (float)nodedata[s][d]; - if(swapByte) UbSystem::swapByteOrder((unsigned char*)&dummy,sizeof(float)); - out.write((const char*)&dummy,sizeof(float)); - } - out<<endl; - } - - out.close(); - - UBLOG(logDEBUG1,"WbWriterVtkBinary::writeOctsWithNodeData to "<<vtkfilename<<" - end"); - return vtkfilename; + // HEADER-SECTION + string vtkfilename = filename + getFileExtension(); + UBLOG(logDEBUG1, "WbWriterVtkBinary::writeOctsWithNodeData to " << vtkfilename << " - start"); + + ofstream out(vtkfilename.c_str(), ofstream::out | ofstream::binary); + if (!out) { + out.clear(); // flags ruecksetzen (ansonsten liefert utern if(!out) weiterhin true!!! + string path = UbSystem::getPathFromString(vtkfilename); + if (path.size() > 0) { + UbSystem::makeDirectory(path); + out.open(vtkfilename.c_str(), ios::out | ios::binary); + } + if (!out) + throw UbException(UB_EXARGS, "couldn't open file " + vtkfilename); + } + + // WRITE BIGENDIAN VtkBinary FILE + bool swapByte = UbSystem::isLittleEndian(); + int nofNodes = (int)nodes.size(); + int nofCells = (int)cells.size(); + + out << "# vtk DataFile Version 4.0" + << "\n"; + out << "D3Q19MasterNodeGrid" + << "\n"; + out << "" + << "\n"; + + // POINTS SECTION + out << "DATASET UNSTRUCTURED_GRID" + << "\n"; + out << "POINTS " << nofNodes << " float" + << "\n"; + for (int n = 0; n < nofNodes; n++) { + float x1 = val<1>(nodes[n]); + float x2 = val<2>(nodes[n]); + float x3 = val<3>(nodes[n]); + + if (swapByte) { + UbSystem::swapByteOrder((unsigned char *)&x1, sizeof(float)); + UbSystem::swapByteOrder((unsigned char *)&x2, sizeof(float)); + UbSystem::swapByteOrder((unsigned char *)&x3, sizeof(float)); + } + + out.write((char *)&x1, sizeof(float)); + out.write((char *)&x2, sizeof(float)); + out.write((char *)&x3, sizeof(float)); + } + out << "\n"; + + // CELLS SECTION + out << "CELLS " << nofCells << " " << nofCells * 9 << "\n"; + + int nodesPerCellDummy = 8; // nofNodesPerCell + if (swapByte) + UbSystem::swapByteOrder((unsigned char *)&nodesPerCellDummy, sizeof(int)); + for (int c = 0; c < (int)cells.size(); c++) { + int BSW = val<1>(cells[c]); + int TSW = val<5>(cells[c]); + int BSE = val<2>(cells[c]); + int TSE = val<6>(cells[c]); + int BNW = val<3>(cells[c]); + int TNW = val<7>(cells[c]); + int BNE = val<4>(cells[c]); + int TNE = val<8>(cells[c]); + if (swapByte) { + UbSystem::swapByteOrder((unsigned char *)&BSW, sizeof(int)); + UbSystem::swapByteOrder((unsigned char *)&BSE, sizeof(int)); + UbSystem::swapByteOrder((unsigned char *)&BNW, sizeof(int)); + UbSystem::swapByteOrder((unsigned char *)&BNE, sizeof(int)); + UbSystem::swapByteOrder((unsigned char *)&TSW, sizeof(int)); + UbSystem::swapByteOrder((unsigned char *)&TSE, sizeof(int)); + UbSystem::swapByteOrder((unsigned char *)&TNW, sizeof(int)); + UbSystem::swapByteOrder((unsigned char *)&TNE, sizeof(int)); + } + + out.write((char *)&nodesPerCellDummy, sizeof(int)); + out.write((char *)&BSW, sizeof(int)); + out.write((char *)&BSE, sizeof(int)); + out.write((char *)&BNE, sizeof(int)); + out.write((char *)&BNW, sizeof(int)); + out.write((char *)&TSW, sizeof(int)); + out.write((char *)&TSE, sizeof(int)); + out.write((char *)&TNE, sizeof(int)); + out.write((char *)&TNW, sizeof(int)); + } + out << "\n"; + + out << "CELL_TYPES " << (int)cells.size() << "\n"; + int celltype = 11; + if (swapByte) + UbSystem::swapByteOrder((unsigned char *)&celltype, sizeof(int)); + for (int c = 0; c < nofCells; c++) + out.write((char *)&celltype, sizeof(int)); + + out << endl; + + // NODE DATA SECTION + // write data section + out << "POINT_DATA " << nofNodes << "\n"; + for (int s = 0; s < (int)datanames.size(); ++s) { + if ((int)nodedata[s].size() != nofNodes) + throw UbException(UB_EXARGS, "datasetsize must be equal to nofNodes"); + out << "SCALARS " << datanames[s] << " float 1 \n LOOKUP_TABLE default \n"; + for (int d = 0; d < (int)nodedata[s].size(); d++) { + float dummy = (float)nodedata[s][d]; + if (swapByte) + UbSystem::swapByteOrder((unsigned char *)&dummy, sizeof(float)); + out.write((const char *)&dummy, sizeof(float)); + } + out << endl; + } + + out.close(); + + UBLOG(logDEBUG1, "WbWriterVtkBinary::writeOctsWithNodeData to " << vtkfilename << " - end"); + return vtkfilename; } /*===============================================================================*/ -std::string WbWriterVtkBinary::writeOcts(const string& filename,vector< UbTupleFloat3 >& nodes, vector< UbTupleInt8 >& cells) +std::string WbWriterVtkBinary::writeOcts(const string &filename, vector<UbTupleFloat3> &nodes, + vector<UbTupleInt8> &cells) { - string vtkfilename = filename + getFileExtension(); - UBLOG(logDEBUG1,"WbWriterVtkBinary::writeOcts to "<<vtkfilename<<" - start"); - - ofstream out(vtkfilename.c_str(),ofstream::out | ofstream::binary); - if(!out) - { - out.clear(); //flags ruecksetzen (ansonsten liefert utern if(!out) weiterhin true!!! - string path = UbSystem::getPathFromString(vtkfilename); - if(path.size()>0){ UbSystem::makeDirectory(path); out.open(vtkfilename.c_str(),ios::out | ios::binary);} - if(!out) throw UbException(UB_EXARGS,"couldn't open file "+vtkfilename); - } - - //HEADER-SECTION - //WRITE BIGENDIAN VtkBinary FILE - bool swapByte = UbSystem::isLittleEndian(); - int nofNodes = (int)nodes.size(); - int nofCells = (int)cells.size(); - - out<<"# vtk DataFile Version 4.0"<<"\n"; - out<<"D3Q19MasterNodeGrid"<<"\n"; - out<<""<<"\n"; - - //POINTS SECTION - out<<"DATASET UNSTRUCTURED_GRID"<<"\n"; - out<<"POINTS "<<nofNodes<<" float"<<"\n"; - for(int n=0; n<nofNodes; n++) - { - float x1 = val<1>(nodes[n]); - float x2 = val<2>(nodes[n]); - float x3 = val<3>(nodes[n]); - - if(swapByte) - { - UbSystem::swapByteOrder((unsigned char*)&x1,sizeof(float)); - UbSystem::swapByteOrder((unsigned char*)&x2,sizeof(float)); - UbSystem::swapByteOrder((unsigned char*)&x3,sizeof(float)); - } - - out.write((char*)&x1,sizeof(float)); - out.write((char*)&x2,sizeof(float)); - out.write((char*)&x3,sizeof(float)); - } - out<<"\n"; - - //CELLS SECTION - out<<"CELLS "<<nofCells<<" "<<nofCells*9<<"\n"; - - int nodesPerCellDummy = 8; //nofNodesPerCell - if(swapByte) UbSystem::swapByteOrder((unsigned char*)&nodesPerCellDummy,sizeof(int)); - for(int c=0; c<(int)cells.size(); c++) - { - int BSW = val<1>(cells[c]); int TSW = val<5>(cells[c]); - int BSE = val<2>(cells[c]); int TSE = val<6>(cells[c]); - int BNW = val<3>(cells[c]); int TNW = val<7>(cells[c]); - int BNE = val<4>(cells[c]); int TNE = val<8>(cells[c]); - if(swapByte) - { - UbSystem::swapByteOrder((unsigned char*)&BSW,sizeof(int)); - UbSystem::swapByteOrder((unsigned char*)&BSE,sizeof(int)); - UbSystem::swapByteOrder((unsigned char*)&BNW,sizeof(int)); - UbSystem::swapByteOrder((unsigned char*)&BNE,sizeof(int)); - UbSystem::swapByteOrder((unsigned char*)&TSW,sizeof(int)); - UbSystem::swapByteOrder((unsigned char*)&TSE,sizeof(int)); - UbSystem::swapByteOrder((unsigned char*)&TNW,sizeof(int)); - UbSystem::swapByteOrder((unsigned char*)&TNE,sizeof(int)); - } - - out.write((char*)&nodesPerCellDummy,sizeof(int)); - out.write((char*)&BSW,sizeof(int)); - out.write((char*)&BSE,sizeof(int)); - out.write((char*)&BNE,sizeof(int)); - out.write((char*)&BNW,sizeof(int)); - out.write((char*)&TSW,sizeof(int)); - out.write((char*)&TSE,sizeof(int)); - out.write((char*)&TNE,sizeof(int)); - out.write((char*)&TNW,sizeof(int)); - } - out<<"\n"; - - out<<"CELL_TYPES "<<(int)cells.size()<<"\n"; - int celltype = 11; - if(swapByte) UbSystem::swapByteOrder((unsigned char*)&celltype,sizeof(int)); - for(int c=0; c<nofCells; c++) - out.write((char*)&celltype,sizeof(int)); - - out<<endl; - out.close(); - - UBLOG(logDEBUG1,"WbWriterVtkBinary::writeOcts to "<<vtkfilename<<" - end"); - return vtkfilename; + string vtkfilename = filename + getFileExtension(); + UBLOG(logDEBUG1, "WbWriterVtkBinary::writeOcts to " << vtkfilename << " - start"); + + ofstream out(vtkfilename.c_str(), ofstream::out | ofstream::binary); + if (!out) { + out.clear(); // flags ruecksetzen (ansonsten liefert utern if(!out) weiterhin true!!! + string path = UbSystem::getPathFromString(vtkfilename); + if (path.size() > 0) { + UbSystem::makeDirectory(path); + out.open(vtkfilename.c_str(), ios::out | ios::binary); + } + if (!out) + throw UbException(UB_EXARGS, "couldn't open file " + vtkfilename); + } + + // HEADER-SECTION + // WRITE BIGENDIAN VtkBinary FILE + bool swapByte = UbSystem::isLittleEndian(); + int nofNodes = (int)nodes.size(); + int nofCells = (int)cells.size(); + + out << "# vtk DataFile Version 4.0" + << "\n"; + out << "D3Q19MasterNodeGrid" + << "\n"; + out << "" + << "\n"; + + // POINTS SECTION + out << "DATASET UNSTRUCTURED_GRID" + << "\n"; + out << "POINTS " << nofNodes << " float" + << "\n"; + for (int n = 0; n < nofNodes; n++) { + float x1 = val<1>(nodes[n]); + float x2 = val<2>(nodes[n]); + float x3 = val<3>(nodes[n]); + + if (swapByte) { + UbSystem::swapByteOrder((unsigned char *)&x1, sizeof(float)); + UbSystem::swapByteOrder((unsigned char *)&x2, sizeof(float)); + UbSystem::swapByteOrder((unsigned char *)&x3, sizeof(float)); + } + + out.write((char *)&x1, sizeof(float)); + out.write((char *)&x2, sizeof(float)); + out.write((char *)&x3, sizeof(float)); + } + out << "\n"; + + // CELLS SECTION + out << "CELLS " << nofCells << " " << nofCells * 9 << "\n"; + + int nodesPerCellDummy = 8; // nofNodesPerCell + if (swapByte) + UbSystem::swapByteOrder((unsigned char *)&nodesPerCellDummy, sizeof(int)); + for (int c = 0; c < (int)cells.size(); c++) { + int BSW = val<1>(cells[c]); + int TSW = val<5>(cells[c]); + int BSE = val<2>(cells[c]); + int TSE = val<6>(cells[c]); + int BNW = val<3>(cells[c]); + int TNW = val<7>(cells[c]); + int BNE = val<4>(cells[c]); + int TNE = val<8>(cells[c]); + if (swapByte) { + UbSystem::swapByteOrder((unsigned char *)&BSW, sizeof(int)); + UbSystem::swapByteOrder((unsigned char *)&BSE, sizeof(int)); + UbSystem::swapByteOrder((unsigned char *)&BNW, sizeof(int)); + UbSystem::swapByteOrder((unsigned char *)&BNE, sizeof(int)); + UbSystem::swapByteOrder((unsigned char *)&TSW, sizeof(int)); + UbSystem::swapByteOrder((unsigned char *)&TSE, sizeof(int)); + UbSystem::swapByteOrder((unsigned char *)&TNW, sizeof(int)); + UbSystem::swapByteOrder((unsigned char *)&TNE, sizeof(int)); + } + + out.write((char *)&nodesPerCellDummy, sizeof(int)); + out.write((char *)&BSW, sizeof(int)); + out.write((char *)&BSE, sizeof(int)); + out.write((char *)&BNE, sizeof(int)); + out.write((char *)&BNW, sizeof(int)); + out.write((char *)&TSW, sizeof(int)); + out.write((char *)&TSE, sizeof(int)); + out.write((char *)&TNE, sizeof(int)); + out.write((char *)&TNW, sizeof(int)); + } + out << "\n"; + + out << "CELL_TYPES " << (int)cells.size() << "\n"; + int celltype = 11; + if (swapByte) + UbSystem::swapByteOrder((unsigned char *)&celltype, sizeof(int)); + for (int c = 0; c < nofCells; c++) + out.write((char *)&celltype, sizeof(int)); + + out << endl; + out.close(); + + UBLOG(logDEBUG1, "WbWriterVtkBinary::writeOcts to " << vtkfilename << " - end"); + return vtkfilename; } - diff --git a/src/basics/basics/writer/WbWriterVtkBinary.h b/src/basics/basics/writer/WbWriterVtkBinary.h index d7dd65e6e072d79b740469a53fc21fb671495bbc..aa39a3daacb6a4bd51794cc1bc72fc5818d473c8 100644 --- a/src/basics/basics/writer/WbWriterVtkBinary.h +++ b/src/basics/basics/writer/WbWriterVtkBinary.h @@ -12,63 +12,79 @@ class WbWriterVtkBinary : public WbWriter { public: - static WbWriterVtkBinary* getInstance() - { - static WbWriterVtkBinary instance; - return &instance; - } + static WbWriterVtkBinary *getInstance() + { + static WbWriterVtkBinary instance; + return &instance; + } + + WbWriterVtkBinary(const WbWriterVtkBinary &) = delete; + const WbWriterVtkBinary &operator=(const WbWriterVtkBinary &) = delete; - WbWriterVtkBinary( const WbWriterVtkBinary& ) = delete; - const WbWriterVtkBinary& operator=( const WbWriterVtkBinary& ) = delete; private: - WbWriterVtkBinary() = default; + WbWriterVtkBinary() = default; public: - std::string getFileExtension() override { return ".bin.vtk"; } + std::string getFileExtension() override { return ".bin.vtk"; } - ////////////////////////////////////////////////////////////////////////// - //lines - // 0 ---- 1 - //nodenumbering must start with 0! - std::string writeLines(const std::string& filename, std::vector<UbTupleFloat3 >& nodes, std::vector<UbTupleInt2 >& lines) override; + ////////////////////////////////////////////////////////////////////////// + // lines + // 0 ---- 1 + // nodenumbering must start with 0! + std::string writeLines(const std::string &filename, std::vector<UbTupleFloat3> &nodes, + std::vector<UbTupleInt2> &lines) override; - ////////////////////////////////////////////////////////////////////////// - //triangles - //cell numbering: - // 2 - // - // 0---1 - //nodenumbering must start with 0! - std::string writeTriangles(const std::string& filename,std::vector< UbTupleFloat3 >& nodes, std::vector< UbTupleInt3 >& cells) override; - std::string writeTrianglesWithNodeData(const std::string& filename,std::vector< UbTupleFloat3 >& nodes, std::vector< UbTupleInt3 >& cells, std::vector< std::string >& datanames, std::vector< std::vector< double > >& nodedata) override; + ////////////////////////////////////////////////////////////////////////// + // triangles + // cell numbering: + // 2 + // + // 0---1 + // nodenumbering must start with 0! + std::string writeTriangles(const std::string &filename, std::vector<UbTupleFloat3> &nodes, + std::vector<UbTupleInt3> &cells) override; + std::string writeTrianglesWithNodeData(const std::string &filename, std::vector<UbTupleFloat3> &nodes, + std::vector<UbTupleInt3> &cells, std::vector<std::string> &datanames, + std::vector<std::vector<double>> &nodedata) override; - ////////////////////////////////////////////////////////////////////////// - //2D - //cell numbering: - // 3---2 - // | | - // 0---1 - //nodenumbering must start with 0! - std::string writeQuads(const std::string& filename,std::vector< UbTupleFloat3 >& nodes, std::vector< UbTupleInt4 >& cells) override; - std::string writeQuadsWithNodeData(const std::string& filename,std::vector< UbTupleFloat3 >& nodes, std::vector< UbTupleInt4 >& cells, std::vector< std::string >& datanames, std::vector< std::vector< double > >& nodedata) override; - std::string writeQuadsWithCellData(const std::string& filename,std::vector< UbTupleFloat3 >& nodes, std::vector< UbTupleInt4 >& cells, std::vector< std::string >& datanames, std::vector< std::vector< double > >& celldata) override; - std::string writeQuadsWithNodeAndCellData(const std::string& filename,std::vector< UbTupleFloat3 >& nodes, std::vector< UbTupleInt4 >& cells, - std::vector< std::string >& nodedatanames, std::vector< std::vector< double > >& nodedata, std::vector< std::string >& celldatanames, - std::vector< std::vector< double > >& celldata ) override; - - ////////////////////////////////////////////////////////////////////////// - //octs - // 7 ---- 6 - // /| /| - // 4 +--- 5 | - // | | | | - // | 3 ---+ 2 - // |/ |/ - // 0 ---- 1 - std::string writeOcts(const std::string& filename,std::vector< UbTupleFloat3 >& nodes, std::vector< UbTupleInt8 >& cells) override; - std::string writeOctsWithCellData(const std::string& filename,std::vector<UbTupleFloat3 >& nodes, std::vector<UbTupleInt8 >& cells, std::vector<std::string >& datanames, std::vector<std::vector<double > >& celldata) override; - std::string writeOctsWithNodeData(const std::string& filename,std::vector<UbTupleFloat3 >& nodes, std::vector<UbTupleUInt8 >& cells, std::vector<std::string >& datanames, std::vector<std::vector<double > >& nodedata) override; + ////////////////////////////////////////////////////////////////////////// + // 2D + // cell numbering: + // 3---2 + // | | + // 0---1 + // nodenumbering must start with 0! + std::string writeQuads(const std::string &filename, std::vector<UbTupleFloat3> &nodes, + std::vector<UbTupleInt4> &cells) override; + std::string writeQuadsWithNodeData(const std::string &filename, std::vector<UbTupleFloat3> &nodes, + std::vector<UbTupleInt4> &cells, std::vector<std::string> &datanames, + std::vector<std::vector<double>> &nodedata) override; + std::string writeQuadsWithCellData(const std::string &filename, std::vector<UbTupleFloat3> &nodes, + std::vector<UbTupleInt4> &cells, std::vector<std::string> &datanames, + std::vector<std::vector<double>> &celldata) override; + std::string writeQuadsWithNodeAndCellData(const std::string &filename, std::vector<UbTupleFloat3> &nodes, + std::vector<UbTupleInt4> &cells, std::vector<std::string> &nodedatanames, + std::vector<std::vector<double>> &nodedata, + std::vector<std::string> &celldatanames, + std::vector<std::vector<double>> &celldata) override; + ////////////////////////////////////////////////////////////////////////// + // octs + // 7 ---- 6 + // /| /| + // 4 +--- 5 | + // | | | | + // | 3 ---+ 2 + // |/ |/ + // 0 ---- 1 + std::string writeOcts(const std::string &filename, std::vector<UbTupleFloat3> &nodes, + std::vector<UbTupleInt8> &cells) override; + std::string writeOctsWithCellData(const std::string &filename, std::vector<UbTupleFloat3> &nodes, + std::vector<UbTupleInt8> &cells, std::vector<std::string> &datanames, + std::vector<std::vector<double>> &celldata) override; + std::string writeOctsWithNodeData(const std::string &filename, std::vector<UbTupleFloat3> &nodes, + std::vector<UbTupleUInt8> &cells, std::vector<std::string> &datanames, + std::vector<std::vector<double>> &nodedata) override; }; -#endif //WBWRITERVTKBINARY_H +#endif // WBWRITERVTKBINARY_H diff --git a/src/basics/basics/writer/WbWriterVtkXmlASCII.cpp b/src/basics/basics/writer/WbWriterVtkXmlASCII.cpp index d4ad420ffcae457c74fbcc0b759b7be2098ab4f1..e217b5e24c328e32fb2e3110986f3bb895b98485 100644 --- a/src/basics/basics/writer/WbWriterVtkXmlASCII.cpp +++ b/src/basics/basics/writer/WbWriterVtkXmlASCII.cpp @@ -1,28 +1,28 @@ //======================================================================================= -// ____ ____ __ ______ __________ __ __ __ __ -// \ \ | | | | | _ \ |___ ___| | | | | / \ | | -// \ \ | | | | | |_) | | | | | | | / \ | | -// \ \ | | | | | _ / | | | | | | / /\ \ | | -// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ -// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| -// \ \ | | ________________________________________________________________ -// \ \ | | | ______________________________________________________________| -// \ \| | | | __ __ __ __ ______ _______ -// \ | | |_____ | | | | | | | | | _ \ / _____) -// \ | | _____| | | | | | | | | | | \ \ \_______ +// ____ ____ __ ______ __________ __ __ __ __ +// \ \ | | | | | _ \ |___ ___| | | | | / \ | | +// \ \ | | | | | |_) | | | | | | | / \ | | +// \ \ | | | | | _ / | | | | | | / /\ \ | | +// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ +// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| +// \ \ | | ________________________________________________________________ +// \ \ | | | ______________________________________________________________| +// \ \| | | | __ __ __ __ ______ _______ +// \ | | |_____ | | | | | | | | | _ \ / _____) +// \ | | _____| | | | | | | | | | | \ \ \_______ // \ | | | | |_____ | \_/ | | | | |_/ / _____ | -// \ _____| |__| |________| \_______/ |__| |______/ (_______/ +// \ _____| |__| |________| \_______/ |__| |______/ (_______/ // -// This file is part of VirtualFluids. VirtualFluids is free software: you can +// This file is part of VirtualFluids. VirtualFluids is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of +// License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. -// -// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// +// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License along // with VirtualFluids (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>. // @@ -30,509 +30,543 @@ //! \ingroup writer //! \author Soeren Freudiger, Sebastian Geller //======================================================================================= -#include <basics/writer/WbWriterVtkXmlASCII.h> #include <basics/utilities/UbLogger.h> +#include <basics/writer/WbWriterVtkXmlASCII.h> #include <cstring> #include <limits> using namespace std; /*===============================================================================*/ -std::string WbWriterVtkXmlASCII::pvdEndTag =" </Collection>\n</VTKFile>"; +std::string WbWriterVtkXmlASCII::pvdEndTag = " </Collection>\n</VTKFile>"; /*===============================================================================*/ -std::string WbWriterVtkXmlASCII::writeCollection(const std::string& filename, const std::vector<std::string>& filenames, const double& timeStep, const bool& sepGroups) +std::string WbWriterVtkXmlASCII::writeCollection(const std::string &filename, const std::vector<std::string> &filenames, + const double &timeStep, const bool &sepGroups) { - std::string vtkfilename=filename+".pvd"; - std::ofstream out(vtkfilename.c_str()); - if(!out) - { - out.clear(); //flags ruecksetzen (ansonsten liefert utern if(!out) weiterhin true!!! - string path = UbSystem::getPathFromString(vtkfilename); - if(path.size()>0){UbSystem::makeDirectory(path);out.open(vtkfilename.c_str());} - if(!out) throw UbException(UB_EXARGS,"couldn't open file "+vtkfilename); - } - - std::string endian; - if(UbSystem::isLittleEndian()) endian = "LittleEndian"; - else endian = "BigEndian"; - out<<"<VTKFile type=\"Collection\" version=\"0.1\" byte_order=\""<<endian<<"\" >\n"; - out<<" <Collection>"<<endl; - - int group = 0, part=0; - for(std::size_t i=0; i<filenames.size(); i++) - { - out<<" <DataSet timestep=\""<<timeStep<<"\" group=\""<<group<<"\" part=\""<<part<<"\" file=\""<<filenames[i]<<"\"/>\n"; - if(sepGroups) group++; - else part++; - } - out<<pvdEndTag; - out.close(); - - return vtkfilename; + std::string vtkfilename = filename + ".pvd"; + std::ofstream out(vtkfilename.c_str()); + if (!out) { + out.clear(); // flags ruecksetzen (ansonsten liefert utern if(!out) weiterhin true!!! + string path = UbSystem::getPathFromString(vtkfilename); + if (path.size() > 0) { + UbSystem::makeDirectory(path); + out.open(vtkfilename.c_str()); + } + if (!out) + throw UbException(UB_EXARGS, "couldn't open file " + vtkfilename); + } + + std::string endian; + if (UbSystem::isLittleEndian()) + endian = "LittleEndian"; + else + endian = "BigEndian"; + out << "<VTKFile type=\"Collection\" version=\"0.1\" byte_order=\"" << endian << "\" >\n"; + out << " <Collection>" << endl; + + int group = 0, part = 0; + for (std::size_t i = 0; i < filenames.size(); i++) { + out << " <DataSet timestep=\"" << timeStep << "\" group=\"" << group << "\" part=\"" << part + << "\" file=\"" << filenames[i] << "\"/>\n"; + if (sepGroups) + group++; + else + part++; + } + out << pvdEndTag; + out.close(); + + return vtkfilename; } /*===============================================================================*/ -std::string WbWriterVtkXmlASCII::addFilesToCollection(const std::string& filename, const std::vector<std::string>& filenames, const double& timeStep, const bool& sepGroups) +std::string WbWriterVtkXmlASCII::addFilesToCollection(const std::string &filename, + const std::vector<std::string> &filenames, const double &timeStep, + const bool &sepGroups) { - std::string vtkfilename=filename; - std::fstream test(vtkfilename.c_str(), ios::in); - if(!test) - { - test.clear(); - vtkfilename += ".pvd"; - test.open(vtkfilename.c_str(), ios::in); - if(!test) return this->writeCollection(filename,filenames,timeStep,sepGroups); - } - - std::fstream out(vtkfilename.c_str(), ios::in | ios::out); - out.seekp(-(int)pvdEndTag.size()-1, ios_base::end); - - int group = 0; - for(std::size_t i=0; i<filenames.size(); i++) - { - out<<" <DataSet timestep=\""<<timeStep<<"\" group=\""<<group<<"\" part=\""<<i<<"\" file=\""<<filenames[i]<<"\"/>\n"; - if(sepGroups) group++; - } - out<<pvdEndTag; - - return vtkfilename; + std::string vtkfilename = filename; + std::fstream test(vtkfilename.c_str(), ios::in); + if (!test) { + test.clear(); + vtkfilename += ".pvd"; + test.open(vtkfilename.c_str(), ios::in); + if (!test) + return this->writeCollection(filename, filenames, timeStep, sepGroups); + } + + std::fstream out(vtkfilename.c_str(), ios::in | ios::out); + out.seekp(-(int)pvdEndTag.size() - 1, ios_base::end); + + int group = 0; + for (std::size_t i = 0; i < filenames.size(); i++) { + out << " <DataSet timestep=\"" << timeStep << "\" group=\"" << group << "\" part=\"" << i << "\" file=\"" + << filenames[i] << "\"/>\n"; + if (sepGroups) + group++; + } + out << pvdEndTag; + + return vtkfilename; } /*===============================================================================*/ -std::string WbWriterVtkXmlASCII::writeParallelFile(const string& filename,vector<string>& pieceSources, vector<string>& pointDataNames, vector<string>& cellDataNames) +std::string WbWriterVtkXmlASCII::writeParallelFile(const string &filename, vector<string> &pieceSources, + vector<string> &pointDataNames, vector<string> &cellDataNames) { - string vtkfilename=filename+".pvtu"; - UBLOG(logDEBUG1,"WbWriterVtkXmlASCII::writeParallelFile to "<<vtkfilename<<" - start"); - - std::ofstream out(vtkfilename.c_str()); - if(!out) - { - out.clear(); //flags ruecksetzen (ansonsten liefert utern if(!out) weiterhin true!!! - string path = UbSystem::getPathFromString(vtkfilename); - if(path.size()>0){UbSystem::makeDirectory(path);out.open(vtkfilename.c_str());} - if(!out) throw UbException(UB_EXARGS,"couldn't open file "+vtkfilename); - } - - //VTK FILE - out<<"<VTKFile type=\"PUnstructuredGrid\" version=\"0.1\" byte_order=\"LittleEndian\">\n"; - out<<" <PUnstructuredGrid GhostLevel=\"0\">\n"; - out<<" <PPoints>\n"; - out<<" <PDataArray type=\"Float32\" NumberOfComponents=\"3\"/>\n"; - out<<" </PPoints>\n"; - out<<" <PPointData>\n"; - for(size_t s=0; s<pointDataNames.size(); s++) - out<< " <PDataArray type=\"Float64\" Name=\""<< pointDataNames[s] <<"\"/>\n"; - out<<" </PPointData>\n"; - if (cellDataNames.size() > 0) - { - out<<" <PCellData>\n"; - for(size_t s=0; s<cellDataNames.size(); s++) - out<< " <PDataArray type=\"Float32\" Name=\""<< cellDataNames[s] <<"\"/>\n"; - out<<" </PCellData>\n"; - } - - for(size_t s=0; s<pieceSources.size(); s++) - out<<" <Piece Source=\""<<pieceSources[s]<<"\"/>\n"; - out<<" </PUnstructuredGrid>\n"; - out<<"</VTKFile>"; - out<<endl; - out.close(); - UBLOG(logDEBUG1,"WbWriterVtkXmlASCII::writeParallelFile to "<<vtkfilename<<" - end"); - - return vtkfilename; + string vtkfilename = filename + ".pvtu"; + UBLOG(logDEBUG1, "WbWriterVtkXmlASCII::writeParallelFile to " << vtkfilename << " - start"); + + std::ofstream out(vtkfilename.c_str()); + if (!out) { + out.clear(); // flags ruecksetzen (ansonsten liefert utern if(!out) weiterhin true!!! + string path = UbSystem::getPathFromString(vtkfilename); + if (path.size() > 0) { + UbSystem::makeDirectory(path); + out.open(vtkfilename.c_str()); + } + if (!out) + throw UbException(UB_EXARGS, "couldn't open file " + vtkfilename); + } + + // VTK FILE + out << "<VTKFile type=\"PUnstructuredGrid\" version=\"0.1\" byte_order=\"LittleEndian\">\n"; + out << " <PUnstructuredGrid GhostLevel=\"0\">\n"; + out << " <PPoints>\n"; + out << " <PDataArray type=\"Float32\" NumberOfComponents=\"3\"/>\n"; + out << " </PPoints>\n"; + out << " <PPointData>\n"; + for (size_t s = 0; s < pointDataNames.size(); s++) + out << " <PDataArray type=\"Float64\" Name=\"" << pointDataNames[s] << "\"/>\n"; + out << " </PPointData>\n"; + if (cellDataNames.size() > 0) { + out << " <PCellData>\n"; + for (size_t s = 0; s < cellDataNames.size(); s++) + out << " <PDataArray type=\"Float32\" Name=\"" << cellDataNames[s] << "\"/>\n"; + out << " </PCellData>\n"; + } + + for (size_t s = 0; s < pieceSources.size(); s++) + out << " <Piece Source=\"" << pieceSources[s] << "\"/>\n"; + out << " </PUnstructuredGrid>\n"; + out << "</VTKFile>"; + out << endl; + out.close(); + UBLOG(logDEBUG1, "WbWriterVtkXmlASCII::writeParallelFile to " << vtkfilename << " - end"); + + return vtkfilename; } /*===============================================================================*/ -std::string WbWriterVtkXmlASCII::writeQuads(const string& filename,vector< UbTupleFloat3 >& nodes, vector< UbTupleInt4 >& cells) +std::string WbWriterVtkXmlASCII::writeQuads(const string &filename, vector<UbTupleFloat3> &nodes, + vector<UbTupleInt4> &cells) { - string vtkfilename=filename+getFileExtension(); - UBLOG(logDEBUG1,"WbWriterVtkXmlASCII::writeQuads to "<<vtkfilename<<" - start"); - - std::ofstream out(vtkfilename.c_str()); - if(!out) - { - out.clear(); //flags ruecksetzen (ansonsten liefert utern if(!out) weiterhin true!!! - string path = UbSystem::getPathFromString(vtkfilename); - if(path.size()>0){UbSystem::makeDirectory(path);out.open(vtkfilename.c_str());} - if(!out) throw UbException(UB_EXARGS,"couldn't open file "+vtkfilename); - } - - int nofNodes = (int)nodes.size(); - int nofCells = (int)cells.size(); - - //VTK FILE - out<<"<VTKFile type=\"UnstructuredGrid\" version=\"0.1\" byte_order=\"LittleEndian\" >"<<"\n"; - out<<" <UnstructuredGrid>"<<"\n"; - out<<" <Piece NumberOfPoints=\""<<nofNodes<<"\" NumberOfCells=\""<<nofCells<<"\"> \n"; - - //POINTS SECTION - out<<" <Points>\n"; - out<<" <DataArray type=\"Float32\" NumberOfComponents=\"3\" format=\"ascii\">\n"; - for(int n=0; n<nofNodes; n++) - out<< val<1>(nodes[n]) <<" "<< val<2>(nodes[n]) <<" "<< val<3>(nodes[n]) <<" "; - - out<<"\n"; - out<<" </DataArray>\n"; - out<<" </Points>\n"; - - //CELLS SECTION - out<<" <Cells>\n"; - out<<" <DataArray type=\"Int32\" Name=\"connectivity\" format=\"ascii\">\n"; - - for(int c=0; c<nofCells; c++) - out<< val<1>(cells[c]) <<" " - << val<2>(cells[c]) <<" " - << val<4>(cells[c]) <<" " - << val<3>(cells[c]) <<" "; - out<<"\n"; - out<<" </DataArray>\n"; - out<<" <DataArray type=\"Int32\" Name=\"offsets\" format=\"ascii\">\n"; - for(int c=1; c<nofCells+1; c++) - out<<c*4<<" " ; - - out<<"\n"; - out<<" </DataArray>\n"; - - out<<" <DataArray type=\"UInt8\" Name=\"types\" format=\"ascii\">\n"; - - for(int c=0; c<nofCells; c++) - out<<"8 "; - out<<"\n"; - out<<" </DataArray>\n"; - out<<" </Cells>\n"; - out<<" </Piece>\n"; - out<<" </UnstructuredGrid>\n"; - out<<"</VTKFile>"; - out<<endl; - out.close(); - UBLOG(logDEBUG1,"WbWriterVtkXmlASCII::writeQuads to "<<vtkfilename<<" - end"); - - return vtkfilename; + string vtkfilename = filename + getFileExtension(); + UBLOG(logDEBUG1, "WbWriterVtkXmlASCII::writeQuads to " << vtkfilename << " - start"); + + std::ofstream out(vtkfilename.c_str()); + if (!out) { + out.clear(); // flags ruecksetzen (ansonsten liefert utern if(!out) weiterhin true!!! + string path = UbSystem::getPathFromString(vtkfilename); + if (path.size() > 0) { + UbSystem::makeDirectory(path); + out.open(vtkfilename.c_str()); + } + if (!out) + throw UbException(UB_EXARGS, "couldn't open file " + vtkfilename); + } + + int nofNodes = (int)nodes.size(); + int nofCells = (int)cells.size(); + + // VTK FILE + out << "<VTKFile type=\"UnstructuredGrid\" version=\"0.1\" byte_order=\"LittleEndian\" >" + << "\n"; + out << " <UnstructuredGrid>" + << "\n"; + out << " <Piece NumberOfPoints=\"" << nofNodes << "\" NumberOfCells=\"" << nofCells << "\"> \n"; + + // POINTS SECTION + out << " <Points>\n"; + out << " <DataArray type=\"Float32\" NumberOfComponents=\"3\" format=\"ascii\">\n"; + for (int n = 0; n < nofNodes; n++) + out << val<1>(nodes[n]) << " " << val<2>(nodes[n]) << " " << val<3>(nodes[n]) << " "; + + out << "\n"; + out << " </DataArray>\n"; + out << " </Points>\n"; + + // CELLS SECTION + out << " <Cells>\n"; + out << " <DataArray type=\"Int32\" Name=\"connectivity\" format=\"ascii\">\n"; + + for (int c = 0; c < nofCells; c++) + out << val<1>(cells[c]) << " " << val<2>(cells[c]) << " " << val<4>(cells[c]) << " " << val<3>(cells[c]) + << " "; + out << "\n"; + out << " </DataArray>\n"; + out << " <DataArray type=\"Int32\" Name=\"offsets\" format=\"ascii\">\n"; + for (int c = 1; c < nofCells + 1; c++) + out << c * 4 << " "; + + out << "\n"; + out << " </DataArray>\n"; + + out << " <DataArray type=\"UInt8\" Name=\"types\" format=\"ascii\">\n"; + + for (int c = 0; c < nofCells; c++) + out << "8 "; + out << "\n"; + out << " </DataArray>\n"; + out << " </Cells>\n"; + out << " </Piece>\n"; + out << " </UnstructuredGrid>\n"; + out << "</VTKFile>"; + out << endl; + out.close(); + UBLOG(logDEBUG1, "WbWriterVtkXmlASCII::writeQuads to " << vtkfilename << " - end"); + + return vtkfilename; } /*===============================================================================*/ -std::string WbWriterVtkXmlASCII::writeQuadsWithNodeData(const string& filename,vector< UbTupleFloat3 >& nodes, vector< UbTupleInt4 >& cells, vector< string >& datanames, vector< vector< double > >& nodedata) +std::string WbWriterVtkXmlASCII::writeQuadsWithNodeData(const string &filename, vector<UbTupleFloat3> &nodes, + vector<UbTupleInt4> &cells, vector<string> &datanames, + vector<vector<double>> &nodedata) { - string vtkfilename=filename+getFileExtension(); - UBLOG(logDEBUG1,"WbWriterVtkXmlASCII::writeQuadsWithNodeData to "<<vtkfilename<<" - start"); - - std::ofstream out(vtkfilename.c_str()); - if(!out) - { - out.clear(); //flags ruecksetzen (ansonsten liefert utern if(!out) weiterhin true!!! - string path = UbSystem::getPathFromString(vtkfilename); - if(path.size()>0){UbSystem::makeDirectory(path);out.open(vtkfilename.c_str());} - if(!out) throw UbException(UB_EXARGS,"couldn't open file "+vtkfilename); - } - - int nofNodes = (int)nodes.size(); - int nofCells = (int)cells.size(); - - //VTK FILE - out<<"<VTKFile type=\"UnstructuredGrid\" version=\"0.1\" byte_order=\"LittleEndian\" >"<<"\n"; - out<<" <UnstructuredGrid>"<<"\n"; - out<<" <Piece NumberOfPoints=\""<<nofNodes<<"\" NumberOfCells=\""<<nofCells<<"\"> \n"; - - //POINTS SECTION - out<<" <Points>\n"; - out<<" <DataArray type=\"Float32\" NumberOfComponents=\"3\" format=\"ascii\">\n "; - for(int n=0; n<nofNodes; n++) - out<< val<1>(nodes[n]) <<" "<< val<2>(nodes[n]) <<" "<< val<3>(nodes[n]) <<" "; - - out<<"\n"; - out<<" </DataArray>\n"; - out<<" </Points>\n"; - - //CELLS SECTION - out<<" <Cells>\n"; - out<<" <DataArray type=\"Int32\" Name=\"connectivity\" format=\"ascii\">\n "; - - for(int c=0; c<nofCells; c++) - out<< val<1>(cells[c]) <<" " - << val<2>(cells[c]) <<" " - << val<4>(cells[c]) <<" " - << val<3>(cells[c]) <<" "; - out<<"\n"; - out<<" </DataArray>\n"; - out<<" <DataArray type=\"Int32\" Name=\"offsets\" format=\"ascii\">\n "; - for(int c=1; c<nofCells+1; c++) - out<<c*4<<" " ; - - out<<"\n"; - out<<" </DataArray>\n"; - - out<<" <DataArray type=\"UInt8\" Name=\"types\" format=\"ascii\">\n "; - - for(int c=0; c<nofCells; c++) - out<<"8 "; - out<<"\n"; - out<<" </DataArray>\n"; - - out<<" </Cells>\n"; - - //write data section - out<<" <PointData Scalars=\"Scalars\"> \n"; - for(int s=0; s<(int)datanames.size(); ++s) - { - out<< " <DataArray type=\"Float32\" Name=\""<< datanames[s] <<"\" format=\"ascii\"> \n"; - - for(int d=0; d<(int)nodedata[s].size(); d++) - out<<nodedata[s][d]<<" "; - - out<<"\n </DataArray>\n"; + string vtkfilename = filename + getFileExtension(); + UBLOG(logDEBUG1, "WbWriterVtkXmlASCII::writeQuadsWithNodeData to " << vtkfilename << " - start"); + + std::ofstream out(vtkfilename.c_str()); + if (!out) { + out.clear(); // flags ruecksetzen (ansonsten liefert utern if(!out) weiterhin true!!! + string path = UbSystem::getPathFromString(vtkfilename); + if (path.size() > 0) { + UbSystem::makeDirectory(path); + out.open(vtkfilename.c_str()); + } + if (!out) + throw UbException(UB_EXARGS, "couldn't open file " + vtkfilename); + } + + int nofNodes = (int)nodes.size(); + int nofCells = (int)cells.size(); + + // VTK FILE + out << "<VTKFile type=\"UnstructuredGrid\" version=\"0.1\" byte_order=\"LittleEndian\" >" + << "\n"; + out << " <UnstructuredGrid>" + << "\n"; + out << " <Piece NumberOfPoints=\"" << nofNodes << "\" NumberOfCells=\"" << nofCells << "\"> \n"; + + // POINTS SECTION + out << " <Points>\n"; + out << " <DataArray type=\"Float32\" NumberOfComponents=\"3\" format=\"ascii\">\n "; + for (int n = 0; n < nofNodes; n++) + out << val<1>(nodes[n]) << " " << val<2>(nodes[n]) << " " << val<3>(nodes[n]) << " "; + + out << "\n"; + out << " </DataArray>\n"; + out << " </Points>\n"; + + // CELLS SECTION + out << " <Cells>\n"; + out << " <DataArray type=\"Int32\" Name=\"connectivity\" format=\"ascii\">\n "; + + for (int c = 0; c < nofCells; c++) + out << val<1>(cells[c]) << " " << val<2>(cells[c]) << " " << val<4>(cells[c]) << " " << val<3>(cells[c]) + << " "; + out << "\n"; + out << " </DataArray>\n"; + out << " <DataArray type=\"Int32\" Name=\"offsets\" format=\"ascii\">\n "; + for (int c = 1; c < nofCells + 1; c++) + out << c * 4 << " "; + + out << "\n"; + out << " </DataArray>\n"; + + out << " <DataArray type=\"UInt8\" Name=\"types\" format=\"ascii\">\n "; + + for (int c = 0; c < nofCells; c++) + out << "8 "; + out << "\n"; + out << " </DataArray>\n"; + + out << " </Cells>\n"; + + // write data section + out << " <PointData Scalars=\"Scalars\"> \n"; + for (int s = 0; s < (int)datanames.size(); ++s) { + out << " <DataArray type=\"Float32\" Name=\"" << datanames[s] << "\" format=\"ascii\"> \n"; + + for (int d = 0; d < (int)nodedata[s].size(); d++) + out << nodedata[s][d] << " "; + + out << "\n </DataArray>\n"; } - out<<" </PointData>\n"; - out<<" </Piece>\n"; - out<<" </UnstructuredGrid>\n"; - out<<"</VTKFile>"; - out<<endl; - out.close(); - UBLOG(logDEBUG1,"WbWriterVtkXmlASCII::writeQuadsWithNodeData to "<<vtkfilename<<" - end"); - return vtkfilename; + out << " </PointData>\n"; + out << " </Piece>\n"; + out << " </UnstructuredGrid>\n"; + out << "</VTKFile>"; + out << endl; + out.close(); + UBLOG(logDEBUG1, "WbWriterVtkXmlASCII::writeQuadsWithNodeData to " << vtkfilename << " - end"); + return vtkfilename; } /*===============================================================================*/ -std::string WbWriterVtkXmlASCII::writeQuadsWithCellData(const string& filename,vector< UbTupleFloat3 >& nodes, vector< UbTupleInt4 >& cells, vector< string >& datanames, vector< vector< double > >& celldata) +std::string WbWriterVtkXmlASCII::writeQuadsWithCellData(const string &filename, vector<UbTupleFloat3> &nodes, + vector<UbTupleInt4> &cells, vector<string> &datanames, + vector<vector<double>> &celldata) { - string vtkfilename=filename+getFileExtension(); - UBLOG(logDEBUG1,"WbWriterVtkXmlASCII::writeQuadsWithCellData to "<<vtkfilename<<" - start"); - - std::ofstream out(vtkfilename.c_str()); - if(!out) - { - out.clear(); //flags ruecksetzen (ansonsten liefert utern if(!out) weiterhin true!!! - string path = UbSystem::getPathFromString(vtkfilename); - if(path.size()>0){UbSystem::makeDirectory(path);out.open(vtkfilename.c_str());} - if(!out) throw UbException(UB_EXARGS,"couldn't open file "+vtkfilename); - } - - int nofNodes = (int)nodes.size(); - int nofCells = (int)cells.size(); - - //VTK FILE - out<<"<VTKFile type=\"UnstructuredGrid\" version=\"0.1\" byte_order=\"LittleEndian\" >"<<"\n"; - out<<" <UnstructuredGrid>"<<"\n"; - out<<" <Piece NumberOfPoints=\""<<nofNodes<<"\" NumberOfCells=\""<<nofCells<<"\"> \n"; - - //POINTS SECTION - out<<" <Points>\n"; - out<<" <DataArray type=\"Float32\" NumberOfComponents=\"3\" format=\"ascii\">\n "; - for(int n=0; n<nofNodes; n++) - out<< val<1>(nodes[n]) <<" "<< val<2>(nodes[n]) <<" "<< val<3>(nodes[n]) <<" "; - - out<<"\n"; - out<<" </DataArray>\n"; - out<<" </Points>\n"; - - //CELLS SECTION - out<<" <Cells>\n"; - out<<" <DataArray type=\"Int32\" Name=\"connectivity\" format=\"ascii\">\n "; - - for(int c=0; c<nofCells; c++) - out<< val<1>(cells[c]) <<" " - << val<2>(cells[c]) <<" " - << val<4>(cells[c]) <<" " - << val<3>(cells[c]) <<" "; - out<<"\n"; - out<<" </DataArray>\n"; - out<<" <DataArray type=\"Int32\" Name=\"offsets\" format=\"ascii\">\n "; - for(int c=1; c<nofCells+1; c++) - out<<c*4<<" " ; - - - out<<"\n"; - out<<" </DataArray>\n"; - - out<<" <DataArray type=\"UInt8\" Name=\"types\" format=\"ascii\">\n "; - - for(int c=0; c<nofCells; c++) - out<<"8 "; - out<<"\n"; - out<<" </DataArray>\n"; - - out<<" </Cells>\n"; - - //write data section - out<<" <CellData Scalars=\"Scalars\"> \n"; - for(int s=0; s<(int)datanames.size(); ++s) - { - out<< " <DataArray type=\"Float32\" Name=\""<< datanames[s] <<"\" format=\"ascii\"> \n"; - - for(int d=0; d<(int)celldata[s].size(); d++) - out<<celldata[s][d]<<" "; - - out<<"\n </DataArray>\n"; - } - out<<" </CellData>\n"; - out<<" </Piece>\n"; - out<<" </UnstructuredGrid>\n"; - out<<"</VTKFile>"; - out<<endl; - - out.close(); - - UBLOG(logDEBUG1,"WbWriterVtkXmlASCII::writeQuadsWithCellData to "<<vtkfilename<<" - end"); - - return vtkfilename; + string vtkfilename = filename + getFileExtension(); + UBLOG(logDEBUG1, "WbWriterVtkXmlASCII::writeQuadsWithCellData to " << vtkfilename << " - start"); + + std::ofstream out(vtkfilename.c_str()); + if (!out) { + out.clear(); // flags ruecksetzen (ansonsten liefert utern if(!out) weiterhin true!!! + string path = UbSystem::getPathFromString(vtkfilename); + if (path.size() > 0) { + UbSystem::makeDirectory(path); + out.open(vtkfilename.c_str()); + } + if (!out) + throw UbException(UB_EXARGS, "couldn't open file " + vtkfilename); + } + + int nofNodes = (int)nodes.size(); + int nofCells = (int)cells.size(); + + // VTK FILE + out << "<VTKFile type=\"UnstructuredGrid\" version=\"0.1\" byte_order=\"LittleEndian\" >" + << "\n"; + out << " <UnstructuredGrid>" + << "\n"; + out << " <Piece NumberOfPoints=\"" << nofNodes << "\" NumberOfCells=\"" << nofCells << "\"> \n"; + + // POINTS SECTION + out << " <Points>\n"; + out << " <DataArray type=\"Float32\" NumberOfComponents=\"3\" format=\"ascii\">\n "; + for (int n = 0; n < nofNodes; n++) + out << val<1>(nodes[n]) << " " << val<2>(nodes[n]) << " " << val<3>(nodes[n]) << " "; + + out << "\n"; + out << " </DataArray>\n"; + out << " </Points>\n"; + + // CELLS SECTION + out << " <Cells>\n"; + out << " <DataArray type=\"Int32\" Name=\"connectivity\" format=\"ascii\">\n "; + + for (int c = 0; c < nofCells; c++) + out << val<1>(cells[c]) << " " << val<2>(cells[c]) << " " << val<4>(cells[c]) << " " << val<3>(cells[c]) + << " "; + out << "\n"; + out << " </DataArray>\n"; + out << " <DataArray type=\"Int32\" Name=\"offsets\" format=\"ascii\">\n "; + for (int c = 1; c < nofCells + 1; c++) + out << c * 4 << " "; + + out << "\n"; + out << " </DataArray>\n"; + + out << " <DataArray type=\"UInt8\" Name=\"types\" format=\"ascii\">\n "; + + for (int c = 0; c < nofCells; c++) + out << "8 "; + out << "\n"; + out << " </DataArray>\n"; + + out << " </Cells>\n"; + + // write data section + out << " <CellData Scalars=\"Scalars\"> \n"; + for (int s = 0; s < (int)datanames.size(); ++s) { + out << " <DataArray type=\"Float32\" Name=\"" << datanames[s] << "\" format=\"ascii\"> \n"; + + for (int d = 0; d < (int)celldata[s].size(); d++) + out << celldata[s][d] << " "; + + out << "\n </DataArray>\n"; + } + out << " </CellData>\n"; + out << " </Piece>\n"; + out << " </UnstructuredGrid>\n"; + out << "</VTKFile>"; + out << endl; + + out.close(); + + UBLOG(logDEBUG1, "WbWriterVtkXmlASCII::writeQuadsWithCellData to " << vtkfilename << " - end"); + + return vtkfilename; } /*===============================================================================*/ -string WbWriterVtkXmlASCII::writeQuadsWithNodeAndCellData(const string& filename,vector< UbTupleFloat3 >& nodes, vector< UbTupleInt4 >& cells, - vector< string >& nodedatanames, vector< vector< double > >& nodedata, vector< string >& celldatanames, - vector< vector< double > >& celldata ) +string WbWriterVtkXmlASCII::writeQuadsWithNodeAndCellData(const string &filename, vector<UbTupleFloat3> &nodes, + vector<UbTupleInt4> &cells, vector<string> &nodedatanames, + vector<vector<double>> &nodedata, + vector<string> &celldatanames, + vector<vector<double>> &celldata) { - string vtkfilename=filename+getFileExtension(); - UBLOG(logDEBUG1,"WbWriterVtkXmlASCII::writeQuadsWithNodeAndCellData to "<<vtkfilename<<" - start"); - - std::ofstream out(vtkfilename.c_str()); - if(!out) - { - out.clear(); //flags ruecksetzen (ansonsten liefert utern if(!out) weiterhin true!!! - string path = UbSystem::getPathFromString(vtkfilename); - if(path.size()>0){UbSystem::makeDirectory(path);out.open(vtkfilename.c_str());} - if(!out) throw UbException(UB_EXARGS,"couldn't open file "+vtkfilename); - } - - int nofNodes = (int)nodes.size(); - int nofCells = (int)cells.size(); - - //VTK FILE - out<<"<VTKFile type=\"UnstructuredGrid\" version=\"0.1\" byte_order=\"LittleEndian\" >"<<"\n"; - out<<" <UnstructuredGrid>"<<"\n"; - out<<" <Piece NumberOfPoints=\""<<nofNodes<<"\" NumberOfCells=\""<<nofCells<<"\"> \n"; - - //POINTS SECTION - out<<" <Points>\n"; - out<<" <DataArray type=\"Float32\" NumberOfComponents=\"3\" format=\"ascii\">\n "; - for(int n=0; n<nofNodes; n++) - out<< val<1>(nodes[n]) <<" "<< val<2>(nodes[n]) <<" "<< val<3>(nodes[n]) <<" "; - - out<<"\n"; - out<<" </DataArray>\n"; - out<<" </Points>\n"; - - //CELLS SECTION - out<<" <Cells>\n"; - out<<" <DataArray type=\"Int32\" Name=\"connectivity\" format=\"ascii\">\n "; - - for(int c=0; c<nofCells; c++) - out<< val<1>(cells[c]) <<" " - << val<2>(cells[c]) <<" " - << val<4>(cells[c]) <<" " - << val<3>(cells[c]) <<" "; - out<<"\n"; - out<<" </DataArray>\n"; - out<<" <DataArray type=\"Int32\" Name=\"offsets\" format=\"ascii\">\n "; - for(int c=1; c<nofCells+1; c++) - out<<c*4<<" " ; - - - out<<"\n"; - out<<" </DataArray>\n"; - - out<<" <DataArray type=\"UInt8\" Name=\"types\" format=\"ascii\">\n "; - - for(int c=0; c<nofCells; c++) - out<<"8 "; - out<<"\n"; - out<<" </DataArray>\n"; - - out<<" </Cells>\n"; - - //write PointData section - out<<" <PointData Scalars=\"PScalars\"> \n"; - for(int s=0; s<(int)nodedatanames.size(); ++s) - { - out<< " <DataArray type=\"Float32\" Name=\""<< nodedatanames[s] <<"\" format=\"ascii\"> \n"; - - for(int d=0; d<(int)nodedata[s].size(); d++) - out<<nodedata[s][d]<<" "; - - out<<"\n </DataArray>\n"; - } - out<<" </PointData>\n"; - - //write celldata section - out<<" <CellData Scalars=\"CScalars\"> \n"; - for(int s=0; s<(int)celldatanames.size(); ++s) - { - out<< " <DataArray type=\"Float32\" Name=\""<< celldatanames[s] <<"\" format=\"ascii\"> \n"; - - for(int d=0; d<(int)celldata[s].size(); d++) - out<<celldata[s][d]<<" "; - - out<<"\n </DataArray>\n"; - } - out<<" </CellData>\n"; - out<<" </Piece>\n"; - out<<" </UnstructuredGrid>\n"; - out<<"</VTKFile>"; - out<<endl; - out.close(); - UBLOG(logDEBUG1,"WbWriterVtkXmlASCII::writeQuadsWithNodeAndCellData to "<<vtkfilename<<" - end"); - - return vtkfilename; + string vtkfilename = filename + getFileExtension(); + UBLOG(logDEBUG1, "WbWriterVtkXmlASCII::writeQuadsWithNodeAndCellData to " << vtkfilename << " - start"); + + std::ofstream out(vtkfilename.c_str()); + if (!out) { + out.clear(); // flags ruecksetzen (ansonsten liefert utern if(!out) weiterhin true!!! + string path = UbSystem::getPathFromString(vtkfilename); + if (path.size() > 0) { + UbSystem::makeDirectory(path); + out.open(vtkfilename.c_str()); + } + if (!out) + throw UbException(UB_EXARGS, "couldn't open file " + vtkfilename); + } + + int nofNodes = (int)nodes.size(); + int nofCells = (int)cells.size(); + + // VTK FILE + out << "<VTKFile type=\"UnstructuredGrid\" version=\"0.1\" byte_order=\"LittleEndian\" >" + << "\n"; + out << " <UnstructuredGrid>" + << "\n"; + out << " <Piece NumberOfPoints=\"" << nofNodes << "\" NumberOfCells=\"" << nofCells << "\"> \n"; + + // POINTS SECTION + out << " <Points>\n"; + out << " <DataArray type=\"Float32\" NumberOfComponents=\"3\" format=\"ascii\">\n "; + for (int n = 0; n < nofNodes; n++) + out << val<1>(nodes[n]) << " " << val<2>(nodes[n]) << " " << val<3>(nodes[n]) << " "; + + out << "\n"; + out << " </DataArray>\n"; + out << " </Points>\n"; + + // CELLS SECTION + out << " <Cells>\n"; + out << " <DataArray type=\"Int32\" Name=\"connectivity\" format=\"ascii\">\n "; + + for (int c = 0; c < nofCells; c++) + out << val<1>(cells[c]) << " " << val<2>(cells[c]) << " " << val<4>(cells[c]) << " " << val<3>(cells[c]) + << " "; + out << "\n"; + out << " </DataArray>\n"; + out << " <DataArray type=\"Int32\" Name=\"offsets\" format=\"ascii\">\n "; + for (int c = 1; c < nofCells + 1; c++) + out << c * 4 << " "; + + out << "\n"; + out << " </DataArray>\n"; + + out << " <DataArray type=\"UInt8\" Name=\"types\" format=\"ascii\">\n "; + + for (int c = 0; c < nofCells; c++) + out << "8 "; + out << "\n"; + out << " </DataArray>\n"; + + out << " </Cells>\n"; + + // write PointData section + out << " <PointData Scalars=\"PScalars\"> \n"; + for (int s = 0; s < (int)nodedatanames.size(); ++s) { + out << " <DataArray type=\"Float32\" Name=\"" << nodedatanames[s] << "\" format=\"ascii\"> \n"; + + for (int d = 0; d < (int)nodedata[s].size(); d++) + out << nodedata[s][d] << " "; + + out << "\n </DataArray>\n"; + } + out << " </PointData>\n"; + + // write celldata section + out << " <CellData Scalars=\"CScalars\"> \n"; + for (int s = 0; s < (int)celldatanames.size(); ++s) { + out << " <DataArray type=\"Float32\" Name=\"" << celldatanames[s] << "\" format=\"ascii\"> \n"; + + for (int d = 0; d < (int)celldata[s].size(); d++) + out << celldata[s][d] << " "; + + out << "\n </DataArray>\n"; + } + out << " </CellData>\n"; + out << " </Piece>\n"; + out << " </UnstructuredGrid>\n"; + out << "</VTKFile>"; + out << endl; + out.close(); + UBLOG(logDEBUG1, "WbWriterVtkXmlASCII::writeQuadsWithNodeAndCellData to " << vtkfilename << " - end"); + + return vtkfilename; } /*===============================================================================*/ -std::string WbWriterVtkXmlASCII::writeLines(const string& filename,vector<UbTupleFloat3 >& nodes, vector<UbTupleInt2 >& lines) +std::string WbWriterVtkXmlASCII::writeLines(const string &filename, vector<UbTupleFloat3> &nodes, + vector<UbTupleInt2> &lines) { - string vtkfilename=filename+getFileExtension(); - UBLOG(logDEBUG1,"WbWriterVtkXmlASCII::writeLines to "<<vtkfilename<<" - start"); - - std::ofstream out(vtkfilename.c_str()); - if(!out) - { - out.clear(); //flags ruecksetzen (ansonsten liefert utern if(!out) weiterhin true!!! - string path = UbSystem::getPathFromString(vtkfilename); - if(path.size()>0){UbSystem::makeDirectory(path);out.open(vtkfilename.c_str());} - if(!out) throw UbException(UB_EXARGS,"couldn't open file "+vtkfilename); - } - - int nofNodes = (int)nodes.size(); - int nofLines = (int)lines.size(); - - //VTK FILE - out<<"<VTKFile type=\"UnstructuredGrid\" version=\"0.1\" byte_order=\"LittleEndian\" >"<<"\n"; - out<<" <UnstructuredGrid>"<<"\n"; - out<<" <Piece NumberOfPoints=\""<<nofNodes<<"\" NumberOfCells=\""<<nofLines<<"\"> \n"; - - //POINTS SECTION - out<<" <Points>\n"; - out<<" <DataArray type=\"Float32\" NumberOfComponents=\"3\" format=\"ascii\">\n"; - for(int n=0; n<nofNodes; n++) - out<< val<1>(nodes[n]) <<" "<< val<2>(nodes[n]) <<" "<< val<3>(nodes[n]) <<" "; - - out<<"\n"; - out<<" </DataArray>\n"; - out<<" </Points>\n"; - - //CELLS SECTION - out<<" <Cells>\n"; - out<<" <DataArray type=\"Int32\" Name=\"connectivity\" format=\"ascii\">\n"; - - for(int c=0; c<nofLines; c++) - out<< val<1>(lines[c]) <<" "<< val<2>(lines[c])<<" "; - out<<"\n"; - out<<" </DataArray>\n"; - out<<" <DataArray type=\"Int32\" Name=\"offsets\" format=\"ascii\">\n"; - for(int c=1; c<=nofLines; c++) - out<<c*2<<" " ; - - out<<"\n"; - out<<" </DataArray>\n"; - - out<<" <DataArray type=\"UInt8\" Name=\"types\" format=\"ascii\">\n"; - - for(int c=0; c<nofLines; c++) - out<<"3 "; - out<<"\n"; - out<<" </DataArray>\n"; - out<<" </Cells>\n"; - out<<" </Piece>\n"; - out<<" </UnstructuredGrid>\n"; - out<<"</VTKFile>"; - out<<endl; - out.close(); - UBLOG(logDEBUG1,"WbWriterVtkXmlASCII::writeLines to "<<vtkfilename<<" - end"); - - return vtkfilename; + string vtkfilename = filename + getFileExtension(); + UBLOG(logDEBUG1, "WbWriterVtkXmlASCII::writeLines to " << vtkfilename << " - start"); + + std::ofstream out(vtkfilename.c_str()); + if (!out) { + out.clear(); // flags ruecksetzen (ansonsten liefert utern if(!out) weiterhin true!!! + string path = UbSystem::getPathFromString(vtkfilename); + if (path.size() > 0) { + UbSystem::makeDirectory(path); + out.open(vtkfilename.c_str()); + } + if (!out) + throw UbException(UB_EXARGS, "couldn't open file " + vtkfilename); + } + + int nofNodes = (int)nodes.size(); + int nofLines = (int)lines.size(); + + // VTK FILE + out << "<VTKFile type=\"UnstructuredGrid\" version=\"0.1\" byte_order=\"LittleEndian\" >" + << "\n"; + out << " <UnstructuredGrid>" + << "\n"; + out << " <Piece NumberOfPoints=\"" << nofNodes << "\" NumberOfCells=\"" << nofLines << "\"> \n"; + + // POINTS SECTION + out << " <Points>\n"; + out << " <DataArray type=\"Float32\" NumberOfComponents=\"3\" format=\"ascii\">\n"; + for (int n = 0; n < nofNodes; n++) + out << val<1>(nodes[n]) << " " << val<2>(nodes[n]) << " " << val<3>(nodes[n]) << " "; + + out << "\n"; + out << " </DataArray>\n"; + out << " </Points>\n"; + + // CELLS SECTION + out << " <Cells>\n"; + out << " <DataArray type=\"Int32\" Name=\"connectivity\" format=\"ascii\">\n"; + + for (int c = 0; c < nofLines; c++) + out << val<1>(lines[c]) << " " << val<2>(lines[c]) << " "; + out << "\n"; + out << " </DataArray>\n"; + out << " <DataArray type=\"Int32\" Name=\"offsets\" format=\"ascii\">\n"; + for (int c = 1; c <= nofLines; c++) + out << c * 2 << " "; + + out << "\n"; + out << " </DataArray>\n"; + + out << " <DataArray type=\"UInt8\" Name=\"types\" format=\"ascii\">\n"; + + for (int c = 0; c < nofLines; c++) + out << "3 "; + out << "\n"; + out << " </DataArray>\n"; + out << " </Cells>\n"; + out << " </Piece>\n"; + out << " </UnstructuredGrid>\n"; + out << "</VTKFile>"; + out << endl; + out.close(); + UBLOG(logDEBUG1, "WbWriterVtkXmlASCII::writeLines to " << vtkfilename << " - end"); + + return vtkfilename; } /*===============================================================================*/ -//std::string WbWriterVtkXmlASCII::writeLinesWithNodeData(const string& filename,vector<UbTupleFloat3 >& nodes, vector<UbTupleInt2 >& lines, std::vector< std::string >& datanames, std::vector< std::vector< double > >& nodedata) +// std::string WbWriterVtkXmlASCII::writeLinesWithNodeData(const string& filename,vector<UbTupleFloat3 >& nodes, +// vector<UbTupleInt2 >& lines, std::vector< std::string >& datanames, std::vector< std::vector< double > >& nodedata) //{ // string vtkfilename=filename+getFileExtension(); // UBLOG(logDEBUG1,"WbWriterVtkXmlASCII::writeLinesWithNodeData to "<<vtkfilename<<" - start"); @@ -609,613 +643,645 @@ std::string WbWriterVtkXmlASCII::writeLines(const string& filename,vector<UbTupl // return vtkfilename; //} /*===============================================================================*/ -std::string WbWriterVtkXmlASCII::writeTriangles(const string& filename,vector<UbTupleFloat3 >& nodes, vector<UbTupleInt3 >& triangles) +std::string WbWriterVtkXmlASCII::writeTriangles(const string &filename, vector<UbTupleFloat3> &nodes, + vector<UbTupleInt3> &triangles) { - string vtkfilename=filename+getFileExtension(); - UBLOG(logDEBUG1,"WbWriterVtkXmlASCII::writeTriangles to "<<vtkfilename<<" - start"); - - std::ofstream out(vtkfilename.c_str()); - if(!out) - { - out.clear(); //flags ruecksetzen (ansonsten liefert utern if(!out) weiterhin true!!! - string path = UbSystem::getPathFromString(vtkfilename); - if(path.size()>0){UbSystem::makeDirectory(path);out.open(vtkfilename.c_str());} - if(!out) throw UbException(UB_EXARGS,"couldn't open file "+vtkfilename); - } - - int nofNodes = (int)nodes.size(); - int nofTriangles= (int)triangles.size(); - - //VTK FILE - out<<"<VTKFile type=\"UnstructuredGrid\" version=\"0.1\" byte_order=\"LittleEndian\" >"<<"\n"; - out<<" <UnstructuredGrid>"<<"\n"; - out<<" <Piece NumberOfPoints=\""<<nofNodes<<"\" NumberOfCells=\""<<nofTriangles<<"\"> \n"; - - //POINTS SECTION - out<<" <Points>\n"; - out<<" <DataArray type=\"Float32\" NumberOfComponents=\"3\" format=\"ascii\">\n"; - for(int n=0; n<nofNodes; n++) - out<< val<1>(nodes[n]) <<" "<< val<2>(nodes[n]) <<" "<< val<3>(nodes[n]) <<" "; - - out<<"\n"; - out<<" </DataArray>\n"; - out<<" </Points>\n"; - - //CELLS SECTION - out<<" <Cells>\n"; - out<<" <DataArray type=\"Int32\" Name=\"connectivity\" format=\"ascii\">\n"; - - for(int c=0; c<nofTriangles; c++) - out<< val<1>(triangles[c]) <<" "<< val<2>(triangles[c])<<" "<< val<3>(triangles[c])<<" "; - out<<"\n"; - out<<" </DataArray>\n"; - out<<" <DataArray type=\"Int32\" Name=\"offsets\" format=\"ascii\">\n"; - for(int c=1; c<nofTriangles+1; c++) - out<<c*3<<" " ; - - out<<"\n"; - out<<" </DataArray>\n"; - - out<<" <DataArray type=\"UInt8\" Name=\"types\" format=\"ascii\">\n"; - - for(int c=0; c<nofTriangles; c++) - out<<"5 "; - out<<"\n"; - out<<" </DataArray>\n"; - out<<" </Cells>\n"; - out<<" </Piece>\n"; - out<<" </UnstructuredGrid>\n"; - out<<"</VTKFile>"; - out<<endl; - out.close(); - UBLOG(logDEBUG1,"WbWriterVtkXmlASCII::writeTriangles to "<<vtkfilename<<" - end"); - - return vtkfilename; + string vtkfilename = filename + getFileExtension(); + UBLOG(logDEBUG1, "WbWriterVtkXmlASCII::writeTriangles to " << vtkfilename << " - start"); + + std::ofstream out(vtkfilename.c_str()); + if (!out) { + out.clear(); // flags ruecksetzen (ansonsten liefert utern if(!out) weiterhin true!!! + string path = UbSystem::getPathFromString(vtkfilename); + if (path.size() > 0) { + UbSystem::makeDirectory(path); + out.open(vtkfilename.c_str()); + } + if (!out) + throw UbException(UB_EXARGS, "couldn't open file " + vtkfilename); + } + + int nofNodes = (int)nodes.size(); + int nofTriangles = (int)triangles.size(); + + // VTK FILE + out << "<VTKFile type=\"UnstructuredGrid\" version=\"0.1\" byte_order=\"LittleEndian\" >" + << "\n"; + out << " <UnstructuredGrid>" + << "\n"; + out << " <Piece NumberOfPoints=\"" << nofNodes << "\" NumberOfCells=\"" << nofTriangles << "\"> \n"; + + // POINTS SECTION + out << " <Points>\n"; + out << " <DataArray type=\"Float32\" NumberOfComponents=\"3\" format=\"ascii\">\n"; + for (int n = 0; n < nofNodes; n++) + out << val<1>(nodes[n]) << " " << val<2>(nodes[n]) << " " << val<3>(nodes[n]) << " "; + + out << "\n"; + out << " </DataArray>\n"; + out << " </Points>\n"; + + // CELLS SECTION + out << " <Cells>\n"; + out << " <DataArray type=\"Int32\" Name=\"connectivity\" format=\"ascii\">\n"; + + for (int c = 0; c < nofTriangles; c++) + out << val<1>(triangles[c]) << " " << val<2>(triangles[c]) << " " << val<3>(triangles[c]) << " "; + out << "\n"; + out << " </DataArray>\n"; + out << " <DataArray type=\"Int32\" Name=\"offsets\" format=\"ascii\">\n"; + for (int c = 1; c < nofTriangles + 1; c++) + out << c * 3 << " "; + + out << "\n"; + out << " </DataArray>\n"; + + out << " <DataArray type=\"UInt8\" Name=\"types\" format=\"ascii\">\n"; + + for (int c = 0; c < nofTriangles; c++) + out << "5 "; + out << "\n"; + out << " </DataArray>\n"; + out << " </Cells>\n"; + out << " </Piece>\n"; + out << " </UnstructuredGrid>\n"; + out << "</VTKFile>"; + out << endl; + out.close(); + UBLOG(logDEBUG1, "WbWriterVtkXmlASCII::writeTriangles to " << vtkfilename << " - end"); + + return vtkfilename; } /*===============================================================================*/ -std::string WbWriterVtkXmlASCII::writeTrianglesWithNodeData(const std::string& filename,std::vector< UbTupleFloat3 >& nodes, std::vector< UbTupleInt3 >& cells, std::vector< std::string >& datanames, std::vector< std::vector< double > >& nodedata) +std::string WbWriterVtkXmlASCII::writeTrianglesWithNodeData(const std::string &filename, + std::vector<UbTupleFloat3> &nodes, + std::vector<UbTupleInt3> &cells, + std::vector<std::string> &datanames, + std::vector<std::vector<double>> &nodedata) { - string vtkfilename=filename+getFileExtension(); - UBLOG(logDEBUG1,"WbWriterVtkXmlASCII::writeTrianglesWithNodeData to "<<vtkfilename<<" - start"); - - std::ofstream out(vtkfilename.c_str()); - if(!out) - { - out.clear(); //flags ruecksetzen (ansonsten liefert utern if(!out) weiterhin true!!! - string path = UbSystem::getPathFromString(vtkfilename); - if(path.size()>0){UbSystem::makeDirectory(path);out.open(vtkfilename.c_str());} - if(!out) throw UbException(UB_EXARGS,"couldn't open file "+vtkfilename); - } - - int nofNodes = (int)nodes.size(); - int nofCells = (int)cells.size(); - - //VTK FILE - out<<"<VTKFile type=\"UnstructuredGrid\" version=\"0.1\" byte_order=\"LittleEndian\" >"<<"\n"; - out<<" <UnstructuredGrid>"<<"\n"; - out<<" <Piece NumberOfPoints=\""<<nofNodes<<"\" NumberOfCells=\""<<nofCells<<"\"> \n"; - - //POINTS SECTION - out<<" <Points>\n"; - out<<" <DataArray type=\"Float32\" NumberOfComponents=\"3\" format=\"ascii\">\n "; - for(int n=0; n<nofNodes; n++) - out<< val<1>(nodes[n]) <<" "<< val<2>(nodes[n]) <<" "<< val<3>(nodes[n]) <<" "; - - out<<"\n"; - out<<" </DataArray>\n"; - out<<" </Points>\n"; - - //CELLS SECTION - out<<" <Cells>\n"; - out<<" <DataArray type=\"Int32\" Name=\"connectivity\" format=\"ascii\">\n "; - - for(int c=0; c<nofCells; c++) - out<< val<1>(cells[c]) <<" "<< val<2>(cells[c]) <<" "<< val<3>(cells[c]) <<" "; - out<<"\n"; - out<<" </DataArray>\n"; - out<<" <DataArray type=\"Int32\" Name=\"offsets\" format=\"ascii\">\n "; - for(int c=1; c<nofCells+1; c++) - out<<c*3<<" " ; - - out<<"\n"; - out<<" </DataArray>\n"; - - out<<" <DataArray type=\"UInt8\" Name=\"types\" format=\"ascii\">\n "; - - for(int c=0; c<nofCells; c++) - out<<"5 "; - out<<"\n"; - out<<" </DataArray>\n"; - - out<<" </Cells>\n"; - - //write data section - out<<" <PointData Scalars=\"Scalars\"> \n"; - for(int s=0; s<(int)datanames.size(); ++s) - { - out<< " <DataArray type=\"Float32\" Name=\""<< datanames[s] <<"\" format=\"ascii\"> \n"; - - for(int d=0; d<(int)nodedata[s].size(); d++) - out<<nodedata[s][d]<<" "; - - out<<"\n </DataArray>\n"; - } - out<<" </PointData>\n"; - out<<" </Piece>\n"; - out<<" </UnstructuredGrid>\n"; - out<<"</VTKFile>"; - out<<endl; - out.close(); - UBLOG(logDEBUG1,"WbWriterVtkXmlASCII::writeTrianglesWithNodeData to "<<vtkfilename<<" - end"); - - return vtkfilename; + string vtkfilename = filename + getFileExtension(); + UBLOG(logDEBUG1, "WbWriterVtkXmlASCII::writeTrianglesWithNodeData to " << vtkfilename << " - start"); + + std::ofstream out(vtkfilename.c_str()); + if (!out) { + out.clear(); // flags ruecksetzen (ansonsten liefert utern if(!out) weiterhin true!!! + string path = UbSystem::getPathFromString(vtkfilename); + if (path.size() > 0) { + UbSystem::makeDirectory(path); + out.open(vtkfilename.c_str()); + } + if (!out) + throw UbException(UB_EXARGS, "couldn't open file " + vtkfilename); + } + + int nofNodes = (int)nodes.size(); + int nofCells = (int)cells.size(); + + // VTK FILE + out << "<VTKFile type=\"UnstructuredGrid\" version=\"0.1\" byte_order=\"LittleEndian\" >" + << "\n"; + out << " <UnstructuredGrid>" + << "\n"; + out << " <Piece NumberOfPoints=\"" << nofNodes << "\" NumberOfCells=\"" << nofCells << "\"> \n"; + + // POINTS SECTION + out << " <Points>\n"; + out << " <DataArray type=\"Float32\" NumberOfComponents=\"3\" format=\"ascii\">\n "; + for (int n = 0; n < nofNodes; n++) + out << val<1>(nodes[n]) << " " << val<2>(nodes[n]) << " " << val<3>(nodes[n]) << " "; + + out << "\n"; + out << " </DataArray>\n"; + out << " </Points>\n"; + + // CELLS SECTION + out << " <Cells>\n"; + out << " <DataArray type=\"Int32\" Name=\"connectivity\" format=\"ascii\">\n "; + + for (int c = 0; c < nofCells; c++) + out << val<1>(cells[c]) << " " << val<2>(cells[c]) << " " << val<3>(cells[c]) << " "; + out << "\n"; + out << " </DataArray>\n"; + out << " <DataArray type=\"Int32\" Name=\"offsets\" format=\"ascii\">\n "; + for (int c = 1; c < nofCells + 1; c++) + out << c * 3 << " "; + + out << "\n"; + out << " </DataArray>\n"; + + out << " <DataArray type=\"UInt8\" Name=\"types\" format=\"ascii\">\n "; + + for (int c = 0; c < nofCells; c++) + out << "5 "; + out << "\n"; + out << " </DataArray>\n"; + + out << " </Cells>\n"; + + // write data section + out << " <PointData Scalars=\"Scalars\"> \n"; + for (int s = 0; s < (int)datanames.size(); ++s) { + out << " <DataArray type=\"Float32\" Name=\"" << datanames[s] << "\" format=\"ascii\"> \n"; + + for (int d = 0; d < (int)nodedata[s].size(); d++) + out << nodedata[s][d] << " "; + + out << "\n </DataArray>\n"; + } + out << " </PointData>\n"; + out << " </Piece>\n"; + out << " </UnstructuredGrid>\n"; + out << "</VTKFile>"; + out << endl; + out.close(); + UBLOG(logDEBUG1, "WbWriterVtkXmlASCII::writeTrianglesWithNodeData to " << vtkfilename << " - end"); + + return vtkfilename; } /*===============================================================================*/ -std::string WbWriterVtkXmlASCII::writeOctsWithCellData(const string& filename,vector< UbTupleFloat3 >& nodes, vector< UbTupleInt8 >& cells, vector< string >& datanames, vector< vector< double > >& celldata) +std::string WbWriterVtkXmlASCII::writeOctsWithCellData(const string &filename, vector<UbTupleFloat3> &nodes, + vector<UbTupleInt8> &cells, vector<string> &datanames, + vector<vector<double>> &celldata) { - string vtkfilename=filename+getFileExtension(); - UBLOG(logDEBUG1,"WbWriterVtkXmlASCII::writeOctsWithCellData to "<<vtkfilename<<" - start"); - - std::ofstream out(vtkfilename.c_str()); - if(!out) - { - out.clear(); //flags ruecksetzen (ansonsten liefert utern if(!out) weiterhin true!!! - string path = UbSystem::getPathFromString(vtkfilename); - if(path.size()>0){UbSystem::makeDirectory(path);out.open(vtkfilename.c_str());} - if(!out) throw UbException(UB_EXARGS,"couldn't open file "+vtkfilename); - } - - int nofNodes = (int)nodes.size(); - int nofCells = (int)cells.size(); - - //VTK FILE - out<<"<VTKFile type=\"UnstructuredGrid\" version=\"0.1\" byte_order=\"LittleEndian\" >"<<"\n"; - out<<" <UnstructuredGrid>"<<"\n"; - out<<" <Piece NumberOfPoints=\""<<nofNodes<<"\" NumberOfCells=\""<<nofCells<<"\"> \n"; - - //POINTS SECTION - out<<" <Points>\n"; - out<<" <DataArray type=\"Float32\" NumberOfComponents=\"3\" format=\"ascii\">\n "; - for(int n=0; n<nofNodes; n++) - out<< val<1>(nodes[n]) <<" "<< val<2>(nodes[n]) <<" "<< val<3>(nodes[n]) <<" "; - - out<<"\n"; - out<<" </DataArray>\n"; - out<<" </Points>\n"; - - //CELLS SECTION - out<<" <Cells>\n"; - out<<" <DataArray type=\"Int32\" Name=\"connectivity\" format=\"ascii\">\n "; - - for(int c=0; c<nofCells; c++) - out<< val<1>(cells[c]) <<" " - << val<2>(cells[c]) <<" " - << val<4>(cells[c]) <<" " - << val<3>(cells[c]) <<" " - << val<5>(cells[c]) <<" " - << val<6>(cells[c]) <<" " - << val<8>(cells[c]) <<" " - << val<7>(cells[c]) <<" "; - out<<"\n"; - out<<" </DataArray>\n"; - out<<" <DataArray type=\"Int32\" Name=\"offsets\" format=\"ascii\">\n "; - for(int c=1; c<nofCells+1; c++) - out<<c*8<<" " ; - - - out<<"\n"; - out<<" </DataArray>\n"; - - out<<" <DataArray type=\"UInt8\" Name=\"types\" format=\"ascii\">\n "; - - for(int c=0; c<nofCells; c++) - out<<"11 "; - out<<"\n"; - out<<" </DataArray>\n"; - - out<<" </Cells>\n"; - - - //write data section - out<<" <CellData Scalars=\"Scalars\"> \n"; - for(int s=0; s<(int)datanames.size(); ++s) - { - out<< " <DataArray type=\"Float32\" Name=\""<< datanames[s] <<"\" format=\"ascii\"> \n"; - - for(int d=0; d<(int)celldata[s].size(); d++) - out<<celldata[s][d]<<" "; - - out<<"\n </DataArray>\n"; - } - out<<" </CellData>\n"; - - out<<" </Piece>\n"; - out<<" </UnstructuredGrid>\n"; - out<<"</VTKFile>"; - out<<endl; - out.close(); - UBLOG(logDEBUG1,"WbWriterVtkXmlASCII::writeOctsWithCellData to "<<vtkfilename<<" - end"); - - return vtkfilename; + string vtkfilename = filename + getFileExtension(); + UBLOG(logDEBUG1, "WbWriterVtkXmlASCII::writeOctsWithCellData to " << vtkfilename << " - start"); + + std::ofstream out(vtkfilename.c_str()); + if (!out) { + out.clear(); // flags ruecksetzen (ansonsten liefert utern if(!out) weiterhin true!!! + string path = UbSystem::getPathFromString(vtkfilename); + if (path.size() > 0) { + UbSystem::makeDirectory(path); + out.open(vtkfilename.c_str()); + } + if (!out) + throw UbException(UB_EXARGS, "couldn't open file " + vtkfilename); + } + + int nofNodes = (int)nodes.size(); + int nofCells = (int)cells.size(); + + // VTK FILE + out << "<VTKFile type=\"UnstructuredGrid\" version=\"0.1\" byte_order=\"LittleEndian\" >" + << "\n"; + out << " <UnstructuredGrid>" + << "\n"; + out << " <Piece NumberOfPoints=\"" << nofNodes << "\" NumberOfCells=\"" << nofCells << "\"> \n"; + + // POINTS SECTION + out << " <Points>\n"; + out << " <DataArray type=\"Float32\" NumberOfComponents=\"3\" format=\"ascii\">\n "; + for (int n = 0; n < nofNodes; n++) + out << val<1>(nodes[n]) << " " << val<2>(nodes[n]) << " " << val<3>(nodes[n]) << " "; + + out << "\n"; + out << " </DataArray>\n"; + out << " </Points>\n"; + + // CELLS SECTION + out << " <Cells>\n"; + out << " <DataArray type=\"Int32\" Name=\"connectivity\" format=\"ascii\">\n "; + + for (int c = 0; c < nofCells; c++) + out << val<1>(cells[c]) << " " << val<2>(cells[c]) << " " << val<4>(cells[c]) << " " << val<3>(cells[c]) << " " + << val<5>(cells[c]) << " " << val<6>(cells[c]) << " " << val<8>(cells[c]) << " " << val<7>(cells[c]) + << " "; + out << "\n"; + out << " </DataArray>\n"; + out << " <DataArray type=\"Int32\" Name=\"offsets\" format=\"ascii\">\n "; + for (int c = 1; c < nofCells + 1; c++) + out << c * 8 << " "; + + out << "\n"; + out << " </DataArray>\n"; + + out << " <DataArray type=\"UInt8\" Name=\"types\" format=\"ascii\">\n "; + + for (int c = 0; c < nofCells; c++) + out << "11 "; + out << "\n"; + out << " </DataArray>\n"; + + out << " </Cells>\n"; + + // write data section + out << " <CellData Scalars=\"Scalars\"> \n"; + for (int s = 0; s < (int)datanames.size(); ++s) { + out << " <DataArray type=\"Float32\" Name=\"" << datanames[s] << "\" format=\"ascii\"> \n"; + + for (int d = 0; d < (int)celldata[s].size(); d++) + out << celldata[s][d] << " "; + + out << "\n </DataArray>\n"; + } + out << " </CellData>\n"; + + out << " </Piece>\n"; + out << " </UnstructuredGrid>\n"; + out << "</VTKFile>"; + out << endl; + out.close(); + UBLOG(logDEBUG1, "WbWriterVtkXmlASCII::writeOctsWithCellData to " << vtkfilename << " - end"); + + return vtkfilename; } /*===============================================================================*/ -std::string WbWriterVtkXmlASCII::writeOctsWithNodeData(const string& filename,vector< UbTupleFloat3 >& nodes, vector< UbTupleUInt8 >& cells, vector< string >& datanames, vector< vector< double > >& nodedata) +std::string WbWriterVtkXmlASCII::writeOctsWithNodeData(const string &filename, vector<UbTupleFloat3> &nodes, + vector<UbTupleUInt8> &cells, vector<string> &datanames, + vector<vector<double>> &nodedata) { - string vtkfilename=filename+getFileExtension(); - UBLOG(logDEBUG1,"WbWriterVtkXmlASCII::writeOctsWithNodeData to "<<vtkfilename<<" - start"); - - std::ofstream out(vtkfilename.c_str()); - if(!out) - { - out.clear(); //flags ruecksetzen (ansonsten liefert utern if(!out) weiterhin true!!! - string path = UbSystem::getPathFromString(vtkfilename); - if(path.size()>0){UbSystem::makeDirectory(path);out.open(vtkfilename.c_str());} - if(!out) throw UbException(UB_EXARGS,"couldn't open file "+vtkfilename); - } - - int nofNodes = (int)nodes.size(); - int nofCells = (int)cells.size(); - - //VTK FILE - out<<"<VTKFile type=\"UnstructuredGrid\" version=\"0.1\" byte_order=\"LittleEndian\" >"<<"\n"; - out<<" <UnstructuredGrid>"<<"\n"; - out<<" <Piece NumberOfPoints=\""<<nofNodes<<"\" NumberOfCells=\""<<nofCells<<"\"> \n"; - - //POINTS SECTION - out<<" <Points>\n"; - out<<" <DataArray type=\"Float32\" NumberOfComponents=\"3\" format=\"ascii\">\n "; - for(int n=0; n<nofNodes; n++) - out<<val<1>(nodes[n])<<" "<<val<2>(nodes[n])<<" "<<val<3>(nodes[n])<<" "; - - out<<"\n"; - out<<" </DataArray>\n"; - out<<" </Points>\n"; - - //CELLS SECTION - out<<" <Cells>\n"; - out<<" <DataArray type=\"Int32\" Name=\"connectivity\" format=\"ascii\">\n "; - - for(int c=0; c<nofCells; c++) - out<< val<1>(cells[c]) <<" " - << val<2>(cells[c]) <<" " - << val<4>(cells[c]) <<" " - << val<3>(cells[c]) <<" " - << val<5>(cells[c]) <<" " - << val<6>(cells[c]) <<" " - << val<8>(cells[c]) <<" " - << val<7>(cells[c]) <<" "; - - out<<"\n"; - out<<" </DataArray>\n"; - out<<" <DataArray type=\"Int32\" Name=\"offsets\" format=\"ascii\">\n "; - for(int c=1; c<nofCells+1; c++) - out<<c*8<<" " ; - - out<<"\n"; - out<<" </DataArray>\n"; - - out<<" <DataArray type=\"UInt8\" Name=\"types\" format=\"ascii\">\n "; - - for(int c=0; c<nofCells; c++) - out<<"11 "; - out<<"\n"; - out<<" </DataArray>\n"; - - out<<" </Cells>\n"; - - //write PointData section - out<<" <PointData Scalars=\"PScalars\"> \n"; - for(int s=0; s<(int)datanames.size(); ++s) - { - out<< " <DataArray type=\"Float64\" Name=\""<< datanames[s] <<"\" format=\"ascii\">"; - - for(int d=0; d<(int)nodedata[s].size(); d++) - { - //out<<base64_encode((unsigned char*)(&nodedata[s][d]),sizeof(float)); - //out.write((char*)&nodedata[s][d],sizeof(float)); - out<<nodedata[s][d]<<" "; - } - out<<"</DataArray>\n"; - } - out<<" </PointData>\n"; - out<<" </Piece>\n"; - out<<" </UnstructuredGrid>\n"; - out<<"</VTKFile>"; - out<<endl; - out.close(); - UBLOG(logDEBUG1,"WbWriterVtkXmlASCII::writeOctsWithNodeData to "<<vtkfilename<<" - end"); - - return vtkfilename; + string vtkfilename = filename + getFileExtension(); + UBLOG(logDEBUG1, "WbWriterVtkXmlASCII::writeOctsWithNodeData to " << vtkfilename << " - start"); + + std::ofstream out(vtkfilename.c_str()); + if (!out) { + out.clear(); // flags ruecksetzen (ansonsten liefert utern if(!out) weiterhin true!!! + string path = UbSystem::getPathFromString(vtkfilename); + if (path.size() > 0) { + UbSystem::makeDirectory(path); + out.open(vtkfilename.c_str()); + } + if (!out) + throw UbException(UB_EXARGS, "couldn't open file " + vtkfilename); + } + + int nofNodes = (int)nodes.size(); + int nofCells = (int)cells.size(); + + // VTK FILE + out << "<VTKFile type=\"UnstructuredGrid\" version=\"0.1\" byte_order=\"LittleEndian\" >" + << "\n"; + out << " <UnstructuredGrid>" + << "\n"; + out << " <Piece NumberOfPoints=\"" << nofNodes << "\" NumberOfCells=\"" << nofCells << "\"> \n"; + + // POINTS SECTION + out << " <Points>\n"; + out << " <DataArray type=\"Float32\" NumberOfComponents=\"3\" format=\"ascii\">\n "; + for (int n = 0; n < nofNodes; n++) + out << val<1>(nodes[n]) << " " << val<2>(nodes[n]) << " " << val<3>(nodes[n]) << " "; + + out << "\n"; + out << " </DataArray>\n"; + out << " </Points>\n"; + + // CELLS SECTION + out << " <Cells>\n"; + out << " <DataArray type=\"Int32\" Name=\"connectivity\" format=\"ascii\">\n "; + + for (int c = 0; c < nofCells; c++) + out << val<1>(cells[c]) << " " << val<2>(cells[c]) << " " << val<4>(cells[c]) << " " << val<3>(cells[c]) << " " + << val<5>(cells[c]) << " " << val<6>(cells[c]) << " " << val<8>(cells[c]) << " " << val<7>(cells[c]) + << " "; + + out << "\n"; + out << " </DataArray>\n"; + out << " <DataArray type=\"Int32\" Name=\"offsets\" format=\"ascii\">\n "; + for (int c = 1; c < nofCells + 1; c++) + out << c * 8 << " "; + + out << "\n"; + out << " </DataArray>\n"; + + out << " <DataArray type=\"UInt8\" Name=\"types\" format=\"ascii\">\n "; + + for (int c = 0; c < nofCells; c++) + out << "11 "; + out << "\n"; + out << " </DataArray>\n"; + + out << " </Cells>\n"; + + // write PointData section + out << " <PointData Scalars=\"PScalars\"> \n"; + for (int s = 0; s < (int)datanames.size(); ++s) { + out << " <DataArray type=\"Float64\" Name=\"" << datanames[s] << "\" format=\"ascii\">"; + + for (int d = 0; d < (int)nodedata[s].size(); d++) { + // out<<base64_encode((unsigned char*)(&nodedata[s][d]),sizeof(float)); + // out.write((char*)&nodedata[s][d],sizeof(float)); + out << nodedata[s][d] << " "; + } + out << "</DataArray>\n"; + } + out << " </PointData>\n"; + out << " </Piece>\n"; + out << " </UnstructuredGrid>\n"; + out << "</VTKFile>"; + out << endl; + out.close(); + UBLOG(logDEBUG1, "WbWriterVtkXmlASCII::writeOctsWithNodeData to " << vtkfilename << " - end"); + + return vtkfilename; } /*===============================================================================*/ -std::string WbWriterVtkXmlASCII::writeOcts(const string& filename,vector< UbTupleFloat3 >& nodes, vector< UbTupleInt8 >& cells) +std::string WbWriterVtkXmlASCII::writeOcts(const string &filename, vector<UbTupleFloat3> &nodes, + vector<UbTupleInt8> &cells) { - string vtkfilename=filename+getFileExtension(); - UBLOG(logDEBUG1,"WbWriterVtkXmlASCII::writeOcts to "<<vtkfilename<<" - start"); - - std::ofstream out(vtkfilename.c_str()); - if(!out) - { - out.clear(); //flags ruecksetzen (ansonsten liefert utern if(!out) weiterhin true!!! - string path = UbSystem::getPathFromString(vtkfilename); - if(path.size()>0){UbSystem::makeDirectory(path);out.open(vtkfilename.c_str());} - if(!out) throw UbException(UB_EXARGS,"couldn't open file "+vtkfilename); - } - - int nofNodes = (int)nodes.size(); - int nofCells = (int)cells.size(); - - //VTK FILE - out<<"<VTKFile type=\"UnstructuredGrid\" version=\"0.1\" byte_order=\"LittleEndian\" >"<<"\n"; - out<<" <UnstructuredGrid>"<<"\n"; - out<<" <Piece NumberOfPoints=\""<<nofNodes<<"\" NumberOfCells=\""<<nofCells<<"\"> \n"; - - //POINTS SECTION - out<<" <Points>\n"; - out<<" <DataArray type=\"Float32\" NumberOfComponents=\"3\" format=\"ascii\">\n "; - for(int n=0; n<nofNodes; n++) - out<< val<1>(nodes[n]) <<" "<< val<2>(nodes[n]) <<" "<< val<3>(nodes[n]) <<" "; - - out<<"\n"; - out<<" </DataArray>\n"; - out<<" </Points>\n"; - - //CELLS SECTION - out<<" <Cells>\n"; - out<<" <DataArray type=\"Int32\" Name=\"connectivity\" format=\"ascii\">\n "; - - for(int c=0; c<nofCells; c++) - out<< val<1>(cells[c]) <<" " - << val<2>(cells[c]) <<" " - << val<4>(cells[c]) <<" " - << val<3>(cells[c]) <<" " - << val<5>(cells[c]) <<" " - << val<6>(cells[c]) <<" " - << val<8>(cells[c]) <<" " - << val<7>(cells[c]) <<" "; - out<<"\n"; - out<<" </DataArray>\n"; - out<<" <DataArray type=\"Int32\" Name=\"offsets\" format=\"ascii\">\n "; - for(int c=1; c<nofCells+1; c++) - out<<c*8<<" " ; - - out<<"\n"; - out<<" </DataArray>\n"; - - out<<" <DataArray type=\"UInt8\" Name=\"types\" format=\"ascii\">\n "; - - for(int c=0; c<nofCells; c++) - out<<"11 "; - out<<"\n"; - out<<" </DataArray>\n"; - out<<" </Cells>\n"; - out<<" </Piece>\n"; - out<<" </UnstructuredGrid>\n"; - out<<"</VTKFile>"; - out<<endl; - out.close(); - UBLOG(logDEBUG1,"WbWriterVtkXmlASCII::writeOcts to "<<vtkfilename<<" - end"); - - return vtkfilename; + string vtkfilename = filename + getFileExtension(); + UBLOG(logDEBUG1, "WbWriterVtkXmlASCII::writeOcts to " << vtkfilename << " - start"); + + std::ofstream out(vtkfilename.c_str()); + if (!out) { + out.clear(); // flags ruecksetzen (ansonsten liefert utern if(!out) weiterhin true!!! + string path = UbSystem::getPathFromString(vtkfilename); + if (path.size() > 0) { + UbSystem::makeDirectory(path); + out.open(vtkfilename.c_str()); + } + if (!out) + throw UbException(UB_EXARGS, "couldn't open file " + vtkfilename); + } + + int nofNodes = (int)nodes.size(); + int nofCells = (int)cells.size(); + + // VTK FILE + out << "<VTKFile type=\"UnstructuredGrid\" version=\"0.1\" byte_order=\"LittleEndian\" >" + << "\n"; + out << " <UnstructuredGrid>" + << "\n"; + out << " <Piece NumberOfPoints=\"" << nofNodes << "\" NumberOfCells=\"" << nofCells << "\"> \n"; + + // POINTS SECTION + out << " <Points>\n"; + out << " <DataArray type=\"Float32\" NumberOfComponents=\"3\" format=\"ascii\">\n "; + for (int n = 0; n < nofNodes; n++) + out << val<1>(nodes[n]) << " " << val<2>(nodes[n]) << " " << val<3>(nodes[n]) << " "; + + out << "\n"; + out << " </DataArray>\n"; + out << " </Points>\n"; + + // CELLS SECTION + out << " <Cells>\n"; + out << " <DataArray type=\"Int32\" Name=\"connectivity\" format=\"ascii\">\n "; + + for (int c = 0; c < nofCells; c++) + out << val<1>(cells[c]) << " " << val<2>(cells[c]) << " " << val<4>(cells[c]) << " " << val<3>(cells[c]) << " " + << val<5>(cells[c]) << " " << val<6>(cells[c]) << " " << val<8>(cells[c]) << " " << val<7>(cells[c]) + << " "; + out << "\n"; + out << " </DataArray>\n"; + out << " <DataArray type=\"Int32\" Name=\"offsets\" format=\"ascii\">\n "; + for (int c = 1; c < nofCells + 1; c++) + out << c * 8 << " "; + + out << "\n"; + out << " </DataArray>\n"; + + out << " <DataArray type=\"UInt8\" Name=\"types\" format=\"ascii\">\n "; + + for (int c = 0; c < nofCells; c++) + out << "11 "; + out << "\n"; + out << " </DataArray>\n"; + out << " </Cells>\n"; + out << " </Piece>\n"; + out << " </UnstructuredGrid>\n"; + out << "</VTKFile>"; + out << endl; + out.close(); + UBLOG(logDEBUG1, "WbWriterVtkXmlASCII::writeOcts to " << vtkfilename << " - end"); + + return vtkfilename; } -std::string WbWriterVtkXmlASCII::writeNodes(const std::string& filename,std::vector< UbTupleFloat3 >& nodes) +std::string WbWriterVtkXmlASCII::writeNodes(const std::string &filename, std::vector<UbTupleFloat3> &nodes) { - string vtkfilename=filename+getFileExtension(); - UBLOG(logDEBUG1,"WbWriterVtkXmlASCII::writeLines to "<<vtkfilename<<" - start"); - - std::ofstream out(vtkfilename.c_str()); - if(!out) - { - out.clear(); //flags ruecksetzen (ansonsten liefert utern if(!out) weiterhin true!!! - string path = UbSystem::getPathFromString(vtkfilename); - if(path.size()>0){UbSystem::makeDirectory(path);out.open(vtkfilename.c_str());} - if(!out) throw UbException(UB_EXARGS,"couldn't open file "+vtkfilename); - } - - int nofNodes = (int)nodes.size(); - - //VTK FILE - out<<"<VTKFile type=\"UnstructuredGrid\" version=\"0.1\" byte_order=\"LittleEndian\" >"<<"\n"; - out<<" <UnstructuredGrid>"<<"\n"; - out<<" <Piece NumberOfPoints=\""<<nofNodes<<"\" NumberOfCells=\""<<nofNodes<<"\"> \n"; - - //POINTS SECTION - out<<" <Points>\n"; - out<<" <DataArray type=\"Float32\" NumberOfComponents=\"3\" format=\"ascii\">\n"; - for(int n=0; n<nofNodes; n++) - out<< val<1>(nodes[n]) <<" "<< val<2>(nodes[n]) <<" "<< val<3>(nodes[n]) <<" "; - - out<<"\n"; - out<<" </DataArray>\n"; - out<<" </Points>\n"; - - //CELLS SECTION - out<<" <Cells>\n"; - out<<" <DataArray type=\"Int32\" Name=\"connectivity\" format=\"ascii\">\n"; - for(int n=0; n<nofNodes; n++) - out<< n << " "; - out<<"\n"; - - out<<" </DataArray>\n"; - out<<" <DataArray type=\"Int32\" Name=\"offsets\" format=\"ascii\">\n"; - for(int n=1; n<=nofNodes; n++) - out << n << " "; - - out<<"\n"; - out<<" </DataArray>\n"; - - out<<" <DataArray type=\"UInt8\" Name=\"types\" format=\"ascii\">\n"; - - for(int n=0; n<nofNodes; n++) - out<<"1 "; - out<<"\n"; - out<<" </DataArray>\n"; - out<<" </Cells>\n"; - out<<" </Piece>\n"; - out<<" </UnstructuredGrid>\n"; - out<<"</VTKFile>"; - out<<endl; - out.close(); - UBLOG(logDEBUG1,"WbWriterVtkXmlASCII::writeLines to "<<vtkfilename<<" - end"); - - return vtkfilename; + string vtkfilename = filename + getFileExtension(); + UBLOG(logDEBUG1, "WbWriterVtkXmlASCII::writeLines to " << vtkfilename << " - start"); + + std::ofstream out(vtkfilename.c_str()); + if (!out) { + out.clear(); // flags ruecksetzen (ansonsten liefert utern if(!out) weiterhin true!!! + string path = UbSystem::getPathFromString(vtkfilename); + if (path.size() > 0) { + UbSystem::makeDirectory(path); + out.open(vtkfilename.c_str()); + } + if (!out) + throw UbException(UB_EXARGS, "couldn't open file " + vtkfilename); + } + + int nofNodes = (int)nodes.size(); + + // VTK FILE + out << "<VTKFile type=\"UnstructuredGrid\" version=\"0.1\" byte_order=\"LittleEndian\" >" + << "\n"; + out << " <UnstructuredGrid>" + << "\n"; + out << " <Piece NumberOfPoints=\"" << nofNodes << "\" NumberOfCells=\"" << nofNodes << "\"> \n"; + + // POINTS SECTION + out << " <Points>\n"; + out << " <DataArray type=\"Float32\" NumberOfComponents=\"3\" format=\"ascii\">\n"; + for (int n = 0; n < nofNodes; n++) + out << val<1>(nodes[n]) << " " << val<2>(nodes[n]) << " " << val<3>(nodes[n]) << " "; + + out << "\n"; + out << " </DataArray>\n"; + out << " </Points>\n"; + + // CELLS SECTION + out << " <Cells>\n"; + out << " <DataArray type=\"Int32\" Name=\"connectivity\" format=\"ascii\">\n"; + for (int n = 0; n < nofNodes; n++) + out << n << " "; + out << "\n"; + + out << " </DataArray>\n"; + out << " <DataArray type=\"Int32\" Name=\"offsets\" format=\"ascii\">\n"; + for (int n = 1; n <= nofNodes; n++) + out << n << " "; + + out << "\n"; + out << " </DataArray>\n"; + + out << " <DataArray type=\"UInt8\" Name=\"types\" format=\"ascii\">\n"; + + for (int n = 0; n < nofNodes; n++) + out << "1 "; + out << "\n"; + out << " </DataArray>\n"; + out << " </Cells>\n"; + out << " </Piece>\n"; + out << " </UnstructuredGrid>\n"; + out << "</VTKFile>"; + out << endl; + out.close(); + UBLOG(logDEBUG1, "WbWriterVtkXmlASCII::writeLines to " << vtkfilename << " - end"); + + return vtkfilename; } -std::string WbWriterVtkXmlASCII::writeNodesWithNodeData(const std::string& filename,std::vector< UbTupleFloat3 >& nodes, std::vector<std::string >& datanames, std::vector<std::vector<double > >& nodedata) +std::string WbWriterVtkXmlASCII::writeNodesWithNodeData(const std::string &filename, std::vector<UbTupleFloat3> &nodes, + std::vector<std::string> &datanames, + std::vector<std::vector<double>> &nodedata) { - string vtkfilename=filename+getFileExtension(); - UBLOG(logDEBUG1,"WbWriterVtkXmlASCII::writeNodesWithNodeData to "<<vtkfilename<<" - start"); - - std::ofstream out(vtkfilename.c_str()); - if(!out) - { - out.clear(); //flags ruecksetzen (ansonsten liefert utern if(!out) weiterhin true!!! - string path = UbSystem::getPathFromString(vtkfilename); - if(path.size()>0){UbSystem::makeDirectory(path);out.open(vtkfilename.c_str());} - if(!out) throw UbException(UB_EXARGS,"couldn't open file "+vtkfilename); - } - - int nofNodes = (int)nodes.size(); - - //VTK FILE - out<<"<VTKFile type=\"UnstructuredGrid\" version=\"0.1\" byte_order=\"LittleEndian\" >"<<"\n"; - out<<" <UnstructuredGrid>"<<"\n"; - out<<" <Piece NumberOfPoints=\""<<nofNodes<<"\" NumberOfCells=\""<<nofNodes<<"\"> \n"; - - //POINTS SECTION - out<<" <Points>\n"; - out<<" <DataArray type=\"Float32\" NumberOfComponents=\"3\" format=\"ascii\">\n "; - for(int n=0; n<nofNodes; n++) - out<< val<1>(nodes[n]) <<" "<< val<2>(nodes[n]) <<" "<< val<3>(nodes[n]) <<" "; - - out<<"\n"; - out<<" </DataArray>\n"; - out<<" </Points>\n"; - - //CELLS SECTION - out<<" <Cells>\n"; - out<<" <DataArray type=\"Int32\" Name=\"connectivity\" format=\"ascii\">\n "; - - for(int c=0; c<nofNodes; c++) - out << c <<" "; - out<<"\n"; - - out<<" </DataArray>\n"; - out<<" <DataArray type=\"Int32\" Name=\"offsets\" format=\"ascii\">\n "; - for(int c=1; c<nofNodes+1; c++) - out<<c<<" " ; - - out<<"\n"; - out<<" </DataArray>\n"; - - out<<" <DataArray type=\"UInt8\" Name=\"types\" format=\"ascii\">\n "; - for(int c=0; c<nofNodes; c++) - out<<"1 "; - - out<<"\n"; - out<<" </DataArray>\n"; - - out<<" </Cells>\n"; - - //write data section - out<<" <PointData Scalars=\"Scalars\"> \n"; - for(int s=0; s<(int)datanames.size(); ++s) - { - out<< " <DataArray type=\"Float32\" Name=\""<< datanames[s] <<"\" format=\"ascii\"> \n"; - - for(int d=0; d<(int)nodedata[s].size(); d++) - out<<nodedata[s][d]<<" "; - - out<<"\n </DataArray>\n"; - } - out<<" </PointData>\n"; - out<<" </Piece>\n"; - out<<" </UnstructuredGrid>\n"; - out<<"</VTKFile>"; - out<<endl; - out.close(); - out.close(); - UBLOG(logDEBUG1,"WbWriterVtkXmlASCII::writeNodesWithNodeData to "<<vtkfilename<<" - end"); - - return vtkfilename; + string vtkfilename = filename + getFileExtension(); + UBLOG(logDEBUG1, "WbWriterVtkXmlASCII::writeNodesWithNodeData to " << vtkfilename << " - start"); + + std::ofstream out(vtkfilename.c_str()); + if (!out) { + out.clear(); // flags ruecksetzen (ansonsten liefert utern if(!out) weiterhin true!!! + string path = UbSystem::getPathFromString(vtkfilename); + if (path.size() > 0) { + UbSystem::makeDirectory(path); + out.open(vtkfilename.c_str()); + } + if (!out) + throw UbException(UB_EXARGS, "couldn't open file " + vtkfilename); + } + + int nofNodes = (int)nodes.size(); + + // VTK FILE + out << "<VTKFile type=\"UnstructuredGrid\" version=\"0.1\" byte_order=\"LittleEndian\" >" + << "\n"; + out << " <UnstructuredGrid>" + << "\n"; + out << " <Piece NumberOfPoints=\"" << nofNodes << "\" NumberOfCells=\"" << nofNodes << "\"> \n"; + + // POINTS SECTION + out << " <Points>\n"; + out << " <DataArray type=\"Float32\" NumberOfComponents=\"3\" format=\"ascii\">\n "; + for (int n = 0; n < nofNodes; n++) + out << val<1>(nodes[n]) << " " << val<2>(nodes[n]) << " " << val<3>(nodes[n]) << " "; + + out << "\n"; + out << " </DataArray>\n"; + out << " </Points>\n"; + + // CELLS SECTION + out << " <Cells>\n"; + out << " <DataArray type=\"Int32\" Name=\"connectivity\" format=\"ascii\">\n "; + + for (int c = 0; c < nofNodes; c++) + out << c << " "; + out << "\n"; + + out << " </DataArray>\n"; + out << " <DataArray type=\"Int32\" Name=\"offsets\" format=\"ascii\">\n "; + for (int c = 1; c < nofNodes + 1; c++) + out << c << " "; + + out << "\n"; + out << " </DataArray>\n"; + + out << " <DataArray type=\"UInt8\" Name=\"types\" format=\"ascii\">\n "; + for (int c = 0; c < nofNodes; c++) + out << "1 "; + + out << "\n"; + out << " </DataArray>\n"; + + out << " </Cells>\n"; + + // write data section + out << " <PointData Scalars=\"Scalars\"> \n"; + for (int s = 0; s < (int)datanames.size(); ++s) { + out << " <DataArray type=\"Float32\" Name=\"" << datanames[s] << "\" format=\"ascii\"> \n"; + + for (int d = 0; d < (int)nodedata[s].size(); d++) + out << nodedata[s][d] << " "; + + out << "\n </DataArray>\n"; + } + out << " </PointData>\n"; + out << " </Piece>\n"; + out << " </UnstructuredGrid>\n"; + out << "</VTKFile>"; + out << endl; + out.close(); + out.close(); + UBLOG(logDEBUG1, "WbWriterVtkXmlASCII::writeNodesWithNodeData to " << vtkfilename << " - end"); + + return vtkfilename; } ////////////////////////////////////////////////////////////////////////// -std::string WbWriterVtkXmlASCII::writeNodesWithNodeDataDouble(const std::string& filename,std::vector< UbTupleDouble3 >& nodes, std::vector<std::string >& datanames, std::vector<std::vector<double > >& nodedata) +std::string WbWriterVtkXmlASCII::writeNodesWithNodeDataDouble(const std::string &filename, + std::vector<UbTupleDouble3> &nodes, + std::vector<std::string> &datanames, + std::vector<std::vector<double>> &nodedata) { - string vtkfilename=filename+getFileExtension(); - UBLOG(logDEBUG1,"WbWriterVtkXmlASCII::writeNodesWithNodeData to "<<vtkfilename<<" - start"); - - std::ofstream out(vtkfilename.c_str()); - out.precision (std::numeric_limits<double>::digits10 + 1); - if(!out) - { - out.clear(); //flags ruecksetzen (ansonsten liefert utern if(!out) weiterhin true!!! - string path = UbSystem::getPathFromString(vtkfilename); - if(path.size()>0){UbSystem::makeDirectory(path);out.open(vtkfilename.c_str());} - if(!out) throw UbException(UB_EXARGS,"couldn't open file "+vtkfilename); - } - - int nofNodes = (int)nodes.size(); - - //VTK FILE - out<<"<VTKFile type=\"UnstructuredGrid\" version=\"0.1\" byte_order=\"LittleEndian\" >"<<"\n"; - out<<" <UnstructuredGrid>"<<"\n"; - out<<" <Piece NumberOfPoints=\""<<nofNodes<<"\" NumberOfCells=\""<<nofNodes<<"\"> \n"; - - //POINTS SECTION - out<<" <Points>\n"; - out<<" <DataArray type=\"Float64\" NumberOfComponents=\"3\" format=\"ascii\">\n "; - for(int n=0; n<nofNodes; n++) - out<< val<1>(nodes[n]) <<" "<< val<2>(nodes[n]) <<" "<< val<3>(nodes[n]) <<" "; - - out<<"\n"; - out<<" </DataArray>\n"; - out<<" </Points>\n"; - - //CELLS SECTION - out<<" <Cells>\n"; - out<<" <DataArray type=\"Int32\" Name=\"connectivity\" format=\"ascii\">\n "; - - for(int c=0; c<nofNodes; c++) - out << c <<" "; - out<<"\n"; - - out<<" </DataArray>\n"; - out<<" <DataArray type=\"Int64\" Name=\"offsets\" format=\"ascii\">\n "; - for(int c=1; c<nofNodes+1; c++) - out<<c<<" " ; - - out<<"\n"; - out<<" </DataArray>\n"; - - out<<" <DataArray type=\"UInt8\" Name=\"types\" format=\"ascii\">\n "; - for(int c=0; c<nofNodes; c++) - out<<"1 "; - - out<<"\n"; - out<<" </DataArray>\n"; - - out<<" </Cells>\n"; - - //write data section - out<<" <PointData Scalars=\"Scalars\"> \n"; - for(int s=0; s<(int)datanames.size(); ++s) - { - out<< " <DataArray type=\"Float64\" Name=\""<< datanames[s] <<"\" format=\"ascii\"> \n"; - - for(int d=0; d<(int)nodedata[s].size(); d++) - out<<nodedata[s][d]<<" "; - - out<<"\n </DataArray>\n"; - } - out<<" </PointData>\n"; - out<<" </Piece>\n"; - out<<" </UnstructuredGrid>\n"; - out<<"</VTKFile>"; - out<<endl; - out.close(); - out.close(); - UBLOG(logDEBUG1,"WbWriterVtkXmlASCII::writeNodesWithNodeData to "<<vtkfilename<<" - end"); - - return vtkfilename; + string vtkfilename = filename + getFileExtension(); + UBLOG(logDEBUG1, "WbWriterVtkXmlASCII::writeNodesWithNodeData to " << vtkfilename << " - start"); + + std::ofstream out(vtkfilename.c_str()); + out.precision(std::numeric_limits<double>::digits10 + 1); + if (!out) { + out.clear(); // flags ruecksetzen (ansonsten liefert utern if(!out) weiterhin true!!! + string path = UbSystem::getPathFromString(vtkfilename); + if (path.size() > 0) { + UbSystem::makeDirectory(path); + out.open(vtkfilename.c_str()); + } + if (!out) + throw UbException(UB_EXARGS, "couldn't open file " + vtkfilename); + } + + int nofNodes = (int)nodes.size(); + + // VTK FILE + out << "<VTKFile type=\"UnstructuredGrid\" version=\"0.1\" byte_order=\"LittleEndian\" >" + << "\n"; + out << " <UnstructuredGrid>" + << "\n"; + out << " <Piece NumberOfPoints=\"" << nofNodes << "\" NumberOfCells=\"" << nofNodes << "\"> \n"; + + // POINTS SECTION + out << " <Points>\n"; + out << " <DataArray type=\"Float64\" NumberOfComponents=\"3\" format=\"ascii\">\n "; + for (int n = 0; n < nofNodes; n++) + out << val<1>(nodes[n]) << " " << val<2>(nodes[n]) << " " << val<3>(nodes[n]) << " "; + + out << "\n"; + out << " </DataArray>\n"; + out << " </Points>\n"; + + // CELLS SECTION + out << " <Cells>\n"; + out << " <DataArray type=\"Int32\" Name=\"connectivity\" format=\"ascii\">\n "; + + for (int c = 0; c < nofNodes; c++) + out << c << " "; + out << "\n"; + + out << " </DataArray>\n"; + out << " <DataArray type=\"Int64\" Name=\"offsets\" format=\"ascii\">\n "; + for (int c = 1; c < nofNodes + 1; c++) + out << c << " "; + + out << "\n"; + out << " </DataArray>\n"; + + out << " <DataArray type=\"UInt8\" Name=\"types\" format=\"ascii\">\n "; + for (int c = 0; c < nofNodes; c++) + out << "1 "; + + out << "\n"; + out << " </DataArray>\n"; + + out << " </Cells>\n"; + + // write data section + out << " <PointData Scalars=\"Scalars\"> \n"; + for (int s = 0; s < (int)datanames.size(); ++s) { + out << " <DataArray type=\"Float64\" Name=\"" << datanames[s] << "\" format=\"ascii\"> \n"; + + for (int d = 0; d < (int)nodedata[s].size(); d++) + out << nodedata[s][d] << " "; + + out << "\n </DataArray>\n"; + } + out << " </PointData>\n"; + out << " </Piece>\n"; + out << " </UnstructuredGrid>\n"; + out << "</VTKFile>"; + out << endl; + out.close(); + out.close(); + UBLOG(logDEBUG1, "WbWriterVtkXmlASCII::writeNodesWithNodeData to " << vtkfilename << " - end"); + + return vtkfilename; } diff --git a/src/basics/basics/writer/WbWriterVtkXmlASCII.h b/src/basics/basics/writer/WbWriterVtkXmlASCII.h index 11b557287ba6f880c889c3a4082dfc6446cfeb66..ac031f2ff3b10a38af0c938edb3f971060b55f01 100644 --- a/src/basics/basics/writer/WbWriterVtkXmlASCII.h +++ b/src/basics/basics/writer/WbWriterVtkXmlASCII.h @@ -1,28 +1,28 @@ //======================================================================================= -// ____ ____ __ ______ __________ __ __ __ __ -// \ \ | | | | | _ \ |___ ___| | | | | / \ | | -// \ \ | | | | | |_) | | | | | | | / \ | | -// \ \ | | | | | _ / | | | | | | / /\ \ | | -// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ -// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| -// \ \ | | ________________________________________________________________ -// \ \ | | | ______________________________________________________________| -// \ \| | | | __ __ __ __ ______ _______ -// \ | | |_____ | | | | | | | | | _ \ / _____) -// \ | | _____| | | | | | | | | | | \ \ \_______ +// ____ ____ __ ______ __________ __ __ __ __ +// \ \ | | | | | _ \ |___ ___| | | | | / \ | | +// \ \ | | | | | |_) | | | | | | | / \ | | +// \ \ | | | | | _ / | | | | | | / /\ \ | | +// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ +// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| +// \ \ | | ________________________________________________________________ +// \ \ | | | ______________________________________________________________| +// \ \| | | | __ __ __ __ ______ _______ +// \ | | |_____ | | | | | | | | | _ \ / _____) +// \ | | _____| | | | | | | | | | | \ \ \_______ // \ | | | | |_____ | \_/ | | | | |_/ / _____ | -// \ _____| |__| |________| \_______/ |__| |______/ (_______/ +// \ _____| |__| |________| \_______/ |__| |______/ (_______/ // -// This file is part of VirtualFluids. VirtualFluids is free software: you can +// This file is part of VirtualFluids. VirtualFluids is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of +// License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. -// -// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// +// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License along // with VirtualFluids (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>. // @@ -37,89 +37,117 @@ #include <basics/writer/WbWriter.h> -class WbWriterVtkXmlASCII : public WbWriter +class WbWriterVtkXmlASCII : public WbWriter { public: - static WbWriterVtkXmlASCII* getInstance() - { - static WbWriterVtkXmlASCII instance; - return &instance; - } + static WbWriterVtkXmlASCII *getInstance() + { + static WbWriterVtkXmlASCII instance; + return &instance; + } - WbWriterVtkXmlASCII( const WbWriterVtkXmlASCII& ) = delete; - const WbWriterVtkXmlASCII& operator=( const WbWriterVtkXmlASCII& ) = delete; + WbWriterVtkXmlASCII(const WbWriterVtkXmlASCII &) = delete; + const WbWriterVtkXmlASCII &operator=(const WbWriterVtkXmlASCII &) = delete; private: - WbWriterVtkXmlASCII() : WbWriter() - { - if(sizeof(unsigned char)!=1) throw UbException(UB_EXARGS,"error char type mismatch"); - if(sizeof(int) !=4) throw UbException(UB_EXARGS,"error int type mismatch"); - if(sizeof(float) !=4) throw UbException(UB_EXARGS,"error float type mismatch"); - } - - static std::string pvdEndTag; + WbWriterVtkXmlASCII() : WbWriter() + { + if (sizeof(unsigned char) != 1) + throw UbException(UB_EXARGS, "error char type mismatch"); + if (sizeof(int) != 4) + throw UbException(UB_EXARGS, "error int type mismatch"); + if (sizeof(float) != 4) + throw UbException(UB_EXARGS, "error float type mismatch"); + } + + static std::string pvdEndTag; public: - std::string getFileExtension() override { return ".ascii.vtu"; } - - //write a metafile - std::string writeCollection(const std::string& filename, const std::vector<std::string>& filenames, const double& timesteps, const bool& sepGroups);//std::vector<double>& groups, std::vector<double>& parts); - std::string addFilesToCollection(const std::string& filename, const std::vector<std::string>& filenames, const double& timestep, const bool& sepGroups); - std::string writeParallelFile(const std::string& filename,std::vector<std::string>& pieceSources, std::vector<std::string>& pointDataNames, std::vector<std::string>& cellDataNames); - - ////////////////////////////////////////////////////////////////////////// - //nodes - std::string writeNodes(const std::string& filename,std::vector< UbTupleFloat3 >& nodes) override; - std::string writeNodesWithNodeData(const std::string& filename,std::vector< UbTupleFloat3 >& nodes, std::vector<std::string >& datanames, std::vector<std::vector<double > >& nodedata) override; - std::string writeNodesWithNodeDataDouble(const std::string& filename,std::vector< UbTupleDouble3 >& nodes, std::vector<std::string >& datanames, std::vector<std::vector<double > >& nodedata) override; - - ////////////////////////////////////////////////////////////////////////// - //lines - // 0 ---- 1 - //nodenumbering must start with 0! - std::string writeLines(const std::string& filename,std::vector<UbTupleFloat3 >& nodes, std::vector<UbTupleInt2 >& lines) override; - //std::string writeLinesWithNodeData(const std::string& filename,std::vector<UbTupleFloat3 >& nodes, std::vector<UbTupleInt2 >& lines, std::vector< std::string >& datanames, std::vector< std::vector< double > >& nodedata); - //FIXME: hides function in base class - - ////////////////////////////////////////////////////////////////////////// - //triangles - // 2 - // - // 0---1 - //nodenumbering must start with 0! - std::string writeTriangles(const std::string& filename,std::vector<UbTupleFloat3 >& nodes, std::vector<UbTupleInt3 >& triangles) override; - std::string writeTrianglesWithNodeData(const std::string& filename,std::vector< UbTupleFloat3 >& nodes, std::vector< UbTupleInt3 >& cells, std::vector< std::string >& datanames, std::vector< std::vector< double > >& nodedata) override; - - ////////////////////////////////////////////////////////////////////////// - //2D - //cell numbering: - // 3---2 - // | | - // 0---1 - //nodenumbering must start with 0! - - std::string writeQuads(const std::string& filename,std::vector< UbTupleFloat3 >& nodes, std::vector< UbTupleInt4 >& cells) override; - std::string writeQuadsWithNodeData(const std::string& filename,std::vector< UbTupleFloat3 >& nodes, std::vector< UbTupleInt4 >& cells, std::vector< std::string >& datanames, std::vector< std::vector< double > >& nodedata) override; - std::string writeQuadsWithCellData(const std::string& filename,std::vector< UbTupleFloat3 >& nodes, std::vector< UbTupleInt4 >& cells, std::vector< std::string >& datanames, std::vector< std::vector< double > >& celldata) override; - std::string writeQuadsWithNodeAndCellData(const std::string& filename,std::vector< UbTupleFloat3 >& nodes, std::vector< UbTupleInt4 >& cells, - std::vector< std::string >& nodedatanames, std::vector< std::vector< double > >& nodedata, std::vector< std::string >& celldatanames, - std::vector< std::vector< double > >& celldata) override; - - ////////////////////////////////////////////////////////////////////////// - //octs - // 7 ---- 6 - // /| /| - // 4 +--- 5 | - // | | | | - // | 3 ---+ 2 - // |/ |/ - // 0 ---- 1 - std::string writeOcts(const std::string& filename,std::vector< UbTupleFloat3 >& nodes, std::vector< UbTupleInt8 >& cells) override; - std::string writeOctsWithCellData(const std::string& filename,std::vector< UbTupleFloat3 >& nodes, std::vector< UbTupleInt8 >& cells, std::vector< std::string >& datanames, std::vector< std::vector< double > >& celldata) override; - std::string writeOctsWithNodeData(const std::string& filename,std::vector< UbTupleFloat3 >& nodes, std::vector< UbTupleUInt8 >& cells, std::vector< std::string >& datanames, std::vector< std::vector< double > >& nodedata) override; + std::string getFileExtension() override { return ".ascii.vtu"; } + + // write a metafile + std::string writeCollection(const std::string &filename, const std::vector<std::string> &filenames, + const double ×teps, + const bool &sepGroups); // std::vector<double>& groups, std::vector<double>& parts); + std::string addFilesToCollection(const std::string &filename, const std::vector<std::string> &filenames, + const double ×tep, const bool &sepGroups); + std::string writeParallelFile(const std::string &filename, std::vector<std::string> &pieceSources, + std::vector<std::string> &pointDataNames, std::vector<std::string> &cellDataNames); + + ////////////////////////////////////////////////////////////////////////// + // nodes + std::string writeNodes(const std::string &filename, std::vector<UbTupleFloat3> &nodes) override; + std::string writeNodesWithNodeData(const std::string &filename, std::vector<UbTupleFloat3> &nodes, + std::vector<std::string> &datanames, + std::vector<std::vector<double>> &nodedata) override; + std::string writeNodesWithNodeDataDouble(const std::string &filename, std::vector<UbTupleDouble3> &nodes, + std::vector<std::string> &datanames, + std::vector<std::vector<double>> &nodedata) override; + + ////////////////////////////////////////////////////////////////////////// + // lines + // 0 ---- 1 + // nodenumbering must start with 0! + std::string writeLines(const std::string &filename, std::vector<UbTupleFloat3> &nodes, + std::vector<UbTupleInt2> &lines) override; + // std::string writeLinesWithNodeData(const std::string& filename,std::vector<UbTupleFloat3 >& nodes, + // std::vector<UbTupleInt2 >& lines, std::vector< std::string >& datanames, std::vector< std::vector< double > >& + // nodedata); + // FIXME: hides function in base class + + ////////////////////////////////////////////////////////////////////////// + // triangles + // 2 + // + // 0---1 + // nodenumbering must start with 0! + std::string writeTriangles(const std::string &filename, std::vector<UbTupleFloat3> &nodes, + std::vector<UbTupleInt3> &triangles) override; + std::string writeTrianglesWithNodeData(const std::string &filename, std::vector<UbTupleFloat3> &nodes, + std::vector<UbTupleInt3> &cells, std::vector<std::string> &datanames, + std::vector<std::vector<double>> &nodedata) override; + + ////////////////////////////////////////////////////////////////////////// + // 2D + // cell numbering: + // 3---2 + // | | + // 0---1 + // nodenumbering must start with 0! + + std::string writeQuads(const std::string &filename, std::vector<UbTupleFloat3> &nodes, + std::vector<UbTupleInt4> &cells) override; + std::string writeQuadsWithNodeData(const std::string &filename, std::vector<UbTupleFloat3> &nodes, + std::vector<UbTupleInt4> &cells, std::vector<std::string> &datanames, + std::vector<std::vector<double>> &nodedata) override; + std::string writeQuadsWithCellData(const std::string &filename, std::vector<UbTupleFloat3> &nodes, + std::vector<UbTupleInt4> &cells, std::vector<std::string> &datanames, + std::vector<std::vector<double>> &celldata) override; + std::string writeQuadsWithNodeAndCellData(const std::string &filename, std::vector<UbTupleFloat3> &nodes, + std::vector<UbTupleInt4> &cells, std::vector<std::string> &nodedatanames, + std::vector<std::vector<double>> &nodedata, + std::vector<std::string> &celldatanames, + std::vector<std::vector<double>> &celldata) override; + + ////////////////////////////////////////////////////////////////////////// + // octs + // 7 ---- 6 + // /| /| + // 4 +--- 5 | + // | | | | + // | 3 ---+ 2 + // |/ |/ + // 0 ---- 1 + std::string writeOcts(const std::string &filename, std::vector<UbTupleFloat3> &nodes, + std::vector<UbTupleInt8> &cells) override; + std::string writeOctsWithCellData(const std::string &filename, std::vector<UbTupleFloat3> &nodes, + std::vector<UbTupleInt8> &cells, std::vector<std::string> &datanames, + std::vector<std::vector<double>> &celldata) override; + std::string writeOctsWithNodeData(const std::string &filename, std::vector<UbTupleFloat3> &nodes, + std::vector<UbTupleUInt8> &cells, std::vector<std::string> &datanames, + std::vector<std::vector<double>> &nodedata) override; private: - }; -#endif //WBWRITERVTKXMLASCII_H +#endif // WBWRITERVTKXMLASCII_H diff --git a/src/basics/basics/writer/WbWriterVtkXmlBinary.cpp b/src/basics/basics/writer/WbWriterVtkXmlBinary.cpp index d88459eb5ed8c0ec90348618a4834def954f965e..6731fa56026ca284ad671cb6ce59000a609bbb8c 100644 --- a/src/basics/basics/writer/WbWriterVtkXmlBinary.cpp +++ b/src/basics/basics/writer/WbWriterVtkXmlBinary.cpp @@ -1,28 +1,28 @@ //======================================================================================= -// ____ ____ __ ______ __________ __ __ __ __ -// \ \ | | | | | _ \ |___ ___| | | | | / \ | | -// \ \ | | | | | |_) | | | | | | | / \ | | -// \ \ | | | | | _ / | | | | | | / /\ \ | | -// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ -// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| -// \ \ | | ________________________________________________________________ -// \ \ | | | ______________________________________________________________| -// \ \| | | | __ __ __ __ ______ _______ -// \ | | |_____ | | | | | | | | | _ \ / _____) -// \ | | _____| | | | | | | | | | | \ \ \_______ +// ____ ____ __ ______ __________ __ __ __ __ +// \ \ | | | | | _ \ |___ ___| | | | | / \ | | +// \ \ | | | | | |_) | | | | | | | / \ | | +// \ \ | | | | | _ / | | | | | | / /\ \ | | +// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ +// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| +// \ \ | | ________________________________________________________________ +// \ \ | | | ______________________________________________________________| +// \ \| | | | __ __ __ __ ______ _______ +// \ | | |_____ | | | | | | | | | _ \ / _____) +// \ | | _____| | | | | | | | | | | \ \ \_______ // \ | | | | |_____ | \_/ | | | | |_/ / _____ | -// \ _____| |__| |________| \_______/ |__| |______/ (_______/ +// \ _____| |__| |________| \_______/ |__| |______/ (_______/ // -// This file is part of VirtualFluids. VirtualFluids is free software: you can +// This file is part of VirtualFluids. VirtualFluids is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of +// License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. -// -// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// +// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License along // with VirtualFluids (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>. // @@ -30,214 +30,234 @@ //! \ingroup writer //! \author Soeren Freudiger, Sebastian Geller //======================================================================================= -#include <basics/writer/WbWriterVtkXmlBinary.h> -#include <basics/writer/WbWriterVtkXmlASCII.h> #include <basics/utilities/UbLogger.h> +#include <basics/writer/WbWriterVtkXmlASCII.h> +#include <basics/writer/WbWriterVtkXmlBinary.h> #include <cstring> using namespace std; /*===============================================================================*/ -const std::string WbWriterVtkXmlBinary::pvdEndTag =" </Collection>\n</VTKFile>"; +const std::string WbWriterVtkXmlBinary::pvdEndTag = " </Collection>\n</VTKFile>"; /*===============================================================================*/ -string WbWriterVtkXmlBinary::writeCollection(const string& filename, const vector<string>& filenames, const double& timeStep, const bool& sepGroups) +string WbWriterVtkXmlBinary::writeCollection(const string &filename, const vector<string> &filenames, + const double &timeStep, const bool &sepGroups) { - string vtkfilename=filename+".pvd"; - ofstream out(vtkfilename.c_str()); - if(!out) - { - out.clear(); //flags ruecksetzen (ansonsten liefert utern if(!out) weiterhin true!!! - string path = UbSystem::getPathFromString(vtkfilename); - if(path.size()>0){ UbSystem::makeDirectory(path); out.open(vtkfilename.c_str());} - if(!out) throw UbException(UB_EXARGS,"couldn't open file "+vtkfilename); - } - - string endian; - if(UbSystem::isLittleEndian()) endian = "LittleEndian"; - else endian = "BigEndian"; - out<<"<VTKFile type=\"Collection\" version=\"0.1\" byte_order=\""<<endian<<"\" >"<<endl; - out<<" <Collection>"<<endl; - - int group = 0, part=0; - for(size_t i=0; i<filenames.size(); i++) - { - out<<" <DataSet timestep=\""<<timeStep<<"\" group=\""<<group<<"\" part=\""<<part<<"\" file=\""<<filenames[i]<<"\"/>"<<endl; - if(sepGroups) group++; - else part++; - } - out<<pvdEndTag; - out.close(); - - return vtkfilename; + string vtkfilename = filename + ".pvd"; + ofstream out(vtkfilename.c_str()); + if (!out) { + out.clear(); // flags ruecksetzen (ansonsten liefert utern if(!out) weiterhin true!!! + string path = UbSystem::getPathFromString(vtkfilename); + if (path.size() > 0) { + UbSystem::makeDirectory(path); + out.open(vtkfilename.c_str()); + } + if (!out) + throw UbException(UB_EXARGS, "couldn't open file " + vtkfilename); + } + + string endian; + if (UbSystem::isLittleEndian()) + endian = "LittleEndian"; + else + endian = "BigEndian"; + out << "<VTKFile type=\"Collection\" version=\"0.1\" byte_order=\"" << endian << "\" >" << endl; + out << " <Collection>" << endl; + + int group = 0, part = 0; + for (size_t i = 0; i < filenames.size(); i++) { + out << " <DataSet timestep=\"" << timeStep << "\" group=\"" << group << "\" part=\"" << part + << "\" file=\"" << filenames[i] << "\"/>" << endl; + if (sepGroups) + group++; + else + part++; + } + out << pvdEndTag; + out.close(); + + return vtkfilename; } /*===============================================================================*/ -string WbWriterVtkXmlBinary::addFilesToCollection(const string& filename, const vector<string>& filenames, const double& timeStep, const bool& sepGroups) +string WbWriterVtkXmlBinary::addFilesToCollection(const string &filename, const vector<string> &filenames, + const double &timeStep, const bool &sepGroups) { - string vtkfilename=filename; - fstream test(vtkfilename.c_str(), ios::in); - if(!test) - { - test.clear(); - vtkfilename += ".pvd"; - test.open(vtkfilename.c_str(), ios::in); - if(!test) return this->writeCollection(filename,filenames,timeStep,sepGroups); - } - - fstream out(vtkfilename.c_str(), ios::in | ios::out); - out.seekp(-(int)pvdEndTag.size()-1, ios_base::end); - - int group = 0; - for(size_t i=0; i<filenames.size(); i++) - { - out<<" <DataSet timestep=\""<<timeStep<<"\" group=\""<<group<<"\" part=\""<<i<<"\" file=\""<<filenames[i]<<"\"/>"<<endl; - if(sepGroups) group++; - } - out<<pvdEndTag; - - return vtkfilename; + string vtkfilename = filename; + fstream test(vtkfilename.c_str(), ios::in); + if (!test) { + test.clear(); + vtkfilename += ".pvd"; + test.open(vtkfilename.c_str(), ios::in); + if (!test) + return this->writeCollection(filename, filenames, timeStep, sepGroups); + } + + fstream out(vtkfilename.c_str(), ios::in | ios::out); + out.seekp(-(int)pvdEndTag.size() - 1, ios_base::end); + + int group = 0; + for (size_t i = 0; i < filenames.size(); i++) { + out << " <DataSet timestep=\"" << timeStep << "\" group=\"" << group << "\" part=\"" << i << "\" file=\"" + << filenames[i] << "\"/>" << endl; + if (sepGroups) + group++; + } + out << pvdEndTag; + + return vtkfilename; } /*===============================================================================*/ -string WbWriterVtkXmlBinary::writeParallelFile(const string& filename,vector<string>& pieceSources, vector<string>& pointDataNames, vector<string>& cellDataNames) +string WbWriterVtkXmlBinary::writeParallelFile(const string &filename, vector<string> &pieceSources, + vector<string> &pointDataNames, vector<string> &cellDataNames) { - string vtkfilename=filename+".pvtu"; - UBLOG(logDEBUG1,"WbWriterVtkXmlBinary::writeParallelFile to "<<vtkfilename<<" - start"); - - ofstream out(vtkfilename.c_str()); - if(!out) - { - out.clear(); //flags ruecksetzen (ansonsten liefert utern if(!out) weiterhin true!!! - string path = UbSystem::getPathFromString(vtkfilename); - if(path.size()>0){ UbSystem::makeDirectory(path); out.open(vtkfilename.c_str());} - if(!out) throw UbException(UB_EXARGS,"couldn't open file "+vtkfilename); - } - - //VTK FILE - out<<"<VTKFile type=\"PUnstructuredGrid\" version=\"0.1\" byte_order=\"LittleEndian\">"<<"\n"; - out<<" <PUnstructuredGrid GhostLevel=\"0\">"<<"\n"; - out<<" <PPoints>\n"; - out<<" <PDataArray type=\"Float32\" NumberOfComponents=\"3\"/>\n"; - out<<" </PPoints>\n"; - out<<" <PPointData>\n"; - for(size_t s=0; s<pointDataNames.size(); s++) - out<< " <PDataArray type=\"Float32\" Name=\""<< pointDataNames[s] <<"\"/>\n"; - out<<" </PPointData>\n"; - if (cellDataNames.size() > 0) - { - out<<" <PCellData>\n"; - for(size_t s=0; s<cellDataNames.size(); s++) - out<< " <PDataArray type=\"Float32\" Name=\""<< cellDataNames[s] <<"\"/>\n"; - out<<" </PCellData>\n"; - } - - for(size_t s=0; s<pieceSources.size(); s++) - out<<" <Piece Source=\""<<pieceSources[s]<<"\"/>\n"; - out<<" </PUnstructuredGrid>\n"; - out<<"</VTKFile>"; - out<<endl; - out.close(); - UBLOG(logDEBUG1,"WbWriterVtkXmlBinary::writeParallelFile to "<<vtkfilename<<" - end"); - - return vtkfilename; + string vtkfilename = filename + ".pvtu"; + UBLOG(logDEBUG1, "WbWriterVtkXmlBinary::writeParallelFile to " << vtkfilename << " - start"); + + ofstream out(vtkfilename.c_str()); + if (!out) { + out.clear(); // flags ruecksetzen (ansonsten liefert utern if(!out) weiterhin true!!! + string path = UbSystem::getPathFromString(vtkfilename); + if (path.size() > 0) { + UbSystem::makeDirectory(path); + out.open(vtkfilename.c_str()); + } + if (!out) + throw UbException(UB_EXARGS, "couldn't open file " + vtkfilename); + } + + // VTK FILE + out << "<VTKFile type=\"PUnstructuredGrid\" version=\"0.1\" byte_order=\"LittleEndian\">" + << "\n"; + out << " <PUnstructuredGrid GhostLevel=\"0\">" + << "\n"; + out << " <PPoints>\n"; + out << " <PDataArray type=\"Float32\" NumberOfComponents=\"3\"/>\n"; + out << " </PPoints>\n"; + out << " <PPointData>\n"; + for (size_t s = 0; s < pointDataNames.size(); s++) + out << " <PDataArray type=\"Float32\" Name=\"" << pointDataNames[s] << "\"/>\n"; + out << " </PPointData>\n"; + if (cellDataNames.size() > 0) { + out << " <PCellData>\n"; + for (size_t s = 0; s < cellDataNames.size(); s++) + out << " <PDataArray type=\"Float32\" Name=\"" << cellDataNames[s] << "\"/>\n"; + out << " </PCellData>\n"; + } + + for (size_t s = 0; s < pieceSources.size(); s++) + out << " <Piece Source=\"" << pieceSources[s] << "\"/>\n"; + out << " </PUnstructuredGrid>\n"; + out << "</VTKFile>"; + out << endl; + out.close(); + UBLOG(logDEBUG1, "WbWriterVtkXmlBinary::writeParallelFile to " << vtkfilename << " - end"); + + return vtkfilename; } /*===============================================================================*/ -string WbWriterVtkXmlBinary::writeLines(const string& filename,vector<UbTupleFloat3 >& nodes, vector<UbTupleInt2 >& lines) +string WbWriterVtkXmlBinary::writeLines(const string &filename, vector<UbTupleFloat3> &nodes, + vector<UbTupleInt2> &lines) { - string vtkfilename = filename+getFileExtension(); - UBLOG(logDEBUG1,"WbWriterVtkXmlBinary::writeLines to "<<vtkfilename<<" - start"); - - ofstream out(vtkfilename.c_str(),ios::out | ios::binary); - if(!out) - { - out.clear(); //flags ruecksetzen (ansonsten liefert utern if(!out) weiterhin true!!! - string path = UbSystem::getPathFromString(vtkfilename); - if(path.size()>0){ UbSystem::makeDirectory(path); out.open(vtkfilename.c_str(),ios::out | ios::binary);} - if(!out) throw UbException(UB_EXARGS,"couldn't open file "+vtkfilename); - } - - int nofNodes = (int)nodes.size(); - int nofCells = (int)lines.size(); - - int bytesPerByteVal = 4; //==sizeof(int) - int bytesPoints = 3 /*x1/x2/x3 */ * nofNodes * sizeof(float); - int bytesCellConnectivty = 2 /*nodes per line */ * nofCells * sizeof(int ); - int bytesCellOffsets = 1 /*offset per line */ * nofCells * sizeof(int ); - int bytesCellTypes = 1 /*type of line */ * nofCells * sizeof(unsigned char); - - int offset = 0; - //VTK FILE - out<<"<?xml version=\"1.0\"?>\n"; - out<<"<VTKFile type=\"UnstructuredGrid\" version=\"0.1\" byte_order=\"LittleEndian\" >"<<"\n"; - out<<" <UnstructuredGrid>"<<"\n"; - out<<" <Piece NumberOfPoints=\""<<nofNodes<<"\" NumberOfCells=\""<<nofCells<<"\">\n"; - - //POINTS SECTION - out<<" <Points>\n"; - out<<" <DataArray type=\"Float32\" NumberOfComponents=\"3\" format=\"appended\" offset=\""<< offset <<"\" />\n"; - out<<" </Points>\n"; - offset += (bytesPerByteVal + bytesPoints); - - //CELLS SECTION - out<<" <Cells>\n"; - out<<" <DataArray type=\"Int32\" Name=\"connectivity\" format=\"appended\" offset=\""<< offset <<"\" />\n"; - offset += (bytesPerByteVal + bytesCellConnectivty); - out<<" <DataArray type=\"Int32\" Name=\"offsets\" format=\"appended\" offset=\""<< offset <<"\" />\n"; - offset += (bytesPerByteVal + bytesCellOffsets); - out<<" <DataArray type=\"UInt8\" Name=\"types\" format=\"appended\" offset=\""<< offset <<"\" />\n "; - offset += (bytesPerByteVal + bytesCellTypes); - out<<" </Cells>\n"; - - out<<" </Piece>\n"; - out<<" </UnstructuredGrid>\n"; - - // AppendedData SECTION - out<<" <AppendedData encoding=\"raw\">\n"; - out<<"_"; - - //POINTS SECTION - out.write((char*)&bytesPoints,bytesPerByteVal); - for(int n=0; n<nofNodes; n++) - { - out.write((char*)&val<1>(nodes[n]),sizeof(float)); - out.write((char*)&val<2>(nodes[n]),sizeof(float)); - out.write((char*)&val<3>(nodes[n]),sizeof(float)); - } - - //CELLS SECTION - //cellConnectivity - out.write( (char*)&bytesCellConnectivty, bytesPerByteVal ); - for(int c=0; c<nofCells; c++) - { - out.write( (char*)&val<1>(lines[c]), sizeof(int) ); - out.write( (char*)&val<2>(lines[c]), sizeof(int) ); - - } - - //cellOffsets - out.write( (char*)&bytesCellOffsets, bytesPerByteVal ); - int itmp; - for(int c=1; c<=nofCells; c++) - { - itmp = 2 * c; - out.write( (char*)&itmp, sizeof(int) ); - } - - //cellTypes - out.write( (char*)&bytesCellTypes, bytesPerByteVal ); - unsigned char vtkCellType = 3; - for(int c=0; c<nofCells; c++) - { - out.write( (char*)&vtkCellType, sizeof(unsigned char) ); - } - out<<"\n</AppendedData>\n"; - out<<"</VTKFile>"; - out<<endl; - out.close(); - UBLOG(logDEBUG1,"WbWriterVtkXmlBinary::writeLines to "<<vtkfilename<<" - end"); - - return vtkfilename; + string vtkfilename = filename + getFileExtension(); + UBLOG(logDEBUG1, "WbWriterVtkXmlBinary::writeLines to " << vtkfilename << " - start"); + + ofstream out(vtkfilename.c_str(), ios::out | ios::binary); + if (!out) { + out.clear(); // flags ruecksetzen (ansonsten liefert utern if(!out) weiterhin true!!! + string path = UbSystem::getPathFromString(vtkfilename); + if (path.size() > 0) { + UbSystem::makeDirectory(path); + out.open(vtkfilename.c_str(), ios::out | ios::binary); + } + if (!out) + throw UbException(UB_EXARGS, "couldn't open file " + vtkfilename); + } + + int nofNodes = (int)nodes.size(); + int nofCells = (int)lines.size(); + + int bytesPerByteVal = 4; //==sizeof(int) + int bytesPoints = 3 /*x1/x2/x3 */ * nofNodes * sizeof(float); + int bytesCellConnectivty = 2 /*nodes per line */ * nofCells * sizeof(int); + int bytesCellOffsets = 1 /*offset per line */ * nofCells * sizeof(int); + int bytesCellTypes = 1 /*type of line */ * nofCells * sizeof(unsigned char); + + int offset = 0; + // VTK FILE + out << "<?xml version=\"1.0\"?>\n"; + out << "<VTKFile type=\"UnstructuredGrid\" version=\"0.1\" byte_order=\"LittleEndian\" >" + << "\n"; + out << " <UnstructuredGrid>" + << "\n"; + out << " <Piece NumberOfPoints=\"" << nofNodes << "\" NumberOfCells=\"" << nofCells << "\">\n"; + + // POINTS SECTION + out << " <Points>\n"; + out << " <DataArray type=\"Float32\" NumberOfComponents=\"3\" format=\"appended\" offset=\"" << offset + << "\" />\n"; + out << " </Points>\n"; + offset += (bytesPerByteVal + bytesPoints); + + // CELLS SECTION + out << " <Cells>\n"; + out << " <DataArray type=\"Int32\" Name=\"connectivity\" format=\"appended\" offset=\"" << offset + << "\" />\n"; + offset += (bytesPerByteVal + bytesCellConnectivty); + out << " <DataArray type=\"Int32\" Name=\"offsets\" format=\"appended\" offset=\"" << offset + << "\" />\n"; + offset += (bytesPerByteVal + bytesCellOffsets); + out << " <DataArray type=\"UInt8\" Name=\"types\" format=\"appended\" offset=\"" << offset << "\" />\n "; + offset += (bytesPerByteVal + bytesCellTypes); + out << " </Cells>\n"; + + out << " </Piece>\n"; + out << " </UnstructuredGrid>\n"; + + // AppendedData SECTION + out << " <AppendedData encoding=\"raw\">\n"; + out << "_"; + + // POINTS SECTION + out.write((char *)&bytesPoints, bytesPerByteVal); + for (int n = 0; n < nofNodes; n++) { + out.write((char *)&val<1>(nodes[n]), sizeof(float)); + out.write((char *)&val<2>(nodes[n]), sizeof(float)); + out.write((char *)&val<3>(nodes[n]), sizeof(float)); + } + + // CELLS SECTION + // cellConnectivity + out.write((char *)&bytesCellConnectivty, bytesPerByteVal); + for (int c = 0; c < nofCells; c++) { + out.write((char *)&val<1>(lines[c]), sizeof(int)); + out.write((char *)&val<2>(lines[c]), sizeof(int)); + } + + // cellOffsets + out.write((char *)&bytesCellOffsets, bytesPerByteVal); + int itmp; + for (int c = 1; c <= nofCells; c++) { + itmp = 2 * c; + out.write((char *)&itmp, sizeof(int)); + } + + // cellTypes + out.write((char *)&bytesCellTypes, bytesPerByteVal); + unsigned char vtkCellType = 3; + for (int c = 0; c < nofCells; c++) { + out.write((char *)&vtkCellType, sizeof(unsigned char)); + } + out << "\n</AppendedData>\n"; + out << "</VTKFile>"; + out << endl; + out.close(); + UBLOG(logDEBUG1, "WbWriterVtkXmlBinary::writeLines to " << vtkfilename << " - end"); + + return vtkfilename; } /*===============================================================================*/ -//std::string WbWriterVtkXmlBinary::writeLinesWithNodeData(const string& filename,vector<UbTupleFloat3 >& nodes, vector<UbTupleInt2 >& lines, std::vector< std::string >& datanames, std::vector< std::vector< double > >& nodedata) +// std::string WbWriterVtkXmlBinary::writeLinesWithNodeData(const string& filename,vector<UbTupleFloat3 >& nodes, +// vector<UbTupleInt2 >& lines, std::vector< std::string >& datanames, std::vector< std::vector< double > >& nodedata) //{ // string vtkfilename = filename+getFileExtension(); // UBLOG(logDEBUG1,"WbWriterVtkXmlBinary::writeLinesWithNodeData to "<<vtkfilename<<" - start"); @@ -270,26 +290,23 @@ string WbWriterVtkXmlBinary::writeLines(const string& filename,vector<UbTupleFlo // // //POINTS SECTION // out<<" <Points>\n"; -// out<<" <DataArray type=\"Float32\" NumberOfComponents=\"3\" format=\"appended\" offset=\""<< offset <<"\" />\n"; -// out<<" </Points>\n"; -// offset += (bytesPerByteVal + bytesPoints); +// out<<" <DataArray type=\"Float32\" NumberOfComponents=\"3\" format=\"appended\" offset=\""<< offset +// <<"\" />\n"; out<<" </Points>\n"; offset += (bytesPerByteVal + bytesPoints); // // //CELLS SECTION // out<<" <Cells>\n"; -// out<<" <DataArray type=\"Int32\" Name=\"connectivity\" format=\"appended\" offset=\""<< offset <<"\" />\n"; -// offset += (bytesPerByteVal + bytesCellConnectivty); -// out<<" <DataArray type=\"Int32\" Name=\"offsets\" format=\"appended\" offset=\""<< offset <<"\" />\n"; -// offset += (bytesPerByteVal + bytesCellOffsets); -// out<<" <DataArray type=\"UInt8\" Name=\"types\" format=\"appended\" offset=\""<< offset <<"\" />\n "; -// offset += (bytesPerByteVal + bytesCellTypes); -// out<<" </Cells>\n"; +// out<<" <DataArray type=\"Int32\" Name=\"connectivity\" format=\"appended\" offset=\""<< offset <<"\" +// />\n"; offset += (bytesPerByteVal + bytesCellConnectivty); out<<" <DataArray type=\"Int32\" +// Name=\"offsets\" format=\"appended\" offset=\""<< offset <<"\" />\n"; offset += (bytesPerByteVal + +// bytesCellOffsets); out<<" <DataArray type=\"UInt8\" Name=\"types\" format=\"appended\" offset=\""<< +// offset <<"\" />\n "; offset += (bytesPerByteVal + bytesCellTypes); out<<" </Cells>\n"; // // //DATA SECTION // out<<" <PointData>\n"; // for(size_t s=0; s<datanames.size(); ++s) // { -// out<< " <DataArray type=\"Float32\" Name=\""<< datanames[s] <<"\" format=\"appended\" offset=\""<< offset <<"\" /> \n"; -// offset += (bytesPerByteVal + bytesScalarData); +// out<< " <DataArray type=\"Float32\" Name=\""<< datanames[s] <<"\" format=\"appended\" offset=\""<< +// offset <<"\" /> \n"; offset += (bytesPerByteVal + bytesScalarData); // } // out<<" </PointData>\n"; // @@ -357,1262 +374,1309 @@ string WbWriterVtkXmlBinary::writeLines(const string& filename,vector<UbTupleFlo // //} /*===============================================================================*/ -string WbWriterVtkXmlBinary::writeTriangles(const string& filename,vector<UbTupleFloat3 >& nodes, vector<UbTupleInt3 >& triangles) +string WbWriterVtkXmlBinary::writeTriangles(const string &filename, vector<UbTupleFloat3> &nodes, + vector<UbTupleInt3> &triangles) { - string vtkfilename = filename+getFileExtension(); - UBLOG(logDEBUG1,"WbWriterVtkXmlBinary::writeTriangles to "<<vtkfilename<<" - start"); - - ofstream out(vtkfilename.c_str(),ios::out | ios::binary); - if(!out) - { - out.clear(); //flags ruecksetzen (ansonsten liefert utern if(!out) weiterhin true!!! - string path = UbSystem::getPathFromString(vtkfilename); - if(path.size()>0){ UbSystem::makeDirectory(path); out.open(vtkfilename.c_str(),ios::out | ios::binary);} - if(!out) throw UbException(UB_EXARGS,"couldn't open file "+vtkfilename); - } - - - int nofNodes = (int)nodes.size(); - int nofCells = (int)triangles.size(); - - int bytesPerByteVal = 4; //==sizeof(int) - int bytesPoints = 3 /*x1/x2/x3 - coord */ * nofNodes * sizeof(float); - int bytesCellConnectivty = 3 /*nodes per triangle */ * nofCells * sizeof(int ); - int bytesCellOffsets = 1 /*offset per triangle */ * nofCells * sizeof(int ); - int bytesCellTypes = 1 /*type of triangle */ * nofCells * sizeof(unsigned char); - - int offset = 0; - //VTK FILE - out<<"<?xml version=\"1.0\"?>\n"; - out<<"<VTKFile type=\"UnstructuredGrid\" version=\"0.1\" byte_order=\"LittleEndian\" >"<<"\n"; - out<<" <UnstructuredGrid>"<<"\n"; - out<<" <Piece NumberOfPoints=\""<<nofNodes<<"\" NumberOfCells=\""<<nofCells<<"\">\n"; - - //POINTS SECTION - out<<" <Points>\n"; - out<<" <DataArray type=\"Float32\" NumberOfComponents=\"3\" format=\"appended\" offset=\""<< offset <<"\" />\n"; - out<<" </Points>\n"; - offset += (bytesPerByteVal + bytesPoints); - - //CELLS SECTION - out<<" <Cells>\n"; - out<<" <DataArray type=\"Int32\" Name=\"connectivity\" format=\"appended\" offset=\""<< offset <<"\" />\n"; - offset += (bytesPerByteVal + bytesCellConnectivty); - out<<" <DataArray type=\"Int32\" Name=\"offsets\" format=\"appended\" offset=\""<< offset <<"\" />\n"; - offset += (bytesPerByteVal + bytesCellOffsets); - out<<" <DataArray type=\"UInt8\" Name=\"types\" format=\"appended\" offset=\""<< offset <<"\" />\n "; - offset += (bytesPerByteVal + bytesCellTypes); - out<<" </Cells>\n"; - - out<<" </Piece>\n"; - out<<" </UnstructuredGrid>\n"; - - // AppendedData SECTION - out<<" <AppendedData encoding=\"raw\">\n"; - out<<"_"; - - //POINTS SECTION - out.write((char*)&bytesPoints,bytesPerByteVal); - for(int n=0; n<nofNodes; n++) - { - out.write((char*)&val<1>(nodes[n]),sizeof(float)); - out.write((char*)&val<2>(nodes[n]),sizeof(float)); - out.write((char*)&val<3>(nodes[n]),sizeof(float)); - } - - //CELLS SECTION - //cellConnectivity - out.write( (char*)&bytesCellConnectivty, bytesPerByteVal ); - for(int c=0; c<nofCells; c++) - { - out.write( (char*)&val<1>(triangles[c]), sizeof(int) ); - out.write( (char*)&val<2>(triangles[c]), sizeof(int) ); - out.write( (char*)&val<3>(triangles[c]), sizeof(int) ); - } - - //cellOffsets - out.write( (char*)&bytesCellOffsets, bytesPerByteVal ); - int itmp; - for(int c=1; c<=nofCells; c++) - { - itmp = 3 * c; - out.write( (char*)&itmp, sizeof(int) ); - } - - //cellTypes - out.write( (char*)&bytesCellTypes, bytesPerByteVal ); - unsigned char vtkCellType = 5; - for(int c=0; c<nofCells; c++) - { - out.write( (char*)&vtkCellType, sizeof(unsigned char) ); - } - - out<<"\n</AppendedData>\n"; - out<<"</VTKFile>"; - out<<endl; - out<<flush; - out.close(); - UBLOG(logDEBUG1,"WbWriterVtkXmlBinary::writeTriangles to "<<vtkfilename<<" - end"); - - return vtkfilename; + string vtkfilename = filename + getFileExtension(); + UBLOG(logDEBUG1, "WbWriterVtkXmlBinary::writeTriangles to " << vtkfilename << " - start"); + + ofstream out(vtkfilename.c_str(), ios::out | ios::binary); + if (!out) { + out.clear(); // flags ruecksetzen (ansonsten liefert utern if(!out) weiterhin true!!! + string path = UbSystem::getPathFromString(vtkfilename); + if (path.size() > 0) { + UbSystem::makeDirectory(path); + out.open(vtkfilename.c_str(), ios::out | ios::binary); + } + if (!out) + throw UbException(UB_EXARGS, "couldn't open file " + vtkfilename); + } + + int nofNodes = (int)nodes.size(); + int nofCells = (int)triangles.size(); + + int bytesPerByteVal = 4; //==sizeof(int) + int bytesPoints = 3 /*x1/x2/x3 - coord */ * nofNodes * sizeof(float); + int bytesCellConnectivty = 3 /*nodes per triangle */ * nofCells * sizeof(int); + int bytesCellOffsets = 1 /*offset per triangle */ * nofCells * sizeof(int); + int bytesCellTypes = 1 /*type of triangle */ * nofCells * sizeof(unsigned char); + + int offset = 0; + // VTK FILE + out << "<?xml version=\"1.0\"?>\n"; + out << "<VTKFile type=\"UnstructuredGrid\" version=\"0.1\" byte_order=\"LittleEndian\" >" + << "\n"; + out << " <UnstructuredGrid>" + << "\n"; + out << " <Piece NumberOfPoints=\"" << nofNodes << "\" NumberOfCells=\"" << nofCells << "\">\n"; + + // POINTS SECTION + out << " <Points>\n"; + out << " <DataArray type=\"Float32\" NumberOfComponents=\"3\" format=\"appended\" offset=\"" << offset + << "\" />\n"; + out << " </Points>\n"; + offset += (bytesPerByteVal + bytesPoints); + + // CELLS SECTION + out << " <Cells>\n"; + out << " <DataArray type=\"Int32\" Name=\"connectivity\" format=\"appended\" offset=\"" << offset + << "\" />\n"; + offset += (bytesPerByteVal + bytesCellConnectivty); + out << " <DataArray type=\"Int32\" Name=\"offsets\" format=\"appended\" offset=\"" << offset + << "\" />\n"; + offset += (bytesPerByteVal + bytesCellOffsets); + out << " <DataArray type=\"UInt8\" Name=\"types\" format=\"appended\" offset=\"" << offset << "\" />\n "; + offset += (bytesPerByteVal + bytesCellTypes); + out << " </Cells>\n"; + + out << " </Piece>\n"; + out << " </UnstructuredGrid>\n"; + + // AppendedData SECTION + out << " <AppendedData encoding=\"raw\">\n"; + out << "_"; + + // POINTS SECTION + out.write((char *)&bytesPoints, bytesPerByteVal); + for (int n = 0; n < nofNodes; n++) { + out.write((char *)&val<1>(nodes[n]), sizeof(float)); + out.write((char *)&val<2>(nodes[n]), sizeof(float)); + out.write((char *)&val<3>(nodes[n]), sizeof(float)); + } + + // CELLS SECTION + // cellConnectivity + out.write((char *)&bytesCellConnectivty, bytesPerByteVal); + for (int c = 0; c < nofCells; c++) { + out.write((char *)&val<1>(triangles[c]), sizeof(int)); + out.write((char *)&val<2>(triangles[c]), sizeof(int)); + out.write((char *)&val<3>(triangles[c]), sizeof(int)); + } + + // cellOffsets + out.write((char *)&bytesCellOffsets, bytesPerByteVal); + int itmp; + for (int c = 1; c <= nofCells; c++) { + itmp = 3 * c; + out.write((char *)&itmp, sizeof(int)); + } + + // cellTypes + out.write((char *)&bytesCellTypes, bytesPerByteVal); + unsigned char vtkCellType = 5; + for (int c = 0; c < nofCells; c++) { + out.write((char *)&vtkCellType, sizeof(unsigned char)); + } + + out << "\n</AppendedData>\n"; + out << "</VTKFile>"; + out << endl; + out << flush; + out.close(); + UBLOG(logDEBUG1, "WbWriterVtkXmlBinary::writeTriangles to " << vtkfilename << " - end"); + + return vtkfilename; } /*===============================================================================*/ -string WbWriterVtkXmlBinary::writeTrianglesWithNodeData(const string& filename,vector< UbTupleFloat3 >& nodes, vector< UbTupleInt3 >& cells, vector< string >& datanames, vector< vector< double > >& nodedata) +string WbWriterVtkXmlBinary::writeTrianglesWithNodeData(const string &filename, vector<UbTupleFloat3> &nodes, + vector<UbTupleInt3> &cells, vector<string> &datanames, + vector<vector<double>> &nodedata) { - string vtkfilename = filename+getFileExtension(); - UBLOG(logDEBUG1,"WbWriterVtkXmlBinary::writeTrianglesWithNodeData to "<<vtkfilename<<" - start"); - - ofstream out(vtkfilename.c_str(),ios::out | ios::binary); - if(!out) - { - out.clear(); //flags ruecksetzen (ansonsten liefert utern if(!out) weiterhin true!!! - string path = UbSystem::getPathFromString(vtkfilename); - if(path.size()>0){ UbSystem::makeDirectory(path); out.open(vtkfilename.c_str(),ios::out | ios::binary);} - if(!out) throw UbException(UB_EXARGS,"couldn't open file "+vtkfilename); - } - - int nofNodes = (int)nodes.size(); - int nofCells = (int)cells.size(); - - int bytesPerByteVal = 4; //==sizeof(int) - int bytesPoints = 3 /*x1/x2/x3 */ * nofNodes * sizeof(float); - int bytesCellConnectivty = 3 /*nodes per tri */ * nofCells * sizeof(int ); - int bytesCellOffsets = 1 /*offset per tri */ * nofCells * sizeof(int ); - int bytesCellTypes = 1 /*type of tri */ * nofCells * sizeof(unsigned char); - int bytesScalarData = 1 /*scalar */ * nofNodes * sizeof(float); - - int offset = 0; - //VTK FILE - out<<"<?xml version=\"1.0\"?>\n"; - out<<"<VTKFile type=\"UnstructuredGrid\" version=\"0.1\" byte_order=\"LittleEndian\" >"<<"\n"; - out<<" <UnstructuredGrid>"<<"\n"; - out<<" <Piece NumberOfPoints=\""<<nofNodes<<"\" NumberOfCells=\""<<nofCells<<"\">\n"; - - //POINTS SECTION - out<<" <Points>\n"; - out<<" <DataArray type=\"Float32\" NumberOfComponents=\"3\" format=\"appended\" offset=\""<< offset <<"\" />\n"; - out<<" </Points>\n"; - offset += (bytesPerByteVal + bytesPoints); - - //CELLS SECTION - out<<" <Cells>\n"; - out<<" <DataArray type=\"Int32\" Name=\"connectivity\" format=\"appended\" offset=\""<< offset <<"\" />\n"; - offset += (bytesPerByteVal + bytesCellConnectivty); - out<<" <DataArray type=\"Int32\" Name=\"offsets\" format=\"appended\" offset=\""<< offset <<"\" />\n"; - offset += (bytesPerByteVal + bytesCellOffsets); - out<<" <DataArray type=\"UInt8\" Name=\"types\" format=\"appended\" offset=\""<< offset <<"\" />\n "; - offset += (bytesPerByteVal + bytesCellTypes); - out<<" </Cells>\n"; - - //DATA SECTION - out<<" <PointData>\n"; - for(size_t s=0; s<datanames.size(); ++s) - { - out<< " <DataArray type=\"Float32\" Name=\""<< datanames[s] <<"\" format=\"appended\" offset=\""<< offset <<"\" /> \n"; - offset += (bytesPerByteVal + bytesScalarData); - } - out<<" </PointData>\n"; - - out<<" </Piece>\n"; - out<<" </UnstructuredGrid>\n"; - - // AppendedData SECTION - out<<" <AppendedData encoding=\"raw\">\n"; - out<<"_"; - - //POINTS SECTION - out.write((char*)&bytesPoints,bytesPerByteVal); - for(int n=0; n<nofNodes; n++) - { - out.write((char*)&val<1>(nodes[n]),sizeof(float)); - out.write((char*)&val<2>(nodes[n]),sizeof(float)); - out.write((char*)&val<3>(nodes[n]),sizeof(float)); - } - - //CELLS SECTION - //cellConnectivity - out.write( (char*)&bytesCellConnectivty, bytesPerByteVal ); - for(int c=0; c<nofCells; c++) - { - out.write( (char*)&val<1>(cells[c]), sizeof(int) ); - out.write( (char*)&val<2>(cells[c]), sizeof(int) ); - out.write( (char*)&val<3>(cells[c]), sizeof(int) ); - } - - //cellOffsets - out.write( (char*)&bytesCellOffsets, bytesPerByteVal ); - int itmp; - for(int c=1; c<=nofCells; c++) - { - itmp = 3 * c; - out.write( (char*)&itmp, sizeof(int) ); - } - - //cellTypes - out.write( (char*)&bytesCellTypes, bytesPerByteVal ); - unsigned char vtkCellType = 5; - for(int c=0; c<nofCells; c++) - { - out.write( (char*)&vtkCellType, sizeof(unsigned char) ); - } - - //DATA SECTION - //scalarData - for(size_t s=0; s<datanames.size(); ++s) - { - out.write((char*)&bytesScalarData,bytesPerByteVal); - for(size_t d=0; d<nodedata[s].size(); ++d) - { - //loake kopie machen, da in nodedata "doubles" sind - float tmp = (float)nodedata[s][d]; - out.write((char*)&tmp,sizeof(float)); - } - } - out<<"\n</AppendedData>\n"; - out<<"</VTKFile>"; - out<<endl; - out.close(); - UBLOG(logDEBUG1,"WbWriterVtkXmlBinary::writeTrianglesWithNodeData to "<<vtkfilename<<" - end"); - - return vtkfilename; + string vtkfilename = filename + getFileExtension(); + UBLOG(logDEBUG1, "WbWriterVtkXmlBinary::writeTrianglesWithNodeData to " << vtkfilename << " - start"); + + ofstream out(vtkfilename.c_str(), ios::out | ios::binary); + if (!out) { + out.clear(); // flags ruecksetzen (ansonsten liefert utern if(!out) weiterhin true!!! + string path = UbSystem::getPathFromString(vtkfilename); + if (path.size() > 0) { + UbSystem::makeDirectory(path); + out.open(vtkfilename.c_str(), ios::out | ios::binary); + } + if (!out) + throw UbException(UB_EXARGS, "couldn't open file " + vtkfilename); + } + + int nofNodes = (int)nodes.size(); + int nofCells = (int)cells.size(); + + int bytesPerByteVal = 4; //==sizeof(int) + int bytesPoints = 3 /*x1/x2/x3 */ * nofNodes * sizeof(float); + int bytesCellConnectivty = 3 /*nodes per tri */ * nofCells * sizeof(int); + int bytesCellOffsets = 1 /*offset per tri */ * nofCells * sizeof(int); + int bytesCellTypes = 1 /*type of tri */ * nofCells * sizeof(unsigned char); + int bytesScalarData = 1 /*scalar */ * nofNodes * sizeof(float); + + int offset = 0; + // VTK FILE + out << "<?xml version=\"1.0\"?>\n"; + out << "<VTKFile type=\"UnstructuredGrid\" version=\"0.1\" byte_order=\"LittleEndian\" >" + << "\n"; + out << " <UnstructuredGrid>" + << "\n"; + out << " <Piece NumberOfPoints=\"" << nofNodes << "\" NumberOfCells=\"" << nofCells << "\">\n"; + + // POINTS SECTION + out << " <Points>\n"; + out << " <DataArray type=\"Float32\" NumberOfComponents=\"3\" format=\"appended\" offset=\"" << offset + << "\" />\n"; + out << " </Points>\n"; + offset += (bytesPerByteVal + bytesPoints); + + // CELLS SECTION + out << " <Cells>\n"; + out << " <DataArray type=\"Int32\" Name=\"connectivity\" format=\"appended\" offset=\"" << offset + << "\" />\n"; + offset += (bytesPerByteVal + bytesCellConnectivty); + out << " <DataArray type=\"Int32\" Name=\"offsets\" format=\"appended\" offset=\"" << offset + << "\" />\n"; + offset += (bytesPerByteVal + bytesCellOffsets); + out << " <DataArray type=\"UInt8\" Name=\"types\" format=\"appended\" offset=\"" << offset << "\" />\n "; + offset += (bytesPerByteVal + bytesCellTypes); + out << " </Cells>\n"; + + // DATA SECTION + out << " <PointData>\n"; + for (size_t s = 0; s < datanames.size(); ++s) { + out << " <DataArray type=\"Float32\" Name=\"" << datanames[s] << "\" format=\"appended\" offset=\"" + << offset << "\" /> \n"; + offset += (bytesPerByteVal + bytesScalarData); + } + out << " </PointData>\n"; + + out << " </Piece>\n"; + out << " </UnstructuredGrid>\n"; + + // AppendedData SECTION + out << " <AppendedData encoding=\"raw\">\n"; + out << "_"; + + // POINTS SECTION + out.write((char *)&bytesPoints, bytesPerByteVal); + for (int n = 0; n < nofNodes; n++) { + out.write((char *)&val<1>(nodes[n]), sizeof(float)); + out.write((char *)&val<2>(nodes[n]), sizeof(float)); + out.write((char *)&val<3>(nodes[n]), sizeof(float)); + } + + // CELLS SECTION + // cellConnectivity + out.write((char *)&bytesCellConnectivty, bytesPerByteVal); + for (int c = 0; c < nofCells; c++) { + out.write((char *)&val<1>(cells[c]), sizeof(int)); + out.write((char *)&val<2>(cells[c]), sizeof(int)); + out.write((char *)&val<3>(cells[c]), sizeof(int)); + } + + // cellOffsets + out.write((char *)&bytesCellOffsets, bytesPerByteVal); + int itmp; + for (int c = 1; c <= nofCells; c++) { + itmp = 3 * c; + out.write((char *)&itmp, sizeof(int)); + } + + // cellTypes + out.write((char *)&bytesCellTypes, bytesPerByteVal); + unsigned char vtkCellType = 5; + for (int c = 0; c < nofCells; c++) { + out.write((char *)&vtkCellType, sizeof(unsigned char)); + } + + // DATA SECTION + // scalarData + for (size_t s = 0; s < datanames.size(); ++s) { + out.write((char *)&bytesScalarData, bytesPerByteVal); + for (size_t d = 0; d < nodedata[s].size(); ++d) { + // loake kopie machen, da in nodedata "doubles" sind + float tmp = (float)nodedata[s][d]; + out.write((char *)&tmp, sizeof(float)); + } + } + out << "\n</AppendedData>\n"; + out << "</VTKFile>"; + out << endl; + out.close(); + UBLOG(logDEBUG1, "WbWriterVtkXmlBinary::writeTrianglesWithNodeData to " << vtkfilename << " - end"); + + return vtkfilename; } /*===============================================================================*/ -string WbWriterVtkXmlBinary::writeQuads(const string& filename,vector< UbTupleFloat3 >& nodes, vector< UbTupleInt4 >& cells) +string WbWriterVtkXmlBinary::writeQuads(const string &filename, vector<UbTupleFloat3> &nodes, + vector<UbTupleInt4> &cells) { - string vtkfilename = filename+getFileExtension(); - UBLOG(logDEBUG1,"WbWriterVtkXmlBinary::writeQuads to "<<vtkfilename<<" - start"); - - ofstream out(vtkfilename.c_str(),ios::out | ios::binary); - if(!out) - { - out.clear(); //flags ruecksetzen (ansonsten liefert utern if(!out) weiterhin true!!! - string path = UbSystem::getPathFromString(vtkfilename); - if(path.size()>0){ UbSystem::makeDirectory(path); out.open(vtkfilename.c_str(),ios::out | ios::binary);} - if(!out) throw UbException(UB_EXARGS,"couldn't open file "+vtkfilename); - } - - int nofNodes = (int)nodes.size(); - int nofCells = (int)cells.size(); - - int bytesPerByteVal = 4; //==sizeof(int) - int bytesPoints = 3 /*x1/x2/x3 */ * nofNodes * sizeof(float); - int bytesCellConnectivty = 4 /*nodes per quad */ * nofCells * sizeof(int ); - int bytesCellOffsets = 1 /*offset per quad */ * nofCells * sizeof(int ); - int bytesCellTypes = 1 /*type of quad */ * nofCells * sizeof(unsigned char); - - int offset = 0; - //VTK FILE - out<<"<?xml version=\"1.0\"?>\n"; - out<<"<VTKFile type=\"UnstructuredGrid\" version=\"0.1\" byte_order=\"LittleEndian\" >"<<"\n"; - out<<" <UnstructuredGrid>"<<"\n"; - out<<" <Piece NumberOfPoints=\""<<nofNodes<<"\" NumberOfCells=\""<<nofCells<<"\">\n"; - - //POINTS SECTION - out<<" <Points>\n"; - out<<" <DataArray type=\"Float32\" NumberOfComponents=\"3\" format=\"appended\" offset=\""<< offset <<"\" />\n"; - out<<" </Points>\n"; - offset += (bytesPerByteVal + bytesPoints); - - //CELLS SECTION - out<<" <Cells>\n"; - out<<" <DataArray type=\"Int32\" Name=\"connectivity\" format=\"appended\" offset=\""<< offset <<"\" />\n"; - offset += (bytesPerByteVal + bytesCellConnectivty); - out<<" <DataArray type=\"Int32\" Name=\"offsets\" format=\"appended\" offset=\""<< offset <<"\" />\n"; - offset += (bytesPerByteVal + bytesCellOffsets); - out<<" <DataArray type=\"UInt8\" Name=\"types\" format=\"appended\" offset=\""<< offset <<"\" />\n "; - offset += (bytesPerByteVal + bytesCellTypes); - out<<" </Cells>\n"; - - out<<" </Piece>\n"; - out<<" </UnstructuredGrid>\n"; - - // AppendedData SECTION - out<<" <AppendedData encoding=\"raw\">\n"; - out<<"_"; - - //POINTS SECTION - out.write((char*)&bytesPoints,bytesPerByteVal); - for(int n=0; n<nofNodes; n++) - { - out.write((char*)&val<1>(nodes[n]),sizeof(float)); - out.write((char*)&val<2>(nodes[n]),sizeof(float)); - out.write((char*)&val<3>(nodes[n]),sizeof(float)); - } - - //CELLS SECTION - //cellConnectivity - out.write( (char*)&bytesCellConnectivty, bytesPerByteVal ); - for(int c=0; c<nofCells; c++) - { - out.write( (char*)&val<1>(cells[c]), sizeof(int) ); - out.write( (char*)&val<2>(cells[c]), sizeof(int) ); - out.write( (char*)&val<4>(cells[c]), sizeof(int) ); - out.write( (char*)&val<3>(cells[c]), sizeof(int) ); - } - - //cellOffsets - out.write( (char*)&bytesCellOffsets, bytesPerByteVal ); - int itmp; - for(int c=1; c<=nofCells; c++) - { - itmp = 4 * c; - out.write( (char*)&itmp, sizeof(int) ); - } - - //cellTypes - out.write( (char*)&bytesCellTypes, bytesPerByteVal ); - unsigned char vtkCellType = 8; - for(int c=0; c<nofCells; c++) - { - out.write( (char*)&vtkCellType, sizeof(unsigned char) ); - } - out<<"\n</AppendedData>\n"; - out<<"</VTKFile>"; - out<<endl; - out<<flush; - out.close(); - UBLOG(logDEBUG1,"WbWriterVtkXmlBinary::writeQuads to "<<vtkfilename<<" - end"); - - return vtkfilename; + string vtkfilename = filename + getFileExtension(); + UBLOG(logDEBUG1, "WbWriterVtkXmlBinary::writeQuads to " << vtkfilename << " - start"); + + ofstream out(vtkfilename.c_str(), ios::out | ios::binary); + if (!out) { + out.clear(); // flags ruecksetzen (ansonsten liefert utern if(!out) weiterhin true!!! + string path = UbSystem::getPathFromString(vtkfilename); + if (path.size() > 0) { + UbSystem::makeDirectory(path); + out.open(vtkfilename.c_str(), ios::out | ios::binary); + } + if (!out) + throw UbException(UB_EXARGS, "couldn't open file " + vtkfilename); + } + + int nofNodes = (int)nodes.size(); + int nofCells = (int)cells.size(); + + int bytesPerByteVal = 4; //==sizeof(int) + int bytesPoints = 3 /*x1/x2/x3 */ * nofNodes * sizeof(float); + int bytesCellConnectivty = 4 /*nodes per quad */ * nofCells * sizeof(int); + int bytesCellOffsets = 1 /*offset per quad */ * nofCells * sizeof(int); + int bytesCellTypes = 1 /*type of quad */ * nofCells * sizeof(unsigned char); + + int offset = 0; + // VTK FILE + out << "<?xml version=\"1.0\"?>\n"; + out << "<VTKFile type=\"UnstructuredGrid\" version=\"0.1\" byte_order=\"LittleEndian\" >" + << "\n"; + out << " <UnstructuredGrid>" + << "\n"; + out << " <Piece NumberOfPoints=\"" << nofNodes << "\" NumberOfCells=\"" << nofCells << "\">\n"; + + // POINTS SECTION + out << " <Points>\n"; + out << " <DataArray type=\"Float32\" NumberOfComponents=\"3\" format=\"appended\" offset=\"" << offset + << "\" />\n"; + out << " </Points>\n"; + offset += (bytesPerByteVal + bytesPoints); + + // CELLS SECTION + out << " <Cells>\n"; + out << " <DataArray type=\"Int32\" Name=\"connectivity\" format=\"appended\" offset=\"" << offset + << "\" />\n"; + offset += (bytesPerByteVal + bytesCellConnectivty); + out << " <DataArray type=\"Int32\" Name=\"offsets\" format=\"appended\" offset=\"" << offset + << "\" />\n"; + offset += (bytesPerByteVal + bytesCellOffsets); + out << " <DataArray type=\"UInt8\" Name=\"types\" format=\"appended\" offset=\"" << offset << "\" />\n "; + offset += (bytesPerByteVal + bytesCellTypes); + out << " </Cells>\n"; + + out << " </Piece>\n"; + out << " </UnstructuredGrid>\n"; + + // AppendedData SECTION + out << " <AppendedData encoding=\"raw\">\n"; + out << "_"; + + // POINTS SECTION + out.write((char *)&bytesPoints, bytesPerByteVal); + for (int n = 0; n < nofNodes; n++) { + out.write((char *)&val<1>(nodes[n]), sizeof(float)); + out.write((char *)&val<2>(nodes[n]), sizeof(float)); + out.write((char *)&val<3>(nodes[n]), sizeof(float)); + } + + // CELLS SECTION + // cellConnectivity + out.write((char *)&bytesCellConnectivty, bytesPerByteVal); + for (int c = 0; c < nofCells; c++) { + out.write((char *)&val<1>(cells[c]), sizeof(int)); + out.write((char *)&val<2>(cells[c]), sizeof(int)); + out.write((char *)&val<4>(cells[c]), sizeof(int)); + out.write((char *)&val<3>(cells[c]), sizeof(int)); + } + + // cellOffsets + out.write((char *)&bytesCellOffsets, bytesPerByteVal); + int itmp; + for (int c = 1; c <= nofCells; c++) { + itmp = 4 * c; + out.write((char *)&itmp, sizeof(int)); + } + + // cellTypes + out.write((char *)&bytesCellTypes, bytesPerByteVal); + unsigned char vtkCellType = 8; + for (int c = 0; c < nofCells; c++) { + out.write((char *)&vtkCellType, sizeof(unsigned char)); + } + out << "\n</AppendedData>\n"; + out << "</VTKFile>"; + out << endl; + out << flush; + out.close(); + UBLOG(logDEBUG1, "WbWriterVtkXmlBinary::writeQuads to " << vtkfilename << " - end"); + + return vtkfilename; } /*===============================================================================*/ -string WbWriterVtkXmlBinary::writeQuadsWithNodeData(const string& filename,vector< UbTupleFloat3 >& nodes, vector< UbTupleInt4 >& cells, vector< string >& datanames, vector< vector< double > >& nodedata) +string WbWriterVtkXmlBinary::writeQuadsWithNodeData(const string &filename, vector<UbTupleFloat3> &nodes, + vector<UbTupleInt4> &cells, vector<string> &datanames, + vector<vector<double>> &nodedata) { - string vtkfilename = filename+getFileExtension(); - UBLOG(logDEBUG1,"WbWriterVtkXmlBinary::writeQuadsWithNodeData to "<<vtkfilename<<" - start"); - - ofstream out(vtkfilename.c_str(),ios::out | ios::binary); - if(!out) - { - out.clear(); //flags ruecksetzen (ansonsten liefert utern if(!out) weiterhin true!!! - string path = UbSystem::getPathFromString(vtkfilename); - if(path.size()>0){ UbSystem::makeDirectory(path); out.open(vtkfilename.c_str(),ios::out | ios::binary);} - if(!out) throw UbException(UB_EXARGS,"couldn't open file "+vtkfilename); - } - - int nofNodes = (int)nodes.size(); - int nofCells = (int)cells.size(); - - int bytesPerByteVal = 4; //==sizeof(int) - int bytesPoints = 3 /*x1/x2/x3 */ * nofNodes * sizeof(float); - int bytesCellConnectivty = 4 /*nodes per quad */ * nofCells * sizeof(int ); - int bytesCellOffsets = 1 /*offset per quad */ * nofCells * sizeof(int ); - int bytesCellTypes = 1 /*type of quad */ * nofCells * sizeof(unsigned char); - int bytesScalarData = 1 /*scalar */ * nofNodes * sizeof(float); - - int offset = 0; - //VTK FILE - out<<"<?xml version=\"1.0\"?>\n"; - out<<"<VTKFile type=\"UnstructuredGrid\" version=\"0.1\" byte_order=\"LittleEndian\" >"<<"\n"; - out<<" <UnstructuredGrid>"<<"\n"; - out<<" <Piece NumberOfPoints=\""<<nofNodes<<"\" NumberOfCells=\""<<nofCells<<"\">\n"; - - //POINTS SECTION - out<<" <Points>\n"; - out<<" <DataArray type=\"Float32\" NumberOfComponents=\"3\" format=\"appended\" offset=\""<< offset <<"\" />\n"; - out<<" </Points>\n"; - offset += (bytesPerByteVal + bytesPoints); - - //CELLS SECTION - out<<" <Cells>\n"; - out<<" <DataArray type=\"Int32\" Name=\"connectivity\" format=\"appended\" offset=\""<< offset <<"\" />\n"; - offset += (bytesPerByteVal + bytesCellConnectivty); - out<<" <DataArray type=\"Int32\" Name=\"offsets\" format=\"appended\" offset=\""<< offset <<"\" />\n"; - offset += (bytesPerByteVal + bytesCellOffsets); - out<<" <DataArray type=\"UInt8\" Name=\"types\" format=\"appended\" offset=\""<< offset <<"\" />\n "; - offset += (bytesPerByteVal + bytesCellTypes); - out<<" </Cells>\n"; - - //DATA SECTION - out<<" <PointData>\n"; - for(size_t s=0; s<datanames.size(); ++s) - { - out<< " <DataArray type=\"Float64\" Name=\""<< datanames[s] <<"\" format=\"appended\" offset=\""<< offset <<"\" /> \n"; - offset += (bytesPerByteVal + bytesScalarData); - } - out<<" </PointData>\n"; - - out<<" </Piece>\n"; - out<<" </UnstructuredGrid>\n"; - - // AppendedData SECTION - out<<" <AppendedData encoding=\"raw\">\n"; - out<<"_"; - - //POINTS SECTION - out.write((char*)&bytesPoints,bytesPerByteVal); - for(int n=0; n<nofNodes; n++) - { - out.write((char*)&val<1>(nodes[n]),sizeof(float)); - out.write((char*)&val<2>(nodes[n]),sizeof(float)); - out.write((char*)&val<3>(nodes[n]),sizeof(float)); - } - - //CELLS SECTION - //cellConnectivity - out.write( (char*)&bytesCellConnectivty, bytesPerByteVal ); - for(int c=0; c<nofCells; c++) - { - out.write( (char*)&val<1>(cells[c]), sizeof(int) ); - out.write( (char*)&val<2>(cells[c]), sizeof(int) ); - out.write( (char*)&val<4>(cells[c]), sizeof(int) ); - out.write( (char*)&val<3>(cells[c]), sizeof(int) ); - } - - //cellOffsets - out.write( (char*)&bytesCellOffsets, bytesPerByteVal ); - int itmp; - for(int c=1; c<=nofCells; c++) - { - itmp = 4 * c; - out.write( (char*)&itmp, sizeof(int) ); - } - - //cellTypes - out.write( (char*)&bytesCellTypes, bytesPerByteVal ); - unsigned char vtkCellType = 8; - for(int c=0; c<nofCells; c++) - { - out.write( (char*)&vtkCellType, sizeof(unsigned char) ); - } - - //DATA SECTION - //scalarData - for(size_t s=0; s<datanames.size(); ++s) - { - out.write((char*)&bytesScalarData,bytesPerByteVal); - for(size_t d=0; d<nodedata[s].size(); ++d) - { - //loake kopie machen, da in nodedata "doubles" sind - float tmp = (float)nodedata[s][d]; - out.write((char*)&tmp,sizeof(float)); - } - } - out<<"\n</AppendedData>\n"; - out<<"</VTKFile>"; - out<<endl; - out.close(); - UBLOG(logDEBUG1,"WbWriterVtkXmlBinary::writeQuadsWithNodeData to "<<vtkfilename<<" - end"); - - return vtkfilename; + string vtkfilename = filename + getFileExtension(); + UBLOG(logDEBUG1, "WbWriterVtkXmlBinary::writeQuadsWithNodeData to " << vtkfilename << " - start"); + + ofstream out(vtkfilename.c_str(), ios::out | ios::binary); + if (!out) { + out.clear(); // flags ruecksetzen (ansonsten liefert utern if(!out) weiterhin true!!! + string path = UbSystem::getPathFromString(vtkfilename); + if (path.size() > 0) { + UbSystem::makeDirectory(path); + out.open(vtkfilename.c_str(), ios::out | ios::binary); + } + if (!out) + throw UbException(UB_EXARGS, "couldn't open file " + vtkfilename); + } + + int nofNodes = (int)nodes.size(); + int nofCells = (int)cells.size(); + + int bytesPerByteVal = 4; //==sizeof(int) + int bytesPoints = 3 /*x1/x2/x3 */ * nofNodes * sizeof(float); + int bytesCellConnectivty = 4 /*nodes per quad */ * nofCells * sizeof(int); + int bytesCellOffsets = 1 /*offset per quad */ * nofCells * sizeof(int); + int bytesCellTypes = 1 /*type of quad */ * nofCells * sizeof(unsigned char); + int bytesScalarData = 1 /*scalar */ * nofNodes * sizeof(float); + + int offset = 0; + // VTK FILE + out << "<?xml version=\"1.0\"?>\n"; + out << "<VTKFile type=\"UnstructuredGrid\" version=\"0.1\" byte_order=\"LittleEndian\" >" + << "\n"; + out << " <UnstructuredGrid>" + << "\n"; + out << " <Piece NumberOfPoints=\"" << nofNodes << "\" NumberOfCells=\"" << nofCells << "\">\n"; + + // POINTS SECTION + out << " <Points>\n"; + out << " <DataArray type=\"Float32\" NumberOfComponents=\"3\" format=\"appended\" offset=\"" << offset + << "\" />\n"; + out << " </Points>\n"; + offset += (bytesPerByteVal + bytesPoints); + + // CELLS SECTION + out << " <Cells>\n"; + out << " <DataArray type=\"Int32\" Name=\"connectivity\" format=\"appended\" offset=\"" << offset + << "\" />\n"; + offset += (bytesPerByteVal + bytesCellConnectivty); + out << " <DataArray type=\"Int32\" Name=\"offsets\" format=\"appended\" offset=\"" << offset + << "\" />\n"; + offset += (bytesPerByteVal + bytesCellOffsets); + out << " <DataArray type=\"UInt8\" Name=\"types\" format=\"appended\" offset=\"" << offset << "\" />\n "; + offset += (bytesPerByteVal + bytesCellTypes); + out << " </Cells>\n"; + + // DATA SECTION + out << " <PointData>\n"; + for (size_t s = 0; s < datanames.size(); ++s) { + out << " <DataArray type=\"Float64\" Name=\"" << datanames[s] << "\" format=\"appended\" offset=\"" + << offset << "\" /> \n"; + offset += (bytesPerByteVal + bytesScalarData); + } + out << " </PointData>\n"; + + out << " </Piece>\n"; + out << " </UnstructuredGrid>\n"; + + // AppendedData SECTION + out << " <AppendedData encoding=\"raw\">\n"; + out << "_"; + + // POINTS SECTION + out.write((char *)&bytesPoints, bytesPerByteVal); + for (int n = 0; n < nofNodes; n++) { + out.write((char *)&val<1>(nodes[n]), sizeof(float)); + out.write((char *)&val<2>(nodes[n]), sizeof(float)); + out.write((char *)&val<3>(nodes[n]), sizeof(float)); + } + + // CELLS SECTION + // cellConnectivity + out.write((char *)&bytesCellConnectivty, bytesPerByteVal); + for (int c = 0; c < nofCells; c++) { + out.write((char *)&val<1>(cells[c]), sizeof(int)); + out.write((char *)&val<2>(cells[c]), sizeof(int)); + out.write((char *)&val<4>(cells[c]), sizeof(int)); + out.write((char *)&val<3>(cells[c]), sizeof(int)); + } + + // cellOffsets + out.write((char *)&bytesCellOffsets, bytesPerByteVal); + int itmp; + for (int c = 1; c <= nofCells; c++) { + itmp = 4 * c; + out.write((char *)&itmp, sizeof(int)); + } + + // cellTypes + out.write((char *)&bytesCellTypes, bytesPerByteVal); + unsigned char vtkCellType = 8; + for (int c = 0; c < nofCells; c++) { + out.write((char *)&vtkCellType, sizeof(unsigned char)); + } + + // DATA SECTION + // scalarData + for (size_t s = 0; s < datanames.size(); ++s) { + out.write((char *)&bytesScalarData, bytesPerByteVal); + for (size_t d = 0; d < nodedata[s].size(); ++d) { + // loake kopie machen, da in nodedata "doubles" sind + float tmp = (float)nodedata[s][d]; + out.write((char *)&tmp, sizeof(float)); + } + } + out << "\n</AppendedData>\n"; + out << "</VTKFile>"; + out << endl; + out.close(); + UBLOG(logDEBUG1, "WbWriterVtkXmlBinary::writeQuadsWithNodeData to " << vtkfilename << " - end"); + + return vtkfilename; } /*===============================================================================*/ -string WbWriterVtkXmlBinary::writeQuadsWithCellData(const string& filename,vector< UbTupleFloat3 >& nodes, vector< UbTupleInt4 >& cells, vector< string >& datanames, vector< vector< double > >& celldata) +string WbWriterVtkXmlBinary::writeQuadsWithCellData(const string &filename, vector<UbTupleFloat3> &nodes, + vector<UbTupleInt4> &cells, vector<string> &datanames, + vector<vector<double>> &celldata) { - string vtkfilename = filename+getFileExtension(); - UBLOG(logDEBUG1,"WbWriterVtkXmlBinary::writeQuadsWithCellData to "<<vtkfilename<<" - start"); - - ofstream out(vtkfilename.c_str(),ios::out | ios::binary); - if(!out) - { - out.clear(); //flags ruecksetzen (ansonsten liefert utern if(!out) weiterhin true!!! - string path = UbSystem::getPathFromString(vtkfilename); - if(path.size()>0){ UbSystem::makeDirectory(path); out.open(vtkfilename.c_str(),ios::out | ios::binary);} - if(!out) throw UbException(UB_EXARGS,"couldn't open file "+vtkfilename); - } - - int nofNodes = (int)nodes.size(); - int nofCells = (int)cells.size(); - - int bytesPerByteVal = 4; //==sizeof(int) - int bytesPoints = 3 /*x1/x2/x3 */ * nofNodes * sizeof(float); - int bytesCellConnectivty = 4 /*nodes per quad */ * nofCells * sizeof(int ); - int bytesCellOffsets = 1 /*offset per quad */ * nofCells * sizeof(int ); - int bytesCellTypes = 1 /*type of quad */ * nofCells * sizeof(unsigned char); - int bytesScalarData = 1 /*scalar */ * nofCells * sizeof(float); - - int offset = 0; - //VTK FILE - out<<"<?xml version=\"1.0\"?>\n"; - out<<"<VTKFile type=\"UnstructuredGrid\" version=\"0.1\" byte_order=\"LittleEndian\" >"<<"\n"; - out<<" <UnstructuredGrid>"<<"\n"; - out<<" <Piece NumberOfPoints=\""<<nofNodes<<"\" NumberOfCells=\""<<nofCells<<"\">\n"; - - //POINTS SECTION - out<<" <Points>\n"; - out<<" <DataArray type=\"Float32\" NumberOfComponents=\"3\" format=\"appended\" offset=\""<< offset <<"\" />\n"; - out<<" </Points>\n"; - offset += (bytesPerByteVal + bytesPoints); - - //CELLS SECTION - out<<" <Cells>\n"; - out<<" <DataArray type=\"Int32\" Name=\"connectivity\" format=\"appended\" offset=\""<< offset <<"\" />\n"; - offset += (bytesPerByteVal + bytesCellConnectivty); - out<<" <DataArray type=\"Int32\" Name=\"offsets\" format=\"appended\" offset=\""<< offset <<"\" />\n"; - offset += (bytesPerByteVal + bytesCellOffsets); - out<<" <DataArray type=\"UInt8\" Name=\"types\" format=\"appended\" offset=\""<< offset <<"\" />\n "; - offset += (bytesPerByteVal + bytesCellTypes); - out<<" </Cells>\n"; - - //DATA SECTION - out<<" <CellData>\n"; - for(size_t s=0; s<datanames.size(); ++s) - { - out<< " <DataArray type=\"Float32\" Name=\""<< datanames[s] <<"\" format=\"appended\" offset=\""<< offset <<"\" /> \n"; - offset += (bytesPerByteVal + bytesScalarData); - } - out<<" </CellData>\n"; - - out<<" </Piece>\n"; - out<<" </UnstructuredGrid>\n"; - - // AppendedData SECTION - out<<" <AppendedData encoding=\"raw\">\n"; - out<<"_"; - - //POINTS SECTION - out.write((char*)&bytesPoints,bytesPerByteVal); - for(int n=0; n<nofNodes; n++) - { - out.write((char*)&val<1>(nodes[n]),sizeof(float)); - out.write((char*)&val<2>(nodes[n]),sizeof(float)); - out.write((char*)&val<3>(nodes[n]),sizeof(float)); - } - - //CELLS SECTION - //cellConnectivity - out.write( (char*)&bytesCellConnectivty, bytesPerByteVal ); - for(int c=0; c<nofCells; c++) - { - out.write( (char*)&val<1>(cells[c]), sizeof(int) ); - out.write( (char*)&val<2>(cells[c]), sizeof(int) ); - out.write( (char*)&val<4>(cells[c]), sizeof(int) ); - out.write( (char*)&val<3>(cells[c]), sizeof(int) ); - } - - //cellOffsets - out.write( (char*)&bytesCellOffsets, bytesPerByteVal ); - int itmp; - for(int c=1; c<=nofCells; c++) - { - itmp = 4 * c; - out.write( (char*)&itmp, sizeof(int) ); - } - - //cellTypes - out.write( (char*)&bytesCellTypes, bytesPerByteVal ); - unsigned char vtkCellType = 8; - for(int c=0; c<nofCells; c++) - { - out.write( (char*)&vtkCellType, sizeof(unsigned char) ); - } - - //DATA SECTION - //scalarData - for(size_t s=0; s<datanames.size(); ++s) - { - out.write((char*)&bytesScalarData,bytesPerByteVal); - for(size_t d=0; d<celldata[s].size(); ++d) - { - //loake kopie machen, da in celldata "doubles" sind - float tmp = (float)celldata[s][d]; - out.write((char*)&tmp,sizeof(float)); - } - } - - out<<"\n</AppendedData>\n"; - - out<<"</VTKFile>"; - out<<endl; - out.close(); - UBLOG(logDEBUG1,"WbWriterVtkXmlBinary::writeQuadsWithCellData to "<<vtkfilename<<" - end"); - - return vtkfilename; + string vtkfilename = filename + getFileExtension(); + UBLOG(logDEBUG1, "WbWriterVtkXmlBinary::writeQuadsWithCellData to " << vtkfilename << " - start"); + + ofstream out(vtkfilename.c_str(), ios::out | ios::binary); + if (!out) { + out.clear(); // flags ruecksetzen (ansonsten liefert utern if(!out) weiterhin true!!! + string path = UbSystem::getPathFromString(vtkfilename); + if (path.size() > 0) { + UbSystem::makeDirectory(path); + out.open(vtkfilename.c_str(), ios::out | ios::binary); + } + if (!out) + throw UbException(UB_EXARGS, "couldn't open file " + vtkfilename); + } + + int nofNodes = (int)nodes.size(); + int nofCells = (int)cells.size(); + + int bytesPerByteVal = 4; //==sizeof(int) + int bytesPoints = 3 /*x1/x2/x3 */ * nofNodes * sizeof(float); + int bytesCellConnectivty = 4 /*nodes per quad */ * nofCells * sizeof(int); + int bytesCellOffsets = 1 /*offset per quad */ * nofCells * sizeof(int); + int bytesCellTypes = 1 /*type of quad */ * nofCells * sizeof(unsigned char); + int bytesScalarData = 1 /*scalar */ * nofCells * sizeof(float); + + int offset = 0; + // VTK FILE + out << "<?xml version=\"1.0\"?>\n"; + out << "<VTKFile type=\"UnstructuredGrid\" version=\"0.1\" byte_order=\"LittleEndian\" >" + << "\n"; + out << " <UnstructuredGrid>" + << "\n"; + out << " <Piece NumberOfPoints=\"" << nofNodes << "\" NumberOfCells=\"" << nofCells << "\">\n"; + + // POINTS SECTION + out << " <Points>\n"; + out << " <DataArray type=\"Float32\" NumberOfComponents=\"3\" format=\"appended\" offset=\"" << offset + << "\" />\n"; + out << " </Points>\n"; + offset += (bytesPerByteVal + bytesPoints); + + // CELLS SECTION + out << " <Cells>\n"; + out << " <DataArray type=\"Int32\" Name=\"connectivity\" format=\"appended\" offset=\"" << offset + << "\" />\n"; + offset += (bytesPerByteVal + bytesCellConnectivty); + out << " <DataArray type=\"Int32\" Name=\"offsets\" format=\"appended\" offset=\"" << offset + << "\" />\n"; + offset += (bytesPerByteVal + bytesCellOffsets); + out << " <DataArray type=\"UInt8\" Name=\"types\" format=\"appended\" offset=\"" << offset << "\" />\n "; + offset += (bytesPerByteVal + bytesCellTypes); + out << " </Cells>\n"; + + // DATA SECTION + out << " <CellData>\n"; + for (size_t s = 0; s < datanames.size(); ++s) { + out << " <DataArray type=\"Float32\" Name=\"" << datanames[s] << "\" format=\"appended\" offset=\"" + << offset << "\" /> \n"; + offset += (bytesPerByteVal + bytesScalarData); + } + out << " </CellData>\n"; + + out << " </Piece>\n"; + out << " </UnstructuredGrid>\n"; + + // AppendedData SECTION + out << " <AppendedData encoding=\"raw\">\n"; + out << "_"; + + // POINTS SECTION + out.write((char *)&bytesPoints, bytesPerByteVal); + for (int n = 0; n < nofNodes; n++) { + out.write((char *)&val<1>(nodes[n]), sizeof(float)); + out.write((char *)&val<2>(nodes[n]), sizeof(float)); + out.write((char *)&val<3>(nodes[n]), sizeof(float)); + } + + // CELLS SECTION + // cellConnectivity + out.write((char *)&bytesCellConnectivty, bytesPerByteVal); + for (int c = 0; c < nofCells; c++) { + out.write((char *)&val<1>(cells[c]), sizeof(int)); + out.write((char *)&val<2>(cells[c]), sizeof(int)); + out.write((char *)&val<4>(cells[c]), sizeof(int)); + out.write((char *)&val<3>(cells[c]), sizeof(int)); + } + + // cellOffsets + out.write((char *)&bytesCellOffsets, bytesPerByteVal); + int itmp; + for (int c = 1; c <= nofCells; c++) { + itmp = 4 * c; + out.write((char *)&itmp, sizeof(int)); + } + + // cellTypes + out.write((char *)&bytesCellTypes, bytesPerByteVal); + unsigned char vtkCellType = 8; + for (int c = 0; c < nofCells; c++) { + out.write((char *)&vtkCellType, sizeof(unsigned char)); + } + + // DATA SECTION + // scalarData + for (size_t s = 0; s < datanames.size(); ++s) { + out.write((char *)&bytesScalarData, bytesPerByteVal); + for (size_t d = 0; d < celldata[s].size(); ++d) { + // loake kopie machen, da in celldata "doubles" sind + float tmp = (float)celldata[s][d]; + out.write((char *)&tmp, sizeof(float)); + } + } + + out << "\n</AppendedData>\n"; + + out << "</VTKFile>"; + out << endl; + out.close(); + UBLOG(logDEBUG1, "WbWriterVtkXmlBinary::writeQuadsWithCellData to " << vtkfilename << " - end"); + + return vtkfilename; } /*===============================================================================*/ -string WbWriterVtkXmlBinary::writeQuadsWithNodeAndCellData(const string& filename,vector< UbTupleFloat3 >& nodes, vector< UbTupleInt4 >& cells, - vector< string >& nodedatanames, vector< vector< double > >& nodedata, vector< string >& celldatanames, - vector< vector< double > >& celldata ) +string WbWriterVtkXmlBinary::writeQuadsWithNodeAndCellData(const string &filename, vector<UbTupleFloat3> &nodes, + vector<UbTupleInt4> &cells, vector<string> &nodedatanames, + vector<vector<double>> &nodedata, + vector<string> &celldatanames, + vector<vector<double>> &celldata) { - string vtkfilename = filename+getFileExtension(); - UBLOG(logDEBUG1,"WbWriterVtkXmlBinary::writeQuadsWithNodeAndCellData to "<<vtkfilename<<" - start"); - - ofstream out(vtkfilename.c_str(),ios::out | ios::binary); - if(!out) - { - out.clear(); //flags ruecksetzen (ansonsten liefert utern if(!out) weiterhin true!!! - string path = UbSystem::getPathFromString(vtkfilename); - if(path.size()>0){ UbSystem::makeDirectory(path); out.open(vtkfilename.c_str(),ios::out | ios::binary);} - if(!out) throw UbException(UB_EXARGS,"couldn't open file "+vtkfilename); - } - - int nofNodes = (int)nodes.size(); - int nofCells = (int)cells.size(); - - int bytesPerByteVal = 4; //==sizeof(int) - int bytesPoints = 3 /*x1/x2/x3 */ * nofNodes * sizeof(float); - int bytesCellConnectivty = 4 /*nodes per quad */ * nofCells * sizeof(int ); - int bytesCellOffsets = 1 /*offset per quad */ * nofCells * sizeof(int ); - int bytesCellTypes = 1 /*type of quad */ * nofCells * sizeof(unsigned char); - int bytesScalarDataPoint = 1 /*scalar */ * nofNodes * sizeof(float); - int bytesScalarDataCell = 1 /*scalar */ * nofCells * sizeof(float); - - int offset = 0; - //VTK FILE - out<<"<?xml version=\"1.0\"?>\n"; - out<<"<VTKFile type=\"UnstructuredGrid\" version=\"0.1\" byte_order=\"LittleEndian\" >"<<"\n"; - out<<" <UnstructuredGrid>"<<"\n"; - out<<" <Piece NumberOfPoints=\""<<nofNodes<<"\" NumberOfCells=\""<<nofCells<<"\">\n"; - - //POINTS SECTION - out<<" <Points>\n"; - out<<" <DataArray type=\"Float32\" NumberOfComponents=\"3\" format=\"appended\" offset=\""<< offset <<"\" />\n"; - out<<" </Points>\n"; - offset += (bytesPerByteVal + bytesPoints); - - //CELLS SECTION - out<<" <Cells>\n"; - out<<" <DataArray type=\"Int32\" Name=\"connectivity\" format=\"appended\" offset=\""<< offset <<"\" />\n"; - offset += (bytesPerByteVal + bytesCellConnectivty); - out<<" <DataArray type=\"Int32\" Name=\"offsets\" format=\"appended\" offset=\""<< offset <<"\" />\n"; - offset += (bytesPerByteVal + bytesCellOffsets); - out<<" <DataArray type=\"UInt8\" Name=\"types\" format=\"appended\" offset=\""<< offset <<"\" />\n "; - offset += (bytesPerByteVal + bytesCellTypes); - out<<" </Cells>\n"; - - // Point DATA SECTION - out<<" <PointData>\n"; - for(size_t s=0; s<nodedatanames.size(); ++s) - { - out<< " <DataArray type=\"Float32\" Name=\""<< nodedatanames[s] <<"\" format=\"appended\" offset=\""<< offset <<"\" /> \n"; - offset += (bytesPerByteVal + bytesScalarDataPoint); - } - out<<" </PointData>\n"; - - - // Cell DATA SECTION - out<<" <CellData>\n"; - for(size_t s=0; s<celldatanames.size(); ++s) - { - out<< " <DataArray type=\"Float32\" Name=\""<< celldatanames[s] <<"\" format=\"appended\" offset=\""<< offset <<"\" /> \n"; - offset += (bytesPerByteVal + bytesScalarDataCell); - } - out<<" </CellData>\n"; - out<<" </Piece>\n"; - out<<" </UnstructuredGrid>\n"; - - // AppendedData SECTION - out<<" <AppendedData encoding=\"raw\">\n"; - out<<"_"; - - //POINTS SECTION - out.write((char*)&bytesPoints,bytesPerByteVal); - for(int n=0; n<nofNodes; n++) - { - out.write((char*)&val<1>(nodes[n]),sizeof(float)); - out.write((char*)&val<2>(nodes[n]),sizeof(float)); - out.write((char*)&val<3>(nodes[n]),sizeof(float)); - } - - //CELLS SECTION - //cellConnectivity - out.write( (char*)&bytesCellConnectivty, bytesPerByteVal ); - for(int c=0; c<nofCells; c++) - { - out.write( (char*)&val<1>(cells[c]), sizeof(int) ); - out.write( (char*)&val<2>(cells[c]), sizeof(int) ); - out.write( (char*)&val<4>(cells[c]), sizeof(int) ); - out.write( (char*)&val<3>(cells[c]), sizeof(int) ); - } - - //cellOffsets - out.write( (char*)&bytesCellOffsets, bytesPerByteVal ); - int itmp; - for(int c=1; c<=nofCells; c++) - { - itmp = 4 * c; - out.write( (char*)&itmp, sizeof(int) ); - } - - //cellTypes - out.write( (char*)&bytesCellTypes, bytesPerByteVal ); - unsigned char vtkCellType = 8; - for(int c=0; c<nofCells; c++) - { - out.write( (char*)&vtkCellType, sizeof(unsigned char) ); - } - - //Point DATA SECTION - //scalarData - for(size_t s=0; s<nodedatanames.size(); ++s) - { - out.write((char*)&bytesScalarDataPoint,bytesPerByteVal); - for(size_t d=0; d<nodedata[s].size(); ++d) - { - //loake kopie machen, da in nodedata "doubles" sind - float tmp = (float)nodedata[s][d]; - out.write((char*)&tmp,sizeof(float)); - } - } - //Cell DATA SECTION - //scalarData - for(size_t s=0; s<celldatanames.size(); ++s) - { - out.write((char*)&bytesScalarDataCell,bytesPerByteVal); - for(size_t d=0; d<celldata[s].size(); ++d) - { - //loake kopie machen, da in celldata "doubles" sind - float tmp = (float)celldata[s][d]; - out.write((char*)&tmp,sizeof(float)); - } - } - out<<"\n</AppendedData>\n"; - out<<"</VTKFile>"; - out<<endl; - out.close(); - UBLOG(logDEBUG1,"WbWriterVtkXmlBinary::writeQuadsWithNodeAndCellData to "<<vtkfilename<<" - end"); - - return vtkfilename; + string vtkfilename = filename + getFileExtension(); + UBLOG(logDEBUG1, "WbWriterVtkXmlBinary::writeQuadsWithNodeAndCellData to " << vtkfilename << " - start"); + + ofstream out(vtkfilename.c_str(), ios::out | ios::binary); + if (!out) { + out.clear(); // flags ruecksetzen (ansonsten liefert utern if(!out) weiterhin true!!! + string path = UbSystem::getPathFromString(vtkfilename); + if (path.size() > 0) { + UbSystem::makeDirectory(path); + out.open(vtkfilename.c_str(), ios::out | ios::binary); + } + if (!out) + throw UbException(UB_EXARGS, "couldn't open file " + vtkfilename); + } + + int nofNodes = (int)nodes.size(); + int nofCells = (int)cells.size(); + + int bytesPerByteVal = 4; //==sizeof(int) + int bytesPoints = 3 /*x1/x2/x3 */ * nofNodes * sizeof(float); + int bytesCellConnectivty = 4 /*nodes per quad */ * nofCells * sizeof(int); + int bytesCellOffsets = 1 /*offset per quad */ * nofCells * sizeof(int); + int bytesCellTypes = 1 /*type of quad */ * nofCells * sizeof(unsigned char); + int bytesScalarDataPoint = 1 /*scalar */ * nofNodes * sizeof(float); + int bytesScalarDataCell = 1 /*scalar */ * nofCells * sizeof(float); + + int offset = 0; + // VTK FILE + out << "<?xml version=\"1.0\"?>\n"; + out << "<VTKFile type=\"UnstructuredGrid\" version=\"0.1\" byte_order=\"LittleEndian\" >" + << "\n"; + out << " <UnstructuredGrid>" + << "\n"; + out << " <Piece NumberOfPoints=\"" << nofNodes << "\" NumberOfCells=\"" << nofCells << "\">\n"; + + // POINTS SECTION + out << " <Points>\n"; + out << " <DataArray type=\"Float32\" NumberOfComponents=\"3\" format=\"appended\" offset=\"" << offset + << "\" />\n"; + out << " </Points>\n"; + offset += (bytesPerByteVal + bytesPoints); + + // CELLS SECTION + out << " <Cells>\n"; + out << " <DataArray type=\"Int32\" Name=\"connectivity\" format=\"appended\" offset=\"" << offset + << "\" />\n"; + offset += (bytesPerByteVal + bytesCellConnectivty); + out << " <DataArray type=\"Int32\" Name=\"offsets\" format=\"appended\" offset=\"" << offset + << "\" />\n"; + offset += (bytesPerByteVal + bytesCellOffsets); + out << " <DataArray type=\"UInt8\" Name=\"types\" format=\"appended\" offset=\"" << offset << "\" />\n "; + offset += (bytesPerByteVal + bytesCellTypes); + out << " </Cells>\n"; + + // Point DATA SECTION + out << " <PointData>\n"; + for (size_t s = 0; s < nodedatanames.size(); ++s) { + out << " <DataArray type=\"Float32\" Name=\"" << nodedatanames[s] + << "\" format=\"appended\" offset=\"" << offset << "\" /> \n"; + offset += (bytesPerByteVal + bytesScalarDataPoint); + } + out << " </PointData>\n"; + + // Cell DATA SECTION + out << " <CellData>\n"; + for (size_t s = 0; s < celldatanames.size(); ++s) { + out << " <DataArray type=\"Float32\" Name=\"" << celldatanames[s] + << "\" format=\"appended\" offset=\"" << offset << "\" /> \n"; + offset += (bytesPerByteVal + bytesScalarDataCell); + } + out << " </CellData>\n"; + out << " </Piece>\n"; + out << " </UnstructuredGrid>\n"; + + // AppendedData SECTION + out << " <AppendedData encoding=\"raw\">\n"; + out << "_"; + + // POINTS SECTION + out.write((char *)&bytesPoints, bytesPerByteVal); + for (int n = 0; n < nofNodes; n++) { + out.write((char *)&val<1>(nodes[n]), sizeof(float)); + out.write((char *)&val<2>(nodes[n]), sizeof(float)); + out.write((char *)&val<3>(nodes[n]), sizeof(float)); + } + + // CELLS SECTION + // cellConnectivity + out.write((char *)&bytesCellConnectivty, bytesPerByteVal); + for (int c = 0; c < nofCells; c++) { + out.write((char *)&val<1>(cells[c]), sizeof(int)); + out.write((char *)&val<2>(cells[c]), sizeof(int)); + out.write((char *)&val<4>(cells[c]), sizeof(int)); + out.write((char *)&val<3>(cells[c]), sizeof(int)); + } + + // cellOffsets + out.write((char *)&bytesCellOffsets, bytesPerByteVal); + int itmp; + for (int c = 1; c <= nofCells; c++) { + itmp = 4 * c; + out.write((char *)&itmp, sizeof(int)); + } + + // cellTypes + out.write((char *)&bytesCellTypes, bytesPerByteVal); + unsigned char vtkCellType = 8; + for (int c = 0; c < nofCells; c++) { + out.write((char *)&vtkCellType, sizeof(unsigned char)); + } + + // Point DATA SECTION + // scalarData + for (size_t s = 0; s < nodedatanames.size(); ++s) { + out.write((char *)&bytesScalarDataPoint, bytesPerByteVal); + for (size_t d = 0; d < nodedata[s].size(); ++d) { + // loake kopie machen, da in nodedata "doubles" sind + float tmp = (float)nodedata[s][d]; + out.write((char *)&tmp, sizeof(float)); + } + } + // Cell DATA SECTION + // scalarData + for (size_t s = 0; s < celldatanames.size(); ++s) { + out.write((char *)&bytesScalarDataCell, bytesPerByteVal); + for (size_t d = 0; d < celldata[s].size(); ++d) { + // loake kopie machen, da in celldata "doubles" sind + float tmp = (float)celldata[s][d]; + out.write((char *)&tmp, sizeof(float)); + } + } + out << "\n</AppendedData>\n"; + out << "</VTKFile>"; + out << endl; + out.close(); + UBLOG(logDEBUG1, "WbWriterVtkXmlBinary::writeQuadsWithNodeAndCellData to " << vtkfilename << " - end"); + + return vtkfilename; } /*===============================================================================*/ -string WbWriterVtkXmlBinary::writeOctsWithCellData(const string& filename,vector<UbTupleFloat3 >& nodes, vector<UbTupleInt8 >& cells, vector<string >& datanames, vector<vector<double > >& celldata) +string WbWriterVtkXmlBinary::writeOctsWithCellData(const string &filename, vector<UbTupleFloat3> &nodes, + vector<UbTupleInt8> &cells, vector<string> &datanames, + vector<vector<double>> &celldata) { - string vtkfilename = filename+getFileExtension(); - UBLOG(logDEBUG1,"WbWriterVtkXmlBinary::writeOctsWithCellData to "<<vtkfilename<<" - start"); - - ofstream out(vtkfilename.c_str(),ios::out | ios::binary); - if(!out) - { - out.clear(); //flags ruecksetzen (ansonsten liefert utern if(!out) weiterhin true!!! - string path = UbSystem::getPathFromString(vtkfilename); - if(path.size()>0){ UbSystem::makeDirectory(path); out.open(vtkfilename.c_str(),ios::out | ios::binary);} - if(!out) throw UbException(UB_EXARGS,"couldn't open file "+vtkfilename); - } - - int nofNodes = (int)nodes.size(); - int nofCells = (int)cells.size(); - - int bytesPerByteVal = 4; //==sizeof(int) - int bytesPoints = 3 /*x1/x2/x3 */ * nofNodes * sizeof(float); - int bytesCellConnectivty = 8 /*nodes per oct */ * nofCells * sizeof(int ); - int bytesCellOffsets = 1 /*offset per oct*/ * nofCells * sizeof(int ); - int bytesCellTypes = 1 /*type of oct */ * nofCells * sizeof(unsigned char); - int bytesScalarData = 1 /*scalar */ * nofCells * sizeof(float); - - int offset = 0; - //VTK FILE - out<<"<?xml version=\"1.0\"?>\n"; - out<<"<VTKFile type=\"UnstructuredGrid\" version=\"0.1\" byte_order=\"LittleEndian\" >"<<"\n"; - out<<" <UnstructuredGrid>"<<"\n"; - out<<" <Piece NumberOfPoints=\""<<nofNodes<<"\" NumberOfCells=\""<<nofCells<<"\">\n"; - - //POINTS SECTION - out<<" <Points>\n"; - out<<" <DataArray type=\"Float32\" NumberOfComponents=\"3\" format=\"appended\" offset=\""<< offset <<"\" />\n"; - out<<" </Points>\n"; - offset += (bytesPerByteVal + bytesPoints); - - //CELLS SECTION - out<<" <Cells>\n"; - out<<" <DataArray type=\"Int32\" Name=\"connectivity\" format=\"appended\" offset=\""<< offset <<"\" />\n"; - offset += (bytesPerByteVal + bytesCellConnectivty); - out<<" <DataArray type=\"Int32\" Name=\"offsets\" format=\"appended\" offset=\""<< offset <<"\" />\n"; - offset += (bytesPerByteVal + bytesCellOffsets); - out<<" <DataArray type=\"UInt8\" Name=\"types\" format=\"appended\" offset=\""<< offset <<"\" />\n "; - offset += (bytesPerByteVal + bytesCellTypes); - out<<" </Cells>\n"; - - //DATA SECTION - out<<" <CellData>\n"; - for(size_t s=0; s<datanames.size(); ++s) - { - out<< " <DataArray type=\"Float32\" Name=\""<< datanames[s] <<"\" format=\"appended\" offset=\""<< offset <<"\" /> \n"; - offset += (bytesPerByteVal + bytesScalarData); - } - out<<" </CellData>\n"; - - out<<" </Piece>\n"; - out<<" </UnstructuredGrid>\n"; - - // AppendedData SECTION - out<<" <AppendedData encoding=\"raw\">\n"; - out<<"_"; - - //POINTS SECTION - out.write((char*)&bytesPoints,bytesPerByteVal); - for(int n=0; n<nofNodes; n++) - { - out.write((char*)&val<1>(nodes[n]),sizeof(float)); - out.write((char*)&val<2>(nodes[n]),sizeof(float)); - out.write((char*)&val<3>(nodes[n]),sizeof(float)); - } - - //CELLS SECTION - //cellConnectivity - out.write( (char*)&bytesCellConnectivty, bytesPerByteVal ); - for(int c=0; c<nofCells; c++) - { - out.write( (char*)&val<1>(cells[c]), sizeof(int) ); - out.write( (char*)&val<2>(cells[c]), sizeof(int) ); - out.write( (char*)&val<4>(cells[c]), sizeof(int) ); - out.write( (char*)&val<3>(cells[c]), sizeof(int) ); - out.write( (char*)&val<5>(cells[c]), sizeof(int) ); - out.write( (char*)&val<6>(cells[c]), sizeof(int) ); - out.write( (char*)&val<8>(cells[c]), sizeof(int) ); - out.write( (char*)&val<7>(cells[c]), sizeof(int) ); - } - - //cellOffsets - out.write( (char*)&bytesCellOffsets, bytesPerByteVal ); - int itmp; - for(int c=1; c<=nofCells; c++) - { - itmp = 8 * c; - out.write( (char*)&itmp, sizeof(int) ); - } - - //cellTypes - out.write( (char*)&bytesCellTypes, bytesPerByteVal ); - unsigned char vtkCellType = 11; - for(int c=0; c<nofCells; c++) - { - out.write( (char*)&vtkCellType, sizeof(unsigned char) ); - } - - //DATA SECTION - //scalarData - for(size_t s=0; s<datanames.size(); ++s) - { - out.write((char*)&bytesScalarData,bytesPerByteVal); - for(size_t d=0; d<celldata[s].size(); ++d) - { - //loake kopie machen, da in celldata "doubles" sind - float tmp = (float)celldata[s][d]; - out.write((char*)&tmp,sizeof(float)); - } - } - out<<"\n</AppendedData>\n"; - out<<"</VTKFile>"; - out<<endl; - out.close(); - UBLOG(logDEBUG1,"WbWriterVtkXmlBinary::writeOctsWithCellData to "<<vtkfilename<<" - end"); - - return vtkfilename; + string vtkfilename = filename + getFileExtension(); + UBLOG(logDEBUG1, "WbWriterVtkXmlBinary::writeOctsWithCellData to " << vtkfilename << " - start"); + + ofstream out(vtkfilename.c_str(), ios::out | ios::binary); + if (!out) { + out.clear(); // flags ruecksetzen (ansonsten liefert utern if(!out) weiterhin true!!! + string path = UbSystem::getPathFromString(vtkfilename); + if (path.size() > 0) { + UbSystem::makeDirectory(path); + out.open(vtkfilename.c_str(), ios::out | ios::binary); + } + if (!out) + throw UbException(UB_EXARGS, "couldn't open file " + vtkfilename); + } + + int nofNodes = (int)nodes.size(); + int nofCells = (int)cells.size(); + + int bytesPerByteVal = 4; //==sizeof(int) + int bytesPoints = 3 /*x1/x2/x3 */ * nofNodes * sizeof(float); + int bytesCellConnectivty = 8 /*nodes per oct */ * nofCells * sizeof(int); + int bytesCellOffsets = 1 /*offset per oct*/ * nofCells * sizeof(int); + int bytesCellTypes = 1 /*type of oct */ * nofCells * sizeof(unsigned char); + int bytesScalarData = 1 /*scalar */ * nofCells * sizeof(float); + + int offset = 0; + // VTK FILE + out << "<?xml version=\"1.0\"?>\n"; + out << "<VTKFile type=\"UnstructuredGrid\" version=\"0.1\" byte_order=\"LittleEndian\" >" + << "\n"; + out << " <UnstructuredGrid>" + << "\n"; + out << " <Piece NumberOfPoints=\"" << nofNodes << "\" NumberOfCells=\"" << nofCells << "\">\n"; + + // POINTS SECTION + out << " <Points>\n"; + out << " <DataArray type=\"Float32\" NumberOfComponents=\"3\" format=\"appended\" offset=\"" << offset + << "\" />\n"; + out << " </Points>\n"; + offset += (bytesPerByteVal + bytesPoints); + + // CELLS SECTION + out << " <Cells>\n"; + out << " <DataArray type=\"Int32\" Name=\"connectivity\" format=\"appended\" offset=\"" << offset + << "\" />\n"; + offset += (bytesPerByteVal + bytesCellConnectivty); + out << " <DataArray type=\"Int32\" Name=\"offsets\" format=\"appended\" offset=\"" << offset + << "\" />\n"; + offset += (bytesPerByteVal + bytesCellOffsets); + out << " <DataArray type=\"UInt8\" Name=\"types\" format=\"appended\" offset=\"" << offset << "\" />\n "; + offset += (bytesPerByteVal + bytesCellTypes); + out << " </Cells>\n"; + + // DATA SECTION + out << " <CellData>\n"; + for (size_t s = 0; s < datanames.size(); ++s) { + out << " <DataArray type=\"Float32\" Name=\"" << datanames[s] << "\" format=\"appended\" offset=\"" + << offset << "\" /> \n"; + offset += (bytesPerByteVal + bytesScalarData); + } + out << " </CellData>\n"; + + out << " </Piece>\n"; + out << " </UnstructuredGrid>\n"; + + // AppendedData SECTION + out << " <AppendedData encoding=\"raw\">\n"; + out << "_"; + + // POINTS SECTION + out.write((char *)&bytesPoints, bytesPerByteVal); + for (int n = 0; n < nofNodes; n++) { + out.write((char *)&val<1>(nodes[n]), sizeof(float)); + out.write((char *)&val<2>(nodes[n]), sizeof(float)); + out.write((char *)&val<3>(nodes[n]), sizeof(float)); + } + + // CELLS SECTION + // cellConnectivity + out.write((char *)&bytesCellConnectivty, bytesPerByteVal); + for (int c = 0; c < nofCells; c++) { + out.write((char *)&val<1>(cells[c]), sizeof(int)); + out.write((char *)&val<2>(cells[c]), sizeof(int)); + out.write((char *)&val<4>(cells[c]), sizeof(int)); + out.write((char *)&val<3>(cells[c]), sizeof(int)); + out.write((char *)&val<5>(cells[c]), sizeof(int)); + out.write((char *)&val<6>(cells[c]), sizeof(int)); + out.write((char *)&val<8>(cells[c]), sizeof(int)); + out.write((char *)&val<7>(cells[c]), sizeof(int)); + } + + // cellOffsets + out.write((char *)&bytesCellOffsets, bytesPerByteVal); + int itmp; + for (int c = 1; c <= nofCells; c++) { + itmp = 8 * c; + out.write((char *)&itmp, sizeof(int)); + } + + // cellTypes + out.write((char *)&bytesCellTypes, bytesPerByteVal); + unsigned char vtkCellType = 11; + for (int c = 0; c < nofCells; c++) { + out.write((char *)&vtkCellType, sizeof(unsigned char)); + } + + // DATA SECTION + // scalarData + for (size_t s = 0; s < datanames.size(); ++s) { + out.write((char *)&bytesScalarData, bytesPerByteVal); + for (size_t d = 0; d < celldata[s].size(); ++d) { + // loake kopie machen, da in celldata "doubles" sind + float tmp = (float)celldata[s][d]; + out.write((char *)&tmp, sizeof(float)); + } + } + out << "\n</AppendedData>\n"; + out << "</VTKFile>"; + out << endl; + out.close(); + UBLOG(logDEBUG1, "WbWriterVtkXmlBinary::writeOctsWithCellData to " << vtkfilename << " - end"); + + return vtkfilename; } /*===============================================================================*/ -string WbWriterVtkXmlBinary::writeOctsWithNodeData(const string& filename,vector<UbTupleFloat3 >& nodes, vector<UbTupleUInt8 >& cells, vector<string >& datanames, vector<vector<double > >& nodedata) +string WbWriterVtkXmlBinary::writeOctsWithNodeData(const string &filename, vector<UbTupleFloat3> &nodes, + vector<UbTupleUInt8> &cells, vector<string> &datanames, + vector<vector<double>> &nodedata) { - string vtkfilename = filename+getFileExtension(); - UBLOG(logDEBUG1,"WbWriterVtkXmlBinary::writeOctsWithNodeData to "<<vtkfilename<<" - start"); - - ofstream out(vtkfilename.c_str(),ios::out | ios::binary); - if(!out) - { - out.clear(); //flags ruecksetzen (ansonsten liefert utern if(!out) weiterhin true!!! - string path = UbSystem::getPathFromString(vtkfilename); - if(path.size()>0){ UbSystem::makeDirectory(path); out.open(vtkfilename.c_str(),ios::out | ios::binary);} - if(!out) throw UbException(UB_EXARGS,"couldn't open file "+vtkfilename); - } - - int nofNodes = (int)nodes.size(); - int nofCells = (int)cells.size(); - - int bytesPerByteVal = 4; //==sizeof(int) - int bytesPoints = 3 /*x1/x2/x3 */ * nofNodes * sizeof(float); - int bytesCellConnectivty = 8 /*nodes per oct */ * nofCells * sizeof(int ); - int bytesCellOffsets = 1 /*offset per oct*/ * nofCells * sizeof(int ); - int bytesCellTypes = 1 /*type of oct */ * nofCells * sizeof(unsigned char); - int bytesScalarData = 1 /*scalar */ * nofNodes * sizeof(double); - - unsigned long long offset = 0; - //VTK FILE - out<<"<?xml version=\"2.0\"?>\n"; - out<<"<VTKFile type=\"UnstructuredGrid\" version=\"0.1\" byte_order=\"LittleEndian\" >"<<"\n"; - out<<" <UnstructuredGrid>"<<"\n"; - out<<" <Piece NumberOfPoints=\""<<nofNodes<<"\" NumberOfCells=\""<<nofCells<<"\">\n"; - - //POINTS SECTION - out<<" <Points>\n"; - out<<" <DataArray type=\"Float32\" NumberOfComponents=\"3\" format=\"appended\" offset=\""<< offset <<"\" />\n"; - out<<" </Points>\n"; - offset += (bytesPerByteVal + bytesPoints); - - //CELLS SECTION - out<<" <Cells>\n"; - out<<" <DataArray type=\"Int32\" Name=\"connectivity\" format=\"appended\" offset=\""<< offset <<"\" />\n"; - offset += (bytesPerByteVal + bytesCellConnectivty); - out<<" <DataArray type=\"Int32\" Name=\"offsets\" format=\"appended\" offset=\""<< offset <<"\" />\n"; - offset += (bytesPerByteVal + bytesCellOffsets); - out<<" <DataArray type=\"UInt8\" Name=\"types\" format=\"appended\" offset=\""<< offset <<"\" />\n "; - offset += (bytesPerByteVal + bytesCellTypes); - out<<" </Cells>\n"; - - //DATA SECTION - out<<" <PointData>\n"; - for(size_t s=0; s<datanames.size(); ++s) - { - out<< " <DataArray type=\"Float64\" Name=\""<< datanames[s] <<"\" format=\"appended\" offset=\""<< offset <<"\" /> \n"; - offset += (bytesPerByteVal + bytesScalarData); - } - out<<" </PointData>\n"; - - out<<" </Piece>\n"; - out<<" </UnstructuredGrid>\n"; - - // AppendedData SECTION - out<<" <AppendedData encoding=\"raw\">\n"; - out<<"_"; - - //POINTS SECTION - out.write((char*)&bytesPoints,bytesPerByteVal); - for(int n=0; n<nofNodes; n++) - { - out.write((char*)&val<1>(nodes[n]),sizeof(float)); - out.write((char*)&val<2>(nodes[n]),sizeof(float)); - out.write((char*)&val<3>(nodes[n]),sizeof(float)); - } - - //CELLS SECTION - //cellConnectivity - out.write( (char*)&bytesCellConnectivty, bytesPerByteVal ); - for(int c=0; c<nofCells; c++) - { - out.write( (char*)&val<1>(cells[c]), sizeof(int) ); - out.write( (char*)&val<2>(cells[c]), sizeof(int) ); - out.write( (char*)&val<4>(cells[c]), sizeof(int) ); - out.write( (char*)&val<3>(cells[c]), sizeof(int) ); - out.write( (char*)&val<5>(cells[c]), sizeof(int) ); - out.write( (char*)&val<6>(cells[c]), sizeof(int) ); - out.write( (char*)&val<8>(cells[c]), sizeof(int) ); - out.write( (char*)&val<7>(cells[c]), sizeof(int) ); - } - - //cellOffsets - out.write( (char*)&bytesCellOffsets, bytesPerByteVal ); - int itmp; - for(int c=1; c<=nofCells; c++) - { - itmp = 8 * c; - out.write( (char*)&itmp, sizeof(int) ); - } - - //cellTypes - out.write( (char*)&bytesCellTypes, bytesPerByteVal ); - unsigned char vtkCellType = 11; - for(int c=0; c<nofCells; c++) - { - out.write( (char*)&vtkCellType, sizeof(unsigned char) ); - } - - //DATA SECTION - //scalarData - for(size_t s=0; s<datanames.size(); ++s) - { - out.write((char*)&bytesScalarData,bytesPerByteVal); - for(size_t d=0; d<nodedata[s].size(); ++d) - { - //loake kopie machen, da in nodedata "doubles" sind - //float tmp = (float)nodedata[s][d]; - //out.write((char*)&tmp,sizeof(float)); - double tmp = nodedata[s][d]; - out.write((char*)&tmp,sizeof(double)); - } - } - out<<"\n</AppendedData>\n"; - out<<"</VTKFile>"; - out<<endl; - out.close(); - UBLOG(logDEBUG1,"WbWriterVtkXmlBinary::writeOctsWithNodeData to "<<vtkfilename<<" - end"); - - return vtkfilename; + string vtkfilename = filename + getFileExtension(); + UBLOG(logDEBUG1, "WbWriterVtkXmlBinary::writeOctsWithNodeData to " << vtkfilename << " - start"); + + ofstream out(vtkfilename.c_str(), ios::out | ios::binary); + if (!out) { + out.clear(); // flags ruecksetzen (ansonsten liefert utern if(!out) weiterhin true!!! + string path = UbSystem::getPathFromString(vtkfilename); + if (path.size() > 0) { + UbSystem::makeDirectory(path); + out.open(vtkfilename.c_str(), ios::out | ios::binary); + } + if (!out) + throw UbException(UB_EXARGS, "couldn't open file " + vtkfilename); + } + + int nofNodes = (int)nodes.size(); + int nofCells = (int)cells.size(); + + int bytesPerByteVal = 4; //==sizeof(int) + int bytesPoints = 3 /*x1/x2/x3 */ * nofNodes * sizeof(float); + int bytesCellConnectivty = 8 /*nodes per oct */ * nofCells * sizeof(int); + int bytesCellOffsets = 1 /*offset per oct*/ * nofCells * sizeof(int); + int bytesCellTypes = 1 /*type of oct */ * nofCells * sizeof(unsigned char); + int bytesScalarData = 1 /*scalar */ * nofNodes * sizeof(double); + + unsigned long long offset = 0; + // VTK FILE + out << "<?xml version=\"2.0\"?>\n"; + out << "<VTKFile type=\"UnstructuredGrid\" version=\"0.1\" byte_order=\"LittleEndian\" >" + << "\n"; + out << " <UnstructuredGrid>" + << "\n"; + out << " <Piece NumberOfPoints=\"" << nofNodes << "\" NumberOfCells=\"" << nofCells << "\">\n"; + + // POINTS SECTION + out << " <Points>\n"; + out << " <DataArray type=\"Float32\" NumberOfComponents=\"3\" format=\"appended\" offset=\"" << offset + << "\" />\n"; + out << " </Points>\n"; + offset += (bytesPerByteVal + bytesPoints); + + // CELLS SECTION + out << " <Cells>\n"; + out << " <DataArray type=\"Int32\" Name=\"connectivity\" format=\"appended\" offset=\"" << offset + << "\" />\n"; + offset += (bytesPerByteVal + bytesCellConnectivty); + out << " <DataArray type=\"Int32\" Name=\"offsets\" format=\"appended\" offset=\"" << offset + << "\" />\n"; + offset += (bytesPerByteVal + bytesCellOffsets); + out << " <DataArray type=\"UInt8\" Name=\"types\" format=\"appended\" offset=\"" << offset << "\" />\n "; + offset += (bytesPerByteVal + bytesCellTypes); + out << " </Cells>\n"; + + // DATA SECTION + out << " <PointData>\n"; + for (size_t s = 0; s < datanames.size(); ++s) { + out << " <DataArray type=\"Float64\" Name=\"" << datanames[s] << "\" format=\"appended\" offset=\"" + << offset << "\" /> \n"; + offset += (bytesPerByteVal + bytesScalarData); + } + out << " </PointData>\n"; + + out << " </Piece>\n"; + out << " </UnstructuredGrid>\n"; + + // AppendedData SECTION + out << " <AppendedData encoding=\"raw\">\n"; + out << "_"; + + // POINTS SECTION + out.write((char *)&bytesPoints, bytesPerByteVal); + for (int n = 0; n < nofNodes; n++) { + out.write((char *)&val<1>(nodes[n]), sizeof(float)); + out.write((char *)&val<2>(nodes[n]), sizeof(float)); + out.write((char *)&val<3>(nodes[n]), sizeof(float)); + } + + // CELLS SECTION + // cellConnectivity + out.write((char *)&bytesCellConnectivty, bytesPerByteVal); + for (int c = 0; c < nofCells; c++) { + out.write((char *)&val<1>(cells[c]), sizeof(int)); + out.write((char *)&val<2>(cells[c]), sizeof(int)); + out.write((char *)&val<4>(cells[c]), sizeof(int)); + out.write((char *)&val<3>(cells[c]), sizeof(int)); + out.write((char *)&val<5>(cells[c]), sizeof(int)); + out.write((char *)&val<6>(cells[c]), sizeof(int)); + out.write((char *)&val<8>(cells[c]), sizeof(int)); + out.write((char *)&val<7>(cells[c]), sizeof(int)); + } + + // cellOffsets + out.write((char *)&bytesCellOffsets, bytesPerByteVal); + int itmp; + for (int c = 1; c <= nofCells; c++) { + itmp = 8 * c; + out.write((char *)&itmp, sizeof(int)); + } + + // cellTypes + out.write((char *)&bytesCellTypes, bytesPerByteVal); + unsigned char vtkCellType = 11; + for (int c = 0; c < nofCells; c++) { + out.write((char *)&vtkCellType, sizeof(unsigned char)); + } + + // DATA SECTION + // scalarData + for (size_t s = 0; s < datanames.size(); ++s) { + out.write((char *)&bytesScalarData, bytesPerByteVal); + for (size_t d = 0; d < nodedata[s].size(); ++d) { + // loake kopie machen, da in nodedata "doubles" sind + // float tmp = (float)nodedata[s][d]; + // out.write((char*)&tmp,sizeof(float)); + double tmp = nodedata[s][d]; + out.write((char *)&tmp, sizeof(double)); + } + } + out << "\n</AppendedData>\n"; + out << "</VTKFile>"; + out << endl; + out.close(); + UBLOG(logDEBUG1, "WbWriterVtkXmlBinary::writeOctsWithNodeData to " << vtkfilename << " - end"); + + return vtkfilename; } /*===============================================================================*/ -string WbWriterVtkXmlBinary::writeOcts(const string& filename,vector< UbTupleFloat3 >& nodes, vector< UbTupleInt8 >& cells) +string WbWriterVtkXmlBinary::writeOcts(const string &filename, vector<UbTupleFloat3> &nodes, vector<UbTupleInt8> &cells) { - string vtkfilename = filename+getFileExtension(); - UBLOG(logDEBUG1,"WbWriterVtkXmlBinary::writeOcts to "<<vtkfilename<<" - start"); - - ofstream out(vtkfilename.c_str(),ios::out | ios::binary); - if(!out) - { - out.clear(); //flags ruecksetzen (ansonsten liefert utern if(!out) weiterhin true!!! - string path = UbSystem::getPathFromString(vtkfilename); - if(path.size()>0){ UbSystem::makeDirectory(path); out.open(vtkfilename.c_str(),ios::out | ios::binary);} - if(!out) throw UbException(UB_EXARGS,"couldn't open file "+vtkfilename); - } - - int nofNodes = (int)nodes.size(); - int nofCells = (int)cells.size(); - - int bytesPerByteVal = 4; //==sizeof(int) - int bytesPoints = 3 /*x1/x2/x3 */ * nofNodes * sizeof(float); - int bytesCellConnectivty = 8 /*nodes per oct */ * nofCells * sizeof(int ); - int bytesCellOffsets = 1 /*offset per oct*/ * nofCells * sizeof(int ); - int bytesCellTypes = 1 /*type of oct */ * nofCells * sizeof(unsigned char); - //int bytesScalarData = 1 /*scalar */ * nofNodes * sizeof(float); - - int offset = 0; - //VTK FILE - out<<"<?xml version=\"1.0\"?>\n"; - out<<"<VTKFile type=\"UnstructuredGrid\" version=\"0.1\" byte_order=\"LittleEndian\" >"<<"\n"; - out<<" <UnstructuredGrid>"<<"\n"; - out<<" <Piece NumberOfPoints=\""<<nofNodes<<"\" NumberOfCells=\""<<nofCells<<"\">\n"; - - //POINTS SECTION - out<<" <Points>\n"; - out<<" <DataArray type=\"Float32\" NumberOfComponents=\"3\" format=\"appended\" offset=\""<< offset <<"\" />\n"; - out<<" </Points>\n"; - offset += (bytesPerByteVal + bytesPoints); - - //CELLS SECTION - out<<" <Cells>\n"; - out<<" <DataArray type=\"Int32\" Name=\"connectivity\" format=\"appended\" offset=\""<< offset <<"\" />\n"; - offset += (bytesPerByteVal + bytesCellConnectivty); - out<<" <DataArray type=\"Int32\" Name=\"offsets\" format=\"appended\" offset=\""<< offset <<"\" />\n"; - offset += (bytesPerByteVal + bytesCellOffsets); - out<<" <DataArray type=\"UInt8\" Name=\"types\" format=\"appended\" offset=\""<< offset <<"\" />\n "; - offset += (bytesPerByteVal + bytesCellTypes); - out<<" </Cells>\n"; - - out<<" </Piece>\n"; - out<<" </UnstructuredGrid>\n"; - - // AppendedData SECTION - out<<" <AppendedData encoding=\"raw\">\n"; - out<<"_"; - - //POINTS SECTION - out.write((char*)&bytesPoints,bytesPerByteVal); - for(int n=0; n<nofNodes; n++) - { - out.write((char*)&val<1>(nodes[n]),sizeof(float)); - out.write((char*)&val<2>(nodes[n]),sizeof(float)); - out.write((char*)&val<3>(nodes[n]),sizeof(float)); - } - - //CELLS SECTION - //cellConnectivity - out.write( (char*)&bytesCellConnectivty, bytesPerByteVal ); - for(int c=0; c<nofCells; c++) - { - out.write( (char*)&val<1>(cells[c]), sizeof(int) ); - out.write( (char*)&val<2>(cells[c]), sizeof(int) ); - out.write( (char*)&val<4>(cells[c]), sizeof(int) ); - out.write( (char*)&val<3>(cells[c]), sizeof(int) ); - out.write( (char*)&val<5>(cells[c]), sizeof(int) ); - out.write( (char*)&val<6>(cells[c]), sizeof(int) ); - out.write( (char*)&val<8>(cells[c]), sizeof(int) ); - out.write( (char*)&val<7>(cells[c]), sizeof(int) ); - } - - //cellOffsets - out.write( (char*)&bytesCellOffsets, bytesPerByteVal ); - int itmp; - for(int c=1; c<=nofCells; c++) - { - itmp = 8 * c; - out.write( (char*)&itmp, sizeof(int) ); - } - - //cellTypes - out.write( (char*)&bytesCellTypes, bytesPerByteVal ); - unsigned char vtkCellType = 11; - for(int c=0; c<nofCells; c++) - { - out.write( (char*)&vtkCellType, sizeof(unsigned char) ); - } - out<<"\n</AppendedData>\n"; - out<<"</VTKFile>"; - out<<endl; - out.close(); - UBLOG(logDEBUG1,"WbWriterVtkXmlBinary::writeOcts to "<<vtkfilename<<" - end"); - - return vtkfilename; + string vtkfilename = filename + getFileExtension(); + UBLOG(logDEBUG1, "WbWriterVtkXmlBinary::writeOcts to " << vtkfilename << " - start"); + + ofstream out(vtkfilename.c_str(), ios::out | ios::binary); + if (!out) { + out.clear(); // flags ruecksetzen (ansonsten liefert utern if(!out) weiterhin true!!! + string path = UbSystem::getPathFromString(vtkfilename); + if (path.size() > 0) { + UbSystem::makeDirectory(path); + out.open(vtkfilename.c_str(), ios::out | ios::binary); + } + if (!out) + throw UbException(UB_EXARGS, "couldn't open file " + vtkfilename); + } + + int nofNodes = (int)nodes.size(); + int nofCells = (int)cells.size(); + + int bytesPerByteVal = 4; //==sizeof(int) + int bytesPoints = 3 /*x1/x2/x3 */ * nofNodes * sizeof(float); + int bytesCellConnectivty = 8 /*nodes per oct */ * nofCells * sizeof(int); + int bytesCellOffsets = 1 /*offset per oct*/ * nofCells * sizeof(int); + int bytesCellTypes = 1 /*type of oct */ * nofCells * sizeof(unsigned char); + // int bytesScalarData = 1 /*scalar */ * nofNodes * sizeof(float); + + int offset = 0; + // VTK FILE + out << "<?xml version=\"1.0\"?>\n"; + out << "<VTKFile type=\"UnstructuredGrid\" version=\"0.1\" byte_order=\"LittleEndian\" >" + << "\n"; + out << " <UnstructuredGrid>" + << "\n"; + out << " <Piece NumberOfPoints=\"" << nofNodes << "\" NumberOfCells=\"" << nofCells << "\">\n"; + + // POINTS SECTION + out << " <Points>\n"; + out << " <DataArray type=\"Float32\" NumberOfComponents=\"3\" format=\"appended\" offset=\"" << offset + << "\" />\n"; + out << " </Points>\n"; + offset += (bytesPerByteVal + bytesPoints); + + // CELLS SECTION + out << " <Cells>\n"; + out << " <DataArray type=\"Int32\" Name=\"connectivity\" format=\"appended\" offset=\"" << offset + << "\" />\n"; + offset += (bytesPerByteVal + bytesCellConnectivty); + out << " <DataArray type=\"Int32\" Name=\"offsets\" format=\"appended\" offset=\"" << offset + << "\" />\n"; + offset += (bytesPerByteVal + bytesCellOffsets); + out << " <DataArray type=\"UInt8\" Name=\"types\" format=\"appended\" offset=\"" << offset << "\" />\n "; + offset += (bytesPerByteVal + bytesCellTypes); + out << " </Cells>\n"; + + out << " </Piece>\n"; + out << " </UnstructuredGrid>\n"; + + // AppendedData SECTION + out << " <AppendedData encoding=\"raw\">\n"; + out << "_"; + + // POINTS SECTION + out.write((char *)&bytesPoints, bytesPerByteVal); + for (int n = 0; n < nofNodes; n++) { + out.write((char *)&val<1>(nodes[n]), sizeof(float)); + out.write((char *)&val<2>(nodes[n]), sizeof(float)); + out.write((char *)&val<3>(nodes[n]), sizeof(float)); + } + + // CELLS SECTION + // cellConnectivity + out.write((char *)&bytesCellConnectivty, bytesPerByteVal); + for (int c = 0; c < nofCells; c++) { + out.write((char *)&val<1>(cells[c]), sizeof(int)); + out.write((char *)&val<2>(cells[c]), sizeof(int)); + out.write((char *)&val<4>(cells[c]), sizeof(int)); + out.write((char *)&val<3>(cells[c]), sizeof(int)); + out.write((char *)&val<5>(cells[c]), sizeof(int)); + out.write((char *)&val<6>(cells[c]), sizeof(int)); + out.write((char *)&val<8>(cells[c]), sizeof(int)); + out.write((char *)&val<7>(cells[c]), sizeof(int)); + } + + // cellOffsets + out.write((char *)&bytesCellOffsets, bytesPerByteVal); + int itmp; + for (int c = 1; c <= nofCells; c++) { + itmp = 8 * c; + out.write((char *)&itmp, sizeof(int)); + } + + // cellTypes + out.write((char *)&bytesCellTypes, bytesPerByteVal); + unsigned char vtkCellType = 11; + for (int c = 0; c < nofCells; c++) { + out.write((char *)&vtkCellType, sizeof(unsigned char)); + } + out << "\n</AppendedData>\n"; + out << "</VTKFile>"; + out << endl; + out.close(); + UBLOG(logDEBUG1, "WbWriterVtkXmlBinary::writeOcts to " << vtkfilename << " - end"); + + return vtkfilename; } -std::string WbWriterVtkXmlBinary::writeNodes(const std::string& filename,std::vector< UbTupleFloat3 >& nodes) +std::string WbWriterVtkXmlBinary::writeNodes(const std::string &filename, std::vector<UbTupleFloat3> &nodes) { - string vtkfilename = filename+getFileExtension(); - UBLOG(logDEBUG1,"WbWriterVtkXmlBinary::writeNodes to "<<vtkfilename<<" - start"); - - ofstream out(vtkfilename.c_str(),ios::out | ios::binary); - if(!out) - { - out.clear(); //flags ruecksetzen (ansonsten liefert utern if(!out) weiterhin true!!! - string path = UbSystem::getPathFromString(vtkfilename); - if(path.size()>0){ UbSystem::makeDirectory(path); out.open(vtkfilename.c_str(),ios::out | ios::binary);} - if(!out) throw UbException(UB_EXARGS,"couldn't open file "+vtkfilename); - } - - int nofNodes = (int)nodes.size(); - - int bytesPerByteVal = 4; //==sizeof(int) - int bytesPoints = 3 /*x1/x2/x3 */ * nofNodes * sizeof(float); - int bytesCellConnectivty = 1 /*nodes per cell */ * nofNodes * sizeof(int ); - int bytesCellOffsets = 1 /*offset per cell */ * nofNodes * sizeof(int ); - int bytesCellTypes = 1 /*type of line */ * nofNodes * sizeof(unsigned char); - - int offset = 0; - //VTK FILE - out<<"<?xml version=\"1.0\"?>\n"; - out<<"<VTKFile type=\"UnstructuredGrid\" version=\"0.1\" byte_order=\"LittleEndian\" >"<<"\n"; - out<<" <UnstructuredGrid>"<<"\n"; - out<<" <Piece NumberOfPoints=\""<<nofNodes<<"\" NumberOfCells=\""<<nofNodes<<"\">\n"; - - //POINTS SECTION - out<<" <Points>\n"; - out<<" <DataArray type=\"Float32\" NumberOfComponents=\"3\" format=\"appended\" offset=\""<< offset <<"\" />\n"; - out<<" </Points>\n"; - offset += (bytesPerByteVal + bytesPoints); - - //CELLS SECTION - out<<" <Cells>\n"; - out<<" <DataArray type=\"Int32\" Name=\"connectivity\" format=\"appended\" offset=\""<< offset <<"\" />\n"; - offset += (bytesPerByteVal + bytesCellConnectivty); - out<<" <DataArray type=\"Int32\" Name=\"offsets\" format=\"appended\" offset=\""<< offset <<"\" />\n"; - offset += (bytesPerByteVal + bytesCellOffsets); - out<<" <DataArray type=\"UInt8\" Name=\"types\" format=\"appended\" offset=\""<< offset <<"\" />\n "; - offset += (bytesPerByteVal + bytesCellTypes); - out<<" </Cells>\n"; - - out<<" </Piece>\n"; - out<<" </UnstructuredGrid>\n"; - - // AppendedData SECTION - out<<" <AppendedData encoding=\"raw\">\n"; - out<<"_"; - - //POINTS SECTION - out.write((char*)&bytesPoints,bytesPerByteVal); - for(int n=0; n<nofNodes; n++) - { - out.write((char*)&val<1>(nodes[n]),sizeof(float)); - out.write((char*)&val<2>(nodes[n]),sizeof(float)); - out.write((char*)&val<3>(nodes[n]),sizeof(float)); - } - - //CELLS SECTION - //cellConnectivity - out.write( (char*)&bytesCellConnectivty, bytesPerByteVal ); - for(int c=0; c<nofNodes; c++) - out.write( (char*)&c, sizeof(int) ); - - //cellOffsets - out.write( (char*)&bytesCellOffsets, bytesPerByteVal ); - for(int c=1; c<=nofNodes; c++) - out.write( (char*)&c, sizeof(int) ); - - //cellTypes - out.write( (char*)&bytesCellTypes, bytesPerByteVal ); - unsigned char vtkCellType = 1; - for(int c=0; c<nofNodes; c++) - out.write( (char*)&vtkCellType, sizeof(unsigned char) ); - - out<<"\n</AppendedData>\n"; - out<<"</VTKFile>"; - out<<endl; - out.close(); - UBLOG(logDEBUG1,"WbWriterVtkXmlBinary::writeNodes to "<<vtkfilename<<" - end"); - - return vtkfilename; + string vtkfilename = filename + getFileExtension(); + UBLOG(logDEBUG1, "WbWriterVtkXmlBinary::writeNodes to " << vtkfilename << " - start"); + + ofstream out(vtkfilename.c_str(), ios::out | ios::binary); + if (!out) { + out.clear(); // flags ruecksetzen (ansonsten liefert utern if(!out) weiterhin true!!! + string path = UbSystem::getPathFromString(vtkfilename); + if (path.size() > 0) { + UbSystem::makeDirectory(path); + out.open(vtkfilename.c_str(), ios::out | ios::binary); + } + if (!out) + throw UbException(UB_EXARGS, "couldn't open file " + vtkfilename); + } + + int nofNodes = (int)nodes.size(); + + int bytesPerByteVal = 4; //==sizeof(int) + int bytesPoints = 3 /*x1/x2/x3 */ * nofNodes * sizeof(float); + int bytesCellConnectivty = 1 /*nodes per cell */ * nofNodes * sizeof(int); + int bytesCellOffsets = 1 /*offset per cell */ * nofNodes * sizeof(int); + int bytesCellTypes = 1 /*type of line */ * nofNodes * sizeof(unsigned char); + + int offset = 0; + // VTK FILE + out << "<?xml version=\"1.0\"?>\n"; + out << "<VTKFile type=\"UnstructuredGrid\" version=\"0.1\" byte_order=\"LittleEndian\" >" + << "\n"; + out << " <UnstructuredGrid>" + << "\n"; + out << " <Piece NumberOfPoints=\"" << nofNodes << "\" NumberOfCells=\"" << nofNodes << "\">\n"; + + // POINTS SECTION + out << " <Points>\n"; + out << " <DataArray type=\"Float32\" NumberOfComponents=\"3\" format=\"appended\" offset=\"" << offset + << "\" />\n"; + out << " </Points>\n"; + offset += (bytesPerByteVal + bytesPoints); + + // CELLS SECTION + out << " <Cells>\n"; + out << " <DataArray type=\"Int32\" Name=\"connectivity\" format=\"appended\" offset=\"" << offset + << "\" />\n"; + offset += (bytesPerByteVal + bytesCellConnectivty); + out << " <DataArray type=\"Int32\" Name=\"offsets\" format=\"appended\" offset=\"" << offset + << "\" />\n"; + offset += (bytesPerByteVal + bytesCellOffsets); + out << " <DataArray type=\"UInt8\" Name=\"types\" format=\"appended\" offset=\"" << offset << "\" />\n "; + offset += (bytesPerByteVal + bytesCellTypes); + out << " </Cells>\n"; + + out << " </Piece>\n"; + out << " </UnstructuredGrid>\n"; + + // AppendedData SECTION + out << " <AppendedData encoding=\"raw\">\n"; + out << "_"; + + // POINTS SECTION + out.write((char *)&bytesPoints, bytesPerByteVal); + for (int n = 0; n < nofNodes; n++) { + out.write((char *)&val<1>(nodes[n]), sizeof(float)); + out.write((char *)&val<2>(nodes[n]), sizeof(float)); + out.write((char *)&val<3>(nodes[n]), sizeof(float)); + } + + // CELLS SECTION + // cellConnectivity + out.write((char *)&bytesCellConnectivty, bytesPerByteVal); + for (int c = 0; c < nofNodes; c++) + out.write((char *)&c, sizeof(int)); + + // cellOffsets + out.write((char *)&bytesCellOffsets, bytesPerByteVal); + for (int c = 1; c <= nofNodes; c++) + out.write((char *)&c, sizeof(int)); + + // cellTypes + out.write((char *)&bytesCellTypes, bytesPerByteVal); + unsigned char vtkCellType = 1; + for (int c = 0; c < nofNodes; c++) + out.write((char *)&vtkCellType, sizeof(unsigned char)); + + out << "\n</AppendedData>\n"; + out << "</VTKFile>"; + out << endl; + out.close(); + UBLOG(logDEBUG1, "WbWriterVtkXmlBinary::writeNodes to " << vtkfilename << " - end"); + + return vtkfilename; } -std::string WbWriterVtkXmlBinary::writeNodesWithNodeData(const std::string& filename,std::vector< UbTupleFloat3 >& nodes, std::vector<std::string >& datanames, std::vector<std::vector<double > >& nodedata) +std::string WbWriterVtkXmlBinary::writeNodesWithNodeData(const std::string &filename, std::vector<UbTupleFloat3> &nodes, + std::vector<std::string> &datanames, + std::vector<std::vector<double>> &nodedata) { - string vtkfilename = filename+getFileExtension(); - UBLOG(logDEBUG1,"WbWriterVtkXmlBinary::writeNodesWithNodeData to "<<vtkfilename<<" - start"); - - ofstream out(vtkfilename.c_str(),ios::out | ios::binary); - if(!out) - { - out.clear(); //flags ruecksetzen (ansonsten liefert utern if(!out) weiterhin true!!! - string path = UbSystem::getPathFromString(vtkfilename); - if(path.size()>0){ UbSystem::makeDirectory(path); out.open(vtkfilename.c_str(),ios::out | ios::binary);} - if(!out) throw UbException(UB_EXARGS,"couldn't open file "+vtkfilename); - } - - int nofNodes = (int)nodes.size(); - - int bytesPerByteVal = 4; //==sizeof(int) - int bytesPoints = 3 /*x1/x2/x3 */ * nofNodes * sizeof(float); - int bytesCellConnectivty = 1 /*nodes per cell */ * nofNodes * sizeof(int ); - int bytesCellOffsets = 1 /*offset per cell*/ * nofNodes * sizeof(int ); - int bytesCellTypes = 1 /*type of oct */ * nofNodes * sizeof(unsigned char); - int bytesScalarData = 1 /*scalar */ * nofNodes * sizeof(double); - - int offset = 0; - //VTK FILE - out<<"<?xml version=\"1.0\"?>\n"; - out<<"<VTKFile type=\"UnstructuredGrid\" version=\"0.1\" byte_order=\"LittleEndian\" >"<<"\n"; - out<<" <UnstructuredGrid>"<<"\n"; - out<<" <Piece NumberOfPoints=\""<<nofNodes<<"\" NumberOfCells=\""<<nofNodes<<"\">\n"; - - //POINTS SECTION - out<<" <Points>\n"; - out<<" <DataArray type=\"Float32\" NumberOfComponents=\"3\" format=\"appended\" offset=\""<< offset <<"\" />\n"; - out<<" </Points>\n"; - offset += (bytesPerByteVal + bytesPoints); - - //CELLS SECTION - out<<" <Cells>\n"; - out<<" <DataArray type=\"Int32\" Name=\"connectivity\" format=\"appended\" offset=\""<< offset <<"\" />\n"; - offset += (bytesPerByteVal + bytesCellConnectivty); - out<<" <DataArray type=\"Int32\" Name=\"offsets\" format=\"appended\" offset=\""<< offset <<"\" />\n"; - offset += (bytesPerByteVal + bytesCellOffsets); - out<<" <DataArray type=\"UInt8\" Name=\"types\" format=\"appended\" offset=\""<< offset <<"\" />\n "; - offset += (bytesPerByteVal + bytesCellTypes); - out<<" </Cells>\n"; - - //DATA SECTION - out<<" <PointData>\n"; - for(size_t s=0; s<datanames.size(); ++s) - { - out<< " <DataArray type=\"Float64\" Name=\""<< datanames[s] <<"\" format=\"appended\" offset=\""<< offset <<"\" /> \n"; - offset += (bytesPerByteVal + bytesScalarData); - } - out<<" </PointData>\n"; - - out<<" </Piece>\n"; - out<<" </UnstructuredGrid>\n"; - - // AppendedData SECTION - out<<" <AppendedData encoding=\"raw\">\n"; - out<<"_"; - - //POINTS SECTION - out.write((char*)&bytesPoints,bytesPerByteVal); - for(int n=0; n<nofNodes; n++) - { - out.write((char*)&val<1>(nodes[n]),sizeof(float)); - out.write((char*)&val<2>(nodes[n]),sizeof(float)); - out.write((char*)&val<3>(nodes[n]),sizeof(float)); - } - - //CELLS SECTION - //cellConnectivity - out.write( (char*)&bytesCellConnectivty, bytesPerByteVal ); - for(int c=0; c<nofNodes; c++) - out.write( (char*)&c, sizeof(int) ); - - //cellOffsets - out.write( (char*)&bytesCellOffsets, bytesPerByteVal ); - for(int c=1; c<=nofNodes; c++) - out.write( (char*)&c, sizeof(int) ); - - //cellTypes - out.write( (char*)&bytesCellTypes, bytesPerByteVal ); - unsigned char vtkCellType = 1; - for(int c=0; c<nofNodes; c++) - out.write( (char*)&vtkCellType, sizeof(unsigned char) ); - - //DATA SECTION - //scalarData - for(size_t s=0; s<datanames.size(); ++s) - { - out.write((char*)&bytesScalarData,bytesPerByteVal); - for(size_t d=0; d<nodedata[s].size(); ++d) - { - //loake kopie machen, da in nodedata "doubles" sind - //float tmp = (float)nodedata[s][d]; - //out.write((char*)&tmp,sizeof(float)); - double tmp = nodedata[s][d]; - out.write((char*)&tmp, sizeof(double)); - } - } - out<<"\n</AppendedData>\n"; - out<<"</VTKFile>"; - out<<endl; - out.close(); - UBLOG(logDEBUG1,"WbWriterVtkXmlBinary::writeNodesWithNodeData to "<<vtkfilename<<" - end"); - - return vtkfilename; - + string vtkfilename = filename + getFileExtension(); + UBLOG(logDEBUG1, "WbWriterVtkXmlBinary::writeNodesWithNodeData to " << vtkfilename << " - start"); + + ofstream out(vtkfilename.c_str(), ios::out | ios::binary); + if (!out) { + out.clear(); // flags ruecksetzen (ansonsten liefert utern if(!out) weiterhin true!!! + string path = UbSystem::getPathFromString(vtkfilename); + if (path.size() > 0) { + UbSystem::makeDirectory(path); + out.open(vtkfilename.c_str(), ios::out | ios::binary); + } + if (!out) + throw UbException(UB_EXARGS, "couldn't open file " + vtkfilename); + } + + int nofNodes = (int)nodes.size(); + + int bytesPerByteVal = 4; //==sizeof(int) + int bytesPoints = 3 /*x1/x2/x3 */ * nofNodes * sizeof(float); + int bytesCellConnectivty = 1 /*nodes per cell */ * nofNodes * sizeof(int); + int bytesCellOffsets = 1 /*offset per cell*/ * nofNodes * sizeof(int); + int bytesCellTypes = 1 /*type of oct */ * nofNodes * sizeof(unsigned char); + int bytesScalarData = 1 /*scalar */ * nofNodes * sizeof(double); + + int offset = 0; + // VTK FILE + out << "<?xml version=\"1.0\"?>\n"; + out << "<VTKFile type=\"UnstructuredGrid\" version=\"0.1\" byte_order=\"LittleEndian\" >" + << "\n"; + out << " <UnstructuredGrid>" + << "\n"; + out << " <Piece NumberOfPoints=\"" << nofNodes << "\" NumberOfCells=\"" << nofNodes << "\">\n"; + + // POINTS SECTION + out << " <Points>\n"; + out << " <DataArray type=\"Float32\" NumberOfComponents=\"3\" format=\"appended\" offset=\"" << offset + << "\" />\n"; + out << " </Points>\n"; + offset += (bytesPerByteVal + bytesPoints); + + // CELLS SECTION + out << " <Cells>\n"; + out << " <DataArray type=\"Int32\" Name=\"connectivity\" format=\"appended\" offset=\"" << offset + << "\" />\n"; + offset += (bytesPerByteVal + bytesCellConnectivty); + out << " <DataArray type=\"Int32\" Name=\"offsets\" format=\"appended\" offset=\"" << offset + << "\" />\n"; + offset += (bytesPerByteVal + bytesCellOffsets); + out << " <DataArray type=\"UInt8\" Name=\"types\" format=\"appended\" offset=\"" << offset << "\" />\n "; + offset += (bytesPerByteVal + bytesCellTypes); + out << " </Cells>\n"; + + // DATA SECTION + out << " <PointData>\n"; + for (size_t s = 0; s < datanames.size(); ++s) { + out << " <DataArray type=\"Float64\" Name=\"" << datanames[s] << "\" format=\"appended\" offset=\"" + << offset << "\" /> \n"; + offset += (bytesPerByteVal + bytesScalarData); + } + out << " </PointData>\n"; + + out << " </Piece>\n"; + out << " </UnstructuredGrid>\n"; + + // AppendedData SECTION + out << " <AppendedData encoding=\"raw\">\n"; + out << "_"; + + // POINTS SECTION + out.write((char *)&bytesPoints, bytesPerByteVal); + for (int n = 0; n < nofNodes; n++) { + out.write((char *)&val<1>(nodes[n]), sizeof(float)); + out.write((char *)&val<2>(nodes[n]), sizeof(float)); + out.write((char *)&val<3>(nodes[n]), sizeof(float)); + } + + // CELLS SECTION + // cellConnectivity + out.write((char *)&bytesCellConnectivty, bytesPerByteVal); + for (int c = 0; c < nofNodes; c++) + out.write((char *)&c, sizeof(int)); + + // cellOffsets + out.write((char *)&bytesCellOffsets, bytesPerByteVal); + for (int c = 1; c <= nofNodes; c++) + out.write((char *)&c, sizeof(int)); + + // cellTypes + out.write((char *)&bytesCellTypes, bytesPerByteVal); + unsigned char vtkCellType = 1; + for (int c = 0; c < nofNodes; c++) + out.write((char *)&vtkCellType, sizeof(unsigned char)); + + // DATA SECTION + // scalarData + for (size_t s = 0; s < datanames.size(); ++s) { + out.write((char *)&bytesScalarData, bytesPerByteVal); + for (size_t d = 0; d < nodedata[s].size(); ++d) { + // loake kopie machen, da in nodedata "doubles" sind + // float tmp = (float)nodedata[s][d]; + // out.write((char*)&tmp,sizeof(float)); + double tmp = nodedata[s][d]; + out.write((char *)&tmp, sizeof(double)); + } + } + out << "\n</AppendedData>\n"; + out << "</VTKFile>"; + out << endl; + out.close(); + UBLOG(logDEBUG1, "WbWriterVtkXmlBinary::writeNodesWithNodeData to " << vtkfilename << " - end"); + + return vtkfilename; } diff --git a/src/basics/basics/writer/WbWriterVtkXmlBinary.h b/src/basics/basics/writer/WbWriterVtkXmlBinary.h index 2beda26b7aa4830b30d47c8bc1c0cddc24c4c730..393c6bb13b268805a3fc2ca0850dd75d3fdd5616 100644 --- a/src/basics/basics/writer/WbWriterVtkXmlBinary.h +++ b/src/basics/basics/writer/WbWriterVtkXmlBinary.h @@ -1,28 +1,28 @@ //======================================================================================= -// ____ ____ __ ______ __________ __ __ __ __ -// \ \ | | | | | _ \ |___ ___| | | | | / \ | | -// \ \ | | | | | |_) | | | | | | | / \ | | -// \ \ | | | | | _ / | | | | | | / /\ \ | | -// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ -// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| -// \ \ | | ________________________________________________________________ -// \ \ | | | ______________________________________________________________| -// \ \| | | | __ __ __ __ ______ _______ -// \ | | |_____ | | | | | | | | | _ \ / _____) -// \ | | _____| | | | | | | | | | | \ \ \_______ +// ____ ____ __ ______ __________ __ __ __ __ +// \ \ | | | | | _ \ |___ ___| | | | | / \ | | +// \ \ | | | | | |_) | | | | | | | / \ | | +// \ \ | | | | | _ / | | | | | | / /\ \ | | +// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ +// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| +// \ \ | | ________________________________________________________________ +// \ \ | | | ______________________________________________________________| +// \ \| | | | __ __ __ __ ______ _______ +// \ | | |_____ | | | | | | | | | _ \ / _____) +// \ | | _____| | | | | | | | | | | \ \ \_______ // \ | | | | |_____ | \_/ | | | | |_/ / _____ | -// \ _____| |__| |________| \_______/ |__| |______/ (_______/ +// \ _____| |__| |________| \_______/ |__| |______/ (_______/ // -// This file is part of VirtualFluids. VirtualFluids is free software: you can +// This file is part of VirtualFluids. VirtualFluids is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of +// License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. -// -// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// +// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License along // with VirtualFluids (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>. // @@ -37,87 +37,113 @@ #include <basics/writer/WbWriter.h> -class WbWriterVtkXmlBinary : public WbWriter +class WbWriterVtkXmlBinary : public WbWriter { public: - static WbWriterVtkXmlBinary* getInstance() - { - static WbWriterVtkXmlBinary instance; - return &instance; - } + static WbWriterVtkXmlBinary *getInstance() + { + static WbWriterVtkXmlBinary instance; + return &instance; + } - WbWriterVtkXmlBinary( const WbWriterVtkXmlBinary& ) = delete; - const WbWriterVtkXmlBinary& operator=( const WbWriterVtkXmlBinary& ) = delete; + WbWriterVtkXmlBinary(const WbWriterVtkXmlBinary &) = delete; + const WbWriterVtkXmlBinary &operator=(const WbWriterVtkXmlBinary &) = delete; private: - WbWriterVtkXmlBinary() : WbWriter() - { - if(sizeof(unsigned char)!=1) throw UbException(UB_EXARGS,"machine error char type mismatch"); - if(sizeof(int) !=4) throw UbException(UB_EXARGS,"machine error int type mismatch"); - if(sizeof(float) !=4) throw UbException(UB_EXARGS,"machine error float type mismatch"); - } - - static const std::string pvdEndTag; + WbWriterVtkXmlBinary() : WbWriter() + { + if (sizeof(unsigned char) != 1) + throw UbException(UB_EXARGS, "machine error char type mismatch"); + if (sizeof(int) != 4) + throw UbException(UB_EXARGS, "machine error int type mismatch"); + if (sizeof(float) != 4) + throw UbException(UB_EXARGS, "machine error float type mismatch"); + } + + static const std::string pvdEndTag; + public: - std::string getFileExtension() override { return ".bin.vtu"; } - - //write a metafile - std::string writeCollection(const std::string& filename, const std::vector<std::string>& filenames, const double& timestep, const bool& sepGroups); - std::string addFilesToCollection(const std::string& filename, const std::vector<std::string>& filenames, const double& timestep, const bool& sepGroups); - std::string writeParallelFile(const std::string& filename,std::vector<std::string>& pieceSources, std::vector<std::string>& pointDataNames, std::vector<std::string>& cellDataNames); - - ////////////////////////////////////////////////////////////////////////// - //nodes - std::string writeNodes(const std::string& filename,std::vector< UbTupleFloat3 >& nodes) override; - std::string writeNodesWithNodeData(const std::string& filename,std::vector< UbTupleFloat3 >& nodes, std::vector<std::string >& datanames, std::vector<std::vector<double > >& nodedata) override; - - ////////////////////////////////////////////////////////////////////////// - //lines - // 0 ---- 1 - //nodenumbering must start with 0! - std::string writeLines(const std::string& filename,std::vector<UbTupleFloat3 >& nodes, std::vector<UbTupleInt2 >& lines) override; - //std::string writeLinesWithNodeData(const std::string& filename,std::vector<UbTupleFloat3 >& nodes, std::vector<UbTupleInt2 >& lines, std::vector< std::string >& datanames, std::vector< std::vector< double > >& nodedata); + std::string getFileExtension() override { return ".bin.vtu"; } + + // write a metafile + std::string writeCollection(const std::string &filename, const std::vector<std::string> &filenames, + const double ×tep, const bool &sepGroups); + std::string addFilesToCollection(const std::string &filename, const std::vector<std::string> &filenames, + const double ×tep, const bool &sepGroups); + std::string writeParallelFile(const std::string &filename, std::vector<std::string> &pieceSources, + std::vector<std::string> &pointDataNames, std::vector<std::string> &cellDataNames); + + ////////////////////////////////////////////////////////////////////////// + // nodes + std::string writeNodes(const std::string &filename, std::vector<UbTupleFloat3> &nodes) override; + std::string writeNodesWithNodeData(const std::string &filename, std::vector<UbTupleFloat3> &nodes, + std::vector<std::string> &datanames, + std::vector<std::vector<double>> &nodedata) override; + + ////////////////////////////////////////////////////////////////////////// + // lines + // 0 ---- 1 + // nodenumbering must start with 0! + std::string writeLines(const std::string &filename, std::vector<UbTupleFloat3> &nodes, + std::vector<UbTupleInt2> &lines) override; + // std::string writeLinesWithNodeData(const std::string& filename,std::vector<UbTupleFloat3 >& nodes, + // std::vector<UbTupleInt2 >& lines, std::vector< std::string >& datanames, std::vector< std::vector< double > >& + // nodedata); // FIXME: hides function in base class - ////////////////////////////////////////////////////////////////////////// - //triangles - // 2 - // - // 0---1 - //nodenumbering must start with 0! - std::string writeTriangles(const std::string& filename,std::vector<UbTupleFloat3 >& nodes, std::vector<UbTupleInt3 >& triangles) override; - std::string writeTrianglesWithNodeData(const std::string& filename,std::vector< UbTupleFloat3 >& nodes, std::vector< UbTupleInt3 >& cells, std::vector<std::string >& datanames, std::vector<std::vector<double > >& nodedata) override; - - ////////////////////////////////////////////////////////////////////////// - //2D - //cell numbering: - // 3---2 - // | | - // 0---1 - //nodenumbering must start with 0! - - std::string writeQuads(const std::string& filename,std::vector< UbTupleFloat3 >& nodes, std::vector< UbTupleInt4 >& cells) override; - std::string writeQuadsWithNodeData(const std::string& filename,std::vector< UbTupleFloat3 >& nodes, std::vector< UbTupleInt4 >& cells, std::vector< std::string >& datanames, std::vector< std::vector< double > >& nodedata) override; - std::string writeQuadsWithCellData(const std::string& filename,std::vector< UbTupleFloat3 >& nodes, std::vector< UbTupleInt4 >& cells, std::vector< std::string >& datanames, std::vector< std::vector< double > >& celldata) override; - std::string writeQuadsWithNodeAndCellData(const std::string& filename,std::vector< UbTupleFloat3 >& nodes, std::vector< UbTupleInt4 >& cells, - std::vector< std::string >& nodedatanames, std::vector< std::vector< double > >& nodedata, std::vector< std::string >& celldatanames, - std::vector< std::vector< double > >& celldata ) override; - - ////////////////////////////////////////////////////////////////////////// - //octs - // 7 ---- 6 - // /| /| - // 4 +--- 5 | - // | | | | - // | 3 ---+ 2 - // |/ |/ - // 0 ---- 1 - std::string writeOcts(const std::string& filename,std::vector< UbTupleFloat3 >& nodes, std::vector< UbTupleInt8 >& cells) override; - std::string writeOctsWithCellData(const std::string& filename,std::vector<UbTupleFloat3 >& nodes, std::vector<UbTupleInt8 >& cells, std::vector<std::string >& datanames, std::vector<std::vector<double > >& celldata) override; - std::string writeOctsWithNodeData(const std::string& filename,std::vector<UbTupleFloat3 >& nodes, std::vector<UbTupleUInt8 >& cells, std::vector<std::string >& datanames, std::vector<std::vector<double > >& nodedata) override; - -private: + ////////////////////////////////////////////////////////////////////////// + // triangles + // 2 + // + // 0---1 + // nodenumbering must start with 0! + std::string writeTriangles(const std::string &filename, std::vector<UbTupleFloat3> &nodes, + std::vector<UbTupleInt3> &triangles) override; + std::string writeTrianglesWithNodeData(const std::string &filename, std::vector<UbTupleFloat3> &nodes, + std::vector<UbTupleInt3> &cells, std::vector<std::string> &datanames, + std::vector<std::vector<double>> &nodedata) override; + + ////////////////////////////////////////////////////////////////////////// + // 2D + // cell numbering: + // 3---2 + // | | + // 0---1 + // nodenumbering must start with 0! + std::string writeQuads(const std::string &filename, std::vector<UbTupleFloat3> &nodes, + std::vector<UbTupleInt4> &cells) override; + std::string writeQuadsWithNodeData(const std::string &filename, std::vector<UbTupleFloat3> &nodes, + std::vector<UbTupleInt4> &cells, std::vector<std::string> &datanames, + std::vector<std::vector<double>> &nodedata) override; + std::string writeQuadsWithCellData(const std::string &filename, std::vector<UbTupleFloat3> &nodes, + std::vector<UbTupleInt4> &cells, std::vector<std::string> &datanames, + std::vector<std::vector<double>> &celldata) override; + std::string writeQuadsWithNodeAndCellData(const std::string &filename, std::vector<UbTupleFloat3> &nodes, + std::vector<UbTupleInt4> &cells, std::vector<std::string> &nodedatanames, + std::vector<std::vector<double>> &nodedata, + std::vector<std::string> &celldatanames, + std::vector<std::vector<double>> &celldata) override; + + ////////////////////////////////////////////////////////////////////////// + // octs + // 7 ---- 6 + // /| /| + // 4 +--- 5 | + // | | | | + // | 3 ---+ 2 + // |/ |/ + // 0 ---- 1 + std::string writeOcts(const std::string &filename, std::vector<UbTupleFloat3> &nodes, + std::vector<UbTupleInt8> &cells) override; + std::string writeOctsWithCellData(const std::string &filename, std::vector<UbTupleFloat3> &nodes, + std::vector<UbTupleInt8> &cells, std::vector<std::string> &datanames, + std::vector<std::vector<double>> &celldata) override; + std::string writeOctsWithNodeData(const std::string &filename, std::vector<UbTupleFloat3> &nodes, + std::vector<UbTupleUInt8> &cells, std::vector<std::string> &datanames, + std::vector<std::vector<double>> &nodedata) override; + +private: }; -#endif //WBWRITERVTKXMLBINARY_H +#endif // WBWRITERVTKXMLBINARY_H diff --git a/src/basics/basics/writer/WbWriterX3D.cpp b/src/basics/basics/writer/WbWriterX3D.cpp index 14d1b3741695e17f5c3608e275b676ea6e739491..3a043252314b44728847480bef5ca535d1f7fb86 100644 --- a/src/basics/basics/writer/WbWriterX3D.cpp +++ b/src/basics/basics/writer/WbWriterX3D.cpp @@ -1,152 +1,159 @@ -#include <basics/writer/WbWriterX3D.h> #include <basics/utilities/UbLogger.h> +#include <basics/writer/WbWriterX3D.h> using namespace std; /*===============================================================================*/ -std::string WbWriterX3D::writeTriangles(const string& filename,vector<UbTupleFloat3 >& nodes, vector<UbTupleInt3 >& triangles) +std::string WbWriterX3D::writeTriangles(const string &filename, vector<UbTupleFloat3> &nodes, + vector<UbTupleInt3> &triangles) { - string X3DFilename=filename+getFileExtension(); - UBLOG(logDEBUG1,"WbWriterX3D::writeTriangles to "<<X3DFilename<<" - start"); - - std::ofstream out(X3DFilename.c_str()); - if(!out) - { - out.clear(); //flags ruecksetzen (ansonsten liefert utern if(!out) weiterhin true!!! - string path = UbSystem::getPathFromString(X3DFilename); - if(path.size()>0){UbSystem::makeDirectory(path);out.open(X3DFilename.c_str());} - if(!out) throw UbException(UB_EXARGS,"couldn't open file "+X3DFilename); - } - - // General part - - //Root Element - out<<"<?xml version=\"1.0\" encoding=\"UTF-8\"?>" <<endl; - out<<"<!DOCTYPE X3D PUBLIC \"ISO//Web3D//DTD X3D 3.1//EN\" \"http://www.web3d.org/specifications/x3d-3.1.dtd\">" <<endl; - out<<"<X3D profile='Interchange' version='3.1' xmlns:xsd='http://www.w3.org/2001/XMLSchema-instance' xsd:noNamespaceSchemaLocation=' http://www.web3d.org/specifications/x3d-3.1.xsd '>"<<endl<<endl; - - //Head - out<<"<head>" <<endl; - out<<"<meta content='Simple X3D Writer for blender'/>"<<endl; - out<<"</head>" <<endl<<endl; - - //Scene, Shape beginn - out<<"<Scene>" <<endl; - out<<"<Shape>" <<endl; - - //IndexedFaceSet => Polylinien der Dreiecke - out<<"<IndexedFaceSet coordIndex=\""<<endl; - - // TRIANGLES Ponits SECTION - int nofTriangles= (int)triangles.size(); - //out<<" triangles "<<nofTriangles<<endl; - for(int c=0; c<nofTriangles; c++) - out<<" "<<val<1>(triangles[c]) <<" "<< val<2>(triangles[c])<<" "<< val<3>(triangles[c])<<" -1"<<endl; - out<<"\">" <<endl; - - //Coordinates - out<<"<Coordinate point=\"" <<endl; - - // Coordinates SECTION - int nofNodes = (int)nodes.size(); - //out<<" points "<<nofNodes<<endl; - for(int n=0; n<nofNodes; n++) - out<<" "<< val<1>(nodes[n]) <<", "<< val<2>(nodes[n]) <<", "<< val<3>(nodes[n])<<", "<<endl; - out<<"\"/>" <<endl; - - //Footer - out<<"</IndexedFaceSet>"<< endl; - out<<"</Shape>" << endl; - out<<"</Scene>" << endl; - out<<"</X3D>" << endl; - - - //// Image details - //out<<"image {" <<endl; - //out<<" resolution 640 480"<<endl; - //out<<" aa 0 1" <<endl; - //out<<" filter mitchell" <<endl; - //out<<"}" <<endl<<endl; - - //// Camera position - //out<<"camera {" <<endl; - //out<<" type pinhole" <<endl; - //out<<" eye -0.25 -0.3 0.13"<<endl; - //out<<" target -0.1 0.1 0.13" <<endl; - //out<<" up 0 0 1" <<endl; - //out<<" fov 60" <<endl; - //out<<" aspect 1.333333" <<endl; - //out<<"}" <<endl<<endl; - - //// Light - //out<<"light {" <<endl; - //out<<" type ibl" <<endl; - //out<<" image sky_small.hdr" <<endl; - //out<<" center 0 -1 0" <<endl; - //out<<" up 0 0 1" <<endl; - //out<<" lock true" <<endl; - //out<<" samples 200" <<endl; - //out<<"}" <<endl<<endl; - - //// Shaders - //out<<"shader {" <<endl; - //out<<" name default-shader" <<endl; - //out<<" type diffuse" <<endl; - //out<<" diff 0.25 0.25 0.25" <<endl; - //out<<"}" <<endl<<endl; - - //out<<"shader {" <<endl; - //out<<" name Glass" <<endl; - //out<<" type glass" <<endl; - //out<<" eta 1.333" <<endl; - //out<<" color 0.1 0.3 0.8" <<endl; - //out<<"}" <<endl<<endl; - // - //out<<"shader {" <<endl; - //out<<" name Mirror" <<endl; - //out<<" type mirror" <<endl; - //out<<" refl 0.7 0.7 0.7" <<endl; - //out<<"}" <<endl<<endl; - - //// Objects - //// a) Ground plane - //out<<"object {" <<endl; - //out<<" shader default-shader" <<endl; - //out<<" type plane" <<endl; - //out<<" p 0 0 0" <<endl; - //out<<" n 0 0 1" <<endl; - //out<<"}" <<endl<<endl; - - //// b) Mesh - //out<<"object {" <<endl; - //out<<" shader Glass" <<endl; - //out<<" transform {" <<endl; - //out<<" rotatey 270.0" <<endl; - //out<<" }" <<endl; - //out<<" type generic-mesh" <<endl; - //out<<" name polySurfac" <<endl<<endl; - - - //// POINTS SECTION - //int nofNodes = (int)nodes.size(); - //out<<" points "<<nofNodes<<endl; - //for(int n=0; n<nofNodes; n++) - // out<<" "<< val<1>(nodes[n]) <<" "<< val<2>(nodes[n]) <<" "<< val<3>(nodes[n]) <<endl; - - //// TRIANGLES SECTION - //int nofTriangles= (int)triangles.size(); - //out<<" triangles "<<nofTriangles<<endl; - //for(int c=0; c<nofTriangles; c++) - // out<<" "<<val<1>(triangles[c]) <<" "<< val<2>(triangles[c])<<" "<< val<3>(triangles[c])<<endl; - - //// FOOTER - //out<<" normals none" << endl; - //out<<" uvs none" << endl; - //out<<"}" << endl; - - out.close(); - UBLOG(logDEBUG1,"WbWriterX3D::writeTriangles to "<<X3DFilename<<" - end"); - - return X3DFilename; + string X3DFilename = filename + getFileExtension(); + UBLOG(logDEBUG1, "WbWriterX3D::writeTriangles to " << X3DFilename << " - start"); + + std::ofstream out(X3DFilename.c_str()); + if (!out) { + out.clear(); // flags ruecksetzen (ansonsten liefert utern if(!out) weiterhin true!!! + string path = UbSystem::getPathFromString(X3DFilename); + if (path.size() > 0) { + UbSystem::makeDirectory(path); + out.open(X3DFilename.c_str()); + } + if (!out) + throw UbException(UB_EXARGS, "couldn't open file " + X3DFilename); + } + + // General part + + // Root Element + out << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" << endl; + out << "<!DOCTYPE X3D PUBLIC \"ISO//Web3D//DTD X3D 3.1//EN\" \"http://www.web3d.org/specifications/x3d-3.1.dtd\">" + << endl; + out << "<X3D profile='Interchange' version='3.1' xmlns:xsd='http://www.w3.org/2001/XMLSchema-instance' " + "xsd:noNamespaceSchemaLocation=' http://www.web3d.org/specifications/x3d-3.1.xsd '>" + << endl + << endl; + + // Head + out << "<head>" << endl; + out << "<meta content='Simple X3D Writer for blender'/>" << endl; + out << "</head>" << endl << endl; + + // Scene, Shape beginn + out << "<Scene>" << endl; + out << "<Shape>" << endl; + + // IndexedFaceSet => Polylinien der Dreiecke + out << "<IndexedFaceSet coordIndex=\"" << endl; + + // TRIANGLES Ponits SECTION + int nofTriangles = (int)triangles.size(); + // out<<" triangles "<<nofTriangles<<endl; + for (int c = 0; c < nofTriangles; c++) + out << " " << val<1>(triangles[c]) << " " << val<2>(triangles[c]) << " " << val<3>(triangles[c]) << " -1" + << endl; + out << "\">" << endl; + + // Coordinates + out << "<Coordinate point=\"" << endl; + + // Coordinates SECTION + int nofNodes = (int)nodes.size(); + // out<<" points "<<nofNodes<<endl; + for (int n = 0; n < nofNodes; n++) + out << " " << val<1>(nodes[n]) << ", " << val<2>(nodes[n]) << ", " << val<3>(nodes[n]) << ", " << endl; + out << "\"/>" << endl; + + // Footer + out << "</IndexedFaceSet>" << endl; + out << "</Shape>" << endl; + out << "</Scene>" << endl; + out << "</X3D>" << endl; + + //// Image details + // out<<"image {" <<endl; + // out<<" resolution 640 480"<<endl; + // out<<" aa 0 1" <<endl; + // out<<" filter mitchell" <<endl; + // out<<"}" <<endl<<endl; + + //// Camera position + // out<<"camera {" <<endl; + // out<<" type pinhole" <<endl; + // out<<" eye -0.25 -0.3 0.13"<<endl; + // out<<" target -0.1 0.1 0.13" <<endl; + // out<<" up 0 0 1" <<endl; + // out<<" fov 60" <<endl; + // out<<" aspect 1.333333" <<endl; + // out<<"}" <<endl<<endl; + + //// Light + // out<<"light {" <<endl; + // out<<" type ibl" <<endl; + // out<<" image sky_small.hdr" <<endl; + // out<<" center 0 -1 0" <<endl; + // out<<" up 0 0 1" <<endl; + // out<<" lock true" <<endl; + // out<<" samples 200" <<endl; + // out<<"}" <<endl<<endl; + + //// Shaders + // out<<"shader {" <<endl; + // out<<" name default-shader" <<endl; + // out<<" type diffuse" <<endl; + // out<<" diff 0.25 0.25 0.25" <<endl; + // out<<"}" <<endl<<endl; + + // out<<"shader {" <<endl; + // out<<" name Glass" <<endl; + // out<<" type glass" <<endl; + // out<<" eta 1.333" <<endl; + // out<<" color 0.1 0.3 0.8" <<endl; + // out<<"}" <<endl<<endl; + // + // out<<"shader {" <<endl; + // out<<" name Mirror" <<endl; + // out<<" type mirror" <<endl; + // out<<" refl 0.7 0.7 0.7" <<endl; + // out<<"}" <<endl<<endl; + + //// Objects + //// a) Ground plane + // out<<"object {" <<endl; + // out<<" shader default-shader" <<endl; + // out<<" type plane" <<endl; + // out<<" p 0 0 0" <<endl; + // out<<" n 0 0 1" <<endl; + // out<<"}" <<endl<<endl; + + //// b) Mesh + // out<<"object {" <<endl; + // out<<" shader Glass" <<endl; + // out<<" transform {" <<endl; + // out<<" rotatey 270.0" <<endl; + // out<<" }" <<endl; + // out<<" type generic-mesh" <<endl; + // out<<" name polySurfac" <<endl<<endl; + + //// POINTS SECTION + // int nofNodes = (int)nodes.size(); + // out<<" points "<<nofNodes<<endl; + // for(int n=0; n<nofNodes; n++) + // out<<" "<< val<1>(nodes[n]) <<" "<< val<2>(nodes[n]) <<" "<< val<3>(nodes[n]) <<endl; + + //// TRIANGLES SECTION + // int nofTriangles= (int)triangles.size(); + // out<<" triangles "<<nofTriangles<<endl; + // for(int c=0; c<nofTriangles; c++) + // out<<" "<<val<1>(triangles[c]) <<" "<< val<2>(triangles[c])<<" "<< val<3>(triangles[c])<<endl; + + //// FOOTER + // out<<" normals none" << endl; + // out<<" uvs none" << endl; + // out<<"}" << endl; + + out.close(); + UBLOG(logDEBUG1, "WbWriterX3D::writeTriangles to " << X3DFilename << " - end"); + + return X3DFilename; } /*===============================================================================*/ diff --git a/src/basics/basics/writer/WbWriterX3D.h b/src/basics/basics/writer/WbWriterX3D.h index a6527ce6a08e28cd87d8c6e446e70000bba3e94d..86f0abfb5da244ba14cc7dcf225c17c3faefa394 100644 --- a/src/basics/basics/writer/WbWriterX3D.h +++ b/src/basics/basics/writer/WbWriterX3D.h @@ -5,31 +5,36 @@ #include <basics/writer/WbWriter.h> -class WbWriterX3D : public WbWriter +class WbWriterX3D : public WbWriter { public: - static WbWriterX3D* getInstance() - { - static WbWriterX3D instance; - return &instance; - } - - WbWriterX3D( const WbWriterX3D& ) = delete; - const WbWriterX3D& operator=( const WbWriterX3D& ) = delete; -private: - WbWriterX3D() : WbWriter() - { - if(sizeof(unsigned char)!=1) throw UbException(UB_EXARGS,"error char type mismatch"); - if(sizeof(int) !=4) throw UbException(UB_EXARGS,"error int type mismatch"); - if(sizeof(float) !=4) throw UbException(UB_EXARGS,"error float type mismatch"); - } + static WbWriterX3D *getInstance() + { + static WbWriterX3D instance; + return &instance; + } + + WbWriterX3D(const WbWriterX3D &) = delete; + const WbWriterX3D &operator=(const WbWriterX3D &) = delete; - static std::string pvdEndTag; +private: + WbWriterX3D() : WbWriter() + { + if (sizeof(unsigned char) != 1) + throw UbException(UB_EXARGS, "error char type mismatch"); + if (sizeof(int) != 4) + throw UbException(UB_EXARGS, "error int type mismatch"); + if (sizeof(float) != 4) + throw UbException(UB_EXARGS, "error float type mismatch"); + } + + static std::string pvdEndTag; public: - std::string getFileExtension() override { return "ascii.X3D"; } + std::string getFileExtension() override { return "ascii.X3D"; } - std::string writeTriangles(const std::string& filename,std::vector<UbTupleFloat3 >& nodes, std::vector<UbTupleInt3 >& triangles) override; + std::string writeTriangles(const std::string &filename, std::vector<UbTupleFloat3> &nodes, + std::vector<UbTupleInt3> &triangles) override; }; -#endif //WBWRITERX3D_H +#endif // WBWRITERX3D_H diff --git a/src/basics/geometry3d/CoordinateTransformation3D.cpp b/src/basics/geometry3d/CoordinateTransformation3D.cpp index c54d0e1c68865028e6c99b10b4c79e252606d84d..be758ced5561449c447abca8b0affd306077c420 100644 --- a/src/basics/geometry3d/CoordinateTransformation3D.cpp +++ b/src/basics/geometry3d/CoordinateTransformation3D.cpp @@ -1,28 +1,28 @@ //======================================================================================= -// ____ ____ __ ______ __________ __ __ __ __ -// \ \ | | | | | _ \ |___ ___| | | | | / \ | | -// \ \ | | | | | |_) | | | | | | | / \ | | -// \ \ | | | | | _ / | | | | | | / /\ \ | | -// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ -// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| -// \ \ | | ________________________________________________________________ -// \ \ | | | ______________________________________________________________| -// \ \| | | | __ __ __ __ ______ _______ -// \ | | |_____ | | | | | | | | | _ \ / _____) -// \ | | _____| | | | | | | | | | | \ \ \_______ +// ____ ____ __ ______ __________ __ __ __ __ +// \ \ | | | | | _ \ |___ ___| | | | | / \ | | +// \ \ | | | | | |_) | | | | | | | / \ | | +// \ \ | | | | | _ / | | | | | | / /\ \ | | +// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ +// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| +// \ \ | | ________________________________________________________________ +// \ \ | | | ______________________________________________________________| +// \ \| | | | __ __ __ __ ______ _______ +// \ | | |_____ | | | | | | | | | _ \ / _____) +// \ | | _____| | | | | | | | | | | \ \ \_______ // \ | | | | |_____ | \_/ | | | | |_/ / _____ | -// \ _____| |__| |________| \_______/ |__| |______/ (_______/ +// \ _____| |__| |________| \_______/ |__| |______/ (_______/ // -// This file is part of VirtualFluids. VirtualFluids is free software: you can +// This file is part of VirtualFluids. VirtualFluids is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of +// License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. -// -// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// +// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License along // with VirtualFluids (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>. // @@ -30,29 +30,36 @@ //! \ingroup geometry3d //! \author Soeren Freudiger, Sebastian Geller //======================================================================================= -#include <geometry3d/CoordinateTransformation3D.h> #include <basics/utilities/UbMath.h> +#include <geometry3d/CoordinateTransformation3D.h> using namespace std; CoordinateTransformation3D::CoordinateTransformation3D() { - this->setTransformationValues(0.0,0.0,0.0,1.0,1.0,1.0,0.0,0.0,0.0); + this->setTransformationValues(0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0); } /*======================================================*/ -CoordinateTransformation3D::CoordinateTransformation3D(const double& originX1, const double& originX2, const double& originX3, const double& dx1, const double& dx2, const double& dx3, const double& alpha, const double& beta, const double& gamma) +CoordinateTransformation3D::CoordinateTransformation3D(const double &originX1, const double &originX2, + const double &originX3, const double &dx1, const double &dx2, + const double &dx3, const double &alpha, const double &beta, + const double &gamma) { - this->setTransformationValues(originX1, originX2, originX3, dx1, dx2, dx3, alpha, beta, gamma); + this->setTransformationValues(originX1, originX2, originX3, dx1, dx2, dx3, alpha, beta, gamma); } /*======================================================*/ -CoordinateTransformation3D::CoordinateTransformation3D(const double& originX1, const double& originX2, const double& originX3, const double& dx1, const double& dx2, const double& dx3) +CoordinateTransformation3D::CoordinateTransformation3D(const double &originX1, const double &originX2, + const double &originX3, const double &dx1, const double &dx2, + const double &dx3) { - this->setTransformationValues(originX1, originX2, originX3, dx1, dx2, dx3, 0.0, 0.0, 0.0); + this->setTransformationValues(originX1, originX2, originX3, dx1, dx2, dx3, 0.0, 0.0, 0.0); } /*======================================================*/ -CoordinateTransformation3D::CoordinateTransformation3D(CoordinateTransformation3D* transformation) +CoordinateTransformation3D::CoordinateTransformation3D(CoordinateTransformation3D *transformation) { - this->setTransformationValues(transformation->Tx1 , transformation->Tx2 , transformation->Tx3 , transformation->Sx1 , transformation->Sx2 , transformation->Sx3, transformation->alpha, transformation->beta, transformation->gamma); + this->setTransformationValues(transformation->Tx1, transformation->Tx2, transformation->Tx3, transformation->Sx1, + transformation->Sx2, transformation->Sx3, transformation->alpha, transformation->beta, + transformation->gamma); } /*======================================================*/ // void CoordinateTransformation3D::init() @@ -60,7 +67,7 @@ CoordinateTransformation3D::CoordinateTransformation3D(CoordinateTransformation3 // this->Tx1 = 0.0; this->Tx2 = 0.0; this->Tx3 = 0.0; // this->Sx1 = 1.0; this->Sx2 = 1.0; this->Sx3 = 1.0; // this->alpha = 0.0; this->beta = 0.0; this->gamma = 0.0; -// +// // this->toX1factorX1 = 1.0; this->toX1factorX2 = 0.0; this->toX1factorX3 = 0.0; // this->toX2factorX1 = 0.0; this->toX2factorX2 = 1.0; this->toX2factorX3 = 0.0; // this->toX3factorX1 = 0.0; this->toX3factorX2 = 0.0; this->toX3factorX3 = 1.0; @@ -68,7 +75,7 @@ CoordinateTransformation3D::CoordinateTransformation3D(CoordinateTransformation3 // this->fromX1factorX1 = 1.0; this->fromX1factorX2 = 0.0; this->fromX1factorX3 = 0.0; // this->fromX2factorX1 = 0.0; this->fromX2factorX2 = 1.0; this->fromX2factorX3 = 0.0; // this->fromX3factorX1 = 0.0; this->fromX3factorX2 = 0.0; this->fromX3factorX3 = 1.0; -// +// // this->active = false; // this->transformation = false; // } @@ -84,88 +91,95 @@ CoordinateTransformation3D::CoordinateTransformation3D(CoordinateTransformation3 @param dx2 y coordinate scaling (dy_transformed/dy_global) @param dx3 z coordinate scaling (dz_transformed/dz_global) @param alpha rotation around z angle (positive FROM global TO transformed coordinate system) -@param beta rotation around y angle -@param gamma rotation around x angle +@param beta rotation around y angle +@param gamma rotation around x angle @exception IllegalArgumentException if c1 of the scale values is between -1.0E-8 and 1.0E-8 */ -void CoordinateTransformation3D::setTransformationValues(const double& originX1, const double& originX2, const double& originX3, const double& dx1, const double& dx2, const double& dx3, const double& alpha, const double& beta, const double& gamma) +void CoordinateTransformation3D::setTransformationValues(const double &originX1, const double &originX2, + const double &originX3, const double &dx1, const double &dx2, + const double &dx3, const double &alpha, const double &beta, + const double &gamma) { - if(UbMath::zero(dx1) || UbMath::zero(dx2) || UbMath::zero(dx3)) - throw UbException(UB_EXARGS,"error: at least one delta==0.0"); - - this->Tx1 = originX1; this->Tx2 = originX2; this->Tx3 = originX3; - this->Sx1 = dx1; this->Sx2 = dx2; this->Sx3 = dx3; - this->alpha = alpha; this->beta = beta; this->gamma = gamma; + if (UbMath::zero(dx1) || UbMath::zero(dx2) || UbMath::zero(dx3)) + throw UbException(UB_EXARGS, "error: at least one delta==0.0"); + + this->Tx1 = originX1; + this->Tx2 = originX2; + this->Tx3 = originX3; + this->Sx1 = dx1; + this->Sx2 = dx2; + this->Sx3 = dx3; + this->alpha = alpha; + this->beta = beta; + this->gamma = gamma; + + double ra = UbMath::PI * alpha / 180.0; + double cosA = cos(ra); + double sinA = sin(ra); + double rb = UbMath::PI * beta / 180.0; + double cosB = cos(rb); + double sinB = sin(rb); + double rg = UbMath::PI * gamma / 180.0; + double cosG = cos(rg); + double sinG = sin(rg); + + // Matrix-Werte von T_invers (indizes: 12 = spalte 1 zeile 2) + double divisor = (Sx1 * Sx2 * Sx3); + + this->toX1factorX1 = +cosB * cosA * Sx2 * Sx3 / divisor; + this->toX1factorX2 = -cosB * sinA * Sx1 * Sx3 / divisor; + this->toX1factorX3 = +sinB * Sx1 * Sx2 / divisor; + this->toX1delta = + (-Tx3 * Sx1 * Sx2 * sinB + Tx2 * Sx1 * Sx3 * sinA * cosB - Tx1 * Sx2 * Sx3 * cosB * cosA) / divisor; + + this->toX2factorX1 = Sx2 * Sx3 * (sinG * sinB * cosA + cosG * sinA) / divisor; + this->toX2factorX2 = Sx1 * Sx3 * (-sinG * sinB * sinA + cosG * cosA) / divisor; + this->toX2factorX3 = -Sx1 * Sx2 * cosB * sinG / divisor; + this->toX2delta = + (-Tx2 * Sx1 * Sx3 * cosG * cosA + Tx3 * Sx1 * Sx2 * sinG * cosB + Tx2 * Sx1 * Sx3 * sinG * sinA * sinB - + Tx1 * Sx2 * Sx3 * cosG * sinA - Tx1 * Sx2 * Sx3 * sinB * sinG * cosA) / + divisor; + + this->toX3factorX1 = Sx2 * Sx3 * (-cosG * sinB * cosA + sinG * sinA) / divisor; + this->toX3factorX2 = Sx1 * Sx3 * (sinB * cosG * sinA + sinG * cosA) / divisor; + this->toX3factorX3 = Sx1 * Sx2 * cosB * cosG / divisor; + this->toX3delta = + (-Tx2 * Sx1 * Sx3 * sinG * cosA - Tx3 * Sx1 * Sx2 * cosG * cosB - Tx2 * Sx1 * Sx3 * cosG * sinA * sinB - + Tx1 * Sx2 * Sx3 * sinG * sinA + Tx1 * Sx2 * Sx3 * sinB * cosG * cosA) / + divisor; - double ra = UbMath::PI*alpha/180.0; - double cosA = cos(ra); - double sinA = sin(ra); - double rb = UbMath::PI*beta/180.0; - double cosB = cos(rb); - double sinB = sin(rb); - double rg = UbMath::PI*gamma/180.0; - double cosG = cos(rg); - double sinG = sin(rg); + // Matrix-Werte von T_invers (indizes: 12 = spalte 1 zeile 2) + this->fromX1factorX1 = cosB * cosA * Sx1; + this->fromX1factorX2 = (sinG * sinB * cosA + cosG * sinA) * Sx1; + this->fromX1factorX3 = (-cosG * sinB * cosA + sinG * sinA) * Sx1; + this->fromX1delta = Tx1; - //Matrix-Werte von T_invers (indizes: 12 = spalte 1 zeile 2) - double divisor = (Sx1*Sx2*Sx3); - - this->toX1factorX1 = +cosB*cosA*Sx2*Sx3/divisor; - this->toX1factorX2 = -cosB*sinA*Sx1*Sx3/divisor; - this->toX1factorX3 = +sinB*Sx1*Sx2/divisor; - this->toX1delta = (-Tx3*Sx1*Sx2*sinB - +Tx2*Sx1*Sx3*sinA*cosB - -Tx1*Sx2*Sx3*cosB*cosA)/divisor; - - this->toX2factorX1 = Sx2*Sx3*(sinG*sinB*cosA+cosG*sinA)/divisor; - this->toX2factorX2 = Sx1*Sx3*(-sinG*sinB*sinA+cosG*cosA)/divisor; - this->toX2factorX3 = -Sx1*Sx2*cosB*sinG/divisor; - this->toX2delta = (-Tx2*Sx1*Sx3*cosG*cosA - +Tx3*Sx1*Sx2*sinG*cosB - +Tx2*Sx1*Sx3*sinG*sinA*sinB - -Tx1*Sx2*Sx3*cosG*sinA - -Tx1*Sx2*Sx3*sinB*sinG*cosA )/divisor; - + this->fromX2factorX1 = -cosB * sinA * Sx2; + this->fromX2factorX2 = -(sinG * sinB * sinA - cosG * cosA) * Sx2; + this->fromX2factorX3 = (cosG * sinB * sinA + sinG * cosA) * Sx2; + this->fromX2delta = Tx2; - this->toX3factorX1 = Sx2*Sx3*(-cosG*sinB*cosA+sinG*sinA)/divisor; - this->toX3factorX2 = Sx1*Sx3*(sinB*cosG*sinA+sinG*cosA)/divisor; - this->toX3factorX3 = Sx1*Sx2*cosB*cosG/divisor; - this->toX3delta = (-Tx2*Sx1*Sx3*sinG*cosA - -Tx3*Sx1*Sx2*cosG*cosB - -Tx2*Sx1*Sx3*cosG*sinA*sinB - -Tx1*Sx2*Sx3*sinG*sinA - +Tx1*Sx2*Sx3*sinB*cosG*cosA )/divisor; - - //Matrix-Werte von T_invers (indizes: 12 = spalte 1 zeile 2) - this->fromX1factorX1 = cosB*cosA*Sx1; - this->fromX1factorX2 = (sinG*sinB*cosA+cosG*sinA)*Sx1; - this->fromX1factorX3 = (-cosG*sinB*cosA+sinG*sinA)*Sx1; - this->fromX1delta = Tx1; + this->fromX3factorX1 = sinB * Sx3; + this->fromX3factorX2 = -sinG * cosB * Sx3; + this->fromX3factorX3 = cosG * cosB * Sx3; + this->fromX3delta = Tx3; - this->fromX2factorX1 = -cosB*sinA*Sx2; - this->fromX2factorX2 = -(sinG*sinB*sinA-cosG*cosA)*Sx2; - this->fromX2factorX3 = (cosG*sinB*sinA+sinG*cosA)*Sx2; - this->fromX2delta = Tx2; - - this->fromX3factorX1 = sinB*Sx3; - this->fromX3factorX2 = -sinG*cosB*Sx3; - this->fromX3factorX3 = cosG*cosB*Sx3; - this->fromX3delta = Tx3; + this->active = true; - this->active = true; - - this->transformation = true; + this->transformation = true; } /*======================================================*/ /*! Set transformation active state (if this IS a transformation) @param active true to be active, false otherwise **/ -void CoordinateTransformation3D::setActive(const bool& active) +void CoordinateTransformation3D::setActive(const bool &active) { - if(this->active == active) return; - if(this->transformation) this->active = active; + if (this->active == active) + return; + if (this->transformation) + this->active = active; } /*======================================================*/ /*! @@ -174,44 +188,59 @@ Transform FROM global coordinates TO transformed coordinates. @param x2 the global y coordinate @param x3 the global z coordinate **/ -double CoordinateTransformation3D::transformForwardToX1Coordinate(const double& x1, const double& x2, const double& x3) const +double CoordinateTransformation3D::transformForwardToX1Coordinate(const double &x1, const double &x2, + const double &x3) const { - if(this->active) return this->toX1factorX1*x1 + this->toX1factorX2*x2 + this->toX1factorX3*x3 + this->toX1delta; - else return x1; + if (this->active) + return this->toX1factorX1 * x1 + this->toX1factorX2 * x2 + this->toX1factorX3 * x3 + this->toX1delta; + else + return x1; } /*======================================================*/ -double CoordinateTransformation3D::transformForwardToX2Coordinate(const double& x1, const double& x2, const double& x3) const +double CoordinateTransformation3D::transformForwardToX2Coordinate(const double &x1, const double &x2, + const double &x3) const { - if(this->active) return this->toX2factorX1*x1 + this->toX2factorX2*x2 + this->toX2factorX3*x3 + this->toX2delta; - else return x2; + if (this->active) + return this->toX2factorX1 * x1 + this->toX2factorX2 * x2 + this->toX2factorX3 * x3 + this->toX2delta; + else + return x2; } /*======================================================*/ -double CoordinateTransformation3D::transformForwardToX3Coordinate(const double& x1, const double& x2, const double& x3) const +double CoordinateTransformation3D::transformForwardToX3Coordinate(const double &x1, const double &x2, + const double &x3) const { - if(this->active) return this->toX3factorX1*x1 + this->toX3factorX2*x2 + this->toX3factorX3*x3 + this->toX3delta; - else return x3; + if (this->active) + return this->toX3factorX1 * x1 + this->toX3factorX2 * x2 + this->toX3factorX3 * x3 + this->toX3delta; + else + return x3; } /*======================================================*/ /*! Transform FROM global coordinates TO transformed coordinates (ignoring rotation). @param x1 the global x coordinate **/ -double CoordinateTransformation3D::transformForwardToX1CoordinateIgnoringRotation(const double& x1) const +double CoordinateTransformation3D::transformForwardToX1CoordinateIgnoringRotation(const double &x1) const { - if(this->active) return (x1-this->Tx1)/this->Sx1; - else return x1; + if (this->active) + return (x1 - this->Tx1) / this->Sx1; + else + return x1; } /*======================================================*/ -double CoordinateTransformation3D::transformForwardToX2CoordinateIgnoringRotation(const double& x2) const +double CoordinateTransformation3D::transformForwardToX2CoordinateIgnoringRotation(const double &x2) const { - if(this->active) return (x2-this->Tx2)/this->Sx2; - else return x2; + if (this->active) + return (x2 - this->Tx2) / this->Sx2; + else + return x2; } /*======================================================*/ -double CoordinateTransformation3D::transformForwardToX3CoordinateIgnoringRotation(const double& x3) const +double CoordinateTransformation3D::transformForwardToX3CoordinateIgnoringRotation(const double &x3) const { - if(this->active) return (x3-this->Tx3)/this->Sx3; - else return x3; + if (this->active) + return (x3 - this->Tx3) / this->Sx3; + else + return x3; } /*======================================================*/ /*! @@ -220,44 +249,59 @@ Transform FROM transformed coordinates TO global coordinates. @param x2 the transformed y coordinate @param x3 the transformed z coordinate **/ -double CoordinateTransformation3D::transformBackwardToX1Coordinate(const double& x1, const double& x2, const double& x3) const +double CoordinateTransformation3D::transformBackwardToX1Coordinate(const double &x1, const double &x2, + const double &x3) const { - if(this->active) return this->fromX1factorX1*x1 + this->fromX1factorX2*x2 + this->fromX1factorX3*x3 + this->fromX1delta; - else return x1; + if (this->active) + return this->fromX1factorX1 * x1 + this->fromX1factorX2 * x2 + this->fromX1factorX3 * x3 + this->fromX1delta; + else + return x1; } /*======================================================*/ -double CoordinateTransformation3D::transformBackwardToX2Coordinate(const double& x1, const double& x2, const double& x3) const +double CoordinateTransformation3D::transformBackwardToX2Coordinate(const double &x1, const double &x2, + const double &x3) const { - if(this->active) return this->fromX2factorX1*x1 + this->fromX2factorX2*x2 + this->fromX2factorX3*x3 + this->fromX2delta; - else return x2; + if (this->active) + return this->fromX2factorX1 * x1 + this->fromX2factorX2 * x2 + this->fromX2factorX3 * x3 + this->fromX2delta; + else + return x2; } /*======================================================*/ -double CoordinateTransformation3D::transformBackwardToX3Coordinate(const double& x1, const double& x2, const double& x3) const +double CoordinateTransformation3D::transformBackwardToX3Coordinate(const double &x1, const double &x2, + const double &x3) const { - if(this->active) return this->fromX3factorX1*x1 + this->fromX3factorX2*x2 + this->fromX3factorX3*x3 + this->fromX3delta; - else return x3; + if (this->active) + return this->fromX3factorX1 * x1 + this->fromX3factorX2 * x2 + this->fromX3factorX3 * x3 + this->fromX3delta; + else + return x3; } /*======================================================*/ /*! Transform FROM transformed coordinates TO global coordinates (ignoring rotation). @param x1 the transformed x coordinate **/ -double CoordinateTransformation3D::transformBackwardToX1CoordinateIgnoringRotation(const double& x1) const +double CoordinateTransformation3D::transformBackwardToX1CoordinateIgnoringRotation(const double &x1) const { - if(this->active) return x1*this->Sx1+this->Tx1; - else return x1; + if (this->active) + return x1 * this->Sx1 + this->Tx1; + else + return x1; } /*======================================================*/ -double CoordinateTransformation3D::transformBackwardToX2CoordinateIgnoringRotation(const double& x2) const +double CoordinateTransformation3D::transformBackwardToX2CoordinateIgnoringRotation(const double &x2) const { - if(this->active) return x2*this->Sx2+this->Tx2; - else return x2; + if (this->active) + return x2 * this->Sx2 + this->Tx2; + else + return x2; } /*======================================================*/ -double CoordinateTransformation3D::transformBackwardToX3CoordinateIgnoringRotation(const double& x3) const +double CoordinateTransformation3D::transformBackwardToX3CoordinateIgnoringRotation(const double &x3) const { - if(this->active) return x3*this->Sx3+this->Tx3; - else return x3; + if (this->active) + return x3 * this->Sx3 + this->Tx3; + else + return x3; } /*======================================================*/ /*! @@ -266,23 +310,22 @@ Returns a string representation of this transformation. **/ string CoordinateTransformation3D::toString() const { - stringstream ss; - ss<<" CoordinateTransformation3D\n"; -// ss<<"[isTransformation="<<this->transformation; -// ss<<", isActive="<<this->active<<endl; - ss<<" ,a="<<this->Tx1<<", b="<<this->Tx2<<", c="<<this->Tx3<<endl; - ss<<" , dx1="<<this->Sx1<<", dx2="<<this->Sx2<<", dx2="<<this->Sx3<<endl; -// ss<<" , alpha="<<this->alpha<<", beta="<<this->beta<endl; -// ss<<"]"; -// ss<<"[to11="<<this->to11<<", to12="<<this->to12<<", to13="<<this->to13; -// ss<<", to21="<<this->to21<<", to22="<<this->to22<<", to23="<<this->to23; -// ss<<", to31="<<this->to31<<", to32="<<this->to32<<", to33="<<this->to33; -// ss<<", toA="<<this->toA<<", toB="<<this->toB<<", toC="<<this->toC; -// ss<<", from11="<<this->from11<<", from12="<<this->from12<<", from13="<<this->from13; -// ss<<", from21="<<this->from21<<", from22="<<this->from22<<", from23="<<this->from23; -// ss<<", from31="<<this->from31<<", from32="<<this->from32<<", from33="<<this->from33; -// ss<<", fromA="<<this->fromA; ss<<", fromB="<<this->fromB; ss<<", fromC="<<this->fromC; -// ss<<"]}"; - return ss.str(); + stringstream ss; + ss << " CoordinateTransformation3D\n"; + // ss<<"[isTransformation="<<this->transformation; + // ss<<", isActive="<<this->active<<endl; + ss << " ,a=" << this->Tx1 << ", b=" << this->Tx2 << ", c=" << this->Tx3 << endl; + ss << " , dx1=" << this->Sx1 << ", dx2=" << this->Sx2 << ", dx2=" << this->Sx3 << endl; + // ss<<" , alpha="<<this->alpha<<", beta="<<this->beta<endl; + // ss<<"]"; + // ss<<"[to11="<<this->to11<<", to12="<<this->to12<<", to13="<<this->to13; + // ss<<", to21="<<this->to21<<", to22="<<this->to22<<", to23="<<this->to23; + // ss<<", to31="<<this->to31<<", to32="<<this->to32<<", to33="<<this->to33; + // ss<<", toA="<<this->toA<<", toB="<<this->toB<<", toC="<<this->toC; + // ss<<", from11="<<this->from11<<", from12="<<this->from12<<", from13="<<this->from13; + // ss<<", from21="<<this->from21<<", from22="<<this->from22<<", from23="<<this->from23; + // ss<<", from31="<<this->from31<<", from32="<<this->from32<<", from33="<<this->from33; + // ss<<", fromA="<<this->fromA; ss<<", fromB="<<this->fromB; ss<<", fromC="<<this->fromC; + // ss<<"]}"; + return ss.str(); } - diff --git a/src/basics/geometry3d/CoordinateTransformation3D.h b/src/basics/geometry3d/CoordinateTransformation3D.h index 112f78789d2dda0f5db279a1ca83d82ff6d844d6..a0f88c1f6b22bfe0655736802c423a00ee2357e2 100644 --- a/src/basics/geometry3d/CoordinateTransformation3D.h +++ b/src/basics/geometry3d/CoordinateTransformation3D.h @@ -1,28 +1,28 @@ //======================================================================================= -// ____ ____ __ ______ __________ __ __ __ __ -// \ \ | | | | | _ \ |___ ___| | | | | / \ | | -// \ \ | | | | | |_) | | | | | | | / \ | | -// \ \ | | | | | _ / | | | | | | / /\ \ | | -// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ -// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| -// \ \ | | ________________________________________________________________ -// \ \ | | | ______________________________________________________________| -// \ \| | | | __ __ __ __ ______ _______ -// \ | | |_____ | | | | | | | | | _ \ / _____) -// \ | | _____| | | | | | | | | | | \ \ \_______ +// ____ ____ __ ______ __________ __ __ __ __ +// \ \ | | | | | _ \ |___ ___| | | | | / \ | | +// \ \ | | | | | |_) | | | | | | | / \ | | +// \ \ | | | | | _ / | | | | | | / /\ \ | | +// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ +// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| +// \ \ | | ________________________________________________________________ +// \ \ | | | ______________________________________________________________| +// \ \| | | | __ __ __ __ ______ _______ +// \ | | |_____ | | | | | | | | | _ \ / _____) +// \ | | _____| | | | | | | | | | | \ \ \_______ // \ | | | | |_____ | \_/ | | | | |_/ / _____ | -// \ _____| |__| |________| \_______/ |__| |______/ (_______/ +// \ _____| |__| |________| \_______/ |__| |______/ (_______/ // -// This file is part of VirtualFluids. VirtualFluids is free software: you can +// This file is part of VirtualFluids. VirtualFluids is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of +// License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. -// -// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// +// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License along // with VirtualFluids (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>. // @@ -34,19 +34,19 @@ #define COORDINATETRANSFORMATION3D_H #include <cmath> -#include <string> #include <sstream> +#include <string> #include <basics/utilities/UbException.h> #include <PointerDefinitions.h> /////////////////////////////////////////////////////////////////////////////////////// -//! +//! //! \brief A class provides 3d coordinate transformation //! \details //! description: x1/x2/x3 = old, x1*/x2*/x3* = new -//! x2 +//! x2 //! ^ x* //! | / //! | 2* @@ -59,74 +59,89 @@ //! 1 \ THEN rotation by gamma around "x3" axis //! | x1* //! |--1--2--3--4--5------------- > x1 -//! +//! //! Remark: It might be that the rotations around x1 and x3 axis are swapped. -//! +//! ////////////////////////////////////////////////////////////////////////////////////// class CoordinateTransformation3D { public: - CoordinateTransformation3D(); - CoordinateTransformation3D(const double& originX1, const double& originX2, const double& originX3, const double& dx1, const double& dx2, const double& dx3, const double& alpha, const double& beta, const double& gamma); - CoordinateTransformation3D(const double& originX1, const double& originX2, const double& originX3, const double& dx1, const double& dx2, const double& dx3); - CoordinateTransformation3D(CoordinateTransformation3D* transformation); - - void setTransformationValues(const double& originX1, const double& originX2, const double& originX3, const double& dx1, const double& dx2, const double& dx3, const double& alpha, const double& beta, const double& gamma); - double getX1CoordinateOffset() const { return this->Tx1; } //Translation - double getX2CoordinateOffset() const { return this->Tx2; } - double getX3CoordinateOffset() const { return this->Tx3; } - double getX1CoordinateScaling() const { return this->Sx1; } //Scaling - double getX2CoordinateScaling() const { return this->Sx2; } - double getX3CoordinateScaling() const { return this->Sx3; } - double getRotationX1Angle() const { return this->alpha; } - double getRotationX2Angle() const { return this->beta; } - double getRotationX3Angle() const { return this->gamma; } //Rotation - - //Achtung die Winkel passen nicht ueberein -siehe setTransformationValues - void setRotationX1Angle(double alpha) { this->setTransformationValues(this->Tx1, this->Tx2, this->Tx3, this->Sx1, this->Sx2, this->Sx3, alpha, this->beta, this->gamma); } - void setRotationX2Angle(double beta ) { this->setTransformationValues(this->Tx1, this->Tx2, this->Tx3, this->Sx1, this->Sx2, this->Sx3, this->alpha, beta, this->gamma); } - void setRotationX3Angle(double gamma) { this->setTransformationValues(this->Tx1, this->Tx2, this->Tx3, this->Sx1, this->Sx2, this->Sx3, this->alpha, this->beta, gamma); } - - void setActive(const bool& active); - bool isActive() const { return this->active; } - bool isTransformation() const { return this->transformation; } - - double transformForwardToX1Coordinate(const double& x1, const double& x2, const double& x3) const; - double transformForwardToX2Coordinate(const double& x1, const double& x2, const double& x3) const; - double transformForwardToX3Coordinate(const double& x1, const double& x2, const double& x3) const; - double transformForwardToX1CoordinateIgnoringRotation(const double& x1) const; - double transformForwardToX2CoordinateIgnoringRotation(const double& x2) const; - double transformForwardToX3CoordinateIgnoringRotation(const double& x3) const; - double transformBackwardToX1Coordinate(const double& x1, const double& x2, const double& x3) const; - double transformBackwardToX2Coordinate(const double& x1, const double& x2, const double& x3) const; - double transformBackwardToX3Coordinate(const double& x1, const double& x2, const double& x3) const; - double transformBackwardToX1CoordinateIgnoringRotation(const double& x1) const; - double transformBackwardToX2CoordinateIgnoringRotation(const double& x2) const; - double transformBackwardToX3CoordinateIgnoringRotation(const double& x3) const; - std::string toString() const; + CoordinateTransformation3D(); + CoordinateTransformation3D(const double &originX1, const double &originX2, const double &originX3, + const double &dx1, const double &dx2, const double &dx3, const double &alpha, + const double &beta, const double &gamma); + CoordinateTransformation3D(const double &originX1, const double &originX2, const double &originX3, + const double &dx1, const double &dx2, const double &dx3); + CoordinateTransformation3D(CoordinateTransformation3D *transformation); + + void setTransformationValues(const double &originX1, const double &originX2, const double &originX3, + const double &dx1, const double &dx2, const double &dx3, const double &alpha, + const double &beta, const double &gamma); + double getX1CoordinateOffset() const { return this->Tx1; } // Translation + double getX2CoordinateOffset() const { return this->Tx2; } + double getX3CoordinateOffset() const { return this->Tx3; } + double getX1CoordinateScaling() const { return this->Sx1; } // Scaling + double getX2CoordinateScaling() const { return this->Sx2; } + double getX3CoordinateScaling() const { return this->Sx3; } + double getRotationX1Angle() const { return this->alpha; } + double getRotationX2Angle() const { return this->beta; } + double getRotationX3Angle() const { return this->gamma; } // Rotation + + // Achtung die Winkel passen nicht ueberein -siehe setTransformationValues + void setRotationX1Angle(double alpha) + { + this->setTransformationValues(this->Tx1, this->Tx2, this->Tx3, this->Sx1, this->Sx2, this->Sx3, alpha, + this->beta, this->gamma); + } + void setRotationX2Angle(double beta) + { + this->setTransformationValues(this->Tx1, this->Tx2, this->Tx3, this->Sx1, this->Sx2, this->Sx3, this->alpha, + beta, this->gamma); + } + void setRotationX3Angle(double gamma) + { + this->setTransformationValues(this->Tx1, this->Tx2, this->Tx3, this->Sx1, this->Sx2, this->Sx3, this->alpha, + this->beta, gamma); + } + + void setActive(const bool &active); + bool isActive() const { return this->active; } + bool isTransformation() const { return this->transformation; } + + double transformForwardToX1Coordinate(const double &x1, const double &x2, const double &x3) const; + double transformForwardToX2Coordinate(const double &x1, const double &x2, const double &x3) const; + double transformForwardToX3Coordinate(const double &x1, const double &x2, const double &x3) const; + double transformForwardToX1CoordinateIgnoringRotation(const double &x1) const; + double transformForwardToX2CoordinateIgnoringRotation(const double &x2) const; + double transformForwardToX3CoordinateIgnoringRotation(const double &x3) const; + double transformBackwardToX1Coordinate(const double &x1, const double &x2, const double &x3) const; + double transformBackwardToX2Coordinate(const double &x1, const double &x2, const double &x3) const; + double transformBackwardToX3Coordinate(const double &x1, const double &x2, const double &x3) const; + double transformBackwardToX1CoordinateIgnoringRotation(const double &x1) const; + double transformBackwardToX2CoordinateIgnoringRotation(const double &x2) const; + double transformBackwardToX3CoordinateIgnoringRotation(const double &x3) const; + std::string toString() const; private: - double Tx1, Tx2, Tx3, Sx1, Sx2, Sx3, alpha, beta, gamma; - - double toX1factorX1, toX1factorX2, toX1factorX3, toX1delta; - double toX2factorX1, toX2factorX2, toX2factorX3, toX2delta; - double toX3factorX1, toX3factorX2, toX3factorX3, toX3delta; - - double fromX1factorX1, fromX1factorX2, fromX1factorX3, fromX1delta; - double fromX2factorX1, fromX2factorX2, fromX2factorX3, fromX2delta; - double fromX3factorX1, fromX3factorX2, fromX3factorX3, fromX3delta; + double Tx1, Tx2, Tx3, Sx1, Sx2, Sx3, alpha, beta, gamma; - bool active; - bool transformation; + double toX1factorX1, toX1factorX2, toX1factorX3, toX1delta; + double toX2factorX1, toX2factorX2, toX2factorX3, toX2delta; + double toX3factorX1, toX3factorX2, toX3factorX3, toX3delta; - friend class MPIIOCoProcessor; - friend class MPIIORestartCoProcessor; - friend class MPIIOMigrationCoProcessor; - friend class MPIIOMigrationBECoProcessor; - friend class CheckpointConverter; + double fromX1factorX1, fromX1factorX2, fromX1factorX3, fromX1delta; + double fromX2factorX1, fromX2factorX2, fromX2factorX3, fromX2delta; + double fromX3factorX1, fromX3factorX2, fromX3factorX3, fromX3delta; + bool active; + bool transformation; + friend class MPIIOCoProcessor; + friend class MPIIORestartCoProcessor; + friend class MPIIOMigrationCoProcessor; + friend class MPIIOMigrationBECoProcessor; + friend class CheckpointConverter; }; -#endif //COORDINATETRANSFORMATION3D_H +#endif // COORDINATETRANSFORMATION3D_H diff --git a/src/basics/geometry3d/GbCuboid3D.cpp b/src/basics/geometry3d/GbCuboid3D.cpp index 55bb6331bdc3dba88a6089d64c9b760c61a2fb6c..3b29cf795ac7700dafec0b5666a1305b67512c5d 100644 --- a/src/basics/geometry3d/GbCuboid3D.cpp +++ b/src/basics/geometry3d/GbCuboid3D.cpp @@ -1,28 +1,28 @@ //======================================================================================= -// ____ ____ __ ______ __________ __ __ __ __ -// \ \ | | | | | _ \ |___ ___| | | | | / \ | | -// \ \ | | | | | |_) | | | | | | | / \ | | -// \ \ | | | | | _ / | | | | | | / /\ \ | | -// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ -// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| -// \ \ | | ________________________________________________________________ -// \ \ | | | ______________________________________________________________| -// \ \| | | | __ __ __ __ ______ _______ -// \ | | |_____ | | | | | | | | | _ \ / _____) -// \ | | _____| | | | | | | | | | | \ \ \_______ +// ____ ____ __ ______ __________ __ __ __ __ +// \ \ | | | | | _ \ |___ ___| | | | | / \ | | +// \ \ | | | | | |_) | | | | | | | / \ | | +// \ \ | | | | | _ / | | | | | | / /\ \ | | +// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ +// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| +// \ \ | | ________________________________________________________________ +// \ \ | | | ______________________________________________________________| +// \ \| | | | __ __ __ __ ______ _______ +// \ | | |_____ | | | | | | | | | _ \ / _____) +// \ | | _____| | | | | | | | | | | \ \ \_______ // \ | | | | |_____ | \_/ | | | | |_/ / _____ | -// \ _____| |__| |________| \_______/ |__| |______/ (_______/ +// \ _____| |__| |________| \_______/ |__| |______/ (_______/ // -// This file is part of VirtualFluids. VirtualFluids is free software: you can +// This file is part of VirtualFluids. VirtualFluids is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of +// License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. -// -// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// +// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License along // with VirtualFluids (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>. // @@ -42,526 +42,514 @@ using namespace std; // Konstruktor GbCuboid3D::GbCuboid3D() : GbObject3D() { - this->setName("cuboid"); - this->p1 = new GbPoint3D(0.0, 0.0, 0.0); - this->p2 = new GbPoint3D(0.0, 0.0, 0.0); - this->p1->addObserver(this); - this->p2->addObserver(this); + this->setName("cuboid"); + this->p1 = new GbPoint3D(0.0, 0.0, 0.0); + this->p2 = new GbPoint3D(0.0, 0.0, 0.0); + this->p1->addObserver(this); + this->p2->addObserver(this); } /*=======================================================*/ -GbCuboid3D::GbCuboid3D(const double& x1a,const double& x2a, const double& x3a, const double& x1b,const double& x2b, const double& x3b):GbObject3D() +GbCuboid3D::GbCuboid3D(const double &x1a, const double &x2a, const double &x3a, const double &x1b, const double &x2b, + const double &x3b) + : GbObject3D() { - this->setName("cuboid"); - this->p1 = new GbPoint3D(x1a, x2a, x3a); - this->p1->addObserver(this); - this->p2 = new GbPoint3D(x1b, x2b, x3b); - this->p2->addObserver(this); + this->setName("cuboid"); + this->p1 = new GbPoint3D(x1a, x2a, x3a); + this->p1->addObserver(this); + this->p2 = new GbPoint3D(x1b, x2b, x3b); + this->p2->addObserver(this); } /*=======================================================*/ -GbCuboid3D::GbCuboid3D(GbPoint3D* p1, GbPoint3D* p2) : GbObject3D() +GbCuboid3D::GbCuboid3D(GbPoint3D *p1, GbPoint3D *p2) : GbObject3D() { - this->setName("cuboid"); - if(!p1 || !p2) throw UbException(UB_EXARGS,"one point ==NULL"); - this->p1 = p1; - this->p1->addObserver(this); - this->p2 = p2; - this->p2->addObserver(this); + this->setName("cuboid"); + if (!p1 || !p2) + throw UbException(UB_EXARGS, "one point ==NULL"); + this->p1 = p1; + this->p1->addObserver(this); + this->p2 = p2; + this->p2->addObserver(this); } /*=======================================================*/ -GbCuboid3D::GbCuboid3D(GbCuboid3D* cuboid) : GbObject3D() +GbCuboid3D::GbCuboid3D(GbCuboid3D *cuboid) : GbObject3D() { - this->setName("cuboid"); - if(!cuboid->getPoint1() || !cuboid->getPoint2()) throw UbException(UB_EXARGS,"cuboid ==NULL"); - this->p1 = cuboid->getPoint1()->clone(); - this->p1->addObserver(this); - this->p2 = cuboid->getPoint2()->clone(); - this->p2->addObserver(this); + this->setName("cuboid"); + if (!cuboid->getPoint1() || !cuboid->getPoint2()) + throw UbException(UB_EXARGS, "cuboid ==NULL"); + this->p1 = cuboid->getPoint1()->clone(); + this->p1->addObserver(this); + this->p2 = cuboid->getPoint2()->clone(); + this->p2->addObserver(this); } /*=======================================================*/ // Destruktor GbCuboid3D::~GbCuboid3D() { - //cout<<"~GbCuboid3D()"<<endl; - if(this->p1) this->p1->removeObserver(this); - if(this->p2) this->p2->removeObserver(this); + // cout<<"~GbCuboid3D()"<<endl; + if (this->p1) + this->p1->removeObserver(this); + if (this->p2) + this->p2->removeObserver(this); } /*=======================================================*/ -void GbCuboid3D::finalize() -{ - if(this->p1) - { - this->p1->removeObserver(this); - this->p1->finalize(); - delete this->p1; - this->p1=NULL; - } - if(this->p2) - { - this->p2->removeObserver(this); - this->p2->finalize(); - delete this->p2; - this->p2=NULL; - } +void GbCuboid3D::finalize() +{ + if (this->p1) { + this->p1->removeObserver(this); + this->p1->finalize(); + delete this->p1; + this->p1 = NULL; + } + if (this->p2) { + this->p2->removeObserver(this); + this->p2->finalize(); + delete this->p2; + this->p2 = NULL; + } } /*=======================================================*/ -void GbCuboid3D::setPoint1(GbPoint3D* point1) -{ - if(this->p1) this->p1->removeObserver(this); - this->p1 = point1; - this->p1->addObserver(this); +void GbCuboid3D::setPoint1(GbPoint3D *point1) +{ + if (this->p1) + this->p1->removeObserver(this); + this->p1 = point1; + this->p1->addObserver(this); - this->notifyObserversObjectChanged(); + this->notifyObserversObjectChanged(); } /*=======================================================*/ -void GbCuboid3D::setPoint2(GbPoint3D* point2) -{ - if(this->p2) this->p2->removeObserver(this); - this->p2 = point2; - this->p2->addObserver(this); +void GbCuboid3D::setPoint2(GbPoint3D *point2) +{ + if (this->p2) + this->p2->removeObserver(this); + this->p2 = point2; + this->p2->addObserver(this); - this->notifyObserversObjectChanged(); + this->notifyObserversObjectChanged(); } /*=======================================================*/ -void GbCuboid3D::setPoints(GbPoint3D* point1, GbPoint3D* point2) -{ - if(this->p1) this->p1->removeObserver(this); - if(this->p2) this->p2->removeObserver(this); +void GbCuboid3D::setPoints(GbPoint3D *point1, GbPoint3D *point2) +{ + if (this->p1) + this->p1->removeObserver(this); + if (this->p2) + this->p2->removeObserver(this); - this->p1 = point1; - this->p2 = point2; + this->p1 = point1; + this->p2 = point2; - this->p1->addObserver(this); - this->p2->addObserver(this); + this->p1->addObserver(this); + this->p2->addObserver(this); - this->notifyObserversObjectChanged(); + this->notifyObserversObjectChanged(); } /*=======================================================*/ -void GbCuboid3D::setCenterCoordinates(const double& x1, const double& x2, const double& x3) +void GbCuboid3D::setCenterCoordinates(const double &x1, const double &x2, const double &x3) { - this->translate(x1-getX1Centroid(), x2-getX2Centroid(), x3-getX3Centroid() ); + this->translate(x1 - getX1Centroid(), x2 - getX2Centroid(), x3 - getX3Centroid()); } /*=======================================================*/ -double GbCuboid3D::getX1Centroid() -{ - return (0.5*(p1->x1 + p2->x1)); -} +double GbCuboid3D::getX1Centroid() { return (0.5 * (p1->x1 + p2->x1)); } /*=======================================================*/ -double GbCuboid3D::getX1Minimum() -{ - return (this->p1->x1 < this->p2->x1 ? this->p1->x1 : this->p2->x1); -} +double GbCuboid3D::getX1Minimum() { return (this->p1->x1 < this->p2->x1 ? this->p1->x1 : this->p2->x1); } /*=======================================================*/ -double GbCuboid3D::getX1Maximum() -{ - return (this->p1->x1 > this->p2->x1 ? this->p1->x1 : this->p2->x1); -} +double GbCuboid3D::getX1Maximum() { return (this->p1->x1 > this->p2->x1 ? this->p1->x1 : this->p2->x1); } /*=======================================================*/ -double GbCuboid3D::getX2Centroid() -{ - return (0.5*(p1->x2 + p2->x2)); -} +double GbCuboid3D::getX2Centroid() { return (0.5 * (p1->x2 + p2->x2)); } /*=======================================================*/ -double GbCuboid3D::getX2Minimum() -{ - return (this->p1->x2 < this->p2->x2 ? this->p1->x2 : this->p2->x2); -} +double GbCuboid3D::getX2Minimum() { return (this->p1->x2 < this->p2->x2 ? this->p1->x2 : this->p2->x2); } /*=======================================================*/ -double GbCuboid3D::getX2Maximum() -{ - return ( this->p1->x2 > this->p2->x2 ? this->p1->x2 : this->p2->x2); -} +double GbCuboid3D::getX2Maximum() { return (this->p1->x2 > this->p2->x2 ? this->p1->x2 : this->p2->x2); } /*=======================================================*/ -double GbCuboid3D::getX3Centroid() -{ - return (0.5*(p1->x3 + p2->x3)); -} +double GbCuboid3D::getX3Centroid() { return (0.5 * (p1->x3 + p2->x3)); } /*=======================================================*/ -double GbCuboid3D::getX3Minimum() -{ - return (this->p1->x3 < this->p2->x3 ? this->p1->x3 : this->p2->x3); -} +double GbCuboid3D::getX3Minimum() { return (this->p1->x3 < this->p2->x3 ? this->p1->x3 : this->p2->x3); } /*=======================================================*/ -double GbCuboid3D::getX3Maximum() -{ - return (this->p1->x3 > this->p2->x3 ? this->p1->x3 : this->p2->x3); -} +double GbCuboid3D::getX3Maximum() { return (this->p1->x3 > this->p2->x3 ? this->p1->x3 : this->p2->x3); } /*=======================================================*/ -double GbCuboid3D::getLengthX1() -{ - return (this->getX1Maximum() - this->getX1Minimum() ); -} +double GbCuboid3D::getLengthX1() { return (this->getX1Maximum() - this->getX1Minimum()); } /*=======================================================*/ -double GbCuboid3D::getLengthX2() -{ - return (this->getX2Maximum() - this->getX2Minimum()); -} +double GbCuboid3D::getLengthX2() { return (this->getX2Maximum() - this->getX2Minimum()); } /*=======================================================*/ -double GbCuboid3D::getLengthX3() -{ - return (this->getX3Maximum() - this->getX3Minimum()); -} +double GbCuboid3D::getLengthX3() { return (this->getX3Maximum() - this->getX3Minimum()); } /*=======================================================*/ -bool GbCuboid3D::isPointInGbObject3D(const double& x1p, const double& x2p, const double& x3p) +bool GbCuboid3D::isPointInGbObject3D(const double &x1p, const double &x2p, const double &x3p) { - //true, wenn 'in Object' oder 'auf Boundary'! - if (UbMath::less(x1p,this->getX1Minimum())) return false; - else if(UbMath::less(x2p,this->getX2Minimum())) return false; - else if(UbMath::less(x3p,this->getX3Minimum())) return false; - else if(UbMath::greater(x1p,this->getX1Maximum())) return false; - else if(UbMath::greater(x2p,this->getX2Maximum())) return false; - else if(UbMath::greater(x3p,this->getX3Maximum())) return false; - - return true; -} -/*=======================================================*/ -bool GbCuboid3D::isPointInGbObject3D(const double& x1p, const double& x2p, const double& x3p, bool& pointIsOnBoundary) + // true, wenn 'in Object' oder 'auf Boundary'! + if (UbMath::less(x1p, this->getX1Minimum())) + return false; + else if (UbMath::less(x2p, this->getX2Minimum())) + return false; + else if (UbMath::less(x3p, this->getX3Minimum())) + return false; + else if (UbMath::greater(x1p, this->getX1Maximum())) + return false; + else if (UbMath::greater(x2p, this->getX2Maximum())) + return false; + else if (UbMath::greater(x3p, this->getX3Maximum())) + return false; + + return true; +} +/*=======================================================*/ +bool GbCuboid3D::isPointInGbObject3D(const double &x1p, const double &x2p, const double &x3p, bool &pointIsOnBoundary) { - pointIsOnBoundary = false; - - //true, wenn 'in Object' oder 'auf Boundary'! - if (UbMath::less(x1p,this->getX1Minimum())) return false; - else if(UbMath::less(x2p,this->getX2Minimum())) return false; - else if(UbMath::less(x3p,this->getX3Minimum())) return false; - else if(UbMath::greater(x1p,this->getX1Maximum())) return false; - else if(UbMath::greater(x2p,this->getX2Maximum())) return false; - else if(UbMath::greater(x3p,this->getX3Maximum())) return false; - - if (UbMath::equal(x1p,this->getX1Minimum())) pointIsOnBoundary = true; - else if(UbMath::equal(x2p,this->getX2Minimum())) pointIsOnBoundary = true; - else if(UbMath::equal(x3p,this->getX3Minimum())) pointIsOnBoundary = true; - else if(UbMath::equal(x1p,this->getX1Maximum())) pointIsOnBoundary = true; - else if(UbMath::equal(x2p,this->getX2Maximum())) pointIsOnBoundary = true; - else if(UbMath::equal(x3p,this->getX3Maximum())) pointIsOnBoundary = true; - - return true; -} -/*=======================================================*/ -bool GbCuboid3D::isCellInsideGbObject3D(const double& x1p1,const double& x2p1,const double& x3p1,const double& x1p2,const double& x2p2,const double& x3p2) + pointIsOnBoundary = false; + + // true, wenn 'in Object' oder 'auf Boundary'! + if (UbMath::less(x1p, this->getX1Minimum())) + return false; + else if (UbMath::less(x2p, this->getX2Minimum())) + return false; + else if (UbMath::less(x3p, this->getX3Minimum())) + return false; + else if (UbMath::greater(x1p, this->getX1Maximum())) + return false; + else if (UbMath::greater(x2p, this->getX2Maximum())) + return false; + else if (UbMath::greater(x3p, this->getX3Maximum())) + return false; + + if (UbMath::equal(x1p, this->getX1Minimum())) + pointIsOnBoundary = true; + else if (UbMath::equal(x2p, this->getX2Minimum())) + pointIsOnBoundary = true; + else if (UbMath::equal(x3p, this->getX3Minimum())) + pointIsOnBoundary = true; + else if (UbMath::equal(x1p, this->getX1Maximum())) + pointIsOnBoundary = true; + else if (UbMath::equal(x2p, this->getX2Maximum())) + pointIsOnBoundary = true; + else if (UbMath::equal(x3p, this->getX3Maximum())) + pointIsOnBoundary = true; + + return true; +} +/*=======================================================*/ +bool GbCuboid3D::isCellInsideGbObject3D(const double &x1p1, const double &x2p1, const double &x3p1, const double &x1p2, + const double &x2p2, const double &x3p2) { - if ( UbMath::less (x1p1, this->getX1Minimum() ) ) return false; - else if( UbMath::less (x2p1, this->getX2Minimum() ) ) return false; - else if( UbMath::less (x3p1, this->getX3Minimum() ) ) return false; - else if( UbMath::greater(x1p2, this->getX1Maximum() ) ) return false; - else if( UbMath::greater(x2p2, this->getX2Maximum() ) ) return false; - else if( UbMath::greater(x3p2, this->getX3Maximum() ) ) return false; - - return true; -} -/*=======================================================*/ -bool GbCuboid3D::isCellCuttingGbObject3D(const double& x1a,const double& x2a,const double& x3a,const double& x1b,const double& x2b,const double& x3b) -//Merksatz: cell oder deren Volumen schneidet oder beinhaltet komplette oder Teile der CuboidUmrandung -//returns true: + if (UbMath::less(x1p1, this->getX1Minimum())) + return false; + else if (UbMath::less(x2p1, this->getX2Minimum())) + return false; + else if (UbMath::less(x3p1, this->getX3Minimum())) + return false; + else if (UbMath::greater(x1p2, this->getX1Maximum())) + return false; + else if (UbMath::greater(x2p2, this->getX2Maximum())) + return false; + else if (UbMath::greater(x3p2, this->getX3Maximum())) + return false; + + return true; +} +/*=======================================================*/ +bool GbCuboid3D::isCellCuttingGbObject3D(const double &x1a, const double &x2a, const double &x3a, const double &x1b, + const double &x2b, const double &x3b) +// Merksatz: cell oder deren Volumen schneidet oder beinhaltet komplette oder Teile der CuboidUmrandung +// returns true: // - cell cuts cuboid3D // - cell boxes cuboid3D -//returns false: +// returns false: // - cell completely inside cuboid3D ( = cuboid3D boxes cell) // - cell und cuboid3D haben kein gemeinsames Volumen { - //erstmal die dumm Loesung - if( !this->isCellInsideGbObject3D(x1a,x2a,x3a,x1b,x2b,x3b) - && this->isCellInsideOrCuttingGbObject3D(x1a,x2a,x3a,x1b,x2b,x3b) ) - { - return true; - } - - return false; - - //GbCuboid3D* cube = GbSystem3D::clipRectangle3D(*this->p1, *this->p2, x1a,x2a,x3a,x1b,x2b,x3b); - //if(cube) - //{ - // cube->finalize(); - // delete cube; - // return true; - //} - - //return false; + // erstmal die dumm Loesung + if (!this->isCellInsideGbObject3D(x1a, x2a, x3a, x1b, x2b, x3b) && + this->isCellInsideOrCuttingGbObject3D(x1a, x2a, x3a, x1b, x2b, x3b)) { + return true; + } + + return false; + + // GbCuboid3D* cube = GbSystem3D::clipRectangle3D(*this->p1, *this->p2, x1a,x2a,x3a,x1b,x2b,x3b); + // if(cube) + //{ + // cube->finalize(); + // delete cube; + // return true; + //} + + // return false; } /*=======================================================*/ -bool GbCuboid3D::isCellInsideOrCuttingGbObject3D(const double& x1a,const double& x2a,const double& x3a,const double& x1b,const double& x2b,const double& x3b) -//returns true: +bool GbCuboid3D::isCellInsideOrCuttingGbObject3D(const double &x1a, const double &x2a, const double &x3a, + const double &x1b, const double &x2b, const double &x3b) +// returns true: // - cell completely inside cuboid3D ( = cuboid3D boxes cell) // - cell cuts cuboid3D // - cell boxes cuboid3D -//returns false: +// returns false: // - cell und cuboid3D haben kein gemeinsames Volumen { - //simpler check, da unser GbCuboid3D ein AABB is: - // anfA midA endA anfB midB endB - // | x<-- dxA -->| |<-dxB->x | - // |<----------------- T --------------->| - //ist |T| <= dxA + dxB -> overlap! - - if( UbMath::lessEqual( std::fabs( this->getX1Centroid() - 0.5*(x1b+x1a) /*Tx1*/ ) - , 0.5*( this->getLengthX1() + std::fabs(x1b-x1a) /*dx1A+dx1B*/) ) - - && UbMath::lessEqual( std::fabs( this->getX2Centroid() - 0.5*(x2b+x2a) /*Tx2*/ ) - , 0.5*( this->getLengthX2() + std::fabs(x2b-x2a) /*dx2A+dx2B*/) ) - - && UbMath::lessEqual( std::fabs( this->getX3Centroid() - 0.5*(x3b+x3a) /*Tx3*/ ) - , 0.5*( this->getLengthX3() + std::fabs(x3b-x3a) /*dx3A+dx3B*/) ) ) - { - return true; + // simpler check, da unser GbCuboid3D ein AABB is: + // anfA midA endA anfB midB endB + // | x<-- dxA -->| |<-dxB->x | + // |<----------------- T --------------->| + // ist |T| <= dxA + dxB -> overlap! + + if (UbMath::lessEqual(std::fabs(this->getX1Centroid() - 0.5 * (x1b + x1a) /*Tx1*/), + 0.5 * (this->getLengthX1() + std::fabs(x1b - x1a) /*dx1A+dx1B*/)) + + && UbMath::lessEqual(std::fabs(this->getX2Centroid() - 0.5 * (x2b + x2a) /*Tx2*/), + 0.5 * (this->getLengthX2() + std::fabs(x2b - x2a) /*dx2A+dx2B*/)) + + && UbMath::lessEqual(std::fabs(this->getX3Centroid() - 0.5 * (x3b + x3a) /*Tx3*/), + 0.5 * (this->getLengthX3() + std::fabs(x3b - x3a) /*dx3A+dx3B*/))) { + return true; } return false; // if( this->isCellInsideGbObject3D(x1a,x2a,x3a,x1b,x2b,x3b) - // || this->isCellCuttingGbObject3D(x1a,x2a,x3a,x1b,x2b,x3b) ) return true; - // - //return false; + // || this->isCellCuttingGbObject3D(x1a,x2a,x3a,x1b,x2b,x3b) ) return true; + // + // return false; } /*=======================================================*/ -vector<GbTriangle3D*> GbCuboid3D::getSurfaceTriangleSet() +vector<GbTriangle3D *> GbCuboid3D::getSurfaceTriangleSet() { - vector<GbTriangle3D*> triangles; - GbPoint3D p1(getX1Minimum(),getX2Minimum(),getX3Minimum()); - GbPoint3D p2(getX1Maximum(),getX2Minimum(),getX3Minimum()); - GbPoint3D p3(getX1Maximum(),getX2Maximum(),getX3Minimum()); - GbPoint3D p4(getX1Minimum(),getX2Maximum(),getX3Minimum()); - GbPoint3D p5(getX1Minimum(),getX2Minimum(),getX3Maximum()); - GbPoint3D p6(getX1Maximum(),getX2Minimum(),getX3Maximum()); - GbPoint3D p7(getX1Maximum(),getX2Maximum(),getX3Maximum()); - GbPoint3D p8(getX1Minimum(),getX2Maximum(),getX3Maximum()); - - GbPoint3D pUnten(getX1Centroid(),getX2Centroid(),getX3Minimum()); - GbPoint3D pOben(getX1Centroid(),getX2Centroid(),getX3Maximum()); - GbPoint3D pLinks(getX1Minimum(), getX2Centroid(),getX3Centroid()); - GbPoint3D pRechts(getX1Maximum(), getX2Centroid(),getX3Centroid()); - GbPoint3D pVorne(getX1Centroid(),getX2Minimum(),getX3Centroid()); - GbPoint3D pHinten(getX1Centroid(),getX2Maximum(),getX3Centroid()); - - //"unten" - triangles.push_back(new GbTriangle3D(new GbPoint3D(p2),new GbPoint3D(pUnten),new GbPoint3D(p3))); - triangles.push_back(new GbTriangle3D(new GbPoint3D(p2),new GbPoint3D(p1),new GbPoint3D(pUnten))); - triangles.push_back(new GbTriangle3D(new GbPoint3D(p3),new GbPoint3D(pUnten),new GbPoint3D(p4))); - triangles.push_back(new GbTriangle3D(new GbPoint3D(p1),new GbPoint3D(p4),new GbPoint3D(pUnten))); - //"oben" - triangles.push_back(new GbTriangle3D(new GbPoint3D(p5),new GbPoint3D(p6),new GbPoint3D(pOben))); - triangles.push_back(new GbTriangle3D(new GbPoint3D(p6),new GbPoint3D(p7),new GbPoint3D(pOben))); - triangles.push_back(new GbTriangle3D(new GbPoint3D(p5),new GbPoint3D(pOben),new GbPoint3D(p8))); - triangles.push_back(new GbTriangle3D(new GbPoint3D(pOben),new GbPoint3D(p7),new GbPoint3D(p8))); - //"links" - triangles.push_back(new GbTriangle3D(new GbPoint3D(p4),new GbPoint3D(p1),new GbPoint3D(pLinks))); - triangles.push_back(new GbTriangle3D(new GbPoint3D(p4),new GbPoint3D(pLinks),new GbPoint3D(p8))); - triangles.push_back(new GbTriangle3D(new GbPoint3D(p8),new GbPoint3D(pLinks),new GbPoint3D(p5))); - triangles.push_back(new GbTriangle3D(new GbPoint3D(pLinks),new GbPoint3D(p1),new GbPoint3D(p5))); - //"rechts" - triangles.push_back(new GbTriangle3D(new GbPoint3D(p2),new GbPoint3D(p3),new GbPoint3D(pRechts))); - triangles.push_back(new GbTriangle3D(new GbPoint3D(pRechts),new GbPoint3D(p3),new GbPoint3D(p7))); - triangles.push_back(new GbTriangle3D(new GbPoint3D(p2),new GbPoint3D(pRechts),new GbPoint3D(p6))); - triangles.push_back(new GbTriangle3D(new GbPoint3D(pRechts),new GbPoint3D(p7),new GbPoint3D(p6))); - //"hinten" - triangles.push_back(new GbTriangle3D(new GbPoint3D(p3),new GbPoint3D(p4),new GbPoint3D(pHinten))); - triangles.push_back(new GbTriangle3D(new GbPoint3D(p3),new GbPoint3D(pHinten),new GbPoint3D(p7))); - triangles.push_back(new GbTriangle3D(new GbPoint3D(p7),new GbPoint3D(pHinten),new GbPoint3D(p8))); - triangles.push_back(new GbTriangle3D(new GbPoint3D(pHinten),new GbPoint3D(p4),new GbPoint3D(p8))); - //"vorne" - triangles.push_back(new GbTriangle3D(new GbPoint3D(p1),new GbPoint3D(p2),new GbPoint3D(pVorne))); - triangles.push_back(new GbTriangle3D(new GbPoint3D(pVorne),new GbPoint3D(p2),new GbPoint3D(p6))); - triangles.push_back(new GbTriangle3D(new GbPoint3D(p1),new GbPoint3D(pVorne),new GbPoint3D(p5))); - triangles.push_back(new GbTriangle3D(new GbPoint3D(pVorne),new GbPoint3D(p6),new GbPoint3D(p5))); - return triangles; -} -/*=======================================================*/ -void GbCuboid3D::addSurfaceTriangleSet(vector<UbTupleFloat3>& nodes, vector<UbTupleInt3>& triangles) + vector<GbTriangle3D *> triangles; + GbPoint3D p1(getX1Minimum(), getX2Minimum(), getX3Minimum()); + GbPoint3D p2(getX1Maximum(), getX2Minimum(), getX3Minimum()); + GbPoint3D p3(getX1Maximum(), getX2Maximum(), getX3Minimum()); + GbPoint3D p4(getX1Minimum(), getX2Maximum(), getX3Minimum()); + GbPoint3D p5(getX1Minimum(), getX2Minimum(), getX3Maximum()); + GbPoint3D p6(getX1Maximum(), getX2Minimum(), getX3Maximum()); + GbPoint3D p7(getX1Maximum(), getX2Maximum(), getX3Maximum()); + GbPoint3D p8(getX1Minimum(), getX2Maximum(), getX3Maximum()); + + GbPoint3D pUnten(getX1Centroid(), getX2Centroid(), getX3Minimum()); + GbPoint3D pOben(getX1Centroid(), getX2Centroid(), getX3Maximum()); + GbPoint3D pLinks(getX1Minimum(), getX2Centroid(), getX3Centroid()); + GbPoint3D pRechts(getX1Maximum(), getX2Centroid(), getX3Centroid()); + GbPoint3D pVorne(getX1Centroid(), getX2Minimum(), getX3Centroid()); + GbPoint3D pHinten(getX1Centroid(), getX2Maximum(), getX3Centroid()); + + //"unten" + triangles.push_back(new GbTriangle3D(new GbPoint3D(p2), new GbPoint3D(pUnten), new GbPoint3D(p3))); + triangles.push_back(new GbTriangle3D(new GbPoint3D(p2), new GbPoint3D(p1), new GbPoint3D(pUnten))); + triangles.push_back(new GbTriangle3D(new GbPoint3D(p3), new GbPoint3D(pUnten), new GbPoint3D(p4))); + triangles.push_back(new GbTriangle3D(new GbPoint3D(p1), new GbPoint3D(p4), new GbPoint3D(pUnten))); + //"oben" + triangles.push_back(new GbTriangle3D(new GbPoint3D(p5), new GbPoint3D(p6), new GbPoint3D(pOben))); + triangles.push_back(new GbTriangle3D(new GbPoint3D(p6), new GbPoint3D(p7), new GbPoint3D(pOben))); + triangles.push_back(new GbTriangle3D(new GbPoint3D(p5), new GbPoint3D(pOben), new GbPoint3D(p8))); + triangles.push_back(new GbTriangle3D(new GbPoint3D(pOben), new GbPoint3D(p7), new GbPoint3D(p8))); + //"links" + triangles.push_back(new GbTriangle3D(new GbPoint3D(p4), new GbPoint3D(p1), new GbPoint3D(pLinks))); + triangles.push_back(new GbTriangle3D(new GbPoint3D(p4), new GbPoint3D(pLinks), new GbPoint3D(p8))); + triangles.push_back(new GbTriangle3D(new GbPoint3D(p8), new GbPoint3D(pLinks), new GbPoint3D(p5))); + triangles.push_back(new GbTriangle3D(new GbPoint3D(pLinks), new GbPoint3D(p1), new GbPoint3D(p5))); + //"rechts" + triangles.push_back(new GbTriangle3D(new GbPoint3D(p2), new GbPoint3D(p3), new GbPoint3D(pRechts))); + triangles.push_back(new GbTriangle3D(new GbPoint3D(pRechts), new GbPoint3D(p3), new GbPoint3D(p7))); + triangles.push_back(new GbTriangle3D(new GbPoint3D(p2), new GbPoint3D(pRechts), new GbPoint3D(p6))); + triangles.push_back(new GbTriangle3D(new GbPoint3D(pRechts), new GbPoint3D(p7), new GbPoint3D(p6))); + //"hinten" + triangles.push_back(new GbTriangle3D(new GbPoint3D(p3), new GbPoint3D(p4), new GbPoint3D(pHinten))); + triangles.push_back(new GbTriangle3D(new GbPoint3D(p3), new GbPoint3D(pHinten), new GbPoint3D(p7))); + triangles.push_back(new GbTriangle3D(new GbPoint3D(p7), new GbPoint3D(pHinten), new GbPoint3D(p8))); + triangles.push_back(new GbTriangle3D(new GbPoint3D(pHinten), new GbPoint3D(p4), new GbPoint3D(p8))); + //"vorne" + triangles.push_back(new GbTriangle3D(new GbPoint3D(p1), new GbPoint3D(p2), new GbPoint3D(pVorne))); + triangles.push_back(new GbTriangle3D(new GbPoint3D(pVorne), new GbPoint3D(p2), new GbPoint3D(p6))); + triangles.push_back(new GbTriangle3D(new GbPoint3D(p1), new GbPoint3D(pVorne), new GbPoint3D(p5))); + triangles.push_back(new GbTriangle3D(new GbPoint3D(pVorne), new GbPoint3D(p6), new GbPoint3D(p5))); + return triangles; +} +/*=======================================================*/ +void GbCuboid3D::addSurfaceTriangleSet(vector<UbTupleFloat3> &nodes, vector<UbTupleInt3> &triangles) { - /*0*/nodes.push_back( makeUbTuple((float)getX1Minimum(),(float)getX2Minimum(),(float)getX3Minimum())); - /*1*/nodes.push_back( makeUbTuple((float)getX1Maximum(),(float)getX2Minimum(),(float)getX3Minimum())); - /*2*/nodes.push_back( makeUbTuple((float)getX1Maximum(),(float)getX2Maximum(),(float)getX3Minimum())); - /*3*/nodes.push_back( makeUbTuple((float)getX1Minimum(),(float)getX2Maximum(),(float)getX3Minimum())); - - /*4*/nodes.push_back( makeUbTuple((float)getX1Minimum(),(float)getX2Minimum(),(float)getX3Maximum())); - /*5*/nodes.push_back( makeUbTuple((float)getX1Maximum(),(float)getX2Minimum(),(float)getX3Maximum())); - /*6*/nodes.push_back( makeUbTuple((float)getX1Maximum(),(float)getX2Maximum(),(float)getX3Maximum())); - /*7*/nodes.push_back( makeUbTuple((float)getX1Minimum(),(float)getX2Maximum(),(float)getX3Maximum())); - - //"unten" - triangles.push_back( makeUbTuple( 0, 1, 2) ); - triangles.push_back( makeUbTuple( 0, 2, 3) ); - //"oben" - triangles.push_back( makeUbTuple( 4, 5, 6) ); - triangles.push_back( makeUbTuple( 4, 6, 7) ); - //"links" - triangles.push_back( makeUbTuple( 0, 3, 7) ); - triangles.push_back( makeUbTuple( 0, 7, 4) ); - //"rechts" - triangles.push_back( makeUbTuple( 1, 2, 6) ); - triangles.push_back( makeUbTuple( 1, 6, 5) ); - //"hinten" - triangles.push_back( makeUbTuple( 3, 2, 7) ); - triangles.push_back( makeUbTuple( 2, 7, 6) ); - //"vorne" - triangles.push_back( makeUbTuple( 0, 1, 5) ); - triangles.push_back( makeUbTuple( 0, 5, 4) ); -} -/*=======================================================*/ -string GbCuboid3D::toString() + /*0*/ nodes.push_back(makeUbTuple((float)getX1Minimum(), (float)getX2Minimum(), (float)getX3Minimum())); + /*1*/ nodes.push_back(makeUbTuple((float)getX1Maximum(), (float)getX2Minimum(), (float)getX3Minimum())); + /*2*/ nodes.push_back(makeUbTuple((float)getX1Maximum(), (float)getX2Maximum(), (float)getX3Minimum())); + /*3*/ nodes.push_back(makeUbTuple((float)getX1Minimum(), (float)getX2Maximum(), (float)getX3Minimum())); + + /*4*/ nodes.push_back(makeUbTuple((float)getX1Minimum(), (float)getX2Minimum(), (float)getX3Maximum())); + /*5*/ nodes.push_back(makeUbTuple((float)getX1Maximum(), (float)getX2Minimum(), (float)getX3Maximum())); + /*6*/ nodes.push_back(makeUbTuple((float)getX1Maximum(), (float)getX2Maximum(), (float)getX3Maximum())); + /*7*/ nodes.push_back(makeUbTuple((float)getX1Minimum(), (float)getX2Maximum(), (float)getX3Maximum())); + + //"unten" + triangles.push_back(makeUbTuple(0, 1, 2)); + triangles.push_back(makeUbTuple(0, 2, 3)); + //"oben" + triangles.push_back(makeUbTuple(4, 5, 6)); + triangles.push_back(makeUbTuple(4, 6, 7)); + //"links" + triangles.push_back(makeUbTuple(0, 3, 7)); + triangles.push_back(makeUbTuple(0, 7, 4)); + //"rechts" + triangles.push_back(makeUbTuple(1, 2, 6)); + triangles.push_back(makeUbTuple(1, 6, 5)); + //"hinten" + triangles.push_back(makeUbTuple(3, 2, 7)); + triangles.push_back(makeUbTuple(2, 7, 6)); + //"vorne" + triangles.push_back(makeUbTuple(0, 1, 5)); + triangles.push_back(makeUbTuple(0, 5, 4)); +} +/*=======================================================*/ +string GbCuboid3D::toString() { - stringstream ss; - ss<<"GbCuboid3D["; - ss<<"p1="<<this->p1->toString(); - ss<<", p2="<<this->p2->toString(); - ss<<"]"; - return ss.str(); + stringstream ss; + ss << "GbCuboid3D["; + ss << "p1=" << this->p1->toString(); + ss << ", p2=" << this->p2->toString(); + ss << "]"; + return ss.str(); } /*=======================================================*/ -GbPoint3D* GbCuboid3D::calculateInterSectionPoint3D(GbPoint3D& /*point1*/, GbPoint3D& /*point2*/) +GbPoint3D *GbCuboid3D::calculateInterSectionPoint3D(GbPoint3D & /*point1*/, GbPoint3D & /*point2*/) { - throw UbException(UB_EXARGS,"not correct implemented"); + throw UbException(UB_EXARGS, "not correct implemented"); } /*=======================================================*/ -GbLine3D* GbCuboid3D::createClippedLine3D(GbPoint3D& point1, GbPoint3D& point2) +GbLine3D *GbCuboid3D::createClippedLine3D(GbPoint3D &point1, GbPoint3D &point2) { - return GbSystem3D::createClipLine3D(point1, point2, - p1->getX1Coordinate(),p1->getX2Coordinate(),p1->getX3Coordinate(), - p2->getX1Coordinate(),p2->getX2Coordinate(),p2->getX3Coordinate() ); + return GbSystem3D::createClipLine3D(point1, point2, p1->getX1Coordinate(), p1->getX2Coordinate(), + p1->getX3Coordinate(), p2->getX1Coordinate(), p2->getX2Coordinate(), + p2->getX3Coordinate()); } /*==========================================================*/ -void GbCuboid3D::objectChanged(UbObservable* changedObject) +void GbCuboid3D::objectChanged(UbObservable *changedObject) { - GbPoint3D* point = dynamic_cast<GbPoint3D*>(changedObject); - if(!point || (this->p1!=point && this->p2!=point)) return; + GbPoint3D *point = dynamic_cast<GbPoint3D *>(changedObject); + if (!point || (this->p1 != point && this->p2 != point)) + return; - this->notifyObserversObjectChanged(); + this->notifyObserversObjectChanged(); } /*==========================================================*/ -void GbCuboid3D::objectWillBeDeleted(UbObservable* objectForDeletion) +void GbCuboid3D::objectWillBeDeleted(UbObservable *objectForDeletion) { - if(this->p1) - { - UbObservable* observedObj = dynamic_cast<UbObservable*>(this->p1); - if(objectForDeletion == observedObj) { this->p1 = NULL; } - } - if(this->p2) - { - UbObservable* observedObj = dynamic_cast<UbObservable*>(this->p2); - if(objectForDeletion == observedObj) { this->p2 = NULL; } - } - //ACHTUNG: eigentlich muessten in allen methoden von GbLine if abfragen fuer NULL pointer hin... toDo + if (this->p1) { + UbObservable *observedObj = dynamic_cast<UbObservable *>(this->p1); + if (objectForDeletion == observedObj) { + this->p1 = NULL; + } + } + if (this->p2) { + UbObservable *observedObj = dynamic_cast<UbObservable *>(this->p2); + if (objectForDeletion == observedObj) { + this->p2 = NULL; + } + } + // ACHTUNG: eigentlich muessten in allen methoden von GbLine if abfragen fuer NULL pointer hin... toDo } /*=======================================================*/ -void GbCuboid3D::translate(const double& tx1, const double& tx2, const double& tx3) -{ - this->p1->translate(tx1, tx2, tx3); - this->p2->translate(tx1, tx2, tx3); - this->notifyObserversObjectChanged(); +void GbCuboid3D::translate(const double &tx1, const double &tx2, const double &tx3) +{ + this->p1->translate(tx1, tx2, tx3); + this->p2->translate(tx1, tx2, tx3); + this->notifyObserversObjectChanged(); } /*=======================================================*/ -void GbCuboid3D::scale(const double& sx1, const double& sx2, const double& sx3) -{ - double lenX1 = this->getLengthX1(); - double lenX2 = this->getLengthX2(); - double lenX3 = this->getLengthX3(); +void GbCuboid3D::scale(const double &sx1, const double &sx2, const double &sx3) +{ + double lenX1 = this->getLengthX1(); + double lenX2 = this->getLengthX2(); + double lenX3 = this->getLengthX3(); - double deltaX1 = lenX1*sx1 - lenX1; - double deltaX2 = lenX2*sx2 - lenX2; - double deltaX3 = lenX3*sx3 - lenX3; + double deltaX1 = lenX1 * sx1 - lenX1; + double deltaX2 = lenX2 * sx2 - lenX2; + double deltaX3 = lenX3 * sx3 - lenX3; - double p1X1 = this->p1->getX1Coordinate(); - double p1X2 = this->p1->getX2Coordinate(); - double p1X3 = this->p1->getX3Coordinate(); + double p1X1 = this->p1->getX1Coordinate(); + double p1X2 = this->p1->getX2Coordinate(); + double p1X3 = this->p1->getX3Coordinate(); - double p2X1 = this->p2->getX1Coordinate(); - double p2X2 = this->p2->getX2Coordinate(); - double p2X3 = this->p2->getX3Coordinate(); + double p2X1 = this->p2->getX1Coordinate(); + double p2X2 = this->p2->getX2Coordinate(); + double p2X3 = this->p2->getX3Coordinate(); - this->p1->setCoordinates(p1X1 - 0.5*deltaX1 - ,p1X2 - 0.5*deltaX2 - ,p1X3 - 0.5*deltaX3); + this->p1->setCoordinates(p1X1 - 0.5 * deltaX1, p1X2 - 0.5 * deltaX2, p1X3 - 0.5 * deltaX3); - this->p2->setCoordinates(p2X1 + 0.5*deltaX1 - ,p2X2 + 0.5*deltaX2 - ,p2X3 + 0.5*deltaX3); + this->p2->setCoordinates(p2X1 + 0.5 * deltaX1, p2X2 + 0.5 * deltaX2, p2X3 + 0.5 * deltaX3); } /*==========================================================*/ -double GbCuboid3D::getCellVolumeInsideGbObject3D(const double& x1a,const double& x2a,const double& x3a,const double& x1b,const double& x2b,const double& x3b) +double GbCuboid3D::getCellVolumeInsideGbObject3D(const double &x1a, const double &x2a, const double &x3a, + const double &x1b, const double &x2b, const double &x3b) { - if( this->isCellInsideGbObject3D(x1a,x2a,x3a,x1b,x2b,x3b) ) return 1.0*(x1b-x1a)*(x2b-x2a)*(x3b-x3a); - if( !(this->isCellCuttingGbObject3D(x1a,x2a,x3a,x1b,x2b,x3b)) ) return 0.0; - - GbCuboid3D* cube = GbSystem3D::clipRectangle3D(*this->p1, *this->p2, x1a,x2a,x3a,x1b,x2b,x3b); - - if(cube) - { - double eps; - eps = (cube->getLengthX1())*(cube->getLengthX2())*(cube->getLengthX3()); - cube->finalize(); - delete cube; - return eps; - } - return 0.0; + if (this->isCellInsideGbObject3D(x1a, x2a, x3a, x1b, x2b, x3b)) + return 1.0 * (x1b - x1a) * (x2b - x2a) * (x3b - x3a); + if (!(this->isCellCuttingGbObject3D(x1a, x2a, x3a, x1b, x2b, x3b))) + return 0.0; + + GbCuboid3D *cube = GbSystem3D::clipRectangle3D(*this->p1, *this->p2, x1a, x2a, x3a, x1b, x2b, x3b); + + if (cube) { + double eps; + eps = (cube->getLengthX1()) * (cube->getLengthX2()) * (cube->getLengthX3()); + cube->finalize(); + delete cube; + return eps; + } + return 0.0; } /*==========================================================*/ -double GbCuboid3D::getIntersectionRaytraceFactor(const double& x1, const double& x2, const double& x3, const double& rx1, const double& rx2, const double& rx3) +double GbCuboid3D::getIntersectionRaytraceFactor(const double &x1, const double &x2, const double &x3, + const double &rx1, const double &rx2, const double &rx3) { - double minB[3] = { this->getX1Minimum(), this->getX2Minimum(), this->getX3Minimum() }; - double maxB[3] = { this->getX1Maximum(), this->getX2Maximum(), this->getX3Maximum() }; - double origin[3] = { x1, x2, x3 }; //point - double dir[3] = { rx1, rx2, rx3 }; //ray - - bool inside = true; - char quadrant[3]; - int whichPlane; - double maxT[3]; - double candidatePlane[3]; - - /* Find candidate planes; this loop can be avoided if - rays cast all from the eye(assume perpsective view) */ - for(int i=0; i<3; i++) - { - if(origin[i] < minB[i]) - { - quadrant[i] = 1/*LEFT*/; - candidatePlane[i] = minB[i]; - inside = false; - } - else if(origin[i] > maxB[i]) - { - quadrant[i] = 0/*RIGHT*/; - candidatePlane[i] = maxB[i]; - inside = false; - } - else - { - quadrant[i] = 2/*MIDDLE*/; - } - } - /* Ray origin inside bounding box */ - if(inside) - { - //throw UbException(UB_EXARGS,"not done"); - return 0.0; - } - - /* Calculate T distances to candidate planes */ - for(int i=0; i<3; i++) - { - if( quadrant[i]!=2/*MIDDLE*/ && fabs(dir[i])>1.E-10 ) - { - maxT[i] = (candidatePlane[i]-origin[i])/dir[i]; - } - else maxT[i] = -1.0; - } - - /* Get largest of the maxT's for final choice of intersection */ - whichPlane = 0; - for(int i=1; i<3; i++) - if (maxT[whichPlane] < maxT[i]) + double minB[3] = { this->getX1Minimum(), this->getX2Minimum(), this->getX3Minimum() }; + double maxB[3] = { this->getX1Maximum(), this->getX2Maximum(), this->getX3Maximum() }; + double origin[3] = { x1, x2, x3 }; // point + double dir[3] = { rx1, rx2, rx3 }; // ray + + bool inside = true; + char quadrant[3]; + int whichPlane; + double maxT[3]; + double candidatePlane[3]; + + /* Find candidate planes; this loop can be avoided if + rays cast all from the eye(assume perpsective view) */ + for (int i = 0; i < 3; i++) { + if (origin[i] < minB[i]) { + quadrant[i] = 1 /*LEFT*/; + candidatePlane[i] = minB[i]; + inside = false; + } else if (origin[i] > maxB[i]) { + quadrant[i] = 0 /*RIGHT*/; + candidatePlane[i] = maxB[i]; + inside = false; + } else { + quadrant[i] = 2 /*MIDDLE*/; + } + } + /* Ray origin inside bounding box */ + if (inside) { + // throw UbException(UB_EXARGS,"not done"); + return 0.0; + } + + /* Calculate T distances to candidate planes */ + for (int i = 0; i < 3; i++) { + if (quadrant[i] != 2 /*MIDDLE*/ && fabs(dir[i]) > 1.E-10) { + maxT[i] = (candidatePlane[i] - origin[i]) / dir[i]; + } else + maxT[i] = -1.0; + } + + /* Get largest of the maxT's for final choice of intersection */ + whichPlane = 0; + for (int i = 1; i < 3; i++) + if (maxT[whichPlane] < maxT[i]) whichPlane = i; - - /* Check final candidate actually inside box */ - if(maxT[whichPlane]< -1.E-10) return -1.0; - double dummy; - for(int i= 0; i<3; i++) - { - if( whichPlane!= i) - { - dummy = origin[i] + maxT[whichPlane]*dir[i]; - if(dummy < minB[i] || dummy > maxB[i]) - return -1.0; - } - } - - return maxT[whichPlane] ; /* ray hits box */ -} + /* Check final candidate actually inside box */ + if (maxT[whichPlane] < -1.E-10) + return -1.0; + double dummy; + for (int i = 0; i < 3; i++) { + if (whichPlane != i) { + dummy = origin[i] + maxT[whichPlane] * dir[i]; + if (dummy < minB[i] || dummy > maxB[i]) + return -1.0; + } + } + + return maxT[whichPlane]; /* ray hits box */ +} diff --git a/src/basics/geometry3d/GbCuboid3D.h b/src/basics/geometry3d/GbCuboid3D.h index 9a099737bd2259a78fcf05e826b488214ef1cc64..f0a0b0f9884999050495156f3c547b26d6398e61 100644 --- a/src/basics/geometry3d/GbCuboid3D.h +++ b/src/basics/geometry3d/GbCuboid3D.h @@ -1,28 +1,28 @@ //======================================================================================= -// ____ ____ __ ______ __________ __ __ __ __ -// \ \ | | | | | _ \ |___ ___| | | | | / \ | | -// \ \ | | | | | |_) | | | | | | | / \ | | -// \ \ | | | | | _ / | | | | | | / /\ \ | | -// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ -// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| -// \ \ | | ________________________________________________________________ -// \ \ | | | ______________________________________________________________| -// \ \| | | | __ __ __ __ ______ _______ -// \ | | |_____ | | | | | | | | | _ \ / _____) -// \ | | _____| | | | | | | | | | | \ \ \_______ +// ____ ____ __ ______ __________ __ __ __ __ +// \ \ | | | | | _ \ |___ ___| | | | | / \ | | +// \ \ | | | | | |_) | | | | | | | / \ | | +// \ \ | | | | | _ / | | | | | | / /\ \ | | +// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ +// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| +// \ \ | | ________________________________________________________________ +// \ \ | | | ______________________________________________________________| +// \ \| | | | __ __ __ __ ______ _______ +// \ | | |_____ | | | | | | | | | _ \ / _____) +// \ | | _____| | | | | | | | | | | \ \ \_______ // \ | | | | |_____ | \_/ | | | | |_/ / _____ | -// \ _____| |__| |________| \_______/ |__| |______/ (_______/ +// \ _____| |__| |________| \_______/ |__| |______/ (_______/ // -// This file is part of VirtualFluids. VirtualFluids is free software: you can +// This file is part of VirtualFluids. VirtualFluids is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of +// License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. -// -// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// +// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License along // with VirtualFluids (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>. // @@ -33,12 +33,12 @@ #ifndef GBCUBOID3D_H #define GBCUBOID3D_H -#include <vector> #include <cmath> +#include <vector> #include <GbPoint3D.h> -#include <basics/utilities/UbObserver.h> #include <basics/utilities/UbMath.h> +#include <basics/utilities/UbObserver.h> class GbLine3D; class GbObject3DCreator; @@ -50,96 +50,98 @@ using GbCuboid3DPtr = SPtr<GbCuboid3D>; //! \brief This Class provides basic 3D box objects. class GbCuboid3D : public GbObject3D, public UbObserver { -public: - GbCuboid3D(); - GbCuboid3D(const double& minX1,const double& minX2, const double& minX3, const double& maxX1,const double& maxX2, const double& maxX3); - GbCuboid3D(GbPoint3D *p1, GbPoint3D *p2); - GbCuboid3D(GbCuboid3D *cuboid); - ~GbCuboid3D() override; - - GbCuboid3D* clone() override { return new GbCuboid3D(this); } - void finalize() override; - - GbPoint3D* getPoint1() { return this->p1; } - GbPoint3D* getPoint2() { return this->p2; } - - void setPoint1(GbPoint3D* point1); - void setPoint2(GbPoint3D* point2); - void setPoints(GbPoint3D* point1, GbPoint3D* point2); - - double getX1Centroid() override; - double getX1Minimum() override; - double getX1Maximum() override; - double getX2Centroid() override; - double getX2Minimum() override; - double getX2Maximum() override; - double getX3Centroid() override; - double getX3Minimum() override; - double getX3Maximum() override; - void setCenterCoordinates(const double& x1, const double& x2, const double& x3) override; - - void translate(const double& x1, const double& x2, const double& x3) override; - void rotate(const double& rx1, const double& rx2, const double& rx3) override {} - void scale(const double& sx1, const double& sx2, const double& sx3) override; - - double getLengthX1(); - double getLengthX2(); - double getLengthX3(); - - bool isPointInGbObject3D(const double& x1p, const double& x2p, const double& x3p, bool& pointIsOnBoundary) override; - bool isPointInGbObject3D(const double& x1p, const double& x2p, const double& x3p) override; - bool isCellInsideGbObject3D(const double& x1a,const double& x2a,const double& x3a,const double& x1b,const double& x2b,const double& x3b) override; - bool isCellCuttingGbObject3D(const double& x1a,const double& x2a,const double& x3a,const double& x1b,const double& x2b,const double& x3b) override; - bool isCellInsideOrCuttingGbObject3D(const double& x1a,const double& x2a,const double& x3a,const double& x1b,const double& x2b,const double& x3b) override; - double getCellVolumeInsideGbObject3D(const double& x1a,const double& x2a,const double& x3a,const double& x1b,const double& x2b,const double& x3b) override; - - GbPoint3D* calculateInterSectionPoint3D(GbPoint3D& point1, GbPoint3D &point2); - //GbCuboid3D* createClippedRectangle3D(const double& x1a,const double& x2a,const double& x3a,const double& x1b,const double& x2b,const double& x3b); - GbLine3D* createClippedLine3D(GbPoint3D& point1, GbPoint3D& point2) override; - - std::vector<GbTriangle3D*> getSurfaceTriangleSet() override; - void addSurfaceTriangleSet(std::vector<UbTupleFloat3>& nodes, std::vector<UbTupleInt3>& triangles) override; - - bool hasRaytracing() override { return true; } - /*|r| must be 1! einheitsvector!!*/ - double getIntersectionRaytraceFactor(const double& x1, const double& x2, const double& x3, const double& rx1, const double& rx2, const double& rx3) override; - - - double getDistance(GbPoint3D* p) - { - return this->getDistance( p->getX1Coordinate(), p->getX2Coordinate(), p->getX3Coordinate() ); - } - double getDistance(const double& x1p, const double& x2p, const double& x3p) - { - throw UbException( UB_EXARGS, "not implemented" ); - - // falls punkt innerhalt ist: minimalen abstand ausrechnen - if( this->isPointInGbObject3D(x1p,x2p,x3p) ) - { - double x1Dist = UbMath::min( std::abs(x1p-this->getX1Minimum()),std::abs(x1p-this->getX1Maximum()) ); - double x2Dist = UbMath::min( std::abs(x2p-this->getX2Minimum()),std::abs(x2p-this->getX2Maximum()) ); - double x3Dist = UbMath::min( std::abs(x3p-this->getX3Minimum()),std::abs(x3p-this->getX3Maximum()) ); - - return UbMath::min( x1Dist, x2Dist, x3Dist ); - } - else - { - - } - } - - std::string toString() override; - - //virtuelle Methoden von UbObserver - void objectChanged(UbObservable* changedObject) override; - void objectWillBeDeleted(UbObservable* objectForDeletion) override; - - - using GbObject3D::isPointInGbObject3D; //Grund: dadurch muss man hier isPointInGbObject3D(GbPoint3D*) nicht ausprogrammieren, welche sonst hier "ueberdeckt" waere +public: + GbCuboid3D(); + GbCuboid3D(const double &minX1, const double &minX2, const double &minX3, const double &maxX1, const double &maxX2, + const double &maxX3); + GbCuboid3D(GbPoint3D *p1, GbPoint3D *p2); + GbCuboid3D(GbCuboid3D *cuboid); + ~GbCuboid3D() override; + + GbCuboid3D *clone() override { return new GbCuboid3D(this); } + void finalize() override; + + GbPoint3D *getPoint1() { return this->p1; } + GbPoint3D *getPoint2() { return this->p2; } + + void setPoint1(GbPoint3D *point1); + void setPoint2(GbPoint3D *point2); + void setPoints(GbPoint3D *point1, GbPoint3D *point2); + + double getX1Centroid() override; + double getX1Minimum() override; + double getX1Maximum() override; + double getX2Centroid() override; + double getX2Minimum() override; + double getX2Maximum() override; + double getX3Centroid() override; + double getX3Minimum() override; + double getX3Maximum() override; + void setCenterCoordinates(const double &x1, const double &x2, const double &x3) override; + + void translate(const double &x1, const double &x2, const double &x3) override; + void rotate(const double &rx1, const double &rx2, const double &rx3) override {} + void scale(const double &sx1, const double &sx2, const double &sx3) override; + + double getLengthX1(); + double getLengthX2(); + double getLengthX3(); + + bool isPointInGbObject3D(const double &x1p, const double &x2p, const double &x3p, bool &pointIsOnBoundary) override; + bool isPointInGbObject3D(const double &x1p, const double &x2p, const double &x3p) override; + bool isCellInsideGbObject3D(const double &x1a, const double &x2a, const double &x3a, const double &x1b, + const double &x2b, const double &x3b) override; + bool isCellCuttingGbObject3D(const double &x1a, const double &x2a, const double &x3a, const double &x1b, + const double &x2b, const double &x3b) override; + bool isCellInsideOrCuttingGbObject3D(const double &x1a, const double &x2a, const double &x3a, const double &x1b, + const double &x2b, const double &x3b) override; + double getCellVolumeInsideGbObject3D(const double &x1a, const double &x2a, const double &x3a, const double &x1b, + const double &x2b, const double &x3b) override; + + GbPoint3D *calculateInterSectionPoint3D(GbPoint3D &point1, GbPoint3D &point2); + // GbCuboid3D* createClippedRectangle3D(const double& x1a,const double& x2a,const double& x3a,const double& + // x1b,const double& x2b,const double& x3b); + GbLine3D *createClippedLine3D(GbPoint3D &point1, GbPoint3D &point2) override; + + std::vector<GbTriangle3D *> getSurfaceTriangleSet() override; + void addSurfaceTriangleSet(std::vector<UbTupleFloat3> &nodes, std::vector<UbTupleInt3> &triangles) override; + + bool hasRaytracing() override { return true; } + /*|r| must be 1! einheitsvector!!*/ + double getIntersectionRaytraceFactor(const double &x1, const double &x2, const double &x3, const double &rx1, + const double &rx2, const double &rx3) override; + + double getDistance(GbPoint3D *p) + { + return this->getDistance(p->getX1Coordinate(), p->getX2Coordinate(), p->getX3Coordinate()); + } + double getDistance(const double &x1p, const double &x2p, const double &x3p) + { + throw UbException(UB_EXARGS, "not implemented"); + + // falls punkt innerhalt ist: minimalen abstand ausrechnen + if (this->isPointInGbObject3D(x1p, x2p, x3p)) { + double x1Dist = UbMath::min(std::abs(x1p - this->getX1Minimum()), std::abs(x1p - this->getX1Maximum())); + double x2Dist = UbMath::min(std::abs(x2p - this->getX2Minimum()), std::abs(x2p - this->getX2Maximum())); + double x3Dist = UbMath::min(std::abs(x3p - this->getX3Minimum()), std::abs(x3p - this->getX3Maximum())); + + return UbMath::min(x1Dist, x2Dist, x3Dist); + } else { + } + } + + std::string toString() override; + + // virtuelle Methoden von UbObserver + void objectChanged(UbObservable *changedObject) override; + void objectWillBeDeleted(UbObservable *objectForDeletion) override; + + using GbObject3D::isPointInGbObject3D; // Grund: dadurch muss man hier isPointInGbObject3D(GbPoint3D*) nicht + // ausprogrammieren, welche sonst hier "ueberdeckt" waere protected: - GbPoint3D* p1; - GbPoint3D* p2; + GbPoint3D *p1; + GbPoint3D *p2; }; -#endif +#endif diff --git a/src/basics/geometry3d/GbCylinder3D.cpp b/src/basics/geometry3d/GbCylinder3D.cpp index e2bb839dd0734cd4b7eb91160afe431d2beea756..f6d1ed6e701fb7e3209a6e67720dc3d41d8f1aeb 100644 --- a/src/basics/geometry3d/GbCylinder3D.cpp +++ b/src/basics/geometry3d/GbCylinder3D.cpp @@ -1,1228 +1,1314 @@ +#include <basics/utilities/UbInfinity.h> #include <geometry3d/GbCylinder3D.h> -#include <geometry3d/GbSystem3D.h> #include <geometry3d/GbPoint3D.h> +#include <geometry3d/GbSystem3D.h> #include <geometry3d/GbTriangle3D.h> -#include <basics/utilities/UbInfinity.h> using namespace std; // Konstruktor /*==========================================================*/ GbCylinder3D::GbCylinder3D() - + { - this->setName("cylinder"); - GbPoint3D* p1 = new GbPoint3D(); - GbPoint3D* p2 = new GbPoint3D(); - mLine = new GbLine3D(p1,p2); - this->mLine->addObserver(this); - mRad = 0.0; - cylinderType = GbCylinder3D::NOTPARALLELTOAXIS; - this->mLine->addObserver(this); - this->calculateValues(); + this->setName("cylinder"); + GbPoint3D *p1 = new GbPoint3D(); + GbPoint3D *p2 = new GbPoint3D(); + mLine = new GbLine3D(p1, p2); + this->mLine->addObserver(this); + mRad = 0.0; + cylinderType = GbCylinder3D::NOTPARALLELTOAXIS; + this->mLine->addObserver(this); + this->calculateValues(); } /*=======================================================*/ -GbCylinder3D::GbCylinder3D(GbCylinder3D* cylinder) +GbCylinder3D::GbCylinder3D(GbCylinder3D *cylinder) { - this->setName("cylinder"); - mRad = cylinder->getRadius(); - cylinderType = cylinder->cylinderType; - mLine = cylinder->getLine()->clone(); + this->setName("cylinder"); + mRad = cylinder->getRadius(); + cylinderType = cylinder->cylinderType; + mLine = cylinder->getLine()->clone(); - this->mLine->addObserver(this); - this->calculateValues(); + this->mLine->addObserver(this); + this->calculateValues(); } /*==========================================================*/ -GbCylinder3D::GbCylinder3D(const double& x1a,const double& x2a, const double& x3a, const double& x1b,const double& x2b, const double& x3b, const double& rad) +GbCylinder3D::GbCylinder3D(const double &x1a, const double &x2a, const double &x3a, const double &x1b, + const double &x2b, const double &x3b, const double &rad) { - this->setName("cylinder"); - mLine = new GbLine3D; - //Min/Max, damit gewaehrleistet ist, dass Startpunkt immer der "Achs-Minimale" ist - //Anm.: bin nich tsicher ob weiter unten irgendwelche Algos drauf beruhen... - // geht nat nur solange, zylinder achs-parallel, aber das ist erzeit so!!! - mLine->setPoints( new GbPoint3D(min(x1a,x1b), min(x2a,x2b), min(x3a,x3b)) - ,new GbPoint3D(max(x1a,x1b), max(x2a,x2b), max(x3a,x3b))); - //mLine->setPoints( new GbPoint3D(x1a,x2a,x3a),new GbPoint3D(x1b, x2b ,x3b )); - this->mLine->addObserver(this); - mRad = fabs(rad); - - this->calculateValues(); + this->setName("cylinder"); + mLine = new GbLine3D; + // Min/Max, damit gewaehrleistet ist, dass Startpunkt immer der "Achs-Minimale" ist + // Anm.: bin nich tsicher ob weiter unten irgendwelche Algos drauf beruhen... + // geht nat nur solange, zylinder achs-parallel, aber das ist erzeit so!!! + mLine->setPoints(new GbPoint3D(min(x1a, x1b), min(x2a, x2b), min(x3a, x3b)), + new GbPoint3D(max(x1a, x1b), max(x2a, x2b), max(x3a, x3b))); + // mLine->setPoints( new GbPoint3D(x1a,x2a,x3a),new GbPoint3D(x1b, x2b ,x3b )); + this->mLine->addObserver(this); + mRad = fabs(rad); + + this->calculateValues(); } /*==========================================================*/ -GbCylinder3D::GbCylinder3D(GbPoint3D* p1, GbPoint3D* p2, const double& rad) +GbCylinder3D::GbCylinder3D(GbPoint3D *p1, GbPoint3D *p2, const double &rad) { - this->setName("cylinder"); - mRad = rad; + this->setName("cylinder"); + mRad = rad; - mLine = new GbLine3D(p1,p2); - this->mLine->addObserver(this); - this->calculateValues(); + mLine = new GbLine3D(p1, p2); + this->mLine->addObserver(this); + this->calculateValues(); } /*==========================================================*/ -GbCylinder3D::GbCylinder3D(GbLine3D* line, const double& rad) +GbCylinder3D::GbCylinder3D(GbLine3D *line, const double &rad) { - this->setName("cylinder"); - mRad = rad; + this->setName("cylinder"); + mRad = rad; - this->mLine = line; - this->mLine->addObserver(this); + this->mLine = line; + this->mLine->addObserver(this); - this->calculateValues(); + this->calculateValues(); } /*==========================================================*/ // Destruktor GbCylinder3D::~GbCylinder3D() { - if(mLine) this->mLine->removeObserver(this); - mLine = NULL; + if (mLine) + this->mLine->removeObserver(this); + mLine = NULL; } /*=======================================================*/ void GbCylinder3D::calculateValues() { - double x1a = mLine->getPoint1()->x1; double x1b = mLine->getPoint2()->x1; - double x2a = mLine->getPoint1()->x2; double x2b = mLine->getPoint2()->x2; - double x3a = mLine->getPoint1()->x3; double x3b = mLine->getPoint2()->x3; - - if (x1a!=x1b && x2a==x2b && x3a==x3b) this->cylinderType = X1PARALLEL; - else if(x2a!=x2b && x1a==x1b && x3a==x3b) this->cylinderType = X2PARALLEL; - else if(x3a!=x3b && x1a==x1b && x2a==x2b) this->cylinderType = X3PARALLEL; - // nach dem serialisieren ruft er den Standardkonstruktor auf wo alles 0 ist und bricht sonst hier ab - else if(x3a==x3b && x1a==x1b && x2a==x2b) this->cylinderType = X1PARALLEL; - else this->cylinderType = NOTPARALLELTOAXIS; - - if((this->cylinderType & NOTPARALLELTOAXIS)==NOTPARALLELTOAXIS) - throw UbException(UB_EXARGS,"derzeit nur zu Achsen orthogonale Zylinder erlaubt... isPointInObject3D funzt sonst ned"); - - if(this->isParallelToX1Axis()) - { - minX1 = mLine->getX1Minimum(); - maxX1 = mLine->getX1Maximum(); - minX2 = mLine->getX2Centroid()-mRad; - maxX2 = mLine->getX2Centroid()+mRad; - minX3 = mLine->getX3Centroid()-mRad; - maxX3 = mLine->getX3Centroid()+mRad; - } - else if(this->isParallelToX2Axis()) - { - minX1 = mLine->getX1Centroid()-mRad; - maxX1 = mLine->getX1Centroid()+mRad; - minX2 = mLine->getX2Minimum(); - maxX2 = mLine->getX2Maximum(); - minX3 = mLine->getX3Centroid()-mRad; - maxX3 = mLine->getX3Centroid()+mRad; - } - else if(this->isParallelToX3Axis()) - { - minX1 = mLine->getX1Centroid()-mRad; - maxX1 = mLine->getX1Centroid()+mRad; - minX2 = mLine->getX2Centroid()-mRad; - maxX2 = mLine->getX2Centroid()+mRad; - minX3 = mLine->getX3Minimum(); - maxX3 = mLine->getX3Maximum(); - } - - centerX1 = mLine->getX1Centroid(); - centerX2 = mLine->getX2Centroid(); - centerX3 = mLine->getX3Centroid(); + double x1a = mLine->getPoint1()->x1; + double x1b = mLine->getPoint2()->x1; + double x2a = mLine->getPoint1()->x2; + double x2b = mLine->getPoint2()->x2; + double x3a = mLine->getPoint1()->x3; + double x3b = mLine->getPoint2()->x3; + + if (x1a != x1b && x2a == x2b && x3a == x3b) + this->cylinderType = X1PARALLEL; + else if (x2a != x2b && x1a == x1b && x3a == x3b) + this->cylinderType = X2PARALLEL; + else if (x3a != x3b && x1a == x1b && x2a == x2b) + this->cylinderType = X3PARALLEL; + // nach dem serialisieren ruft er den Standardkonstruktor auf wo alles 0 ist und bricht sonst hier ab + else if (x3a == x3b && x1a == x1b && x2a == x2b) + this->cylinderType = X1PARALLEL; + else + this->cylinderType = NOTPARALLELTOAXIS; + + if ((this->cylinderType & NOTPARALLELTOAXIS) == NOTPARALLELTOAXIS) + throw UbException(UB_EXARGS, + "derzeit nur zu Achsen orthogonale Zylinder erlaubt... isPointInObject3D funzt sonst ned"); + + if (this->isParallelToX1Axis()) { + minX1 = mLine->getX1Minimum(); + maxX1 = mLine->getX1Maximum(); + minX2 = mLine->getX2Centroid() - mRad; + maxX2 = mLine->getX2Centroid() + mRad; + minX3 = mLine->getX3Centroid() - mRad; + maxX3 = mLine->getX3Centroid() + mRad; + } else if (this->isParallelToX2Axis()) { + minX1 = mLine->getX1Centroid() - mRad; + maxX1 = mLine->getX1Centroid() + mRad; + minX2 = mLine->getX2Minimum(); + maxX2 = mLine->getX2Maximum(); + minX3 = mLine->getX3Centroid() - mRad; + maxX3 = mLine->getX3Centroid() + mRad; + } else if (this->isParallelToX3Axis()) { + minX1 = mLine->getX1Centroid() - mRad; + maxX1 = mLine->getX1Centroid() + mRad; + minX2 = mLine->getX2Centroid() - mRad; + maxX2 = mLine->getX2Centroid() + mRad; + minX3 = mLine->getX3Minimum(); + maxX3 = mLine->getX3Maximum(); + } + + centerX1 = mLine->getX1Centroid(); + centerX2 = mLine->getX2Centroid(); + centerX3 = mLine->getX3Centroid(); } - + /*=======================================================*/ void GbCylinder3D::finalize() { - if(this->mLine) - { - mLine->finalize(); - delete mLine; - mLine=NULL; - } + if (this->mLine) { + mLine->finalize(); + delete mLine; + mLine = NULL; + } } /*=======================================================*/ double GbCylinder3D::getHeight() { - if(mLine) - return mLine->getLength(); - - return 0.0; + if (mLine) + return mLine->getLength(); + + return 0.0; } /*=======================================================*/ -GbPoint3D* GbCylinder3D::getPoint1() +GbPoint3D *GbCylinder3D::getPoint1() { - if(this->mLine) return this->mLine->getPoint1(); - return NULL; + if (this->mLine) + return this->mLine->getPoint1(); + return NULL; } /*=======================================================*/ -GbPoint3D* GbCylinder3D::getPoint2() +GbPoint3D *GbCylinder3D::getPoint2() { - if(this->mLine) return this->mLine->getPoint2(); - return NULL; + if (this->mLine) + return this->mLine->getPoint2(); + return NULL; } /*=======================================================*/ -void GbCylinder3D::setRadius(const double& radius) +void GbCylinder3D::setRadius(const double &radius) { - this->mRad = std::fabs(radius); - this->notifyObserversObjectChanged(); + this->mRad = std::fabs(radius); + this->notifyObserversObjectChanged(); } /*=======================================================*/ -void GbCylinder3D::setLine(GbLine3D* line) +void GbCylinder3D::setLine(GbLine3D *line) { - if(this->mLine) this->mLine->removeObserver(this); - this->mLine = line; - this->mLine->addObserver(this); - this->calculateValues(); + if (this->mLine) + this->mLine->removeObserver(this); + this->mLine = line; + this->mLine->addObserver(this); + this->calculateValues(); - this->notifyObserversObjectChanged(); + this->notifyObserversObjectChanged(); } /*=======================================================*/ -void GbCylinder3D::setPoint1(const double& x1, const double& x2, const double& x3) +void GbCylinder3D::setPoint1(const double &x1, const double &x2, const double &x3) { - if(!mLine->getPoint1()) throw UbException(UB_EXARGS,"line has no point1"); - mLine->getPoint1()->setCoordinates(x1,x2,x3); - this->calculateValues(); + if (!mLine->getPoint1()) + throw UbException(UB_EXARGS, "line has no point1"); + mLine->getPoint1()->setCoordinates(x1, x2, x3); + this->calculateValues(); - //this->notifyObserversObjectChanged(); //wird automatisch aufgerufen, da der point (this) benachrichtigt... + // this->notifyObserversObjectChanged(); //wird automatisch aufgerufen, da der point (this) benachrichtigt... } /*=======================================================*/ -void GbCylinder3D::setPoint2(const double& x1, const double& x2, const double& x3) +void GbCylinder3D::setPoint2(const double &x1, const double &x2, const double &x3) { - if(!mLine->getPoint2()) throw UbException(UB_EXARGS,"line has no point2"); - mLine->getPoint2()->setCoordinates(x1,x2,x3); - this->calculateValues(); + if (!mLine->getPoint2()) + throw UbException(UB_EXARGS, "line has no point2"); + mLine->getPoint2()->setCoordinates(x1, x2, x3); + this->calculateValues(); - //this->notifyObserversObjectChanged(); //wird automatisch aufgerufen, da der point (this) benachrichtigt... + // this->notifyObserversObjectChanged(); //wird automatisch aufgerufen, da der point (this) benachrichtigt... } /*==========================================================*/ -bool GbCylinder3D::isPointInGbObject3D(const double& x1p, const double& x2p, const double& x3p) +bool GbCylinder3D::isPointInGbObject3D(const double &x1p, const double &x2p, const double &x3p) { - //true, wenn 'in Object' oder 'auf Boundary'! - if ( this->isParallelToX1Axis() && (UbMath::less(x1p,minX1) || UbMath::greater(x1p,maxX1))) return false; - else if( this->isParallelToX2Axis() && (UbMath::less(x2p,minX2) || UbMath::greater(x2p,maxX2))) return false; - else if( this->isParallelToX3Axis() && (UbMath::less(x3p,minX3) || UbMath::greater(x3p,maxX3))) return false; - else if( this->isNotParallelToAxis() ) throw UbException(UB_EXARGS,"derzeit nur zu Achsen orthogonale Zylinder erlaubt... isPointInObject3D funzt sonst ned"); - - return UbMath::lessEqual(fabs(mLine->getDistance(x1p,x2p,x3p)),fabs(mRad)); + // true, wenn 'in Object' oder 'auf Boundary'! + if (this->isParallelToX1Axis() && (UbMath::less(x1p, minX1) || UbMath::greater(x1p, maxX1))) + return false; + else if (this->isParallelToX2Axis() && (UbMath::less(x2p, minX2) || UbMath::greater(x2p, maxX2))) + return false; + else if (this->isParallelToX3Axis() && (UbMath::less(x3p, minX3) || UbMath::greater(x3p, maxX3))) + return false; + else if (this->isNotParallelToAxis()) + throw UbException(UB_EXARGS, + "derzeit nur zu Achsen orthogonale Zylinder erlaubt... isPointInObject3D funzt sonst ned"); + + return UbMath::lessEqual(fabs(mLine->getDistance(x1p, x2p, x3p)), fabs(mRad)); } /*==========================================================*/ -bool GbCylinder3D::isPointInGbObject3D(const double& x1p, const double& x2p, const double& x3p, bool& pointIsOnBoundary) +bool GbCylinder3D::isPointInGbObject3D(const double &x1p, const double &x2p, const double &x3p, bool &pointIsOnBoundary) { - //funzt derzeit nur bei achsparallelen cylindern - pointIsOnBoundary = false; - - if ( this->isParallelToX1Axis() && (UbMath::less(x1p,minX1) || UbMath::greater(x1p,maxX1))) return false; - else if( this->isParallelToX2Axis() && (UbMath::less(x2p,minX2) || UbMath::greater(x2p,maxX2))) return false; - else if( this->isParallelToX3Axis() && (UbMath::less(x3p,minX3) || UbMath::greater(x3p,maxX3))) return false; - else if( this->isNotParallelToAxis() ) throw UbException(UB_EXARGS,"derzeit nur zu Achsen orthogonale Zylinder erlaubt... isPointInObject3D funzt sonst ned"); - - //true, wenn 'in Object' oder 'auf Boundary'! - - double dis = mLine->getDistance(x1p,x2p,x3p); - - if(UbMath::equal(dis,mRad)) pointIsOnBoundary = true; - - if (this->isParallelToX1Axis() && (UbMath::equal(x1p,minX1) || UbMath::equal(x1p,maxX1))) pointIsOnBoundary = true; - else if(this->isParallelToX2Axis() && (UbMath::equal(x2p,minX2) || UbMath::equal(x2p,maxX2))) pointIsOnBoundary = true; - else if(this->isParallelToX3Axis() && (UbMath::equal(x3p,minX3) || UbMath::equal(x3p,maxX3))) pointIsOnBoundary = true; - - return UbMath::lessEqual(dis,mRad); + // funzt derzeit nur bei achsparallelen cylindern + pointIsOnBoundary = false; + + if (this->isParallelToX1Axis() && (UbMath::less(x1p, minX1) || UbMath::greater(x1p, maxX1))) + return false; + else if (this->isParallelToX2Axis() && (UbMath::less(x2p, minX2) || UbMath::greater(x2p, maxX2))) + return false; + else if (this->isParallelToX3Axis() && (UbMath::less(x3p, minX3) || UbMath::greater(x3p, maxX3))) + return false; + else if (this->isNotParallelToAxis()) + throw UbException(UB_EXARGS, + "derzeit nur zu Achsen orthogonale Zylinder erlaubt... isPointInObject3D funzt sonst ned"); + + // true, wenn 'in Object' oder 'auf Boundary'! + + double dis = mLine->getDistance(x1p, x2p, x3p); + + if (UbMath::equal(dis, mRad)) + pointIsOnBoundary = true; + + if (this->isParallelToX1Axis() && (UbMath::equal(x1p, minX1) || UbMath::equal(x1p, maxX1))) + pointIsOnBoundary = true; + else if (this->isParallelToX2Axis() && (UbMath::equal(x2p, minX2) || UbMath::equal(x2p, maxX2))) + pointIsOnBoundary = true; + else if (this->isParallelToX3Axis() && (UbMath::equal(x3p, minX3) || UbMath::equal(x3p, maxX3))) + pointIsOnBoundary = true; + + return UbMath::lessEqual(dis, mRad); } /*==========================================================*/ string GbCylinder3D::toString() { - stringstream ss; - ss<<"GbCylinder3D["; - ss<<"line="<<this->mLine->toString(); - ss<<", r="<<this->mRad; - ss<<"]"; - return(ss.str()); + stringstream ss; + ss << "GbCylinder3D["; + ss << "line=" << this->mLine->toString(); + ss << ", r=" << this->mRad; + ss << "]"; + return (ss.str()); } /*=======================================================*/ -bool GbCylinder3D::isCellInsideGbObject3D(const double& x1a,const double& x2a,const double& x3a,const double& x1b,const double& x2b,const double& x3b) +bool GbCylinder3D::isCellInsideGbObject3D(const double &x1a, const double &x2a, const double &x3a, const double &x1b, + const double &x2b, const double &x3b) { - if( this->isPointInGbObject3D(x1a, x2a, x3a) - && this->isPointInGbObject3D(x1b, x2a, x3a) - && this->isPointInGbObject3D(x1b, x2b, x3a) - && this->isPointInGbObject3D(x1a, x2b, x3a) - && this->isPointInGbObject3D(x1a, x2a, x3b) - && this->isPointInGbObject3D(x1b, x2a, x3b) - && this->isPointInGbObject3D(x1b, x2b, x3b) - && this->isPointInGbObject3D(x1a, x2b, x3b)) - { - return true; - } - return false; + if (this->isPointInGbObject3D(x1a, x2a, x3a) && this->isPointInGbObject3D(x1b, x2a, x3a) && + this->isPointInGbObject3D(x1b, x2b, x3a) && this->isPointInGbObject3D(x1a, x2b, x3a) && + this->isPointInGbObject3D(x1a, x2a, x3b) && this->isPointInGbObject3D(x1b, x2a, x3b) && + this->isPointInGbObject3D(x1b, x2b, x3b) && this->isPointInGbObject3D(x1a, x2b, x3b)) { + return true; + } + return false; } /*==========================================================*/ -bool GbCylinder3D::isCellCuttingGbObject3D(const double& x1a,const double& x2a,const double& x3a,const double& x1b,const double& x2b,const double& x3b) -//Merksatz: cell oder deren Volumen schneidet oder beinhaltet komplette oder Teile der CuboidUmrandung -//returns true: +bool GbCylinder3D::isCellCuttingGbObject3D(const double &x1a, const double &x2a, const double &x3a, const double &x1b, + const double &x2b, const double &x3b) +// Merksatz: cell oder deren Volumen schneidet oder beinhaltet komplette oder Teile der CuboidUmrandung +// returns true: // - cell cuts cylinder3D // - cell boxes cylinder3D -//returns false: +// returns false: // - cell completely inside cylinder3D ( = cylinder3D boxes cell) // - cell und cylinder3D haben kein gemeinsames Volumen { - //erstmal wieder die dumm Loesung - if( this->isCellInsideOrCuttingGbObject3D(x1a,x2a,x3a,x1b,x2b,x3b) - && !this->isCellInsideGbObject3D(x1a,x2a,x3a,x1b,x2b,x3b) ) - { - return true; - } - - return false; + // erstmal wieder die dumm Loesung + if (this->isCellInsideOrCuttingGbObject3D(x1a, x2a, x3a, x1b, x2b, x3b) && + !this->isCellInsideGbObject3D(x1a, x2a, x3a, x1b, x2b, x3b)) { + return true; + } + + return false; } /*==========================================================*/ -bool GbCylinder3D::isCellInsideOrCuttingGbObject3D(const double& x1a,const double& x2a,const double& x3a,const double& x1b,const double& x2b,const double& x3b) -//returns true: +bool GbCylinder3D::isCellInsideOrCuttingGbObject3D(const double &x1a, const double &x2a, const double &x3a, + const double &x1b, const double &x2b, const double &x3b) +// returns true: // - cell completely inside cylinder3D ( = cylinder3D boxes cell) // - cell cuts cylinder3D // - cell boxes cylinder3D -//returns false: +// returns false: // - cell und cylinder3D haben kein gemeinsames Volumen { - double dmin = 0.0; - - if(this->isParallelToX1Axis()) - { - //check liegt Cell komplett !x1-ausserhalb"? - if( UbMath::less (x1a,minX1) && UbMath::less (x1b,minX1) ) return false; - if( UbMath::greater(x1a,maxX1) && UbMath::greater(x1b,maxX1) ) return false; - - //mittelpunkt kreis-querschnitt - double& midX2 = mLine->getPoint1()->x2; - double& midX3 = mLine->getPoint1()->x3; - if ( UbMath::less ( midX2, x2a ) ) dmin += std::pow( midX2 - x2a, 2.0 ); - else if( UbMath::greater( midX2, x2b ) ) dmin += std::pow( midX2 - x2b, 2.0 ); - if ( UbMath::less ( midX3, x3a ) ) dmin += std::pow( midX3 - x3a, 2.0 ); - else if( UbMath::greater( midX3, x3b ) ) dmin += std::pow( midX3 - x3b, 2.0 ); - if( UbMath::lessEqual( dmin, mRad*mRad) ) return true; - - return false; - } - else if(this->isParallelToX2Axis()) - { - //check liegt Cell komplett !x2-ausserhalb"? - if( UbMath::less (x2a,minX2) && UbMath::less (x2b,minX2) ) return false; - if( UbMath::greater(x2a,maxX2 ) && UbMath::greater(x2b,maxX2) ) return false; - - //mittelpunkt kreis-querschnitt - double& midX1 = mLine->getPoint1()->x1; - double& midX3 = mLine->getPoint1()->x3; - if ( UbMath::less ( midX1, x1a ) ) dmin += std::pow( midX1 - x1a, 2.0 ); - else if( UbMath::greater( midX1, x1b ) ) dmin += std::pow( midX1 - x1b, 2.0 ); - if ( UbMath::less ( midX3, x3a ) ) dmin += std::pow( midX3 - x3a, 2.0 ); - else if( UbMath::greater( midX3, x3b ) ) dmin += std::pow( midX3 - x3b, 2.0 ); - if( UbMath::lessEqual( dmin, mRad*mRad ) ) return true; - - } - else if(this->isParallelToX3Axis()) - { - //check liegt Cell komplett !x3-ausserhalb"? - if( UbMath::less (x3a,minX3) && UbMath::less (x3b,minX3) ) return false; - if( UbMath::greater(x3a,maxX3) && UbMath::greater(x3b,maxX3) ) return false; - - //mittelpunkt kreis-querschnitt - double& midX1 = mLine->getPoint1()->x1; - double& midX2 = mLine->getPoint1()->x2; - if ( UbMath::less ( midX1, x1a ) ) dmin += std::pow( midX1 - x1a, 2.0 ); - else if( UbMath::greater( midX1, x1b ) ) dmin += std::pow( midX1 - x1b, 2.0 ); - if ( UbMath::less ( midX2, x2a ) ) dmin += std::pow( midX2 - x2a, 2.0 ); - else if( UbMath::greater( midX2, x2b ) ) dmin += std::pow( midX2 - x2b, 2.0 ); - if( UbMath::lessEqual( dmin, mRad*mRad ) ) return true; - } - - return false; + double dmin = 0.0; + + if (this->isParallelToX1Axis()) { + // check liegt Cell komplett !x1-ausserhalb"? + if (UbMath::less(x1a, minX1) && UbMath::less(x1b, minX1)) + return false; + if (UbMath::greater(x1a, maxX1) && UbMath::greater(x1b, maxX1)) + return false; + + // mittelpunkt kreis-querschnitt + double &midX2 = mLine->getPoint1()->x2; + double &midX3 = mLine->getPoint1()->x3; + if (UbMath::less(midX2, x2a)) + dmin += std::pow(midX2 - x2a, 2.0); + else if (UbMath::greater(midX2, x2b)) + dmin += std::pow(midX2 - x2b, 2.0); + if (UbMath::less(midX3, x3a)) + dmin += std::pow(midX3 - x3a, 2.0); + else if (UbMath::greater(midX3, x3b)) + dmin += std::pow(midX3 - x3b, 2.0); + if (UbMath::lessEqual(dmin, mRad * mRad)) + return true; + + return false; + } else if (this->isParallelToX2Axis()) { + // check liegt Cell komplett !x2-ausserhalb"? + if (UbMath::less(x2a, minX2) && UbMath::less(x2b, minX2)) + return false; + if (UbMath::greater(x2a, maxX2) && UbMath::greater(x2b, maxX2)) + return false; + + // mittelpunkt kreis-querschnitt + double &midX1 = mLine->getPoint1()->x1; + double &midX3 = mLine->getPoint1()->x3; + if (UbMath::less(midX1, x1a)) + dmin += std::pow(midX1 - x1a, 2.0); + else if (UbMath::greater(midX1, x1b)) + dmin += std::pow(midX1 - x1b, 2.0); + if (UbMath::less(midX3, x3a)) + dmin += std::pow(midX3 - x3a, 2.0); + else if (UbMath::greater(midX3, x3b)) + dmin += std::pow(midX3 - x3b, 2.0); + if (UbMath::lessEqual(dmin, mRad * mRad)) + return true; + + } else if (this->isParallelToX3Axis()) { + // check liegt Cell komplett !x3-ausserhalb"? + if (UbMath::less(x3a, minX3) && UbMath::less(x3b, minX3)) + return false; + if (UbMath::greater(x3a, maxX3) && UbMath::greater(x3b, maxX3)) + return false; + + // mittelpunkt kreis-querschnitt + double &midX1 = mLine->getPoint1()->x1; + double &midX2 = mLine->getPoint1()->x2; + if (UbMath::less(midX1, x1a)) + dmin += std::pow(midX1 - x1a, 2.0); + else if (UbMath::greater(midX1, x1b)) + dmin += std::pow(midX1 - x1b, 2.0); + if (UbMath::less(midX2, x2a)) + dmin += std::pow(midX2 - x2a, 2.0); + else if (UbMath::greater(midX2, x2b)) + dmin += std::pow(midX2 - x2b, 2.0); + if (UbMath::lessEqual(dmin, mRad * mRad)) + return true; + } + + return false; } /*==========================================================*/ -GbLine3D* GbCylinder3D::createClippedLine3D(GbPoint3D& point1, GbPoint3D& point2) +GbLine3D *GbCylinder3D::createClippedLine3D(GbPoint3D &point1, GbPoint3D &point2) { - //liefert immer "innere" linie, also der teil, der vom Zylinder "abgeschnitten" wurde! - //funktioniert derzeit nur mit achsenparallelen Zylindern! - vector<GbPoint3D*> schnittpunkte; - - double xa,ya,za,xb,yb,zb,xm,ym,zStart,zEnd,t1,t2; - - if(this->isParallelToX1Axis()) - { - xa = point1.getX2Coordinate(); - ya = point1.getX3Coordinate(); - za = point1.getX1Coordinate(); - xb = point2.getX2Coordinate(); - yb = point2.getX3Coordinate(); - zb = point2.getX1Coordinate(); - xm = mLine->getPoint1()->getX2Coordinate(); - ym = mLine->getPoint1()->getX3Coordinate(); - zStart = mLine->getPoint1()->getX1Coordinate(); - zEnd = mLine->getPoint2()->getX1Coordinate(); - } - else if(this->isParallelToX2Axis()) - { - xa = point1.getX1Coordinate(); - ya = point1.getX3Coordinate(); - za = point1.getX2Coordinate(); - xb = point2.getX1Coordinate(); - yb = point2.getX3Coordinate(); - zb = point2.getX2Coordinate(); - xm = mLine->getPoint1()->getX1Coordinate(); - ym = mLine->getPoint1()->getX3Coordinate(); - zStart = mLine->getPoint1()->getX2Coordinate(); - zEnd = mLine->getPoint2()->getX2Coordinate(); - } - else if(this->isParallelToX3Axis()) - { - xa = point1.getX1Coordinate(); - ya = point1.getX2Coordinate(); - za = point1.getX3Coordinate(); - xb = point2.getX1Coordinate(); - yb = point2.getX2Coordinate(); - zb = point2.getX3Coordinate(); - xm = mLine->getPoint1()->getX1Coordinate(); - ym = mLine->getPoint1()->getX2Coordinate(); - zStart = mLine->getPoint1()->getX3Coordinate(); - zEnd = mLine->getPoint2()->getX3Coordinate(); - } - else throw UbException(UB_EXARGS,"funktioniert derzeit nur mit achsenparallelen Zylindern"); - - //Bestimmung des Schnittpunktes mit unendlich ausgedehntem Zylinder - double r = mRad; - double r2 = r*r; - double xa2 = xa*xa; - double xb2 = xb*xb; - double ya2 = ya*ya; - double yb2 = yb*yb; - double xm2 = xm*xm; - double ym2 = ym*ym; - - double wurzel = 2.0*xa*xm*yb2+2.0*ya*ym*xb2-2.0*xa*xb*r2+2.0*xa*xb*ym2-2.0*ya*yb*r2+2.0*xa2*yb*ym - +2.0*xa*xm*ya*ym-2.0*xa*xm*yb*ym-2.0*ya*ym*xb*xm+2.0*xb*xm*yb*ym+2.0*ya*yb*xa*xb - -2.0*ya*yb*xa*xm-2.0*ya*yb*xb*xm-2.0*xa*xb*ya*ym-2.0*xa*xb*yb*ym+2.0*xb*xm*ya2 - +2.0*ya*yb*xm2-xa2*yb2-xb2*ya2+xa2*r2-xa2*ym2+xb2*r2-xb2*ym2+ya2*r2-ya2*xm2+yb2*r2-yb2*xm2; - double nenner = -2.0*(ya*yb+xa*xb)+xa2+xb2+ya2+yb2; - double zaehler = 2.0*(-xa*xm+xb*xm-ya*ym+yb*ym)+xa2-xb2+ya2-yb2; - - if(UbMath::greaterEqual(wurzel,0.0) && !UbMath::zero(nenner) )//fabs(nenner)>1.E-13) - { - t1 = (zaehler+2.0*sqrt(wurzel))/nenner; - t2 = (zaehler-2.0*sqrt(wurzel))/nenner; - - if(UbMath::inClosedInterval(t1, -1.0, 1.0)) //Schnittpunkt innerhalb der Strecke - { - double x = xa*(0.5-0.5*t1)+xb*(0.5+0.5*t1); - double y = ya*(0.5-0.5*t1)+yb*(0.5+0.5*t1); - double z = za*(0.5-0.5*t1)+zb*(0.5+0.5*t1); - - if(UbMath::inClosedInterval(z,zStart,zEnd)) //zWert muss sich innerhal der cylinderlaenge befinden - { - if (this->isParallelToX1Axis()) schnittpunkte.push_back(new GbPoint3D(z,x,y)); - else if(this->isParallelToX2Axis()) schnittpunkte.push_back(new GbPoint3D(x,z,y)); - else if(this->isParallelToX3Axis()) schnittpunkte.push_back(new GbPoint3D(x,y,z)); - } - } - if(fabs(t2-t1)>1.E-13 && UbMath::inClosedInterval(t2, -1.0, 1.0)) //Schnittpunkt innerhalb der Strecke - { - double x = xa*(0.5-0.5*t2)+xb*(0.5+0.5*t2); - double y = ya*(0.5-0.5*t2)+yb*(0.5+0.5*t2); - double z = za*(0.5-0.5*t2)+zb*(0.5+0.5*t2); - - if(UbMath::inClosedInterval(z,zStart,zEnd)) //zWert muss sich innerhal der cylinderlaenge befinden - { - if (this->isParallelToX1Axis()) schnittpunkte.push_back(new GbPoint3D(z,x,y)); - else if(this->isParallelToX2Axis()) schnittpunkte.push_back(new GbPoint3D(x,z,y)); - else if(this->isParallelToX3Axis()) schnittpunkte.push_back(new GbPoint3D(x,y,z)); - } - } - } - //wenn nenner==0 -> Strecke parallel zu Zylinder! Es muss noch auf Schnittpunkt mit "Deckeln" geprueft werden - - //Schnittpunkt mit Seitenflaechen bestimmen - //hierzu wird der schnittpunkt der gegebnen strecke mit den seitenflaechenberechnet - //als erstes "schaut man seitlich auf den Zylinder" --> kreisflaechen wird als strecke darsgestellt - //mit diesen "strecken" berechnet man Schnittpunkte. - //anschliessend wird geprueft, ob der berechnete Schnittpunkt ueberhaupt im kreis liegt - //falls ja --> Schnittpunkt vorhanden - - double x1a,y1a,z1a,x1b,y1b,z1b, //uebergebene Strecke - x2a,y2a,x2b,y2b, //erste "Kreisstrecke" - x3a,y3a,x3b,y3b, //zweite "Kreisstrecke" - y2m,/*z2m,*/y3m,z3m; - double nenner1ab; - - if(this->isParallelToX1Axis()) - { - x1a=point1.getX1Coordinate(); - y1a=point1.getX2Coordinate(); - z1a=point1.getX3Coordinate(); - x1b=point2.getX1Coordinate(); - y1b=point2.getX2Coordinate(); - z1b=point2.getX3Coordinate(); - - x2a=mLine->getPoint1()->getX1Coordinate(); - y2m=mLine->getPoint1()->getX2Coordinate(); -// z2m=mLine->getPoint1()->getX3Coordinate(); - y2a=y2m+mRad; - x2b=mLine->getPoint1()->getX1Coordinate(); - y2b=y2m-mRad; - - x3a=mLine->getPoint2()->getX1Coordinate(); // - y3m=mLine->getPoint2()->getX2Coordinate(); - z3m=mLine->getPoint2()->getX3Coordinate(); - y3a=y3m+mRad; - x3b=mLine->getPoint2()->getX1Coordinate(); - y3b=y3m-mRad; - } - else if(this->isParallelToX2Axis()) - { - x1a=point1.getX2Coordinate(); - y1a=point1.getX3Coordinate(); - z1a=point1.getX1Coordinate(); - x1b=point2.getX2Coordinate(); - y1b=point2.getX3Coordinate(); - z1b=point2.getX1Coordinate(); - - x2a=mLine->getPoint1()->getX2Coordinate(); - y2m=mLine->getPoint1()->getX3Coordinate(); -// z2m=mLine->getPoint1()->getX1Coordinate(); - y2a=y2m+mRad; - x2b=mLine->getPoint1()->getX2Coordinate(); - y2b=y2m-mRad; - - x3a=mLine->getPoint2()->getX2Coordinate(); // - y3m=mLine->getPoint2()->getX3Coordinate(); - z3m=mLine->getPoint2()->getX1Coordinate(); - y3a=y3m+mRad; - x3b=mLine->getPoint2()->getX2Coordinate(); - y3b=y3m-mRad; - } - else if(this->isParallelToX3Axis()) - { - x1a=point1.getX3Coordinate(); - y1a=point1.getX2Coordinate(); - z1a=point1.getX1Coordinate(); - x1b=point2.getX3Coordinate(); - y1b=point2.getX2Coordinate(); - z1b=point2.getX1Coordinate(); - - x2a=mLine->getPoint1()->getX3Coordinate(); - y2m=mLine->getPoint1()->getX2Coordinate(); -// z2m=mLine->getPoint1()->getX1Coordinate(); - y2a=y2m+mRad; - x2b=mLine->getPoint1()->getX3Coordinate(); - y2b=y2m-mRad; - - x3a=mLine->getPoint2()->getX3Coordinate(); // - y3m=mLine->getPoint2()->getX2Coordinate(); - z3m=mLine->getPoint2()->getX1Coordinate(); - y3a=y3m+mRad; - x3b=mLine->getPoint2()->getX3Coordinate(); - y3b=y3m-mRad; - } - else throw UbException(UB_EXARGS,"funktioniert derzeit nur mit achsenparallelen Zylindern"); - - nenner1ab = -y1a*x2a+y1a*x2b+y1b*x2a-y1b*x2b+x1a*y2a-x1a*y2b-x1b*y2a+x1b*y2b; - //double nenner2 = x1a*y2a-x1a*y2b-x1b*y2a+x1b*y2b-y1a*x2a+y1a*x2b+y1b*x2a-y1b*x2b; - if(fabs(nenner1ab)>1.E-13) //andernfalls sind die beiden Strecken parallel - { - //tStrecke ist fuer gegebene Strecke! - double t1ab = (-y1a*x2a+y1a*x2b-2.0*y2a*x2b+x1a*y2a-x1a*y2b-x1b*y2b+2.0*y2b*x2a+x1b*y2a-y1b*x2a+y1b*x2b)/nenner1ab; - //double tStrecke = -(-x1a*y2a+x1a*y2b+2.0*y2a*x2b+y1a*x2a-2.0*x2a*y2b-y1a*x2b+y1b*x2a-y1b*x2b-x1b*y2a+x1b*y2b)/nenner2; - //wenn -1 <= t2 <= +1 -> SP mit strecke - if(UbMath::inClosedInterval(t1ab, -1.0, 1.0)) //Schnittpunkt innerhalb der Strecke - { - double x,y,z,abstand_ist; - if (this->isParallelToX1Axis()) - { - x = x1a*(0.5-0.5*t1ab)+x1b*(0.5+0.5*t1ab); - y = y1a*(0.5-0.5*t1ab)+y1b*(0.5+0.5*t1ab); - z = z1a*(0.5-0.5*t1ab)+z1b*(0.5+0.5*t1ab); - abstand_ist=sqrt((y3m-y)*(y3m-y)+(z3m-z)*(z3m-z)); - } - else if(this->isParallelToX2Axis()) - { - y = x1a*(0.5-0.5*t1ab)+x1b*(0.5+0.5*t1ab); - z = y1a*(0.5-0.5*t1ab)+y1b*(0.5+0.5*t1ab); - x = z1a*(0.5-0.5*t1ab)+z1b*(0.5+0.5*t1ab); - abstand_ist=sqrt((y3m-z)*(y3m-z)+(z3m-x)*(z3m-x)); - } - else if(this->isParallelToX3Axis()) - { - z = x1a*(0.5-0.5*t1ab)+x1b*(0.5+0.5*t1ab); - y = y1a*(0.5-0.5*t1ab)+y1b*(0.5+0.5*t1ab); - x = z1a*(0.5-0.5*t1ab)+z1b*(0.5+0.5*t1ab); - abstand_ist=sqrt((y3m-y)*(y3m-y)+(z3m-x)*(z3m-x)); - } - else throw UbException(UB_EXARGS,"funktioniert derzeit nur mit achsenparallelen Zylindern"); - - //pruefen, ob Punkt Element von Kreisflaeche - //double abstand_ist=sqrt((y2m-y)*(y2m-y)+(z2m-z)*(z2m-z)); - if(UbMath::lessEqual(abstand_ist,mRad)) //Punkt ist Schnittpunkt - { - bool exists = false; - for(int pos=0;pos<(int)schnittpunkte.size();++pos) + // liefert immer "innere" linie, also der teil, der vom Zylinder "abgeschnitten" wurde! + // funktioniert derzeit nur mit achsenparallelen Zylindern! + vector<GbPoint3D *> schnittpunkte; + + double xa, ya, za, xb, yb, zb, xm, ym, zStart, zEnd, t1, t2; + + if (this->isParallelToX1Axis()) { + xa = point1.getX2Coordinate(); + ya = point1.getX3Coordinate(); + za = point1.getX1Coordinate(); + xb = point2.getX2Coordinate(); + yb = point2.getX3Coordinate(); + zb = point2.getX1Coordinate(); + xm = mLine->getPoint1()->getX2Coordinate(); + ym = mLine->getPoint1()->getX3Coordinate(); + zStart = mLine->getPoint1()->getX1Coordinate(); + zEnd = mLine->getPoint2()->getX1Coordinate(); + } else if (this->isParallelToX2Axis()) { + xa = point1.getX1Coordinate(); + ya = point1.getX3Coordinate(); + za = point1.getX2Coordinate(); + xb = point2.getX1Coordinate(); + yb = point2.getX3Coordinate(); + zb = point2.getX2Coordinate(); + xm = mLine->getPoint1()->getX1Coordinate(); + ym = mLine->getPoint1()->getX3Coordinate(); + zStart = mLine->getPoint1()->getX2Coordinate(); + zEnd = mLine->getPoint2()->getX2Coordinate(); + } else if (this->isParallelToX3Axis()) { + xa = point1.getX1Coordinate(); + ya = point1.getX2Coordinate(); + za = point1.getX3Coordinate(); + xb = point2.getX1Coordinate(); + yb = point2.getX2Coordinate(); + zb = point2.getX3Coordinate(); + xm = mLine->getPoint1()->getX1Coordinate(); + ym = mLine->getPoint1()->getX2Coordinate(); + zStart = mLine->getPoint1()->getX3Coordinate(); + zEnd = mLine->getPoint2()->getX3Coordinate(); + } else + throw UbException(UB_EXARGS, "funktioniert derzeit nur mit achsenparallelen Zylindern"); + + // Bestimmung des Schnittpunktes mit unendlich ausgedehntem Zylinder + double r = mRad; + double r2 = r * r; + double xa2 = xa * xa; + double xb2 = xb * xb; + double ya2 = ya * ya; + double yb2 = yb * yb; + double xm2 = xm * xm; + double ym2 = ym * ym; + + double wurzel = 2.0 * xa * xm * yb2 + 2.0 * ya * ym * xb2 - 2.0 * xa * xb * r2 + 2.0 * xa * xb * ym2 - + 2.0 * ya * yb * r2 + 2.0 * xa2 * yb * ym + 2.0 * xa * xm * ya * ym - 2.0 * xa * xm * yb * ym - + 2.0 * ya * ym * xb * xm + 2.0 * xb * xm * yb * ym + 2.0 * ya * yb * xa * xb - + 2.0 * ya * yb * xa * xm - 2.0 * ya * yb * xb * xm - 2.0 * xa * xb * ya * ym - + 2.0 * xa * xb * yb * ym + 2.0 * xb * xm * ya2 + 2.0 * ya * yb * xm2 - xa2 * yb2 - xb2 * ya2 + + xa2 * r2 - xa2 * ym2 + xb2 * r2 - xb2 * ym2 + ya2 * r2 - ya2 * xm2 + yb2 * r2 - yb2 * xm2; + double nenner = -2.0 * (ya * yb + xa * xb) + xa2 + xb2 + ya2 + yb2; + double zaehler = 2.0 * (-xa * xm + xb * xm - ya * ym + yb * ym) + xa2 - xb2 + ya2 - yb2; + + if (UbMath::greaterEqual(wurzel, 0.0) && !UbMath::zero(nenner)) // fabs(nenner)>1.E-13) + { + t1 = (zaehler + 2.0 * sqrt(wurzel)) / nenner; + t2 = (zaehler - 2.0 * sqrt(wurzel)) / nenner; + + if (UbMath::inClosedInterval(t1, -1.0, 1.0)) // Schnittpunkt innerhalb der Strecke + { + double x = xa * (0.5 - 0.5 * t1) + xb * (0.5 + 0.5 * t1); + double y = ya * (0.5 - 0.5 * t1) + yb * (0.5 + 0.5 * t1); + double z = za * (0.5 - 0.5 * t1) + zb * (0.5 + 0.5 * t1); + + if (UbMath::inClosedInterval(z, zStart, zEnd)) // zWert muss sich innerhal der cylinderlaenge befinden { - if( fabs(schnittpunkte[pos]->getX1Coordinate()-x)<1.E-13 - && fabs(schnittpunkte[pos]->getX2Coordinate()-y)<1.E-13 - && fabs(schnittpunkte[pos]->getX3Coordinate()-z)<1.E-13 ) exists=true; + if (this->isParallelToX1Axis()) + schnittpunkte.push_back(new GbPoint3D(z, x, y)); + else if (this->isParallelToX2Axis()) + schnittpunkte.push_back(new GbPoint3D(x, z, y)); + else if (this->isParallelToX3Axis()) + schnittpunkte.push_back(new GbPoint3D(x, y, z)); } - - if(!exists) schnittpunkte.push_back(new GbPoint3D(x,y,z)); - } - } - } - - nenner1ab = -y1a*x3a+y1a*x3b+y1b*x3a-y1b*x3b+x1a*y3a-x1a*y3b-x1b*y3a+x1b*y3b; - - if(fabs(nenner1ab)>1.E-13) //andernfalls sind die beiden Strecken parallel - { - //tStrecke ist fuer gegebene Strecke! - double t1ab = (-y1a*x3a+y1a*x3b-x1b*y3b-2.0*y3a*x3b-x1a*y3b+2.0*y3b*x3a+x1a*y3a+x1b*y3a-y1b*x3a+y1b*x3b)/nenner1ab; - - if(UbMath::inClosedInterval(t1ab, -1.0, 1.0)) //Schnittpunkt innerhalb der Strecke - { - double x,y,z,abstand_ist; - if (this->isParallelToX1Axis()) - { - x = x1a*(0.5-0.5*t1ab)+x1b*(0.5+0.5*t1ab); - y = y1a*(0.5-0.5*t1ab)+y1b*(0.5+0.5*t1ab); - z = z1a*(0.5-0.5*t1ab)+z1b*(0.5+0.5*t1ab); - abstand_ist=sqrt((y3m-y)*(y3m-y)+(z3m-z)*(z3m-z)); - } - else if(this->isParallelToX2Axis()) - { - y = x1a*(0.5-0.5*t1ab)+x1b*(0.5+0.5*t1ab); - z = y1a*(0.5-0.5*t1ab)+y1b*(0.5+0.5*t1ab); - x = z1a*(0.5-0.5*t1ab)+z1b*(0.5+0.5*t1ab); - abstand_ist=sqrt((y3m-z)*(y3m-z)+(z3m-x)*(z3m-x)); - } - else if(this->isParallelToX3Axis()) - { - z = x1a*(0.5-0.5*t1ab)+x1b*(0.5+0.5*t1ab); - y = y1a*(0.5-0.5*t1ab)+y1b*(0.5+0.5*t1ab); - x = z1a*(0.5-0.5*t1ab)+z1b*(0.5+0.5*t1ab); - abstand_ist=sqrt((y3m-y)*(y3m-y)+(z3m-x)*(z3m-x)); - } - else throw UbException(UB_EXARGS,"cylinder must be parallel to one axis"); - - //pruefen, ob Punkt Element von Kreisflaeche - //double abstand_ist=sqrt((y2m-y)*(y2m-y)+(z2m-z)*(z2m-z)); - - if(UbMath::lessEqual(abstand_ist,mRad)) //Punkt ist Schnittpunkt - { - bool exists = false; - for(int pos=0;pos<(int)schnittpunkte.size();++pos) + } + if (fabs(t2 - t1) > 1.E-13 && UbMath::inClosedInterval(t2, -1.0, 1.0)) // Schnittpunkt innerhalb der Strecke + { + double x = xa * (0.5 - 0.5 * t2) + xb * (0.5 + 0.5 * t2); + double y = ya * (0.5 - 0.5 * t2) + yb * (0.5 + 0.5 * t2); + double z = za * (0.5 - 0.5 * t2) + zb * (0.5 + 0.5 * t2); + + if (UbMath::inClosedInterval(z, zStart, zEnd)) // zWert muss sich innerhal der cylinderlaenge befinden { - if( fabs(schnittpunkte[pos]->getX1Coordinate()-x)<1.E-13 - && fabs(schnittpunkte[pos]->getX2Coordinate()-y)<1.E-13 - && fabs(schnittpunkte[pos]->getX3Coordinate()-z)<1.E-13 ) exists=true; + if (this->isParallelToX1Axis()) + schnittpunkte.push_back(new GbPoint3D(z, x, y)); + else if (this->isParallelToX2Axis()) + schnittpunkte.push_back(new GbPoint3D(x, z, y)); + else if (this->isParallelToX3Axis()) + schnittpunkte.push_back(new GbPoint3D(x, y, z)); } - - if(!exists) schnittpunkte.push_back(new GbPoint3D(x,y,z)); - } - } - } - - int nofSchnittpunkte = (int)schnittpunkte.size(); - if (nofSchnittpunkte==0) return NULL; - else if(nofSchnittpunkte >2) throw UbException(UB_EXARGS,"more than three intersection points - not possible"); - else if(nofSchnittpunkte==2) return new GbLine3D(schnittpunkte[0],schnittpunkte[1]); - else if(nofSchnittpunkte==1) - { - if (this->isPointInGbObject3D(&point1)) return new GbLine3D(schnittpunkte[0],new GbPoint3D(point1)); - else if(this->isPointInGbObject3D(&point2)) return new GbLine3D(schnittpunkte[0],new GbPoint3D(point2)); - else return new GbLine3D(schnittpunkte[0],new GbPoint3D(*(schnittpunkte[0]))); //strecke beruehrt clippedLine reduziert sich auf einen Punkt!!! - } - - return NULL; + } + } + // wenn nenner==0 -> Strecke parallel zu Zylinder! Es muss noch auf Schnittpunkt mit "Deckeln" geprueft werden + + // Schnittpunkt mit Seitenflaechen bestimmen + // hierzu wird der schnittpunkt der gegebnen strecke mit den seitenflaechenberechnet + // als erstes "schaut man seitlich auf den Zylinder" --> kreisflaechen wird als strecke darsgestellt + // mit diesen "strecken" berechnet man Schnittpunkte. + // anschliessend wird geprueft, ob der berechnete Schnittpunkt ueberhaupt im kreis liegt + // falls ja --> Schnittpunkt vorhanden + + double x1a, y1a, z1a, x1b, y1b, z1b, // uebergebene Strecke + x2a, y2a, x2b, y2b, // erste "Kreisstrecke" + x3a, y3a, x3b, y3b, // zweite "Kreisstrecke" + y2m, /*z2m,*/ y3m, z3m; + double nenner1ab; + + if (this->isParallelToX1Axis()) { + x1a = point1.getX1Coordinate(); + y1a = point1.getX2Coordinate(); + z1a = point1.getX3Coordinate(); + x1b = point2.getX1Coordinate(); + y1b = point2.getX2Coordinate(); + z1b = point2.getX3Coordinate(); + + x2a = mLine->getPoint1()->getX1Coordinate(); + y2m = mLine->getPoint1()->getX2Coordinate(); + // z2m=mLine->getPoint1()->getX3Coordinate(); + y2a = y2m + mRad; + x2b = mLine->getPoint1()->getX1Coordinate(); + y2b = y2m - mRad; + + x3a = mLine->getPoint2()->getX1Coordinate(); // + y3m = mLine->getPoint2()->getX2Coordinate(); + z3m = mLine->getPoint2()->getX3Coordinate(); + y3a = y3m + mRad; + x3b = mLine->getPoint2()->getX1Coordinate(); + y3b = y3m - mRad; + } else if (this->isParallelToX2Axis()) { + x1a = point1.getX2Coordinate(); + y1a = point1.getX3Coordinate(); + z1a = point1.getX1Coordinate(); + x1b = point2.getX2Coordinate(); + y1b = point2.getX3Coordinate(); + z1b = point2.getX1Coordinate(); + + x2a = mLine->getPoint1()->getX2Coordinate(); + y2m = mLine->getPoint1()->getX3Coordinate(); + // z2m=mLine->getPoint1()->getX1Coordinate(); + y2a = y2m + mRad; + x2b = mLine->getPoint1()->getX2Coordinate(); + y2b = y2m - mRad; + + x3a = mLine->getPoint2()->getX2Coordinate(); // + y3m = mLine->getPoint2()->getX3Coordinate(); + z3m = mLine->getPoint2()->getX1Coordinate(); + y3a = y3m + mRad; + x3b = mLine->getPoint2()->getX2Coordinate(); + y3b = y3m - mRad; + } else if (this->isParallelToX3Axis()) { + x1a = point1.getX3Coordinate(); + y1a = point1.getX2Coordinate(); + z1a = point1.getX1Coordinate(); + x1b = point2.getX3Coordinate(); + y1b = point2.getX2Coordinate(); + z1b = point2.getX1Coordinate(); + + x2a = mLine->getPoint1()->getX3Coordinate(); + y2m = mLine->getPoint1()->getX2Coordinate(); + // z2m=mLine->getPoint1()->getX1Coordinate(); + y2a = y2m + mRad; + x2b = mLine->getPoint1()->getX3Coordinate(); + y2b = y2m - mRad; + + x3a = mLine->getPoint2()->getX3Coordinate(); // + y3m = mLine->getPoint2()->getX2Coordinate(); + z3m = mLine->getPoint2()->getX1Coordinate(); + y3a = y3m + mRad; + x3b = mLine->getPoint2()->getX3Coordinate(); + y3b = y3m - mRad; + } else + throw UbException(UB_EXARGS, "funktioniert derzeit nur mit achsenparallelen Zylindern"); + + nenner1ab = -y1a * x2a + y1a * x2b + y1b * x2a - y1b * x2b + x1a * y2a - x1a * y2b - x1b * y2a + x1b * y2b; + // double nenner2 = x1a*y2a-x1a*y2b-x1b*y2a+x1b*y2b-y1a*x2a+y1a*x2b+y1b*x2a-y1b*x2b; + if (fabs(nenner1ab) > 1.E-13) // andernfalls sind die beiden Strecken parallel + { + // tStrecke ist fuer gegebene Strecke! + double t1ab = (-y1a * x2a + y1a * x2b - 2.0 * y2a * x2b + x1a * y2a - x1a * y2b - x1b * y2b + 2.0 * y2b * x2a + + x1b * y2a - y1b * x2a + y1b * x2b) / + nenner1ab; + // double tStrecke = + // -(-x1a*y2a+x1a*y2b+2.0*y2a*x2b+y1a*x2a-2.0*x2a*y2b-y1a*x2b+y1b*x2a-y1b*x2b-x1b*y2a+x1b*y2b)/nenner2; wenn -1 + // <= t2 <= +1 -> SP mit strecke + if (UbMath::inClosedInterval(t1ab, -1.0, 1.0)) // Schnittpunkt innerhalb der Strecke + { + double x, y, z, abstand_ist; + if (this->isParallelToX1Axis()) { + x = x1a * (0.5 - 0.5 * t1ab) + x1b * (0.5 + 0.5 * t1ab); + y = y1a * (0.5 - 0.5 * t1ab) + y1b * (0.5 + 0.5 * t1ab); + z = z1a * (0.5 - 0.5 * t1ab) + z1b * (0.5 + 0.5 * t1ab); + abstand_ist = sqrt((y3m - y) * (y3m - y) + (z3m - z) * (z3m - z)); + } else if (this->isParallelToX2Axis()) { + y = x1a * (0.5 - 0.5 * t1ab) + x1b * (0.5 + 0.5 * t1ab); + z = y1a * (0.5 - 0.5 * t1ab) + y1b * (0.5 + 0.5 * t1ab); + x = z1a * (0.5 - 0.5 * t1ab) + z1b * (0.5 + 0.5 * t1ab); + abstand_ist = sqrt((y3m - z) * (y3m - z) + (z3m - x) * (z3m - x)); + } else if (this->isParallelToX3Axis()) { + z = x1a * (0.5 - 0.5 * t1ab) + x1b * (0.5 + 0.5 * t1ab); + y = y1a * (0.5 - 0.5 * t1ab) + y1b * (0.5 + 0.5 * t1ab); + x = z1a * (0.5 - 0.5 * t1ab) + z1b * (0.5 + 0.5 * t1ab); + abstand_ist = sqrt((y3m - y) * (y3m - y) + (z3m - x) * (z3m - x)); + } else + throw UbException(UB_EXARGS, "funktioniert derzeit nur mit achsenparallelen Zylindern"); + + // pruefen, ob Punkt Element von Kreisflaeche + // double abstand_ist=sqrt((y2m-y)*(y2m-y)+(z2m-z)*(z2m-z)); + if (UbMath::lessEqual(abstand_ist, mRad)) // Punkt ist Schnittpunkt + { + bool exists = false; + for (int pos = 0; pos < (int)schnittpunkte.size(); ++pos) { + if (fabs(schnittpunkte[pos]->getX1Coordinate() - x) < 1.E-13 && + fabs(schnittpunkte[pos]->getX2Coordinate() - y) < 1.E-13 && + fabs(schnittpunkte[pos]->getX3Coordinate() - z) < 1.E-13) + exists = true; + } + + if (!exists) + schnittpunkte.push_back(new GbPoint3D(x, y, z)); + } + } + } + + nenner1ab = -y1a * x3a + y1a * x3b + y1b * x3a - y1b * x3b + x1a * y3a - x1a * y3b - x1b * y3a + x1b * y3b; + + if (fabs(nenner1ab) > 1.E-13) // andernfalls sind die beiden Strecken parallel + { + // tStrecke ist fuer gegebene Strecke! + double t1ab = (-y1a * x3a + y1a * x3b - x1b * y3b - 2.0 * y3a * x3b - x1a * y3b + 2.0 * y3b * x3a + x1a * y3a + + x1b * y3a - y1b * x3a + y1b * x3b) / + nenner1ab; + + if (UbMath::inClosedInterval(t1ab, -1.0, 1.0)) // Schnittpunkt innerhalb der Strecke + { + double x, y, z, abstand_ist; + if (this->isParallelToX1Axis()) { + x = x1a * (0.5 - 0.5 * t1ab) + x1b * (0.5 + 0.5 * t1ab); + y = y1a * (0.5 - 0.5 * t1ab) + y1b * (0.5 + 0.5 * t1ab); + z = z1a * (0.5 - 0.5 * t1ab) + z1b * (0.5 + 0.5 * t1ab); + abstand_ist = sqrt((y3m - y) * (y3m - y) + (z3m - z) * (z3m - z)); + } else if (this->isParallelToX2Axis()) { + y = x1a * (0.5 - 0.5 * t1ab) + x1b * (0.5 + 0.5 * t1ab); + z = y1a * (0.5 - 0.5 * t1ab) + y1b * (0.5 + 0.5 * t1ab); + x = z1a * (0.5 - 0.5 * t1ab) + z1b * (0.5 + 0.5 * t1ab); + abstand_ist = sqrt((y3m - z) * (y3m - z) + (z3m - x) * (z3m - x)); + } else if (this->isParallelToX3Axis()) { + z = x1a * (0.5 - 0.5 * t1ab) + x1b * (0.5 + 0.5 * t1ab); + y = y1a * (0.5 - 0.5 * t1ab) + y1b * (0.5 + 0.5 * t1ab); + x = z1a * (0.5 - 0.5 * t1ab) + z1b * (0.5 + 0.5 * t1ab); + abstand_ist = sqrt((y3m - y) * (y3m - y) + (z3m - x) * (z3m - x)); + } else + throw UbException(UB_EXARGS, "cylinder must be parallel to one axis"); + + // pruefen, ob Punkt Element von Kreisflaeche + // double abstand_ist=sqrt((y2m-y)*(y2m-y)+(z2m-z)*(z2m-z)); + + if (UbMath::lessEqual(abstand_ist, mRad)) // Punkt ist Schnittpunkt + { + bool exists = false; + for (int pos = 0; pos < (int)schnittpunkte.size(); ++pos) { + if (fabs(schnittpunkte[pos]->getX1Coordinate() - x) < 1.E-13 && + fabs(schnittpunkte[pos]->getX2Coordinate() - y) < 1.E-13 && + fabs(schnittpunkte[pos]->getX3Coordinate() - z) < 1.E-13) + exists = true; + } + + if (!exists) + schnittpunkte.push_back(new GbPoint3D(x, y, z)); + } + } + } + + int nofSchnittpunkte = (int)schnittpunkte.size(); + if (nofSchnittpunkte == 0) + return NULL; + else if (nofSchnittpunkte > 2) + throw UbException(UB_EXARGS, "more than three intersection points - not possible"); + else if (nofSchnittpunkte == 2) + return new GbLine3D(schnittpunkte[0], schnittpunkte[1]); + else if (nofSchnittpunkte == 1) { + if (this->isPointInGbObject3D(&point1)) + return new GbLine3D(schnittpunkte[0], new GbPoint3D(point1)); + else if (this->isPointInGbObject3D(&point2)) + return new GbLine3D(schnittpunkte[0], new GbPoint3D(point2)); + else + return new GbLine3D( + schnittpunkte[0], + new GbPoint3D(*(schnittpunkte[0]))); // strecke beruehrt clippedLine reduziert sich auf einen Punkt!!! + } + + return NULL; } /*==========================================================*/ -vector<GbTriangle3D*> GbCylinder3D::getSurfaceTriangleSet() +vector<GbTriangle3D *> GbCylinder3D::getSurfaceTriangleSet() { - double x1ma,x1mb,x2m,x3m; - if( this->isParallelToX1Axis() ) - { - x1ma = this->getX1Minimum(); - x1mb = this->getX1Maximum(); - x2m = this->getX2Centroid(); - x3m = this->getX3Centroid(); - } - else if( this->isParallelToX2Axis() ) - { - x1ma = this->getX2Minimum(); - x1mb = this->getX2Maximum(); - x2m = this->getX1Centroid(); - x3m = this->getX3Centroid(); - } - else if( this->isParallelToX3Axis() ) - { - x1ma = this->getX3Minimum(); - x1mb = this->getX3Maximum(); - x2m = this->getX2Centroid(); - x3m = this->getX1Centroid(); - } - else throw UbException(UB_EXARGS,"cylinder not axis prallel"); - - vector<GbTriangle3D*> triangles; - - int segmentsCircle = 20; - double deltaPhi = UbMath::PI/(double)segmentsCircle; - - double phiX1a,phiX1b; - double x1a,x2a,x3a,x1b,x2b,x3b,x1c,x2c,x3c,x1d,x2d,x3d; - - double dXCylinder = fabs((x1mb-x1ma))/(double)segmentsCircle; - int segmentsCylinder = (int)(fabs(x1mb-x1ma)/dXCylinder); - for(int segCyl = 0; segCyl<segmentsCylinder; segCyl++) - { - x1a = x1d = x1ma+segCyl*dXCylinder; - x1b = x1c = x1a+dXCylinder; - - for(phiX1a=2.0*UbMath::PI; phiX1a>0; phiX1a-=deltaPhi) - { - phiX1b = phiX1a+deltaPhi; - - x2a = x2m+mRad*std::sin(phiX1a); - x3a = x3m+mRad*std::cos(phiX1a); - x2b = x2m+mRad*std::sin(phiX1b); - x3b = x3m+mRad*std::cos(phiX1b); - - if( this->isParallelToX1Axis() ) - { - triangles.push_back(new GbTriangle3D(new GbPoint3D(x1b,x2b,x3b),new GbPoint3D(x1b,x2a,x3a),new GbPoint3D(x1a,x2a,x3a))); - triangles.push_back(new GbTriangle3D(new GbPoint3D(x1a,x2a,x3a),new GbPoint3D(x1a,x2b,x3b),new GbPoint3D(x1b,x2b,x3b))); - } - else if( this->isParallelToX2Axis() ) - { - triangles.push_back(new GbTriangle3D(new GbPoint3D(x2b,x1b,x3b),new GbPoint3D(x2a,x1b,x3a),new GbPoint3D(x2a,x1a,x3a))); - triangles.push_back(new GbTriangle3D(new GbPoint3D(x2a,x1a,x3a),new GbPoint3D(x2b,x1a,x3b),new GbPoint3D(x2b,x1b,x3b))); - } - else if( this->isParallelToX3Axis() ) - { - triangles.push_back(new GbTriangle3D(new GbPoint3D(x3b,x2b,x1b),new GbPoint3D(x3a,x2a,x1b),new GbPoint3D(x3a,x2a,x1a))); - triangles.push_back(new GbTriangle3D(new GbPoint3D(x3a,x2a,x1a),new GbPoint3D(x3b,x2b,x1a),new GbPoint3D(x3b,x2b,x1b))); - } - - } - } - - int segmentsSide = (int)(mRad/dXCylinder); - double radius0, radius1; - for(int segCyl = 0; segCyl<segmentsSide; segCyl++) - { - radius0 = segCyl*dXCylinder; - radius1 = radius0+dXCylinder; - if(segCyl==segmentsSide-1) radius1=mRad; - - for(phiX1a=2.0*UbMath::PI; phiX1a>0; phiX1a-=deltaPhi) - { - phiX1b = phiX1a+deltaPhi; - - x2a = x2m+radius0*std::sin(phiX1a); - x3a = x3m+radius0*std::cos(phiX1a); - x2b = x2m+radius0*std::sin(phiX1b); - x3b = x3m+radius0*std::cos(phiX1b); - x2c = x2m+radius1*std::sin(phiX1b); - x3c = x3m+radius1*std::cos(phiX1b); - x2d = x2m+radius1*std::sin(phiX1a); - x3d = x3m+radius1*std::cos(phiX1a); - - if( this->isParallelToX1Axis() ) - { - triangles.push_back(new GbTriangle3D(new GbPoint3D(x1ma,x2a,x3a),new GbPoint3D(x1ma,x2b,x3b),new GbPoint3D(x1ma,x2c,x3c))); - triangles.push_back(new GbTriangle3D(new GbPoint3D(x1ma,x2c,x3c),new GbPoint3D(x1ma,x2d,x3d),new GbPoint3D(x1ma,x2a,x3a))); - triangles.push_back(new GbTriangle3D(new GbPoint3D(x1mb,x2c,x3c),new GbPoint3D(x1mb,x2b,x3b),new GbPoint3D(x1mb,x2a,x3a))); - triangles.push_back(new GbTriangle3D(new GbPoint3D(x1mb,x2a,x3a),new GbPoint3D(x1mb,x2d,x3d),new GbPoint3D(x1mb,x2c,x3c))); - } - else if( this->isParallelToX2Axis() ) - { - triangles.push_back(new GbTriangle3D(new GbPoint3D(x2a,x1ma,x3a),new GbPoint3D(x2b,x1ma,x3b),new GbPoint3D(x2c,x1ma,x3c))); - triangles.push_back(new GbTriangle3D(new GbPoint3D(x2c,x1ma,x3c),new GbPoint3D(x2d,x1ma,x3d),new GbPoint3D(x2a,x1ma,x3a))); - triangles.push_back(new GbTriangle3D(new GbPoint3D(x2c,x1mb,x3c),new GbPoint3D(x2b,x1mb,x3b),new GbPoint3D(x2a,x1mb,x3a))); - triangles.push_back(new GbTriangle3D(new GbPoint3D(x2a,x1mb,x3a),new GbPoint3D(x2d,x1mb,x3d),new GbPoint3D(x2c,x1mb,x3c))); - } - else if( this->isParallelToX3Axis() ) - { - triangles.push_back(new GbTriangle3D(new GbPoint3D(x3a,x2a,x1ma),new GbPoint3D(x3b,x2b,x1ma),new GbPoint3D(x3c,x2c,x1ma))); - triangles.push_back(new GbTriangle3D(new GbPoint3D(x3c,x2c,x1ma),new GbPoint3D(x3d,x2d,x1ma),new GbPoint3D(x3a,x2a,x1ma))); - triangles.push_back(new GbTriangle3D(new GbPoint3D(x3c,x2c,x1mb),new GbPoint3D(x3b,x2b,x1mb),new GbPoint3D(x3a,x2a,x1mb))); - triangles.push_back(new GbTriangle3D(new GbPoint3D(x3a,x2a,x1mb),new GbPoint3D(x3d,x2d,x1mb),new GbPoint3D(x3c,x2c,x1mb))); - } - } - } - - return triangles; + double x1ma, x1mb, x2m, x3m; + if (this->isParallelToX1Axis()) { + x1ma = this->getX1Minimum(); + x1mb = this->getX1Maximum(); + x2m = this->getX2Centroid(); + x3m = this->getX3Centroid(); + } else if (this->isParallelToX2Axis()) { + x1ma = this->getX2Minimum(); + x1mb = this->getX2Maximum(); + x2m = this->getX1Centroid(); + x3m = this->getX3Centroid(); + } else if (this->isParallelToX3Axis()) { + x1ma = this->getX3Minimum(); + x1mb = this->getX3Maximum(); + x2m = this->getX2Centroid(); + x3m = this->getX1Centroid(); + } else + throw UbException(UB_EXARGS, "cylinder not axis prallel"); + + vector<GbTriangle3D *> triangles; + + int segmentsCircle = 20; + double deltaPhi = UbMath::PI / (double)segmentsCircle; + + double phiX1a, phiX1b; + double x1a, x2a, x3a, x1b, x2b, x3b, x1c, x2c, x3c, x1d, x2d, x3d; + + double dXCylinder = fabs((x1mb - x1ma)) / (double)segmentsCircle; + int segmentsCylinder = (int)(fabs(x1mb - x1ma) / dXCylinder); + for (int segCyl = 0; segCyl < segmentsCylinder; segCyl++) { + x1a = x1d = x1ma + segCyl * dXCylinder; + x1b = x1c = x1a + dXCylinder; + + for (phiX1a = 2.0 * UbMath::PI; phiX1a > 0; phiX1a -= deltaPhi) { + phiX1b = phiX1a + deltaPhi; + + x2a = x2m + mRad * std::sin(phiX1a); + x3a = x3m + mRad * std::cos(phiX1a); + x2b = x2m + mRad * std::sin(phiX1b); + x3b = x3m + mRad * std::cos(phiX1b); + + if (this->isParallelToX1Axis()) { + triangles.push_back(new GbTriangle3D(new GbPoint3D(x1b, x2b, x3b), new GbPoint3D(x1b, x2a, x3a), + new GbPoint3D(x1a, x2a, x3a))); + triangles.push_back(new GbTriangle3D(new GbPoint3D(x1a, x2a, x3a), new GbPoint3D(x1a, x2b, x3b), + new GbPoint3D(x1b, x2b, x3b))); + } else if (this->isParallelToX2Axis()) { + triangles.push_back(new GbTriangle3D(new GbPoint3D(x2b, x1b, x3b), new GbPoint3D(x2a, x1b, x3a), + new GbPoint3D(x2a, x1a, x3a))); + triangles.push_back(new GbTriangle3D(new GbPoint3D(x2a, x1a, x3a), new GbPoint3D(x2b, x1a, x3b), + new GbPoint3D(x2b, x1b, x3b))); + } else if (this->isParallelToX3Axis()) { + triangles.push_back(new GbTriangle3D(new GbPoint3D(x3b, x2b, x1b), new GbPoint3D(x3a, x2a, x1b), + new GbPoint3D(x3a, x2a, x1a))); + triangles.push_back(new GbTriangle3D(new GbPoint3D(x3a, x2a, x1a), new GbPoint3D(x3b, x2b, x1a), + new GbPoint3D(x3b, x2b, x1b))); + } + } + } + + int segmentsSide = (int)(mRad / dXCylinder); + double radius0, radius1; + for (int segCyl = 0; segCyl < segmentsSide; segCyl++) { + radius0 = segCyl * dXCylinder; + radius1 = radius0 + dXCylinder; + if (segCyl == segmentsSide - 1) + radius1 = mRad; + + for (phiX1a = 2.0 * UbMath::PI; phiX1a > 0; phiX1a -= deltaPhi) { + phiX1b = phiX1a + deltaPhi; + + x2a = x2m + radius0 * std::sin(phiX1a); + x3a = x3m + radius0 * std::cos(phiX1a); + x2b = x2m + radius0 * std::sin(phiX1b); + x3b = x3m + radius0 * std::cos(phiX1b); + x2c = x2m + radius1 * std::sin(phiX1b); + x3c = x3m + radius1 * std::cos(phiX1b); + x2d = x2m + radius1 * std::sin(phiX1a); + x3d = x3m + radius1 * std::cos(phiX1a); + + if (this->isParallelToX1Axis()) { + triangles.push_back(new GbTriangle3D(new GbPoint3D(x1ma, x2a, x3a), new GbPoint3D(x1ma, x2b, x3b), + new GbPoint3D(x1ma, x2c, x3c))); + triangles.push_back(new GbTriangle3D(new GbPoint3D(x1ma, x2c, x3c), new GbPoint3D(x1ma, x2d, x3d), + new GbPoint3D(x1ma, x2a, x3a))); + triangles.push_back(new GbTriangle3D(new GbPoint3D(x1mb, x2c, x3c), new GbPoint3D(x1mb, x2b, x3b), + new GbPoint3D(x1mb, x2a, x3a))); + triangles.push_back(new GbTriangle3D(new GbPoint3D(x1mb, x2a, x3a), new GbPoint3D(x1mb, x2d, x3d), + new GbPoint3D(x1mb, x2c, x3c))); + } else if (this->isParallelToX2Axis()) { + triangles.push_back(new GbTriangle3D(new GbPoint3D(x2a, x1ma, x3a), new GbPoint3D(x2b, x1ma, x3b), + new GbPoint3D(x2c, x1ma, x3c))); + triangles.push_back(new GbTriangle3D(new GbPoint3D(x2c, x1ma, x3c), new GbPoint3D(x2d, x1ma, x3d), + new GbPoint3D(x2a, x1ma, x3a))); + triangles.push_back(new GbTriangle3D(new GbPoint3D(x2c, x1mb, x3c), new GbPoint3D(x2b, x1mb, x3b), + new GbPoint3D(x2a, x1mb, x3a))); + triangles.push_back(new GbTriangle3D(new GbPoint3D(x2a, x1mb, x3a), new GbPoint3D(x2d, x1mb, x3d), + new GbPoint3D(x2c, x1mb, x3c))); + } else if (this->isParallelToX3Axis()) { + triangles.push_back(new GbTriangle3D(new GbPoint3D(x3a, x2a, x1ma), new GbPoint3D(x3b, x2b, x1ma), + new GbPoint3D(x3c, x2c, x1ma))); + triangles.push_back(new GbTriangle3D(new GbPoint3D(x3c, x2c, x1ma), new GbPoint3D(x3d, x2d, x1ma), + new GbPoint3D(x3a, x2a, x1ma))); + triangles.push_back(new GbTriangle3D(new GbPoint3D(x3c, x2c, x1mb), new GbPoint3D(x3b, x2b, x1mb), + new GbPoint3D(x3a, x2a, x1mb))); + triangles.push_back(new GbTriangle3D(new GbPoint3D(x3a, x2a, x1mb), new GbPoint3D(x3d, x2d, x1mb), + new GbPoint3D(x3c, x2c, x1mb))); + } + } + } + + return triangles; } /*==========================================================*/ -void GbCylinder3D::addSurfaceTriangleSet(vector<UbTupleFloat3>& nodes, vector<UbTupleInt3>& triangles) +void GbCylinder3D::addSurfaceTriangleSet(vector<UbTupleFloat3> &nodes, vector<UbTupleInt3> &triangles) { - float x1ma,x1mb,x2m,x3m; - if( this->isParallelToX1Axis() ) - { - x1ma = (float)this->getX1Minimum(); - x1mb = (float)this->getX1Maximum(); - x2m = (float)this->getX2Centroid(); - x3m = (float)this->getX3Centroid(); - } - else if( this->isParallelToX2Axis() ) - { - x1ma = (float)this->getX2Minimum(); - x1mb = (float)this->getX2Maximum(); - x2m = (float)this->getX1Centroid(); - x3m = (float)this->getX3Centroid(); - } - else if( this->isParallelToX3Axis() ) - { - x1ma = (float)this->getX3Minimum(); - x1mb = (float)this->getX3Maximum(); - x2m = (float)this->getX2Centroid(); - x3m = (float)this->getX1Centroid(); - } - else throw UbException(UB_EXARGS,"cylinder not axis prallel"); - - int segmentsCircle = 20; - double deltaPhi = UbMath::PI/(double)segmentsCircle; - - double phiX1a,phiX1b; - float x1a,x2a,x3a,x1b,x2b,x3b,x1c,x2c,x3c,x1d,x2d,x3d; - - double dXCylinder = fabs((x1mb-x1ma))/(double)segmentsCircle; - int segmentsCylinder = (int)(fabs(x1mb-x1ma)/dXCylinder); - int nodenr = 0; - for(int segCyl = 0; segCyl<segmentsCylinder; segCyl++) - { - x1a = x1d = (float)(x1ma+segCyl*dXCylinder); - x1b = x1c = (float)(x1a+dXCylinder); - - for(phiX1a=2.0*UbMath::PI; phiX1a>0; phiX1a-=deltaPhi) - { - phiX1b = phiX1a+deltaPhi; - - x2a = (float)(x2m+mRad*std::sin(phiX1a)); - x3a = (float)(x3m+mRad*std::cos(phiX1a)); - x2b = (float)(x2m+mRad*std::sin(phiX1b)); - x3b = (float)(x3m+mRad*std::cos(phiX1b)); - - if( this->isParallelToX1Axis() ) - { - nodes.push_back( makeUbTuple(x1b,x2b,x3b) ); nodes.push_back( makeUbTuple(x1b,x2a,x3a) ); nodes.push_back( makeUbTuple(x1a,x2a,x3a) ); - nodes.push_back( makeUbTuple(x1a,x2a,x3a) ); nodes.push_back( makeUbTuple(x1a,x2b,x3b) ); nodes.push_back( makeUbTuple(x1b,x2b,x3b) ); - } - else if( this->isParallelToX2Axis() ) - { - nodes.push_back( makeUbTuple(x2b,x1b,x3b) ); nodes.push_back( makeUbTuple(x2a,x1b,x3a) ); nodes.push_back( makeUbTuple(x2a,x1a,x3a) ); - nodes.push_back( makeUbTuple(x2a,x1a,x3a) ); nodes.push_back( makeUbTuple(x2b,x1a,x3b) ); nodes.push_back( makeUbTuple(x2b,x1b,x3b) ); - } - else if( this->isParallelToX3Axis() ) - { - nodes.push_back( makeUbTuple(x3b,x2b,x1b) ); nodes.push_back( makeUbTuple(x3a,x2a,x1b) ); nodes.push_back( makeUbTuple(x3a,x2a,x1a) ); - nodes.push_back( makeUbTuple(x3a,x2a,x1a) ); nodes.push_back( makeUbTuple(x3b,x2b,x1a) ); nodes.push_back( makeUbTuple(x3b,x2b,x1b) ); - } - triangles.push_back( makeUbTuple(nodenr , nodenr+1, nodenr+2) ); nodenr+=3; - triangles.push_back( makeUbTuple(nodenr , nodenr+1, nodenr+2) ); nodenr+=3; - } - } - - int segmentsSide = (int)(mRad/dXCylinder); - double radius0, radius1; - for(int segCyl = 0; segCyl<segmentsSide; segCyl++) - { - radius0 = segCyl*dXCylinder; - radius1 = radius0+dXCylinder; - if(segCyl==segmentsSide-1) radius1=mRad; - - for(phiX1a=2.0*UbMath::PI; phiX1a>0; phiX1a-=deltaPhi) - { - phiX1b = phiX1a+deltaPhi; - - x2a = x2m+(float)(radius0*std::sin(phiX1a)); - x3a = x3m+(float)(radius0*std::cos(phiX1a)); - x2b = x2m+(float)(radius0*std::sin(phiX1b)); - x3b = x3m+(float)(radius0*std::cos(phiX1b)); - x2c = x2m+(float)(radius1*std::sin(phiX1b)); - x3c = x3m+(float)(radius1*std::cos(phiX1b)); - x2d = x2m+(float)(radius1*std::sin(phiX1a)); - x3d = x3m+(float)(radius1*std::cos(phiX1a)); - - if( this->isParallelToX1Axis() ) - { - nodes.push_back( makeUbTuple(x1ma,x2a,x3a) ); nodes.push_back( makeUbTuple(x1ma,x2b,x3b) ); nodes.push_back( makeUbTuple(x1ma,x2c,x3c) ); - nodes.push_back( makeUbTuple(x1ma,x2c,x3c) ); nodes.push_back( makeUbTuple(x1ma,x2d,x3d) ); nodes.push_back( makeUbTuple(x1ma,x2a,x3a) ); - nodes.push_back( makeUbTuple(x1mb,x2c,x3c) ); nodes.push_back( makeUbTuple(x1mb,x2b,x3b) ); nodes.push_back( makeUbTuple(x1mb,x2a,x3a) ); - nodes.push_back( makeUbTuple(x1mb,x2a,x3a) ); nodes.push_back( makeUbTuple(x1mb,x2d,x3d) ); nodes.push_back( makeUbTuple(x1mb,x2c,x3c) ); - } - else if( this->isParallelToX2Axis() ) - { - nodes.push_back( makeUbTuple(x2a,x1ma,x3a) ); nodes.push_back( makeUbTuple(x2b,x1ma,x3b) ); nodes.push_back( makeUbTuple(x2c,x1ma,x3c) ); - nodes.push_back( makeUbTuple(x2c,x1ma,x3c) ); nodes.push_back( makeUbTuple(x2d,x1ma,x3d) ); nodes.push_back( makeUbTuple(x2a,x1ma,x3a) ); - nodes.push_back( makeUbTuple(x2c,x1mb,x3c) ); nodes.push_back( makeUbTuple(x2b,x1mb,x3b) ); nodes.push_back( makeUbTuple(x2a,x1mb,x3a) ); - nodes.push_back( makeUbTuple(x2a,x1mb,x3a) ); nodes.push_back( makeUbTuple(x2d,x1mb,x3d) ); nodes.push_back( makeUbTuple(x2c,x1mb,x3c) ); - } - else if( this->isParallelToX3Axis() ) - { - nodes.push_back( makeUbTuple(x3a,x2a,x1ma) ); nodes.push_back( makeUbTuple(x3b,x2b,x1ma) ); nodes.push_back( makeUbTuple(x3c,x2c,x1ma) ); - nodes.push_back( makeUbTuple(x3c,x2c,x1ma) ); nodes.push_back( makeUbTuple(x3d,x2d,x1ma) ); nodes.push_back( makeUbTuple(x3a,x2a,x1ma) ); - nodes.push_back( makeUbTuple(x3c,x2c,x1mb) ); nodes.push_back( makeUbTuple(x3b,x2b,x1mb) ); nodes.push_back( makeUbTuple(x3a,x2a,x1mb) ); - nodes.push_back( makeUbTuple(x3a,x2a,x1mb) ); nodes.push_back( makeUbTuple(x3d,x2d,x1mb) ); nodes.push_back( makeUbTuple(x3c,x2c,x1mb) ); - } - - triangles.push_back( makeUbTuple(nodenr , nodenr+1, nodenr+2) ); nodenr+=3; - triangles.push_back( makeUbTuple(nodenr , nodenr+1, nodenr+2) ); nodenr+=3; - triangles.push_back( makeUbTuple(nodenr , nodenr+1, nodenr+2) ); nodenr+=3; - triangles.push_back( makeUbTuple(nodenr , nodenr+1, nodenr+2) ); nodenr+=3; - } - } + float x1ma, x1mb, x2m, x3m; + if (this->isParallelToX1Axis()) { + x1ma = (float)this->getX1Minimum(); + x1mb = (float)this->getX1Maximum(); + x2m = (float)this->getX2Centroid(); + x3m = (float)this->getX3Centroid(); + } else if (this->isParallelToX2Axis()) { + x1ma = (float)this->getX2Minimum(); + x1mb = (float)this->getX2Maximum(); + x2m = (float)this->getX1Centroid(); + x3m = (float)this->getX3Centroid(); + } else if (this->isParallelToX3Axis()) { + x1ma = (float)this->getX3Minimum(); + x1mb = (float)this->getX3Maximum(); + x2m = (float)this->getX2Centroid(); + x3m = (float)this->getX1Centroid(); + } else + throw UbException(UB_EXARGS, "cylinder not axis prallel"); + + int segmentsCircle = 20; + double deltaPhi = UbMath::PI / (double)segmentsCircle; + + double phiX1a, phiX1b; + float x1a, x2a, x3a, x1b, x2b, x3b, x1c, x2c, x3c, x1d, x2d, x3d; + + double dXCylinder = fabs((x1mb - x1ma)) / (double)segmentsCircle; + int segmentsCylinder = (int)(fabs(x1mb - x1ma) / dXCylinder); + int nodenr = 0; + for (int segCyl = 0; segCyl < segmentsCylinder; segCyl++) { + x1a = x1d = (float)(x1ma + segCyl * dXCylinder); + x1b = x1c = (float)(x1a + dXCylinder); + + for (phiX1a = 2.0 * UbMath::PI; phiX1a > 0; phiX1a -= deltaPhi) { + phiX1b = phiX1a + deltaPhi; + + x2a = (float)(x2m + mRad * std::sin(phiX1a)); + x3a = (float)(x3m + mRad * std::cos(phiX1a)); + x2b = (float)(x2m + mRad * std::sin(phiX1b)); + x3b = (float)(x3m + mRad * std::cos(phiX1b)); + + if (this->isParallelToX1Axis()) { + nodes.push_back(makeUbTuple(x1b, x2b, x3b)); + nodes.push_back(makeUbTuple(x1b, x2a, x3a)); + nodes.push_back(makeUbTuple(x1a, x2a, x3a)); + nodes.push_back(makeUbTuple(x1a, x2a, x3a)); + nodes.push_back(makeUbTuple(x1a, x2b, x3b)); + nodes.push_back(makeUbTuple(x1b, x2b, x3b)); + } else if (this->isParallelToX2Axis()) { + nodes.push_back(makeUbTuple(x2b, x1b, x3b)); + nodes.push_back(makeUbTuple(x2a, x1b, x3a)); + nodes.push_back(makeUbTuple(x2a, x1a, x3a)); + nodes.push_back(makeUbTuple(x2a, x1a, x3a)); + nodes.push_back(makeUbTuple(x2b, x1a, x3b)); + nodes.push_back(makeUbTuple(x2b, x1b, x3b)); + } else if (this->isParallelToX3Axis()) { + nodes.push_back(makeUbTuple(x3b, x2b, x1b)); + nodes.push_back(makeUbTuple(x3a, x2a, x1b)); + nodes.push_back(makeUbTuple(x3a, x2a, x1a)); + nodes.push_back(makeUbTuple(x3a, x2a, x1a)); + nodes.push_back(makeUbTuple(x3b, x2b, x1a)); + nodes.push_back(makeUbTuple(x3b, x2b, x1b)); + } + triangles.push_back(makeUbTuple(nodenr, nodenr + 1, nodenr + 2)); + nodenr += 3; + triangles.push_back(makeUbTuple(nodenr, nodenr + 1, nodenr + 2)); + nodenr += 3; + } + } + + int segmentsSide = (int)(mRad / dXCylinder); + double radius0, radius1; + for (int segCyl = 0; segCyl < segmentsSide; segCyl++) { + radius0 = segCyl * dXCylinder; + radius1 = radius0 + dXCylinder; + if (segCyl == segmentsSide - 1) + radius1 = mRad; + + for (phiX1a = 2.0 * UbMath::PI; phiX1a > 0; phiX1a -= deltaPhi) { + phiX1b = phiX1a + deltaPhi; + + x2a = x2m + (float)(radius0 * std::sin(phiX1a)); + x3a = x3m + (float)(radius0 * std::cos(phiX1a)); + x2b = x2m + (float)(radius0 * std::sin(phiX1b)); + x3b = x3m + (float)(radius0 * std::cos(phiX1b)); + x2c = x2m + (float)(radius1 * std::sin(phiX1b)); + x3c = x3m + (float)(radius1 * std::cos(phiX1b)); + x2d = x2m + (float)(radius1 * std::sin(phiX1a)); + x3d = x3m + (float)(radius1 * std::cos(phiX1a)); + + if (this->isParallelToX1Axis()) { + nodes.push_back(makeUbTuple(x1ma, x2a, x3a)); + nodes.push_back(makeUbTuple(x1ma, x2b, x3b)); + nodes.push_back(makeUbTuple(x1ma, x2c, x3c)); + nodes.push_back(makeUbTuple(x1ma, x2c, x3c)); + nodes.push_back(makeUbTuple(x1ma, x2d, x3d)); + nodes.push_back(makeUbTuple(x1ma, x2a, x3a)); + nodes.push_back(makeUbTuple(x1mb, x2c, x3c)); + nodes.push_back(makeUbTuple(x1mb, x2b, x3b)); + nodes.push_back(makeUbTuple(x1mb, x2a, x3a)); + nodes.push_back(makeUbTuple(x1mb, x2a, x3a)); + nodes.push_back(makeUbTuple(x1mb, x2d, x3d)); + nodes.push_back(makeUbTuple(x1mb, x2c, x3c)); + } else if (this->isParallelToX2Axis()) { + nodes.push_back(makeUbTuple(x2a, x1ma, x3a)); + nodes.push_back(makeUbTuple(x2b, x1ma, x3b)); + nodes.push_back(makeUbTuple(x2c, x1ma, x3c)); + nodes.push_back(makeUbTuple(x2c, x1ma, x3c)); + nodes.push_back(makeUbTuple(x2d, x1ma, x3d)); + nodes.push_back(makeUbTuple(x2a, x1ma, x3a)); + nodes.push_back(makeUbTuple(x2c, x1mb, x3c)); + nodes.push_back(makeUbTuple(x2b, x1mb, x3b)); + nodes.push_back(makeUbTuple(x2a, x1mb, x3a)); + nodes.push_back(makeUbTuple(x2a, x1mb, x3a)); + nodes.push_back(makeUbTuple(x2d, x1mb, x3d)); + nodes.push_back(makeUbTuple(x2c, x1mb, x3c)); + } else if (this->isParallelToX3Axis()) { + nodes.push_back(makeUbTuple(x3a, x2a, x1ma)); + nodes.push_back(makeUbTuple(x3b, x2b, x1ma)); + nodes.push_back(makeUbTuple(x3c, x2c, x1ma)); + nodes.push_back(makeUbTuple(x3c, x2c, x1ma)); + nodes.push_back(makeUbTuple(x3d, x2d, x1ma)); + nodes.push_back(makeUbTuple(x3a, x2a, x1ma)); + nodes.push_back(makeUbTuple(x3c, x2c, x1mb)); + nodes.push_back(makeUbTuple(x3b, x2b, x1mb)); + nodes.push_back(makeUbTuple(x3a, x2a, x1mb)); + nodes.push_back(makeUbTuple(x3a, x2a, x1mb)); + nodes.push_back(makeUbTuple(x3d, x2d, x1mb)); + nodes.push_back(makeUbTuple(x3c, x2c, x1mb)); + } + + triangles.push_back(makeUbTuple(nodenr, nodenr + 1, nodenr + 2)); + nodenr += 3; + triangles.push_back(makeUbTuple(nodenr, nodenr + 1, nodenr + 2)); + nodenr += 3; + triangles.push_back(makeUbTuple(nodenr, nodenr + 1, nodenr + 2)); + nodenr += 3; + triangles.push_back(makeUbTuple(nodenr, nodenr + 1, nodenr + 2)); + nodenr += 3; + } + } } /*==========================================================*/ -void GbCylinder3D::addSurfaceTriangleSetSegments(vector<UbTupleFloat3>& nodes, vector<UbTupleInt3>& triangles, int segmentsRound, int segmentsHeight ) +void GbCylinder3D::addSurfaceTriangleSetSegments(vector<UbTupleFloat3> &nodes, vector<UbTupleInt3> &triangles, + int segmentsRound, int segmentsHeight) { - float x1ma,x1mb,x2m,x3m; - if( this->isParallelToX1Axis() ) - { - x1ma = (float)this->getX1Minimum(); - x1mb = (float)this->getX1Maximum(); - x2m = (float)this->getX2Centroid(); - x3m = (float)this->getX3Centroid(); - } - else if( this->isParallelToX2Axis() ) - { - x1ma = (float)this->getX2Minimum(); - x1mb = (float)this->getX2Maximum(); - x2m = (float)this->getX1Centroid(); - x3m = (float)this->getX3Centroid(); - } - else if( this->isParallelToX3Axis() ) - { - x1ma = (float)this->getX3Minimum(); - x1mb = (float)this->getX3Maximum(); - x2m = (float)this->getX2Centroid(); - x3m = (float)this->getX1Centroid(); - } - else throw UbException(UB_EXARGS,"cylinder not axis prallel"); - - int segmentsCircle = segmentsRound; - double deltaPhi = UbMath::PI/(double)segmentsCircle; - - double phiX1a,phiX1b; - float x1a,x2a,x3a,x1b,x2b,x3b,x1c,x2c,x3c,x1d,x2d,x3d; - - double dXCylinder = fabs((x1mb-x1ma))/(double)segmentsHeight; //hier evtl. segmentsheight - int segmentsCylinder = (int)(fabs(x1mb-x1ma)/dXCylinder); - int nodenr = 0; - for(int segCyl = 0; segCyl<segmentsCylinder; segCyl++) - { - x1a = x1d = (float)(x1ma+segCyl*dXCylinder); - x1b = x1c = (float)(x1a+dXCylinder); - - //for(phiX1a=2.0*UbMath::PI; phiX1a>0.0; phiX1a-=deltaPhi) - for(phiX1a=0.0; phiX1a<2.0*UbMath::PI-0.5*deltaPhi; phiX1a+=deltaPhi) - { - phiX1b = phiX1a+deltaPhi; - - x2a = (float)(x2m+mRad*std::sin(phiX1a)); - x3a = (float)(x3m+mRad*std::cos(phiX1a)); - x2b = (float)(x2m+mRad*std::sin(phiX1b)); - x3b = (float)(x3m+mRad*std::cos(phiX1b)); - - if( this->isParallelToX1Axis() ) - { - nodes.push_back( makeUbTuple(x1b,x2b,x3b) ); nodes.push_back( makeUbTuple(x1b,x2a,x3a) ); nodes.push_back( makeUbTuple(x1a,x2a,x3a) ); - nodes.push_back( makeUbTuple(x1a,x2a,x3a) ); nodes.push_back( makeUbTuple(x1a,x2b,x3b) ); nodes.push_back( makeUbTuple(x1b,x2b,x3b) ); - } - else if( this->isParallelToX2Axis() ) - { - nodes.push_back( makeUbTuple(x2b,x1b,x3b) ); nodes.push_back( makeUbTuple(x2a,x1b,x3a) ); nodes.push_back( makeUbTuple(x2a,x1a,x3a) ); - nodes.push_back( makeUbTuple(x2a,x1a,x3a) ); nodes.push_back( makeUbTuple(x2b,x1a,x3b) ); nodes.push_back( makeUbTuple(x2b,x1b,x3b) ); - } - else if( this->isParallelToX3Axis() ) - { - nodes.push_back( makeUbTuple(x3b,x2b,x1b) ); nodes.push_back( makeUbTuple(x3a,x2a,x1b) ); nodes.push_back( makeUbTuple(x3a,x2a,x1a) ); - nodes.push_back( makeUbTuple(x3a,x2a,x1a) ); nodes.push_back( makeUbTuple(x3b,x2b,x1a) ); nodes.push_back( makeUbTuple(x3b,x2b,x1b) ); - } - triangles.push_back( makeUbTuple(nodenr , nodenr+1, nodenr+2) ); nodenr+=3; - triangles.push_back( makeUbTuple(nodenr , nodenr+1, nodenr+2) ); nodenr+=3; - } - } - - int segmentsSide = (int)(mRad/dXCylinder); - double radius0, radius1; - for(int segCyl = 0; segCyl<segmentsSide; segCyl++) - { - radius0 = segCyl*dXCylinder; - radius1 = radius0+dXCylinder; - if(segCyl==segmentsSide-1) radius1=mRad; - - //for(phiX1a=2.0*UbMath::PI; phiX1a>0.0; phiX1a-=deltaPhi) - for(phiX1a=0.0; phiX1a<2.0*UbMath::PI-0.5*deltaPhi; phiX1a+=deltaPhi) - { - phiX1b = phiX1a+deltaPhi; - - x2a = x2m+(float)(radius0*std::sin(phiX1a)); - x3a = x3m+(float)(radius0*std::cos(phiX1a)); - x2b = x2m+(float)(radius0*std::sin(phiX1b)); - x3b = x3m+(float)(radius0*std::cos(phiX1b)); - x2c = x2m+(float)(radius1*std::sin(phiX1b)); - x3c = x3m+(float)(radius1*std::cos(phiX1b)); - x2d = x2m+(float)(radius1*std::sin(phiX1a)); - x3d = x3m+(float)(radius1*std::cos(phiX1a)); - - if( this->isParallelToX1Axis() ) - { - nodes.push_back( makeUbTuple(x1ma,x2a,x3a) ); nodes.push_back( makeUbTuple(x1ma,x2b,x3b) ); nodes.push_back( makeUbTuple(x1ma,x2c,x3c) ); - nodes.push_back( makeUbTuple(x1ma,x2c,x3c) ); nodes.push_back( makeUbTuple(x1ma,x2d,x3d) ); nodes.push_back( makeUbTuple(x1ma,x2a,x3a) ); - nodes.push_back( makeUbTuple(x1mb,x2c,x3c) ); nodes.push_back( makeUbTuple(x1mb,x2b,x3b) ); nodes.push_back( makeUbTuple(x1mb,x2a,x3a) ); - nodes.push_back( makeUbTuple(x1mb,x2a,x3a) ); nodes.push_back( makeUbTuple(x1mb,x2d,x3d) ); nodes.push_back( makeUbTuple(x1mb,x2c,x3c) ); - } - else if( this->isParallelToX2Axis() ) - { - nodes.push_back( makeUbTuple(x2a,x1ma,x3a) ); nodes.push_back( makeUbTuple(x2b,x1ma,x3b) ); nodes.push_back( makeUbTuple(x2c,x1ma,x3c) ); - nodes.push_back( makeUbTuple(x2c,x1ma,x3c) ); nodes.push_back( makeUbTuple(x2d,x1ma,x3d) ); nodes.push_back( makeUbTuple(x2a,x1ma,x3a) ); - nodes.push_back( makeUbTuple(x2c,x1mb,x3c) ); nodes.push_back( makeUbTuple(x2b,x1mb,x3b) ); nodes.push_back( makeUbTuple(x2a,x1mb,x3a) ); - nodes.push_back( makeUbTuple(x2a,x1mb,x3a) ); nodes.push_back( makeUbTuple(x2d,x1mb,x3d) ); nodes.push_back( makeUbTuple(x2c,x1mb,x3c) ); - } - else if( this->isParallelToX3Axis() ) - { - nodes.push_back( makeUbTuple(x3a,x2a,x1ma) ); nodes.push_back( makeUbTuple(x3b,x2b,x1ma) ); nodes.push_back( makeUbTuple(x3c,x2c,x1ma) ); - nodes.push_back( makeUbTuple(x3c,x2c,x1ma) ); nodes.push_back( makeUbTuple(x3d,x2d,x1ma) ); nodes.push_back( makeUbTuple(x3a,x2a,x1ma) ); - nodes.push_back( makeUbTuple(x3c,x2c,x1mb) ); nodes.push_back( makeUbTuple(x3b,x2b,x1mb) ); nodes.push_back( makeUbTuple(x3a,x2a,x1mb) ); - nodes.push_back( makeUbTuple(x3a,x2a,x1mb) ); nodes.push_back( makeUbTuple(x3d,x2d,x1mb) ); nodes.push_back( makeUbTuple(x3c,x2c,x1mb) ); - } - - triangles.push_back( makeUbTuple(nodenr , nodenr+1, nodenr+2) ); nodenr+=3; - triangles.push_back( makeUbTuple(nodenr , nodenr+1, nodenr+2) ); nodenr+=3; - triangles.push_back( makeUbTuple(nodenr , nodenr+1, nodenr+2) ); nodenr+=3; - triangles.push_back( makeUbTuple(nodenr , nodenr+1, nodenr+2) ); nodenr+=3; - } - } + float x1ma, x1mb, x2m, x3m; + if (this->isParallelToX1Axis()) { + x1ma = (float)this->getX1Minimum(); + x1mb = (float)this->getX1Maximum(); + x2m = (float)this->getX2Centroid(); + x3m = (float)this->getX3Centroid(); + } else if (this->isParallelToX2Axis()) { + x1ma = (float)this->getX2Minimum(); + x1mb = (float)this->getX2Maximum(); + x2m = (float)this->getX1Centroid(); + x3m = (float)this->getX3Centroid(); + } else if (this->isParallelToX3Axis()) { + x1ma = (float)this->getX3Minimum(); + x1mb = (float)this->getX3Maximum(); + x2m = (float)this->getX2Centroid(); + x3m = (float)this->getX1Centroid(); + } else + throw UbException(UB_EXARGS, "cylinder not axis prallel"); + + int segmentsCircle = segmentsRound; + double deltaPhi = UbMath::PI / (double)segmentsCircle; + + double phiX1a, phiX1b; + float x1a, x2a, x3a, x1b, x2b, x3b, x1c, x2c, x3c, x1d, x2d, x3d; + + double dXCylinder = fabs((x1mb - x1ma)) / (double)segmentsHeight; // hier evtl. segmentsheight + int segmentsCylinder = (int)(fabs(x1mb - x1ma) / dXCylinder); + int nodenr = 0; + for (int segCyl = 0; segCyl < segmentsCylinder; segCyl++) { + x1a = x1d = (float)(x1ma + segCyl * dXCylinder); + x1b = x1c = (float)(x1a + dXCylinder); + + // for(phiX1a=2.0*UbMath::PI; phiX1a>0.0; phiX1a-=deltaPhi) + for (phiX1a = 0.0; phiX1a < 2.0 * UbMath::PI - 0.5 * deltaPhi; phiX1a += deltaPhi) { + phiX1b = phiX1a + deltaPhi; + + x2a = (float)(x2m + mRad * std::sin(phiX1a)); + x3a = (float)(x3m + mRad * std::cos(phiX1a)); + x2b = (float)(x2m + mRad * std::sin(phiX1b)); + x3b = (float)(x3m + mRad * std::cos(phiX1b)); + + if (this->isParallelToX1Axis()) { + nodes.push_back(makeUbTuple(x1b, x2b, x3b)); + nodes.push_back(makeUbTuple(x1b, x2a, x3a)); + nodes.push_back(makeUbTuple(x1a, x2a, x3a)); + nodes.push_back(makeUbTuple(x1a, x2a, x3a)); + nodes.push_back(makeUbTuple(x1a, x2b, x3b)); + nodes.push_back(makeUbTuple(x1b, x2b, x3b)); + } else if (this->isParallelToX2Axis()) { + nodes.push_back(makeUbTuple(x2b, x1b, x3b)); + nodes.push_back(makeUbTuple(x2a, x1b, x3a)); + nodes.push_back(makeUbTuple(x2a, x1a, x3a)); + nodes.push_back(makeUbTuple(x2a, x1a, x3a)); + nodes.push_back(makeUbTuple(x2b, x1a, x3b)); + nodes.push_back(makeUbTuple(x2b, x1b, x3b)); + } else if (this->isParallelToX3Axis()) { + nodes.push_back(makeUbTuple(x3b, x2b, x1b)); + nodes.push_back(makeUbTuple(x3a, x2a, x1b)); + nodes.push_back(makeUbTuple(x3a, x2a, x1a)); + nodes.push_back(makeUbTuple(x3a, x2a, x1a)); + nodes.push_back(makeUbTuple(x3b, x2b, x1a)); + nodes.push_back(makeUbTuple(x3b, x2b, x1b)); + } + triangles.push_back(makeUbTuple(nodenr, nodenr + 1, nodenr + 2)); + nodenr += 3; + triangles.push_back(makeUbTuple(nodenr, nodenr + 1, nodenr + 2)); + nodenr += 3; + } + } + + int segmentsSide = (int)(mRad / dXCylinder); + double radius0, radius1; + for (int segCyl = 0; segCyl < segmentsSide; segCyl++) { + radius0 = segCyl * dXCylinder; + radius1 = radius0 + dXCylinder; + if (segCyl == segmentsSide - 1) + radius1 = mRad; + + // for(phiX1a=2.0*UbMath::PI; phiX1a>0.0; phiX1a-=deltaPhi) + for (phiX1a = 0.0; phiX1a < 2.0 * UbMath::PI - 0.5 * deltaPhi; phiX1a += deltaPhi) { + phiX1b = phiX1a + deltaPhi; + + x2a = x2m + (float)(radius0 * std::sin(phiX1a)); + x3a = x3m + (float)(radius0 * std::cos(phiX1a)); + x2b = x2m + (float)(radius0 * std::sin(phiX1b)); + x3b = x3m + (float)(radius0 * std::cos(phiX1b)); + x2c = x2m + (float)(radius1 * std::sin(phiX1b)); + x3c = x3m + (float)(radius1 * std::cos(phiX1b)); + x2d = x2m + (float)(radius1 * std::sin(phiX1a)); + x3d = x3m + (float)(radius1 * std::cos(phiX1a)); + + if (this->isParallelToX1Axis()) { + nodes.push_back(makeUbTuple(x1ma, x2a, x3a)); + nodes.push_back(makeUbTuple(x1ma, x2b, x3b)); + nodes.push_back(makeUbTuple(x1ma, x2c, x3c)); + nodes.push_back(makeUbTuple(x1ma, x2c, x3c)); + nodes.push_back(makeUbTuple(x1ma, x2d, x3d)); + nodes.push_back(makeUbTuple(x1ma, x2a, x3a)); + nodes.push_back(makeUbTuple(x1mb, x2c, x3c)); + nodes.push_back(makeUbTuple(x1mb, x2b, x3b)); + nodes.push_back(makeUbTuple(x1mb, x2a, x3a)); + nodes.push_back(makeUbTuple(x1mb, x2a, x3a)); + nodes.push_back(makeUbTuple(x1mb, x2d, x3d)); + nodes.push_back(makeUbTuple(x1mb, x2c, x3c)); + } else if (this->isParallelToX2Axis()) { + nodes.push_back(makeUbTuple(x2a, x1ma, x3a)); + nodes.push_back(makeUbTuple(x2b, x1ma, x3b)); + nodes.push_back(makeUbTuple(x2c, x1ma, x3c)); + nodes.push_back(makeUbTuple(x2c, x1ma, x3c)); + nodes.push_back(makeUbTuple(x2d, x1ma, x3d)); + nodes.push_back(makeUbTuple(x2a, x1ma, x3a)); + nodes.push_back(makeUbTuple(x2c, x1mb, x3c)); + nodes.push_back(makeUbTuple(x2b, x1mb, x3b)); + nodes.push_back(makeUbTuple(x2a, x1mb, x3a)); + nodes.push_back(makeUbTuple(x2a, x1mb, x3a)); + nodes.push_back(makeUbTuple(x2d, x1mb, x3d)); + nodes.push_back(makeUbTuple(x2c, x1mb, x3c)); + } else if (this->isParallelToX3Axis()) { + nodes.push_back(makeUbTuple(x3a, x2a, x1ma)); + nodes.push_back(makeUbTuple(x3b, x2b, x1ma)); + nodes.push_back(makeUbTuple(x3c, x2c, x1ma)); + nodes.push_back(makeUbTuple(x3c, x2c, x1ma)); + nodes.push_back(makeUbTuple(x3d, x2d, x1ma)); + nodes.push_back(makeUbTuple(x3a, x2a, x1ma)); + nodes.push_back(makeUbTuple(x3c, x2c, x1mb)); + nodes.push_back(makeUbTuple(x3b, x2b, x1mb)); + nodes.push_back(makeUbTuple(x3a, x2a, x1mb)); + nodes.push_back(makeUbTuple(x3a, x2a, x1mb)); + nodes.push_back(makeUbTuple(x3d, x2d, x1mb)); + nodes.push_back(makeUbTuple(x3c, x2c, x1mb)); + } + + triangles.push_back(makeUbTuple(nodenr, nodenr + 1, nodenr + 2)); + nodenr += 3; + triangles.push_back(makeUbTuple(nodenr, nodenr + 1, nodenr + 2)); + nodenr += 3; + triangles.push_back(makeUbTuple(nodenr, nodenr + 1, nodenr + 2)); + nodenr += 3; + triangles.push_back(makeUbTuple(nodenr, nodenr + 1, nodenr + 2)); + nodenr += 3; + } + } } /*==========================================================*/ -void GbCylinder3D::objectChanged(UbObservable* changedObject) +void GbCylinder3D::objectChanged(UbObservable *changedObject) { - GbLine3D* line = dynamic_cast<GbLine3D*>(changedObject); - if(!line || this->mLine!=line) return; + GbLine3D *line = dynamic_cast<GbLine3D *>(changedObject); + if (!line || this->mLine != line) + return; - this->notifyObserversObjectChanged(); + this->notifyObserversObjectChanged(); } /*==========================================================*/ -void GbCylinder3D::objectWillBeDeleted(UbObservable* objectForDeletion) +void GbCylinder3D::objectWillBeDeleted(UbObservable *objectForDeletion) { - if(this->mLine) - { - UbObservable* observedObj = dynamic_cast<UbObservable*>(this->mLine); - if(objectForDeletion == observedObj) { this->mLine = NULL; } - } + if (this->mLine) { + UbObservable *observedObj = dynamic_cast<UbObservable *>(this->mLine); + if (objectForDeletion == observedObj) { + this->mLine = NULL; + } + } } /*=======================================================*/ -void GbCylinder3D::scale(const double& sx1, const double& sx2, const double& sx3) +void GbCylinder3D::scale(const double &sx1, const double &sx2, const double &sx3) { - if( this->isParallelToX1Axis() ) - { - if(!UbMath::equal(sx2,sx3)) throw UbException(UB_EXARGS,"|| to x1 -> different scaling sx2 and sx3 not possible"); - this->mRad*=sx2; - } - else if( this->isParallelToX2Axis() ) - { - if(!UbMath::equal(sx1,sx3)) throw UbException(UB_EXARGS,"|| to x2 -> different scaling sx1 and sx3 not possible"); - this->mRad*=sx1; - } - else if( this->isParallelToX3Axis() ) - { - if(!UbMath::equal(sx1,sx2)) throw UbException(UB_EXARGS,"|| to x3 -> different scaling sx1 and sx2 not possible"); - this->mRad*=sx1; - } - else throw UbException(UB_EXARGS,"unknown direction"); - - this->mLine->scale(sx1,sx2,sx3); - //notify observer wird automatisch aufgerufen + if (this->isParallelToX1Axis()) { + if (!UbMath::equal(sx2, sx3)) + throw UbException(UB_EXARGS, "|| to x1 -> different scaling sx2 and sx3 not possible"); + this->mRad *= sx2; + } else if (this->isParallelToX2Axis()) { + if (!UbMath::equal(sx1, sx3)) + throw UbException(UB_EXARGS, "|| to x2 -> different scaling sx1 and sx3 not possible"); + this->mRad *= sx1; + } else if (this->isParallelToX3Axis()) { + if (!UbMath::equal(sx1, sx2)) + throw UbException(UB_EXARGS, "|| to x3 -> different scaling sx1 and sx2 not possible"); + this->mRad *= sx1; + } else + throw UbException(UB_EXARGS, "unknown direction"); + + this->mLine->scale(sx1, sx2, sx3); + // notify observer wird automatisch aufgerufen } /*==========================================================*/ -double GbCylinder3D::getIntersectionRaytraceFactor(const double& x1, const double& x2, const double& x3, const double& rx1, const double& rx2, const double& rx3) +double GbCylinder3D::getIntersectionRaytraceFactor(const double &x1, const double &x2, const double &x3, + const double &rx1, const double &rx2, const double &rx3) { - /* - Distance D of the intersection between a Ray((ox1,ox2,ox3),(dx1,dx2,dx3)) and a Plane P: ax+by+cz+d=0 - dc = a*dx1 + b*dx2 + c*dx3 - dw = a*ox1 + b*ox2 + c*ox3 + d - D = - dw / dc - */ - double px1, px2, px3; - double d = Ub::inf; // Distance to Min or Max Plane of the Zylinder - // final distance should be less that d - - if( this->isParallelToX1Axis() ) - { - if (UbMath::equal(x1 ,minX1) && UbMath::negative(rx1)) return -1.0; - else if(UbMath::equal(x1 ,maxX1) && UbMath::positive(rx1)) return -1.0; - - //falls die Linie nicht parallel zu den Seitenflaechen ist - if( x1< minX1 || x1 > maxX1 ) //nur fuer punkte links und rechts des cylinders - { - px1 = (x1 < minX1 ? minX1 : maxX1); - //falls die Linie nicht parallel zu den Seitenflaechen ist - if( !UbMath::zero(rx1) ) - { - // Plane a= 0, b= 1, c=0 d= -1*px2 - d = -1.0*(x1 - px1) / rx1; - px2 = x2 + d*rx2; - px3 = x3 + d*rx3; - - if(UbMath::greater(mLine->getDistance(px1,px2,px3) , mRad)) - { - if (x1 < minX1 && rx1>0.0 ) d = Ub::inf; //punkt liegt "links" vom cylinder und strahl hat evtl weiteren SP auf oberflaeche - else if(x1 > maxX1 && rx1<0.0 ) d = Ub::inf; - else return -1.0; - } - else return d; - } - else return -1.0; - } - else - { - //if (UbMath::negative(rx1)) d = -1.0 * (x1 - minX1) / rx1; - //else if(UbMath::positive(rx1)) d = -1.0 * (x1 - maxX1) / rx1; - if (UbMath::negative(rx1)) d = -1.0 * (x1 - maxX1) / rx1; - else if(UbMath::positive(rx1)) d = -1.0 * (x1 - minX1) / rx1; - } - } - else if( this->isParallelToX2Axis() ) - { - if (UbMath::equal(x2 ,minX2) && UbMath::negative(rx2)) return -1; - else if(UbMath::equal(x2 ,maxX2) && UbMath::positive(rx2)) return -1; - - if( minX2 > x2 || x2 > maxX2 ) - { - px2 = (x2 < minX2 ? minX2 : maxX2); - //falls die Linie nicht parallel zu den Seitenflaechen ist - if( !UbMath::zero(rx2) ) - { - // Plane a= 0, b= 1, c=0 d= -1*px2 - d = -1*(x2 - px2) / rx2; - px1 = x1 + d*rx1; - px3 = x3 + d*rx3; - - if (UbMath::greater(mLine->getDistance(px1,px2,px3) , mRad)) - { - if (x2 < minX2 && rx2>0.0 ) d = Ub::inf; //punkt liegt "links oberhalb" vom cylinder und strahl mit pos x1 hat evtl weiteren SP auf oberflaeche - else if(x2 > maxX2 && rx2<0.0 ) d = Ub::inf; - else return -1.0; - } - else return d; - } - else return -1.0; - } - else - { - if (UbMath::negative(rx2)) d = -1.0 * (x2 - minX2) / rx2; - else if(UbMath::positive(rx2)) d = -1.0 * (x2 - maxX2) / rx2; - } - } - else if( this->isParallelToX3Axis() ) - { - if (UbMath::equal(x3, minX3) && UbMath::negative(rx3)) return -1.0; - else if(UbMath::equal(x3, maxX3) && UbMath::positive(rx3)) return -1.0; - - if(minX3 > x3 || x3 > maxX3 ) - { - px3 = (x3 < minX3 ? minX3 : maxX3); - //falls die Linie nicht parallel zu den Seitenflaechen ist - if (!UbMath::zero(rx3)) - { - // Plane a= 0, b= 0, c=1 d= -1*px3 - d = -1.0*(x3 - px3) / rx3; - px2 = x2 + d*rx2; - px1 = x1 + d*rx1; - if( UbMath::greater(mLine->getDistance(px1,px2,px3) , mRad) ) - { - if (x3 < minX3 && rx3>0.0 ) d = Ub::inf; - else if(x3 > maxX3 && rx3<0.0 ) d = Ub::inf; - else return -1.0; - } - else return d; - } - else return -1.0; - } - else - { - if (UbMath::negative(rx3)) d = -1.0 * (x3 - minX3) / rx3; - else if(UbMath::positive(rx3)) d = -1.0 * (x3 - maxX3) / rx3; - } - } - else throw UbException(UB_EXARGS,"funzt nur bei achsen parallelem cylinder"); - ////////////////////////////////////////////////////////////////////////// - //Q berechnen fuer Infinity Zylinder - double axisX1 = mLine->getPoint2()->x1 - mLine->getPoint1()->x1; /* Axis of the cylinder */ - double axisX2 = mLine->getPoint2()->x2 - mLine->getPoint1()->x2; /* mit p1 als base of cylinder */ - double axisX3 = mLine->getPoint2()->x3 - mLine->getPoint1()->x3; - - //double dirlen = mLine->getLength(); - //double abs, t, s; - - double RCx1 = x1 - mLine->getPoint1()->x1; - double RCx2 = x2 - mLine->getPoint1()->x2; - double RCx3 = x3 - mLine->getPoint1()->x3; - - //n = ray x axis - double nx1 = rx2*axisX3 - rx3*axisX2; - double nx2 = rx3*axisX1 - rx1*axisX3; - double nx3 = rx1*axisX2 - rx2*axisX1; - double nLength = nx1*nx1 + nx2*nx2 + nx3*nx3; - - double abs; - if( UbMath::zero( nLength ) ) - { /* ray parallel to cyl */ - //abs = RC dot axis - double tmpabs = RCx1*axisX1 + RCx2*axisX2 + RCx3*axisX3; - double dx1 = RCx1 - tmpabs*axisX1; - double dx2 = RCx2 - tmpabs*axisX2; - double dx3 = RCx3 - tmpabs*axisX3; - if( UbMath::greater( dx1*dx1 + dx2*dx2 + dx3*dx3 , mRad*mRad) ) - return -1.0; - } - - //normalize "n" - nLength = std::sqrt(nLength); - double invnLength = 1.0/nLength; - nx1*=invnLength; - nx2*=invnLength; - nx3*=invnLength; - - //shortest distance = fabs( RC dot n ) - abs = std::fabs( RCx1*nx1 + RCx2*nx2 + RCx3*nx3 ); - - if( UbMath::lessEqual(abs, mRad) ) - { /* if ray hits cylinder */ - //Ox1 = RC x axis - double Ox1 = RCx2*axisX3 - RCx3*axisX2; - double Ox2 = RCx3*axisX1 - RCx1*axisX3; - double Ox3 = RCx1*axisX2 - RCx2*axisX1; - //t = - O dot n / nLength; - double t = - (Ox1*nx1 + Ox2*nx2 + Ox3*nx3) / nLength; - - //O = n x axis; - Ox1 = nx2*axisX3 - nx3*axisX2; - Ox2 = nx3*axisX1 - nx1*axisX3; - Ox3 = nx1*axisX2 - nx2*axisX1; - - //normalize O - invnLength = 1.0/std::sqrt(Ox1*Ox1 + Ox2*Ox2 + Ox3*Ox3); - Ox1*=invnLength; - Ox2*=invnLength; - Ox3*=invnLength; - - double s = std::fabs( sqrt(mRad*mRad - abs*abs) / (rx1*Ox1 + rx2*Ox2 + rx3*Ox3) ); - - //Wert a) t-s: entering distance - // b) t+s: exiting distance - // - // -> we only consider factors in ray-dir -> means positive values! - // (s is always positive) - - if(t>s) - { - return UbMath::min( t-s, d ); - } - else if( (t+s) > 0 ) - { - return UbMath::min( t+s, d ); - } - } - - return -1.0; + /* + Distance D of the intersection between a Ray((ox1,ox2,ox3),(dx1,dx2,dx3)) and a Plane P: ax+by+cz+d=0 + dc = a*dx1 + b*dx2 + c*dx3 + dw = a*ox1 + b*ox2 + c*ox3 + d + D = - dw / dc + */ + double px1, px2, px3; + double d = Ub::inf; // Distance to Min or Max Plane of the Zylinder + // final distance should be less that d + + if (this->isParallelToX1Axis()) { + if (UbMath::equal(x1, minX1) && UbMath::negative(rx1)) + return -1.0; + else if (UbMath::equal(x1, maxX1) && UbMath::positive(rx1)) + return -1.0; + + // falls die Linie nicht parallel zu den Seitenflaechen ist + if (x1 < minX1 || x1 > maxX1) // nur fuer punkte links und rechts des cylinders + { + px1 = (x1 < minX1 ? minX1 : maxX1); + // falls die Linie nicht parallel zu den Seitenflaechen ist + if (!UbMath::zero(rx1)) { + // Plane a= 0, b= 1, c=0 d= -1*px2 + d = -1.0 * (x1 - px1) / rx1; + px2 = x2 + d * rx2; + px3 = x3 + d * rx3; + + if (UbMath::greater(mLine->getDistance(px1, px2, px3), mRad)) { + if (x1 < minX1 && rx1 > 0.0) + d = Ub::inf; // punkt liegt "links" vom cylinder und strahl hat evtl weiteren SP auf oberflaeche + else if (x1 > maxX1 && rx1 < 0.0) + d = Ub::inf; + else + return -1.0; + } else + return d; + } else + return -1.0; + } else { + // if (UbMath::negative(rx1)) d = -1.0 * (x1 - minX1) / rx1; + // else if(UbMath::positive(rx1)) d = -1.0 * (x1 - maxX1) / rx1; + if (UbMath::negative(rx1)) + d = -1.0 * (x1 - maxX1) / rx1; + else if (UbMath::positive(rx1)) + d = -1.0 * (x1 - minX1) / rx1; + } + } else if (this->isParallelToX2Axis()) { + if (UbMath::equal(x2, minX2) && UbMath::negative(rx2)) + return -1; + else if (UbMath::equal(x2, maxX2) && UbMath::positive(rx2)) + return -1; + + if (minX2 > x2 || x2 > maxX2) { + px2 = (x2 < minX2 ? minX2 : maxX2); + // falls die Linie nicht parallel zu den Seitenflaechen ist + if (!UbMath::zero(rx2)) { + // Plane a= 0, b= 1, c=0 d= -1*px2 + d = -1 * (x2 - px2) / rx2; + px1 = x1 + d * rx1; + px3 = x3 + d * rx3; + + if (UbMath::greater(mLine->getDistance(px1, px2, px3), mRad)) { + if (x2 < minX2 && rx2 > 0.0) + d = Ub::inf; // punkt liegt "links oberhalb" vom cylinder und strahl mit pos x1 hat evtl + // weiteren SP auf oberflaeche + else if (x2 > maxX2 && rx2 < 0.0) + d = Ub::inf; + else + return -1.0; + } else + return d; + } else + return -1.0; + } else { + if (UbMath::negative(rx2)) + d = -1.0 * (x2 - minX2) / rx2; + else if (UbMath::positive(rx2)) + d = -1.0 * (x2 - maxX2) / rx2; + } + } else if (this->isParallelToX3Axis()) { + if (UbMath::equal(x3, minX3) && UbMath::negative(rx3)) + return -1.0; + else if (UbMath::equal(x3, maxX3) && UbMath::positive(rx3)) + return -1.0; + + if (minX3 > x3 || x3 > maxX3) { + px3 = (x3 < minX3 ? minX3 : maxX3); + // falls die Linie nicht parallel zu den Seitenflaechen ist + if (!UbMath::zero(rx3)) { + // Plane a= 0, b= 0, c=1 d= -1*px3 + d = -1.0 * (x3 - px3) / rx3; + px2 = x2 + d * rx2; + px1 = x1 + d * rx1; + if (UbMath::greater(mLine->getDistance(px1, px2, px3), mRad)) { + if (x3 < minX3 && rx3 > 0.0) + d = Ub::inf; + else if (x3 > maxX3 && rx3 < 0.0) + d = Ub::inf; + else + return -1.0; + } else + return d; + } else + return -1.0; + } else { + if (UbMath::negative(rx3)) + d = -1.0 * (x3 - minX3) / rx3; + else if (UbMath::positive(rx3)) + d = -1.0 * (x3 - maxX3) / rx3; + } + } else + throw UbException(UB_EXARGS, "funzt nur bei achsen parallelem cylinder"); + ////////////////////////////////////////////////////////////////////////// + // Q berechnen fuer Infinity Zylinder + double axisX1 = mLine->getPoint2()->x1 - mLine->getPoint1()->x1; /* Axis of the cylinder */ + double axisX2 = mLine->getPoint2()->x2 - mLine->getPoint1()->x2; /* mit p1 als base of cylinder */ + double axisX3 = mLine->getPoint2()->x3 - mLine->getPoint1()->x3; + + // double dirlen = mLine->getLength(); + // double abs, t, s; + + double RCx1 = x1 - mLine->getPoint1()->x1; + double RCx2 = x2 - mLine->getPoint1()->x2; + double RCx3 = x3 - mLine->getPoint1()->x3; + + // n = ray x axis + double nx1 = rx2 * axisX3 - rx3 * axisX2; + double nx2 = rx3 * axisX1 - rx1 * axisX3; + double nx3 = rx1 * axisX2 - rx2 * axisX1; + double nLength = nx1 * nx1 + nx2 * nx2 + nx3 * nx3; + + double abs; + if (UbMath::zero(nLength)) { /* ray parallel to cyl */ + // abs = RC dot axis + double tmpabs = RCx1 * axisX1 + RCx2 * axisX2 + RCx3 * axisX3; + double dx1 = RCx1 - tmpabs * axisX1; + double dx2 = RCx2 - tmpabs * axisX2; + double dx3 = RCx3 - tmpabs * axisX3; + if (UbMath::greater(dx1 * dx1 + dx2 * dx2 + dx3 * dx3, mRad * mRad)) + return -1.0; + } + + // normalize "n" + nLength = std::sqrt(nLength); + double invnLength = 1.0 / nLength; + nx1 *= invnLength; + nx2 *= invnLength; + nx3 *= invnLength; + + // shortest distance = fabs( RC dot n ) + abs = std::fabs(RCx1 * nx1 + RCx2 * nx2 + RCx3 * nx3); + + if (UbMath::lessEqual(abs, mRad)) { /* if ray hits cylinder */ + // Ox1 = RC x axis + double Ox1 = RCx2 * axisX3 - RCx3 * axisX2; + double Ox2 = RCx3 * axisX1 - RCx1 * axisX3; + double Ox3 = RCx1 * axisX2 - RCx2 * axisX1; + // t = - O dot n / nLength; + double t = -(Ox1 * nx1 + Ox2 * nx2 + Ox3 * nx3) / nLength; + + // O = n x axis; + Ox1 = nx2 * axisX3 - nx3 * axisX2; + Ox2 = nx3 * axisX1 - nx1 * axisX3; + Ox3 = nx1 * axisX2 - nx2 * axisX1; + + // normalize O + invnLength = 1.0 / std::sqrt(Ox1 * Ox1 + Ox2 * Ox2 + Ox3 * Ox3); + Ox1 *= invnLength; + Ox2 *= invnLength; + Ox3 *= invnLength; + + double s = std::fabs(sqrt(mRad * mRad - abs * abs) / (rx1 * Ox1 + rx2 * Ox2 + rx3 * Ox3)); + + // Wert a) t-s: entering distance + // b) t+s: exiting distance + // + // -> we only consider factors in ray-dir -> means positive values! + // (s is always positive) + + if (t > s) { + return UbMath::min(t - s, d); + } else if ((t + s) > 0) { + return UbMath::min(t + s, d); + } + } + + return -1.0; } /*==========================================================*/ diff --git a/src/basics/geometry3d/GbCylinder3D.h b/src/basics/geometry3d/GbCylinder3D.h index bf8e19a2843837bb9b9ac7155771d5560c8bb8f5..3740f18b11ea1f7820fe930dc91a5c264b5a600d 100644 --- a/src/basics/geometry3d/GbCylinder3D.h +++ b/src/basics/geometry3d/GbCylinder3D.h @@ -7,13 +7,12 @@ #ifndef GBCYLINDER3D_H #define GBCYLINDER3D_H - -#include <vector> #include <cmath> +#include <vector> -#include <geometry3d/GbObject3D.h> -#include <geometry3d/GbLine3D.h> #include <basics/utilities/UbObserver.h> +#include <geometry3d/GbLine3D.h> +#include <geometry3d/GbObject3D.h> class GbPoint3D; class GbLine3D; @@ -25,104 +24,107 @@ class GbObject3DCreator; class GbCylinder3D; using GbCylinder3DPtr = SPtr<GbCylinder3D>; - -class GbCylinder3D : public GbObject3D , public UbObserver +class GbCylinder3D : public GbObject3D, public UbObserver { public: - GbCylinder3D(); - GbCylinder3D(const double& x1a,const double& x2a, const double& x3a, const double& x1b,const double& x2b, const double& x3b, const double& radius); - GbCylinder3D(GbPoint3D* p1, GbPoint3D* p2, const double& radius); - GbCylinder3D(GbLine3D* line, const double& rad); - GbCylinder3D(GbCylinder3D* cylinder); - ~GbCylinder3D() override; - - GbCylinder3D* clone() override { return new GbCylinder3D(this); } - void finalize() override; - - double getRadius() { return this->mRad; }; - GbLine3D* getLine() {return mLine;} - GbPoint3D* getPoint1(); - GbPoint3D* getPoint2(); - - void setRadius(const double& radius); - void setLine(GbLine3D* line); - void setPoint1(const double& x1, const double& x2, const double& x3); - void setPoint2(const double& x1, const double& x2, const double& x3); - - bool isParallelToX1Axis() { return((this->cylinderType & X1PARALLEL ) == X1PARALLEL );} - bool isParallelToX2Axis() { return((this->cylinderType & X2PARALLEL ) == X2PARALLEL );} - bool isParallelToX3Axis() { return((this->cylinderType & X3PARALLEL ) == X3PARALLEL );} - bool isNotParallelToAxis(){ return((this->cylinderType & NOTPARALLELTOAXIS ) == NOTPARALLELTOAXIS );} - - double getHeight(); - - void scale(const double& sx1, const double& sx2, const double& sx3) override; - - void translate(const double& x1, const double& x2, const double& x3) override - { - this->mLine->translate( x1, x2, x3 ); - this->calculateValues(); - //this->notifyObserversObjectChanged(); - } - - double getX1Centroid() override { return centerX1; } - double getX1Minimum() override { return minX1; } - double getX1Maximum() override { return maxX1; } - double getX2Centroid() override { return centerX2; } - double getX2Minimum() override { return minX2; } - double getX2Maximum() override { return maxX2; } - double getX3Centroid() override { return centerX3; } - double getX3Minimum() override { return minX3; } - double getX3Maximum() override { return maxX3; } - - bool isPointInGbObject3D(const double& x1p, const double& x2p, const double& x3p) override; - bool isPointInGbObject3D(const double& x1p, const double& x2p, const double& x3p, bool& pointIsOnBoundary) override; - bool isCellInsideGbObject3D(const double& x1a,const double& x2a,const double& x3a,const double& x1b,const double& x2b,const double& x3b) override; - bool isCellCuttingGbObject3D(const double& x1a,const double& x2a,const double& x3a,const double& x1b,const double& x2b,const double& x3b) override; - bool isCellInsideOrCuttingGbObject3D(const double& x1a,const double& x2a,const double& x3a,const double& x1b,const double& x2b,const double& x3b) override; - - GbLine3D* createClippedLine3D(GbPoint3D& point1, GbPoint3D& point2) override; - - //SG ausdokumentieren, da der nur unendlcihe Zylinder macht ... - //bool hasRaytracing() { return true; } - bool hasRaytracing() override { return false; } - bool raytracingSupportsPointsInside() override { return true; } - - - /*|r| must be 1! einheitsvector!!*/ - double getIntersectionRaytraceFactor(const double& x1, const double& x2, const double& x3, const double& rx1, const double& rx2, const double& rx3) override; - - std::vector<GbTriangle3D*> getSurfaceTriangleSet() override; - void addSurfaceTriangleSet(std::vector<UbTupleFloat3>& nodes, std::vector<UbTupleInt3>& triangles) override; - void addSurfaceTriangleSetSegments(std::vector<UbTupleFloat3>& nodes, std::vector<UbTupleInt3>& triangles, int segmentsRound, int segmentsHeight ); - - std::string toString() override; - - //virtuelle Methoden von UbObserver - void objectChanged(UbObservable* changedObject) override; - void objectWillBeDeleted(UbObservable* objectForDeletion) override; - - - using GbObject3D::isPointInGbObject3D; //Grund: dadurch muss man hier isPointInGbObject3D(GbPoint3D*) nicht ausprogrammieren, welche sonst hier "ueberdeckt" waere - + GbCylinder3D(); + GbCylinder3D(const double &x1a, const double &x2a, const double &x3a, const double &x1b, const double &x2b, + const double &x3b, const double &radius); + GbCylinder3D(GbPoint3D *p1, GbPoint3D *p2, const double &radius); + GbCylinder3D(GbLine3D *line, const double &rad); + GbCylinder3D(GbCylinder3D *cylinder); + ~GbCylinder3D() override; + + GbCylinder3D *clone() override { return new GbCylinder3D(this); } + void finalize() override; + + double getRadius() { return this->mRad; }; + GbLine3D *getLine() { return mLine; } + GbPoint3D *getPoint1(); + GbPoint3D *getPoint2(); + + void setRadius(const double &radius); + void setLine(GbLine3D *line); + void setPoint1(const double &x1, const double &x2, const double &x3); + void setPoint2(const double &x1, const double &x2, const double &x3); + + bool isParallelToX1Axis() { return ((this->cylinderType & X1PARALLEL) == X1PARALLEL); } + bool isParallelToX2Axis() { return ((this->cylinderType & X2PARALLEL) == X2PARALLEL); } + bool isParallelToX3Axis() { return ((this->cylinderType & X3PARALLEL) == X3PARALLEL); } + bool isNotParallelToAxis() { return ((this->cylinderType & NOTPARALLELTOAXIS) == NOTPARALLELTOAXIS); } + + double getHeight(); + + void scale(const double &sx1, const double &sx2, const double &sx3) override; + + void translate(const double &x1, const double &x2, const double &x3) override + { + this->mLine->translate(x1, x2, x3); + this->calculateValues(); + // this->notifyObserversObjectChanged(); + } + + double getX1Centroid() override { return centerX1; } + double getX1Minimum() override { return minX1; } + double getX1Maximum() override { return maxX1; } + double getX2Centroid() override { return centerX2; } + double getX2Minimum() override { return minX2; } + double getX2Maximum() override { return maxX2; } + double getX3Centroid() override { return centerX3; } + double getX3Minimum() override { return minX3; } + double getX3Maximum() override { return maxX3; } + + bool isPointInGbObject3D(const double &x1p, const double &x2p, const double &x3p) override; + bool isPointInGbObject3D(const double &x1p, const double &x2p, const double &x3p, bool &pointIsOnBoundary) override; + bool isCellInsideGbObject3D(const double &x1a, const double &x2a, const double &x3a, const double &x1b, + const double &x2b, const double &x3b) override; + bool isCellCuttingGbObject3D(const double &x1a, const double &x2a, const double &x3a, const double &x1b, + const double &x2b, const double &x3b) override; + bool isCellInsideOrCuttingGbObject3D(const double &x1a, const double &x2a, const double &x3a, const double &x1b, + const double &x2b, const double &x3b) override; + + GbLine3D *createClippedLine3D(GbPoint3D &point1, GbPoint3D &point2) override; + + // SG ausdokumentieren, da der nur unendlcihe Zylinder macht ... + // bool hasRaytracing() { return true; } + bool hasRaytracing() override { return false; } + bool raytracingSupportsPointsInside() override { return true; } + + /*|r| must be 1! einheitsvector!!*/ + double getIntersectionRaytraceFactor(const double &x1, const double &x2, const double &x3, const double &rx1, + const double &rx2, const double &rx3) override; + + std::vector<GbTriangle3D *> getSurfaceTriangleSet() override; + void addSurfaceTriangleSet(std::vector<UbTupleFloat3> &nodes, std::vector<UbTupleInt3> &triangles) override; + void addSurfaceTriangleSetSegments(std::vector<UbTupleFloat3> &nodes, std::vector<UbTupleInt3> &triangles, + int segmentsRound, int segmentsHeight); + + std::string toString() override; + + // virtuelle Methoden von UbObserver + void objectChanged(UbObservable *changedObject) override; + void objectWillBeDeleted(UbObservable *objectForDeletion) override; + + using GbObject3D::isPointInGbObject3D; // Grund: dadurch muss man hier isPointInGbObject3D(GbPoint3D*) nicht + // ausprogrammieren, welche sonst hier "ueberdeckt" waere protected: - void calculateValues(); + void calculateValues(); - GbLine3D* mLine; - double mRad; + GbLine3D *mLine; + double mRad; - double minX1{0.0}, minX2{0.0}, minX3{0.0}; - double maxX1{0.0}, maxX2{0.0}, maxX3{0.0}; - double centerX1{0.0}, centerX2{0.0}, centerX3{0.0}; + double minX1{ 0.0 }, minX2{ 0.0 }, minX3{ 0.0 }; + double maxX1{ 0.0 }, maxX2{ 0.0 }, maxX3{ 0.0 }; + double centerX1{ 0.0 }, centerX2{ 0.0 }, centerX3{ 0.0 }; - int cylinderType; + int cylinderType; - //void berechneQuerschnittsWerte(); - static const int NOTPARALLELTOAXIS = (1<<0); //1 - static const int X1PARALLEL = (1<<1); //2 - static const int X2PARALLEL = (1<<2); //4 - static const int X3PARALLEL = (1<<3); //8 + // void berechneQuerschnittsWerte(); + static const int NOTPARALLELTOAXIS = (1 << 0); // 1 + static const int X1PARALLEL = (1 << 1); // 2 + static const int X2PARALLEL = (1 << 2); // 4 + static const int X3PARALLEL = (1 << 3); // 8 }; -#endif +#endif diff --git a/src/basics/geometry3d/GbHalfSpace3D.cpp b/src/basics/geometry3d/GbHalfSpace3D.cpp index 04d8a39d8ea3760610c36089cb52bd968aa3d83e..8566d337d32ae269bb630d3f2a44f49b0cd70118 100644 --- a/src/basics/geometry3d/GbHalfSpace3D.cpp +++ b/src/basics/geometry3d/GbHalfSpace3D.cpp @@ -3,97 +3,97 @@ using namespace std; /*==========================================================*/ -GbHalfSpace3D::GbHalfSpace3D(GbTriangle3D* triangle) +GbHalfSpace3D::GbHalfSpace3D(GbTriangle3D *triangle) { - GbPoint3D* PointA = triangle->getPoint1(); - GbPoint3D* PointB = triangle->getPoint2(); - GbPoint3D* PointC = triangle->getPoint3(); - - GbVector3D A(PointA->x1, PointA->x2, PointA->x3 ); - GbVector3D BA(PointB->x1-PointA->x1, PointB->x2-PointA->x2, PointB->x3-PointA->x3 ); - GbVector3D CA(PointC->x1-PointA->x1, PointC->x2-PointA->x2, PointC->x3-PointA->x3 ); - GbVector3D BACA = BA.Cross(CA); - //this->Normal = PointB->subtract(PointA)->cross(PointC->subtract(PointA))->normalize(); - BACA.Normalize(); - //this->Normal = BACA; - normalX = BACA[0]; - normalY = BACA[1]; - normalZ = BACA[2]; - //this->d = this->Normal.Dot(A); - this->d = normalX*A[0] + normalY*A[1] + normalZ*A[2] ; + GbPoint3D *PointA = triangle->getPoint1(); + GbPoint3D *PointB = triangle->getPoint2(); + GbPoint3D *PointC = triangle->getPoint3(); + + GbVector3D A(PointA->x1, PointA->x2, PointA->x3); + GbVector3D BA(PointB->x1 - PointA->x1, PointB->x2 - PointA->x2, PointB->x3 - PointA->x3); + GbVector3D CA(PointC->x1 - PointA->x1, PointC->x2 - PointA->x2, PointC->x3 - PointA->x3); + GbVector3D BACA = BA.Cross(CA); + // this->Normal = PointB->subtract(PointA)->cross(PointC->subtract(PointA))->normalize(); + BACA.Normalize(); + // this->Normal = BACA; + normalX = BACA[0]; + normalY = BACA[1]; + normalZ = BACA[2]; + // this->d = this->Normal.Dot(A); + this->d = normalX * A[0] + normalY * A[1] + normalZ * A[2]; } /*==========================================================*/ -GbHalfSpace3D::GbHalfSpace3D(GbPoint3D* PointA, GbPoint3D* PointB, GbPoint3D* PointC) +GbHalfSpace3D::GbHalfSpace3D(GbPoint3D *PointA, GbPoint3D *PointB, GbPoint3D *PointC) { - GbVector3D A(PointA->x1, PointA->x2, PointA->x3 ); - GbVector3D BA(PointB->x1-PointA->x1, PointB->x2-PointA->x2, PointB->x3-PointA->x3 ); - GbVector3D CA(PointC->x1-PointA->x1, PointC->x2-PointA->x2, PointC->x3-PointA->x3 ); - GbVector3D BACA = BA.Cross(CA); - //this->Normal = PointB->subtract(PointA)->cross(PointC->subtract(PointA))->normalize(); - BACA.Normalize(); - //this->Normal = BACA; - normalX = BACA[0]; - normalY = BACA[1]; - normalZ = BACA[2]; - //this->d = this->Normal.Dot(A); - this->d = normalX*A[0] + normalY*A[1] + normalZ*A[2] ; + GbVector3D A(PointA->x1, PointA->x2, PointA->x3); + GbVector3D BA(PointB->x1 - PointA->x1, PointB->x2 - PointA->x2, PointB->x3 - PointA->x3); + GbVector3D CA(PointC->x1 - PointA->x1, PointC->x2 - PointA->x2, PointC->x3 - PointA->x3); + GbVector3D BACA = BA.Cross(CA); + // this->Normal = PointB->subtract(PointA)->cross(PointC->subtract(PointA))->normalize(); + BACA.Normalize(); + // this->Normal = BACA; + normalX = BACA[0]; + normalY = BACA[1]; + normalZ = BACA[2]; + // this->d = this->Normal.Dot(A); + this->d = normalX * A[0] + normalY * A[1] + normalZ * A[2]; } /*==========================================================*/ -GbHalfSpace3D::GbHalfSpace3D(GbPoint3D* PointA, GbPoint3D* PointB) +GbHalfSpace3D::GbHalfSpace3D(GbPoint3D *PointA, GbPoint3D *PointB) { - GbVector3D A(PointA->x1, PointA->x2, PointA->x3 ); - GbVector3D B(PointB->x1, PointB->x2, PointB->x3 ); - GbVector3D K(0.0,0.0,0.99); // the vector from PointA - third point - - GbVector3D PointBA = B-A; - GbVector3D PointBAK = PointBA.Cross(K); - PointBAK.Normalize(); - - //this->Normal = PointBAK; - normalX = PointBAK[0]; - normalY = PointBAK[1]; - normalZ = PointBAK[2]; - - //this->d = this->Normal.Dot(A); - this->d = normalX*PointA->x1 + normalY*PointA->x2 + normalZ*PointA->x3; + GbVector3D A(PointA->x1, PointA->x2, PointA->x3); + GbVector3D B(PointB->x1, PointB->x2, PointB->x3); + GbVector3D K(0.0, 0.0, 0.99); // the vector from PointA - third point + + GbVector3D PointBA = B - A; + GbVector3D PointBAK = PointBA.Cross(K); + PointBAK.Normalize(); + + // this->Normal = PointBAK; + normalX = PointBAK[0]; + normalY = PointBAK[1]; + normalZ = PointBAK[2]; + + // this->d = this->Normal.Dot(A); + this->d = normalX * PointA->x1 + normalY * PointA->x2 + normalZ * PointA->x3; } /*==========================================================*/ -GbHalfSpace3D::GbHalfSpace3D( const double& p1x, const double& p1y, const double& p1z - , const double& p2x, const double& p2y, const double& p2z - , const double& p3x, const double& p3y, const double& p3z ) +GbHalfSpace3D::GbHalfSpace3D(const double &p1x, const double &p1y, const double &p1z, const double &p2x, + const double &p2y, const double &p2z, const double &p3x, const double &p3y, + const double &p3z) { - double p2minusP1x = p2x-p1x; - double p2minusP1y = p2y-p1y; - double p2minusP1z = p2z-p1z; - - double P3minusP1x = p3x-p1x; - double P3minusP1y = p3y-p1y; - double P3minusP1z = p3z-p1z; - - //normal = BA x CA - normalX = p2minusP1y*P3minusP1z - p2minusP1z*P3minusP1y; - normalY = p2minusP1z*P3minusP1x - p2minusP1x*P3minusP1z; - normalZ = p2minusP1x*P3minusP1y - p2minusP1y*P3minusP1x; - - //normalize BACA - double oneOverNormalLength = 1.0 / ( std::sqrt( normalX*normalX + normalY*normalY + normalZ*normalZ ) ); - normalX *= oneOverNormalLength; - normalY *= oneOverNormalLength; - normalZ *= oneOverNormalLength; + double p2minusP1x = p2x - p1x; + double p2minusP1y = p2y - p1y; + double p2minusP1z = p2z - p1z; + + double P3minusP1x = p3x - p1x; + double P3minusP1y = p3y - p1y; + double P3minusP1z = p3z - p1z; + + // normal = BA x CA + normalX = p2minusP1y * P3minusP1z - p2minusP1z * P3minusP1y; + normalY = p2minusP1z * P3minusP1x - p2minusP1x * P3minusP1z; + normalZ = p2minusP1x * P3minusP1y - p2minusP1y * P3minusP1x; + + // normalize BACA + double oneOverNormalLength = 1.0 / (std::sqrt(normalX * normalX + normalY * normalY + normalZ * normalZ)); + normalX *= oneOverNormalLength; + normalY *= oneOverNormalLength; + normalZ *= oneOverNormalLength; - //d = normal * p1 - this->d = normalX*p1x + normalY*p1y + normalZ*p1z; + // d = normal * p1 + this->d = normalX * p1x + normalY * p1y + normalZ * p1z; } /*==========================================================*/ -GbHalfSpace3D::GbHalfSpace3D( const double& p1x, const double& p1y, const double& p1z, - const double& nx, const double& ny, const double& nz) +GbHalfSpace3D::GbHalfSpace3D(const double &p1x, const double &p1y, const double &p1z, const double &nx, + const double &ny, const double &nz) { - //normal = BA x CA - normalX =nx; - normalY =ny; - normalZ =nz; + // normal = BA x CA + normalX = nx; + normalY = ny; + normalZ = nz; - //d = normal * p1 - this->d = nx*p1x + ny*p1y + nz*p1z; + // d = normal * p1 + this->d = nx * p1x + ny * p1y + nz * p1z; } /*==========================================================*/ diff --git a/src/basics/geometry3d/GbHalfSpace3D.h b/src/basics/geometry3d/GbHalfSpace3D.h index b63f550dd6d7e2760e126ce3e945fd41907f93a3..768a01c96c831405fb6024d1bd92d1d92de38c7a 100644 --- a/src/basics/geometry3d/GbHalfSpace3D.h +++ b/src/basics/geometry3d/GbHalfSpace3D.h @@ -7,8 +7,8 @@ #ifndef GBHALFSPACE3D_H #define GBHALFSPACE3D_H -#include <sstream> #include <iostream> +#include <sstream> #include <basics/utilities/UbMath.h> @@ -18,67 +18,65 @@ #include <PointerDefinitions.h> - /*=========================================================================*/ /* GbHalfSpace3D */ /* */ /** -* This Class helps in performing some operations on a halfspace defined by 2 or 3 points -*/ + * This Class helps in performing some operations on a halfspace defined by 2 or 3 points + */ -class GbHalfSpace3D +class GbHalfSpace3D { public: - GbHalfSpace3D(GbTriangle3D* triangle); + GbHalfSpace3D(GbTriangle3D *triangle); - GbHalfSpace3D(GbPoint3D* PointA, GbPoint3D* PointB, GbPoint3D* PointC); + GbHalfSpace3D(GbPoint3D *PointA, GbPoint3D *PointB, GbPoint3D *PointC); - GbHalfSpace3D(GbPoint3D* PointA, GbPoint3D* PointB); + GbHalfSpace3D(GbPoint3D *PointA, GbPoint3D *PointB); - GbHalfSpace3D( const double& p1x, const double& p1y, const double& p1z - , const double& p2x, const double& p2y, const double& p2z - , const double& p3x, const double& p3y, const double& p3z ); - GbHalfSpace3D( const double& p1x, const double& p1y, const double& p1z, - const double& nx, const double& ny, const double& nz); + GbHalfSpace3D(const double &p1x, const double &p1y, const double &p1z, const double &p2x, const double &p2y, + const double &p2z, const double &p3x, const double &p3y, const double &p3z); + GbHalfSpace3D(const double &p1x, const double &p1y, const double &p1z, const double &nx, const double &ny, + const double &nz); - /*=======================================================*/ - std::string getTypeID() {return "GbHalfSpace3D"; } - /*=============================================*/ - bool ptInside(const double& x, const double& y, const double& z) - { - return UbMath::greaterEqual( normalX*x + normalY*y + normalZ*z, this->d ); - } - /*=============================================*/ - bool ptInside(GbPoint3D* pointX) - { - //GbVector3D X(PointX->x1, PointX->x2, PointX->x3 ); - //return UbMath::greaterEqual(this->Normal.Dot(X), this->d); - return UbMath::greaterEqual( normalX*pointX->x1 + normalY*pointX->x2 + normalZ*pointX->x3, this->d ); - } - /*=============================================*/ - bool ptInside(GbVector3D& x) - { - //return UbMath::greaterEqual(this->Normal.Dot(X), this->d); - return UbMath::greaterEqual( normalX*x[0] + normalY*x[1] + normalZ*x[2], this->d ); - } - /*=============================================*/ - double getDistance(const double& x1p, const double& x2p, const double& x3p) - { - return (normalX*x1p + normalY*x2p + normalZ*x3p) - this->d; - } + /*=======================================================*/ + std::string getTypeID() { return "GbHalfSpace3D"; } + /*=============================================*/ + bool ptInside(const double &x, const double &y, const double &z) + { + return UbMath::greaterEqual(normalX * x + normalY * y + normalZ * z, this->d); + } + /*=============================================*/ + bool ptInside(GbPoint3D *pointX) + { + // GbVector3D X(PointX->x1, PointX->x2, PointX->x3 ); + // return UbMath::greaterEqual(this->Normal.Dot(X), this->d); + return UbMath::greaterEqual(normalX * pointX->x1 + normalY * pointX->x2 + normalZ * pointX->x3, this->d); + } + /*=============================================*/ + bool ptInside(GbVector3D &x) + { + // return UbMath::greaterEqual(this->Normal.Dot(X), this->d); + return UbMath::greaterEqual(normalX * x[0] + normalY * x[1] + normalZ * x[2], this->d); + } + /*=============================================*/ + double getDistance(const double &x1p, const double &x2p, const double &x3p) + { + return (normalX * x1p + normalY * x2p + normalZ * x3p) - this->d; + } - const double& getNormalX() { return this->normalX; } - const double& getNormalY() { return this->normalY; } - const double& getNormalZ() { return this->normalZ; } - const double& getD() { return this->d; } + const double &getNormalX() { return this->normalX; } + const double &getNormalY() { return this->normalY; } + const double &getNormalZ() { return this->normalZ; } + const double &getD() { return this->d; } private: - //GbVector3D Normal; - double normalX; - double normalY; - double normalZ; - double d; + // GbVector3D Normal; + double normalX; + double normalY; + double normalZ; + double d; }; /*=========================================================================*/ -#endif //GBHALFSPACE3D_H +#endif // GBHALFSPACE3D_H diff --git a/src/basics/geometry3d/GbHalfSpaceKrischan3D.cpp b/src/basics/geometry3d/GbHalfSpaceKrischan3D.cpp index b8a00c647d335fb13d0031f2908a77ffbada8c62..903cffa95f56a0258989f477e07e37d7a7dcaadf 100644 --- a/src/basics/geometry3d/GbHalfSpaceKrischan3D.cpp +++ b/src/basics/geometry3d/GbHalfSpaceKrischan3D.cpp @@ -3,265 +3,269 @@ using namespace std; /*==========================================================*/ -GbHalfSpaceKrischan3D::GbHalfSpaceKrischan3D(GbTriangle3D* triangle) +GbHalfSpaceKrischan3D::GbHalfSpaceKrischan3D(GbTriangle3D *triangle) { - GbPoint3D* PointA = triangle->getPoint1(); - GbPoint3D* PointB = triangle->getPoint2(); - GbPoint3D* PointC = triangle->getPoint3(); - - GbVector3D A(PointA->x1, PointA->x2, PointA->x3 ); - GbVector3D BA(PointB->x1-PointA->x1, PointB->x2-PointA->x2, PointB->x3-PointA->x3 ); - GbVector3D CA(PointC->x1-PointA->x1, PointC->x2-PointA->x2, PointC->x3-PointA->x3 ); - GbVector3D BACA = BA.Cross(CA); - //this->Normal = PointB->subtract(PointA)->cross(PointC->subtract(PointA))->normalize(); - BACA.Normalize(); - this->Normal = BACA; - this->d = this->Normal.Dot(A); + GbPoint3D *PointA = triangle->getPoint1(); + GbPoint3D *PointB = triangle->getPoint2(); + GbPoint3D *PointC = triangle->getPoint3(); + + GbVector3D A(PointA->x1, PointA->x2, PointA->x3); + GbVector3D BA(PointB->x1 - PointA->x1, PointB->x2 - PointA->x2, PointB->x3 - PointA->x3); + GbVector3D CA(PointC->x1 - PointA->x1, PointC->x2 - PointA->x2, PointC->x3 - PointA->x3); + GbVector3D BACA = BA.Cross(CA); + // this->Normal = PointB->subtract(PointA)->cross(PointC->subtract(PointA))->normalize(); + BACA.Normalize(); + this->Normal = BACA; + this->d = this->Normal.Dot(A); } /*==========================================================*/ -GbHalfSpaceKrischan3D::GbHalfSpaceKrischan3D(GbPoint3D* PointA, GbPoint3D* PointB, GbPoint3D* PointC) +GbHalfSpaceKrischan3D::GbHalfSpaceKrischan3D(GbPoint3D *PointA, GbPoint3D *PointB, GbPoint3D *PointC) { - GbVector3D A(PointA->x1, PointA->x2, PointA->x3 ); - GbVector3D BA(PointB->x1-PointA->x1, PointB->x2-PointA->x2, PointB->x3-PointA->x3 ); - GbVector3D CA(PointC->x1-PointA->x1, PointC->x2-PointA->x2, PointC->x3-PointA->x3 ); - GbVector3D BACA = BA.Cross(CA); - //this->Normal = PointB->subtract(PointA)->cross(PointC->subtract(PointA))->normalize(); - BACA.Normalize(); - this->Normal = BACA; - this->d = this->Normal.Dot(A); + GbVector3D A(PointA->x1, PointA->x2, PointA->x3); + GbVector3D BA(PointB->x1 - PointA->x1, PointB->x2 - PointA->x2, PointB->x3 - PointA->x3); + GbVector3D CA(PointC->x1 - PointA->x1, PointC->x2 - PointA->x2, PointC->x3 - PointA->x3); + GbVector3D BACA = BA.Cross(CA); + // this->Normal = PointB->subtract(PointA)->cross(PointC->subtract(PointA))->normalize(); + BACA.Normalize(); + this->Normal = BACA; + this->d = this->Normal.Dot(A); } /*==========================================================*/ -GbHalfSpaceKrischan3D::GbHalfSpaceKrischan3D(GbPoint3D* PointA, GbPoint3D* PointB) +GbHalfSpaceKrischan3D::GbHalfSpaceKrischan3D(GbPoint3D *PointA, GbPoint3D *PointB) { - GbVector3D A(PointA->x1, PointA->x2, PointA->x3 ); - GbVector3D B(PointB->x1, PointB->x2, PointB->x3 ); - GbVector3D K(0.0,0.0,0.99); // the vector from PointA - third point - - GbVector3D PointBA = B-A; - GbVector3D PointBAK = PointBA.Cross(K); - PointBAK.Normalize(); - this->Normal = PointBAK; - this->d = this->Normal.Dot(A); + GbVector3D A(PointA->x1, PointA->x2, PointA->x3); + GbVector3D B(PointB->x1, PointB->x2, PointB->x3); + GbVector3D K(0.0, 0.0, 0.99); // the vector from PointA - third point + + GbVector3D PointBA = B - A; + GbVector3D PointBAK = PointBA.Cross(K); + PointBAK.Normalize(); + this->Normal = PointBAK; + this->d = this->Normal.Dot(A); } /*==========================================================*/ -GbHalfSpaceKrischan3D::GbHalfSpaceKrischan3D( const double& p1x, const double& p1y, const double& p1z - , const double& p2x, const double& p2y, const double& p2z - , const double& p3x, const double& p3y, const double& p3z ) +GbHalfSpaceKrischan3D::GbHalfSpaceKrischan3D(const double &p1x, const double &p1y, const double &p1z, const double &p2x, + const double &p2y, const double &p2z, const double &p3x, const double &p3y, + const double &p3z) { - GbVector3D A( p1x, p1y, p1z ); - GbVector3D BA(p2x-p1x, p2y-p1y, p2z-p1z ); - GbVector3D CA(p3x-p1x, p3y-p1y, p3z-p1z ); - GbVector3D BACA = BA.Cross(CA); - - BACA.Normalize(); - this->Normal = BACA; - this->d = this->Normal.Dot(A); + GbVector3D A(p1x, p1y, p1z); + GbVector3D BA(p2x - p1x, p2y - p1y, p2z - p1z); + GbVector3D CA(p3x - p1x, p3y - p1y, p3z - p1z); + GbVector3D BACA = BA.Cross(CA); + + BACA.Normalize(); + this->Normal = BACA; + this->d = this->Normal.Dot(A); } /*==========================================================*/ GbHalfSpaceKrischan3D::GbHalfSpaceKrischan3D(double nx, double ny, double nz, double dist) { - this->Normal = GbVector3D(nx,ny,nz); - this->Normal.Normalize(); - this->d = dist; + this->Normal = GbVector3D(nx, ny, nz); + this->Normal.Normalize(); + this->d = dist; } /*==========================================================*/ -double GbHalfSpaceKrischan3D::getCellVolumeInsideGbObject3D(const double& x1a,const double& x2a,const double& x3a,const double& x1b,const double& x2b,const double& x3b) +double GbHalfSpaceKrischan3D::getCellVolumeInsideGbObject3D(const double &x1a, const double &x2a, const double &x3a, + const double &x1b, const double &x2b, const double &x3b) { - double x1 = x1b-x1a; - double x2 = x2b-x2a; - double x3 = x3b-x3a; - - if( this->isCellInsideGbObject3D(x1a,x2a,x3a,x1b,x2b,x3b) ) return 1.0*x1*x2*x3; - if( !(this->isCellCuttingGbObject3D(x1a,x2a,x3a,x1b,x2b,x3b)) ) return 0.0; - - double alpha=0.0; - double internX1,internX2,internX3; - - for(int x1vers=0;x1vers<2;x1vers++){ - for(int x2vers=0;x2vers<2;x2vers++){ - for(int x3vers=0;x3vers<2;x3vers++){ - internX1 = x1a + (x1b-x1a)*x1vers; - internX2 = x2a + (x2b-x2a)*x2vers; - internX3 = x3a + (x3b-x3a)*x3vers; - - // if point is INSIDE the halfspace, distance is smaller than zero - // --> loop determines the minimum alpha...i.e. the alpha with maximum absolute value for all points INSIDE the halfspace - if( UbMath::lessEqual( this->getDistance(internX1,internX2,internX3) , alpha ) ) - alpha = this->getDistance(internX1,internX2,internX3); - //cout<<zelltyp<<" "<<kugel->getDistance(internX1,internX2,internX3)<<" "<<alpha<<endl; - }//end first for - }//end second for - }//end third for - - // PLIC needs alphas > 0.0 - alpha = (-1)*alpha; - - - - double n[3]; - n[0] = this->Normal[0]; - n[1] = this->Normal[1]; - n[2] = this->Normal[2]; - - //cout << "Koordinaten: "<<x1<<" "<<x2<<" "<<x3<<endl; - //cout << "Deltas: "<<deltaX1<<" "<<deltaX2<<" "<<deltaX3<<endl; - //cout << "Halbe Zelle: "<<halfcelldelta<<endl; - - //cout<<"Centroid: "<<kugel->getX1Centroid()<<" "<<kugel->getX2Centroid()<<" "<<kugel->getX3Centroid()<<endl; - - //cout<<"Normals: "<<n[0]<<" "<<n[1]<<" "<<n[2]<<endl; - - double normLength; - normLength = sqrt(n[0]*n[0] + n[1]*n[1] + n[2]*n[2]); - n[0] /= normLength; - n[1] /= normLength; - n[2] /= normLength; - - if( UbMath::less(n[0],0.0) ) n[0] = -n[0]; - if( UbMath::less(n[1],0.0) ) n[1] = -n[1]; - if( UbMath::less(n[2],0.0) ) n[2] = -n[2]; - - //cout<<"Normals: "<<n[0]<<" "<<n[1]<<" "<<n[2]<<endl; - - double dummy; - if( UbMath::greater(n[0],n[1])) {dummy=n[1]; n[1]=n[0]; n[0]=dummy;} - if( UbMath::greater(n[1],n[2])) {dummy=n[2]; n[2]=n[1]; n[1]=dummy;} - if( UbMath::greater(n[0],n[1])) {dummy=n[1]; n[1]=n[0]; n[0]=dummy;} - - //cout<<"Normals: "<<n[0]<<" "<<n[1]<<" "<<n[2]<<endl; - - double n1,n2,n3; - n1=n[0]; - n2=n[1]; - n3=n[2]; - - double preresult=0.0,result=0.0; - - // 1D Check - if ( UbMath::lessEqual(n1,0.00001)&&UbMath::lessEqual(n2,0.00001) ) - { - result = alpha * x1 * x2; - } - // 2D Check - else if ( UbMath::lessEqual(n1,0.00001) ) - { - preresult = (2*n2*n3); - result = (alpha*alpha)/preresult; - - if( UbMath::greater(alpha,n2*x2) ) - { - result += -(alpha-n2*x2)*(alpha-n2*x2)/preresult; - } - if( UbMath::greater(alpha,n3*x3) ) - { - result += -(alpha-n3*x3)*(alpha-n3*x3)/preresult; - } - if( UbMath::greater(alpha,n2*x2+n3*x3) ) - { - result += (alpha-n2*x2-n3*x3)*(alpha-n2*x2-n3*x3)/preresult; - } - - // tiefenrichtung mit einmultiplizieren... - result *= x1; - } - // 3D Check - else - { - preresult =6*n1*n2*n3; - - result = alpha*alpha*alpha/preresult; - - if ( UbMath::greater (alpha,n1*x1)) - { - result+=-((alpha-n1*x1)*(alpha-n1*x1)*(alpha-n1*x1))/preresult; - } - if (UbMath::greater(alpha,n2*x2)) - { - result+=-((alpha-n2*x2)*(alpha-n2*x2)*(alpha-n2*x2))/preresult; - } - if (UbMath::greater(alpha,n3*x3)) - { - result+=-((alpha-n3*x3)*(alpha-n3*x3)*(alpha-n3*x3))/preresult; - } - if (UbMath::greater(alpha,(n1*x1+n2*x2))) - { - result+=((alpha-(n1*x1+n2*x2))*(alpha-(n1*x1+n2*x2))*(alpha-(n1*x1+n2*x2)))/preresult; - } - if (UbMath::greater(alpha,(n1*x1+n3*x3))) - { - result+=((alpha-(n1*x1+n3*x3))*(alpha-(n1*x1+n3*x3))*(alpha-(n1*x1+n3*x3)))/preresult; - } - if (UbMath::greater(alpha,(n2*x2+n3*x3))) - { - result+=((alpha-(n2*x2+n3*x3))*(alpha-(n2*x2+n3*x3))*(alpha-(n2*x2+n3*x3)))/preresult; - } - - //NEW - if (UbMath::greater(alpha,(n1*x1+n2*x2+n3*x3))) - { - result+= -((alpha-(n1*x1+n2*x2+n3*x3))*(alpha-(n1*x1+n2*x2+n3*x3))*(alpha-(n1*x1+n2*x2+n3*x3)))/preresult; - } - - } - - if( !UbMath::inClosedInterval( result/ (x1*x2*x3), -0.01, 1.01) ) - { - stringstream errMsg; - - errMsg << "Danger...Fuellstand "<<result<<" nicht im Interfall [0.0..1.0]" << endl; - errMsg << "NormVec: " << n1 << " " << n2 << " " << n3 << endl; - errMsg << "Cell: " << x1 << " " << x2 << " " << x3 << endl; - errMsg << "Alpha: " << alpha << endl; - - - throw UbException( UB_EXARGS, errMsg.str() ); - } - - return result; - - - //double eps=0.0; - //if( UbMath::equal(n1,0.0) && UbMath::equal(n2,0.0) ) - //{ - // eps = alpha/n3; - //} - //else if( UbMath::equal(n1,0.0) ) - //{ - // double dim1,dim2; - // dim1 = alpha/n2; - // dim2 = alpha/n3; - - // eps = 0.5*dim1*dim2; - // if( UbMath::greater(dim1,1.0) ) eps -= 0.5*(dim1-1.0)*dim2/dim1*(dim1-1.0); - // if( UbMath::greater(dim2,1.0) ) eps -= 0.5*(dim2-1.0)*dim1/dim2*(dim2-1.0); - //} - //else - //{ - // eps = alpha*alpha*alpha; - // if( UbMath::greater(alpha,n1) ) - // eps -= (alpha-n1)*(alpha-n1)*(alpha-n1); - // if( UbMath::greater(alpha,n2) ) - // eps -= (alpha-n2)*(alpha-n2)*(alpha-n2); - // if( UbMath::greater(alpha,n3) ) - // eps -= (alpha-n3)*(alpha-n3)*(alpha-n3); - - // if( UbMath::greater(alpha,n1+n2) ) - // eps += (alpha-n1-n2)*(alpha-n1-n2)*(alpha-n1-n2); - // if( UbMath::greater(alpha,n1+n3) ) - // eps += (alpha-n1-n3)*(alpha-n1-n3)*(alpha-n1-n3); - // if( UbMath::greater(alpha,n2+n3) ) - // eps += (alpha-n2-n3)*(alpha-n2-n3)*(alpha-n2-n3); - - // //attention: use without delta_i - // eps = eps / (6*n[0]*n[1]*n[2]); - - // eps = eps / (deltaX1*deltaX2*deltaX3); - //} - - - //return(eps) ; - //cout << "alpha ist " << alpha << endl; - //cout << "fillLevel ist " << eps << endl; + double x1 = x1b - x1a; + double x2 = x2b - x2a; + double x3 = x3b - x3a; + + if (this->isCellInsideGbObject3D(x1a, x2a, x3a, x1b, x2b, x3b)) + return 1.0 * x1 * x2 * x3; + if (!(this->isCellCuttingGbObject3D(x1a, x2a, x3a, x1b, x2b, x3b))) + return 0.0; + + double alpha = 0.0; + double internX1, internX2, internX3; + + for (int x1vers = 0; x1vers < 2; x1vers++) { + for (int x2vers = 0; x2vers < 2; x2vers++) { + for (int x3vers = 0; x3vers < 2; x3vers++) { + internX1 = x1a + (x1b - x1a) * x1vers; + internX2 = x2a + (x2b - x2a) * x2vers; + internX3 = x3a + (x3b - x3a) * x3vers; + + // if point is INSIDE the halfspace, distance is smaller than zero + // --> loop determines the minimum alpha...i.e. the alpha with maximum absolute value for all points + // INSIDE the halfspace + if (UbMath::lessEqual(this->getDistance(internX1, internX2, internX3), alpha)) + alpha = this->getDistance(internX1, internX2, internX3); + // cout<<zelltyp<<" "<<kugel->getDistance(internX1,internX2,internX3)<<" "<<alpha<<endl; + } // end first for + } // end second for + } // end third for + + // PLIC needs alphas > 0.0 + alpha = (-1) * alpha; + + double n[3]; + n[0] = this->Normal[0]; + n[1] = this->Normal[1]; + n[2] = this->Normal[2]; + + // cout << "Koordinaten: "<<x1<<" "<<x2<<" "<<x3<<endl; + // cout << "Deltas: "<<deltaX1<<" "<<deltaX2<<" "<<deltaX3<<endl; + // cout << "Halbe Zelle: "<<halfcelldelta<<endl; + + // cout<<"Centroid: "<<kugel->getX1Centroid()<<" "<<kugel->getX2Centroid()<<" "<<kugel->getX3Centroid()<<endl; + + // cout<<"Normals: "<<n[0]<<" "<<n[1]<<" "<<n[2]<<endl; + + double normLength; + normLength = sqrt(n[0] * n[0] + n[1] * n[1] + n[2] * n[2]); + n[0] /= normLength; + n[1] /= normLength; + n[2] /= normLength; + + if (UbMath::less(n[0], 0.0)) + n[0] = -n[0]; + if (UbMath::less(n[1], 0.0)) + n[1] = -n[1]; + if (UbMath::less(n[2], 0.0)) + n[2] = -n[2]; + + // cout<<"Normals: "<<n[0]<<" "<<n[1]<<" "<<n[2]<<endl; + + double dummy; + if (UbMath::greater(n[0], n[1])) { + dummy = n[1]; + n[1] = n[0]; + n[0] = dummy; + } + if (UbMath::greater(n[1], n[2])) { + dummy = n[2]; + n[2] = n[1]; + n[1] = dummy; + } + if (UbMath::greater(n[0], n[1])) { + dummy = n[1]; + n[1] = n[0]; + n[0] = dummy; + } + + // cout<<"Normals: "<<n[0]<<" "<<n[1]<<" "<<n[2]<<endl; + + double n1, n2, n3; + n1 = n[0]; + n2 = n[1]; + n3 = n[2]; + + double preresult = 0.0, result = 0.0; + + // 1D Check + if (UbMath::lessEqual(n1, 0.00001) && UbMath::lessEqual(n2, 0.00001)) { + result = alpha * x1 * x2; + } + // 2D Check + else if (UbMath::lessEqual(n1, 0.00001)) { + preresult = (2 * n2 * n3); + result = (alpha * alpha) / preresult; + + if (UbMath::greater(alpha, n2 * x2)) { + result += -(alpha - n2 * x2) * (alpha - n2 * x2) / preresult; + } + if (UbMath::greater(alpha, n3 * x3)) { + result += -(alpha - n3 * x3) * (alpha - n3 * x3) / preresult; + } + if (UbMath::greater(alpha, n2 * x2 + n3 * x3)) { + result += (alpha - n2 * x2 - n3 * x3) * (alpha - n2 * x2 - n3 * x3) / preresult; + } + + // tiefenrichtung mit einmultiplizieren... + result *= x1; + } + // 3D Check + else { + preresult = 6 * n1 * n2 * n3; + + result = alpha * alpha * alpha / preresult; + + if (UbMath::greater(alpha, n1 * x1)) { + result += -((alpha - n1 * x1) * (alpha - n1 * x1) * (alpha - n1 * x1)) / preresult; + } + if (UbMath::greater(alpha, n2 * x2)) { + result += -((alpha - n2 * x2) * (alpha - n2 * x2) * (alpha - n2 * x2)) / preresult; + } + if (UbMath::greater(alpha, n3 * x3)) { + result += -((alpha - n3 * x3) * (alpha - n3 * x3) * (alpha - n3 * x3)) / preresult; + } + if (UbMath::greater(alpha, (n1 * x1 + n2 * x2))) { + result += ((alpha - (n1 * x1 + n2 * x2)) * (alpha - (n1 * x1 + n2 * x2)) * (alpha - (n1 * x1 + n2 * x2))) / + preresult; + } + if (UbMath::greater(alpha, (n1 * x1 + n3 * x3))) { + result += ((alpha - (n1 * x1 + n3 * x3)) * (alpha - (n1 * x1 + n3 * x3)) * (alpha - (n1 * x1 + n3 * x3))) / + preresult; + } + if (UbMath::greater(alpha, (n2 * x2 + n3 * x3))) { + result += ((alpha - (n2 * x2 + n3 * x3)) * (alpha - (n2 * x2 + n3 * x3)) * (alpha - (n2 * x2 + n3 * x3))) / + preresult; + } + + // NEW + if (UbMath::greater(alpha, (n1 * x1 + n2 * x2 + n3 * x3))) { + result += -((alpha - (n1 * x1 + n2 * x2 + n3 * x3)) * (alpha - (n1 * x1 + n2 * x2 + n3 * x3)) * + (alpha - (n1 * x1 + n2 * x2 + n3 * x3))) / + preresult; + } + } + + if (!UbMath::inClosedInterval(result / (x1 * x2 * x3), -0.01, 1.01)) { + stringstream errMsg; + + errMsg << "Danger...Fuellstand " << result << " nicht im Interfall [0.0..1.0]" << endl; + errMsg << "NormVec: " << n1 << " " << n2 << " " << n3 << endl; + errMsg << "Cell: " << x1 << " " << x2 << " " << x3 << endl; + errMsg << "Alpha: " << alpha << endl; + + throw UbException(UB_EXARGS, errMsg.str()); + } + + return result; + + // double eps=0.0; + // if( UbMath::equal(n1,0.0) && UbMath::equal(n2,0.0) ) + //{ + // eps = alpha/n3; + //} + // else if( UbMath::equal(n1,0.0) ) + //{ + // double dim1,dim2; + // dim1 = alpha/n2; + // dim2 = alpha/n3; + + // eps = 0.5*dim1*dim2; + // if( UbMath::greater(dim1,1.0) ) eps -= 0.5*(dim1-1.0)*dim2/dim1*(dim1-1.0); + // if( UbMath::greater(dim2,1.0) ) eps -= 0.5*(dim2-1.0)*dim1/dim2*(dim2-1.0); + //} + // else + //{ + // eps = alpha*alpha*alpha; + // if( UbMath::greater(alpha,n1) ) + // eps -= (alpha-n1)*(alpha-n1)*(alpha-n1); + // if( UbMath::greater(alpha,n2) ) + // eps -= (alpha-n2)*(alpha-n2)*(alpha-n2); + // if( UbMath::greater(alpha,n3) ) + // eps -= (alpha-n3)*(alpha-n3)*(alpha-n3); + + // if( UbMath::greater(alpha,n1+n2) ) + // eps += (alpha-n1-n2)*(alpha-n1-n2)*(alpha-n1-n2); + // if( UbMath::greater(alpha,n1+n3) ) + // eps += (alpha-n1-n3)*(alpha-n1-n3)*(alpha-n1-n3); + // if( UbMath::greater(alpha,n2+n3) ) + // eps += (alpha-n2-n3)*(alpha-n2-n3)*(alpha-n2-n3); + + // //attention: use without delta_i + // eps = eps / (6*n[0]*n[1]*n[2]); + + // eps = eps / (deltaX1*deltaX2*deltaX3); + //} + + // return(eps) ; + // cout << "alpha ist " << alpha << endl; + // cout << "fillLevel ist " << eps << endl; } /*==========================================================*/ diff --git a/src/basics/geometry3d/GbHalfSpaceKrischan3D.h b/src/basics/geometry3d/GbHalfSpaceKrischan3D.h index d3769a5f664ca060f2eeb51691fd81dd3bebc5ab..df01e6c7b30c5ebcc6a2bdbfd828e2523c4f927d 100644 --- a/src/basics/geometry3d/GbHalfSpaceKrischan3D.h +++ b/src/basics/geometry3d/GbHalfSpaceKrischan3D.h @@ -7,196 +7,194 @@ #ifndef GbHalfSpaceKrischan3D_H #define GbHalfSpaceKrischan3D_H -#include <sstream> #include <iostream> +#include <sstream> #include <basics/utilities/UbMath.h> +#include <geometry3d/GbLine3D.h> #include <geometry3d/GbPoint3D.h> #include <geometry3d/GbTriangle3D.h> #include <geometry3d/GbVector3D.h> -#include <geometry3d/GbLine3D.h> /*=========================================================================*/ /* GbHalfSpaceKrischan3D */ /* */ /** -* This Class helps in performing some operations on a halfspace defined by 2 or 3 points -*/ + * This Class helps in performing some operations on a halfspace defined by 2 or 3 points + */ -class GbHalfSpaceKrischan3D : public GbObject3D , public UbObserver +class GbHalfSpaceKrischan3D : public GbObject3D, public UbObserver { public: - GbHalfSpaceKrischan3D(GbTriangle3D* triangle); - - GbHalfSpaceKrischan3D(GbPoint3D* PointA, GbPoint3D* PointB, GbPoint3D* PointC); - - GbHalfSpaceKrischan3D(double nx, double ny, double nz, double dist); - - GbHalfSpaceKrischan3D(GbPoint3D* PointA, GbPoint3D* PointB); - - GbHalfSpaceKrischan3D( const double& p1x, const double& p1y, const double& p1z - , const double& p2x, const double& p2y, const double& p2z - , const double& p3x, const double& p3y, const double& p3z ); - - /*=======================================================*/ - ~GbHalfSpaceKrischan3D() override = default; - /*=======================================================*/ - std::string getTypeID() {return "GbHalfSpaceKrischan3D"; } - /*=============================================*/ - bool ptInside(const double& x, const double& y, const double& z) - { - return UbMath::lessEqual(Normal[0]*x+Normal[1]*y+Normal[2]*z, this->d); - } - /*=============================================*/ - bool ptInside(GbPoint3D* PointX) - { - GbVector3D X(PointX->x1, PointX->x2, PointX->x3 ); - return UbMath::lessEqual(this->Normal.Dot(X), this->d); - } - /*=============================================*/ - bool ptInside(GbVector3D &X) - { - return UbMath::lessEqual(this->Normal.Dot(X), this->d); - } - - /*=====================================================*/ - //true, wenn 'in Object' oder 'auf Boundary'! - bool isPointInGbObject3D(const double& x1p, const double& x2p, const double& x3p) override - { - return (ptInside(x1p,x2p,x3p)); - } - /*=====================================================*/ - //true, wenn 'in Object' oder 'auf Boundary'! - bool isPointInGbObject3D(const double& x1p, const double& x2p, const double& x3p, bool& /*pointIsOnBoundary*/) override - { - return (ptInside(x1p,x2p,x3p)); - } - - void finalize() override{} - - double getX1Centroid() override{ return 0.0; } - double getX1Minimum() override { return -99999.0; } - double getX1Maximum() override { return 99999.0; } - double getX2Centroid() override{ return 0.0; } - double getX2Minimum() override { return -99999.0; } - double getX2Maximum() override { return 99999.0; } - double getX3Centroid() override{ return 0.0; } - double getX3Minimum() override { return -99999.0; } - double getX3Maximum() override { return 99999.0; } - - - GbLine3D* createClippedLine3D (GbPoint3D &point1, GbPoint3D &point2) override - { - GbPoint3D *p1 = new GbPoint3D(point1); - GbPoint3D *p2 = new GbPoint3D(point2); - - GbVector3D p1p2( p2->x1-p1->x1, p2->x2-p1->x2, p2->x3-p1->x3); - - double dist1 = getDistance( p1->x1,p1->x2,p1->x3 ); - double dist2 = getDistance( p2->x1,p2->x2,p2->x3 ); - - double totalDist = std::abs(dist1) + std::abs(dist2); - - // Falls erster Punkt nicht drinliegt - if( !ptInside(p1) ) - { - if( !ptInside(p2) ) return NULL; - - // distance ausrechnen (groesser null) - if( UbMath::less( dist1, 0.0 ) ) throw UbException( UB_EXARGS, "Punkt ausserhalb, aber Distanz kleiner null???" ); - - p1->x1 = p1->x1 + dist1/totalDist*p1p2[0]; - p1->x2 = p1->x2 + dist1/totalDist*p1p2[1]; - p1->x3 = p1->x3 + dist1/totalDist*p1p2[2]; - } - // Falls zweiter Punkt nicht drinliegt - if( !ptInside(p2) ) - { - if( !ptInside(p1) ) return NULL; - - // distance ausrechnen (groesser null) - if( UbMath::less( dist2, 0.0 ) ) throw UbException( UB_EXARGS, "Punkt ausserhalb, aber Distanz kleiner null???" ); - - p2->x1 = p2->x1 - dist2/totalDist*p1p2[0]; - p2->x2 = p2->x2 - dist2/totalDist*p1p2[1]; - p2->x3 = p2->x3 - dist2/totalDist*p1p2[2]; - } - - return new GbLine3D(p1,p2); - } - - - double getCellVolumeInsideGbObject3D(const double& x1a,const double& x2a,const double& x3a,const double& x1b,const double& x2b,const double& x3b) override; - - double getDistance(const double& x1p, const double& x2p, const double& x3p) - { - return (Normal[0]*x1p + Normal[1]*x2p + Normal[2]*x3p) - this->d; - } - - void getNormal( double& n1, double& n2, double& n3 ) - { - n1 = this->Normal[0]; - n2 = this->Normal[1]; - n3 = this->Normal[2]; - } - - void addSurfaceTriangleSet(std::vector<UbTupleFloat3>& /*nodes*/, std::vector<UbTupleInt3>& /*triangles*/) override - { - std::cout << " addSurfaceTriangleSet(): TO BE DONE AND CHECKED ... " << std::endl; - } - - std::vector<GbTriangle3D*> getSurfaceTriangleSet() override - { - std::vector<GbTriangle3D*> triangles; - GbPoint3D p1( 0.0,0.0,0.0 ); - GbPoint3D p2( 1.0,0.0,0.0 ); - GbPoint3D p3( 0.0,1.0,0.0 ); - - triangles.push_back(new GbTriangle3D(new GbPoint3D(p1),new GbPoint3D(p2),new GbPoint3D(p3))); - - return triangles; - } - - void objectChanged(UbObservable* /*changedObject*/) override - { - return; - - //GbLine3D* line = dynamic_cast<GbLine3D*>(changedObject); - //if(!line || this->mLine!=line) return; - //this->notifyObserversObjectChanged(); - } - /*==========================================================*/ - void objectWillBeDeleted(UbObservable* /*objectForDeletion*/) override - { - return; - //if(this->mLine) - //{ - // UbObservable* observedObj = dynamic_cast<UbObservable*>(this->mLine); - // if(objectForDeletion == observedObj) { this->mLine = NULL; } - //} - } - - ObObject* clone() override{ return NULL; }; - - std::string toString() override - { - std::stringstream temp; - - temp << "GbHalfSpaceKrischan3D: "; - temp << " Distance " << this->d; - temp << " Norm vec " << this->Normal[0]; - temp << " " << this->Normal[1]; - temp << " " << this->Normal[2]; - - - return temp.str(); - }; + GbHalfSpaceKrischan3D(GbTriangle3D *triangle); + + GbHalfSpaceKrischan3D(GbPoint3D *PointA, GbPoint3D *PointB, GbPoint3D *PointC); + + GbHalfSpaceKrischan3D(double nx, double ny, double nz, double dist); + + GbHalfSpaceKrischan3D(GbPoint3D *PointA, GbPoint3D *PointB); + + GbHalfSpaceKrischan3D(const double &p1x, const double &p1y, const double &p1z, const double &p2x, const double &p2y, + const double &p2z, const double &p3x, const double &p3y, const double &p3z); + + /*=======================================================*/ + ~GbHalfSpaceKrischan3D() override = default; + /*=======================================================*/ + std::string getTypeID() { return "GbHalfSpaceKrischan3D"; } + /*=============================================*/ + bool ptInside(const double &x, const double &y, const double &z) + { + return UbMath::lessEqual(Normal[0] * x + Normal[1] * y + Normal[2] * z, this->d); + } + /*=============================================*/ + bool ptInside(GbPoint3D *PointX) + { + GbVector3D X(PointX->x1, PointX->x2, PointX->x3); + return UbMath::lessEqual(this->Normal.Dot(X), this->d); + } + /*=============================================*/ + bool ptInside(GbVector3D &X) { return UbMath::lessEqual(this->Normal.Dot(X), this->d); } + + /*=====================================================*/ + // true, wenn 'in Object' oder 'auf Boundary'! + bool isPointInGbObject3D(const double &x1p, const double &x2p, const double &x3p) override + { + return (ptInside(x1p, x2p, x3p)); + } + /*=====================================================*/ + // true, wenn 'in Object' oder 'auf Boundary'! + bool isPointInGbObject3D(const double &x1p, const double &x2p, const double &x3p, + bool & /*pointIsOnBoundary*/) override + { + return (ptInside(x1p, x2p, x3p)); + } + + void finalize() override {} + + double getX1Centroid() override { return 0.0; } + double getX1Minimum() override { return -99999.0; } + double getX1Maximum() override { return 99999.0; } + double getX2Centroid() override { return 0.0; } + double getX2Minimum() override { return -99999.0; } + double getX2Maximum() override { return 99999.0; } + double getX3Centroid() override { return 0.0; } + double getX3Minimum() override { return -99999.0; } + double getX3Maximum() override { return 99999.0; } + + GbLine3D *createClippedLine3D(GbPoint3D &point1, GbPoint3D &point2) override + { + GbPoint3D *p1 = new GbPoint3D(point1); + GbPoint3D *p2 = new GbPoint3D(point2); + + GbVector3D p1p2(p2->x1 - p1->x1, p2->x2 - p1->x2, p2->x3 - p1->x3); + + double dist1 = getDistance(p1->x1, p1->x2, p1->x3); + double dist2 = getDistance(p2->x1, p2->x2, p2->x3); + + double totalDist = std::abs(dist1) + std::abs(dist2); + + // Falls erster Punkt nicht drinliegt + if (!ptInside(p1)) { + if (!ptInside(p2)) + return NULL; + + // distance ausrechnen (groesser null) + if (UbMath::less(dist1, 0.0)) + throw UbException(UB_EXARGS, "Punkt ausserhalb, aber Distanz kleiner null???"); + + p1->x1 = p1->x1 + dist1 / totalDist * p1p2[0]; + p1->x2 = p1->x2 + dist1 / totalDist * p1p2[1]; + p1->x3 = p1->x3 + dist1 / totalDist * p1p2[2]; + } + // Falls zweiter Punkt nicht drinliegt + if (!ptInside(p2)) { + if (!ptInside(p1)) + return NULL; + + // distance ausrechnen (groesser null) + if (UbMath::less(dist2, 0.0)) + throw UbException(UB_EXARGS, "Punkt ausserhalb, aber Distanz kleiner null???"); + + p2->x1 = p2->x1 - dist2 / totalDist * p1p2[0]; + p2->x2 = p2->x2 - dist2 / totalDist * p1p2[1]; + p2->x3 = p2->x3 - dist2 / totalDist * p1p2[2]; + } + + return new GbLine3D(p1, p2); + } + + double getCellVolumeInsideGbObject3D(const double &x1a, const double &x2a, const double &x3a, const double &x1b, + const double &x2b, const double &x3b) override; + + double getDistance(const double &x1p, const double &x2p, const double &x3p) + { + return (Normal[0] * x1p + Normal[1] * x2p + Normal[2] * x3p) - this->d; + } + + void getNormal(double &n1, double &n2, double &n3) + { + n1 = this->Normal[0]; + n2 = this->Normal[1]; + n3 = this->Normal[2]; + } + + void addSurfaceTriangleSet(std::vector<UbTupleFloat3> & /*nodes*/, + std::vector<UbTupleInt3> & /*triangles*/) override + { + std::cout << " addSurfaceTriangleSet(): TO BE DONE AND CHECKED ... " << std::endl; + } + + std::vector<GbTriangle3D *> getSurfaceTriangleSet() override + { + std::vector<GbTriangle3D *> triangles; + GbPoint3D p1(0.0, 0.0, 0.0); + GbPoint3D p2(1.0, 0.0, 0.0); + GbPoint3D p3(0.0, 1.0, 0.0); + + triangles.push_back(new GbTriangle3D(new GbPoint3D(p1), new GbPoint3D(p2), new GbPoint3D(p3))); + + return triangles; + } + + void objectChanged(UbObservable * /*changedObject*/) override + { + return; + + // GbLine3D* line = dynamic_cast<GbLine3D*>(changedObject); + // if(!line || this->mLine!=line) return; + // this->notifyObserversObjectChanged(); + } + /*==========================================================*/ + void objectWillBeDeleted(UbObservable * /*objectForDeletion*/) override + { + return; + // if(this->mLine) + //{ + // UbObservable* observedObj = dynamic_cast<UbObservable*>(this->mLine); + // if(objectForDeletion == observedObj) { this->mLine = NULL; } + //} + } + + ObObject *clone() override { return NULL; }; + + std::string toString() override + { + std::stringstream temp; + + temp << "GbHalfSpaceKrischan3D: "; + temp << " Distance " << this->d; + temp << " Norm vec " << this->Normal[0]; + temp << " " << this->Normal[1]; + temp << " " << this->Normal[2]; + + return temp.str(); + }; private: - GbVector3D Normal; - double d; + GbVector3D Normal; + double d; }; /*=========================================================================*/ -#endif //GbHalfSpaceKrischan3D_H +#endif // GbHalfSpaceKrischan3D_H diff --git a/src/basics/geometry3d/GbLine3D.cpp b/src/basics/geometry3d/GbLine3D.cpp index 752e3a421c982fd7606f5b4ed6f73218f0ca7014..d883de49a91612d5a6b2fbc0903f3fca4cfeea6d 100644 --- a/src/basics/geometry3d/GbLine3D.cpp +++ b/src/basics/geometry3d/GbLine3D.cpp @@ -1,28 +1,28 @@ //======================================================================================= -// ____ ____ __ ______ __________ __ __ __ __ -// \ \ | | | | | _ \ |___ ___| | | | | / \ | | -// \ \ | | | | | |_) | | | | | | | / \ | | -// \ \ | | | | | _ / | | | | | | / /\ \ | | -// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ -// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| -// \ \ | | ________________________________________________________________ -// \ \ | | | ______________________________________________________________| -// \ \| | | | __ __ __ __ ______ _______ -// \ | | |_____ | | | | | | | | | _ \ / _____) -// \ | | _____| | | | | | | | | | | \ \ \_______ +// ____ ____ __ ______ __________ __ __ __ __ +// \ \ | | | | | _ \ |___ ___| | | | | / \ | | +// \ \ | | | | | |_) | | | | | | | / \ | | +// \ \ | | | | | _ / | | | | | | / /\ \ | | +// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ +// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| +// \ \ | | ________________________________________________________________ +// \ \ | | | ______________________________________________________________| +// \ \| | | | __ __ __ __ ______ _______ +// \ | | |_____ | | | | | | | | | _ \ / _____) +// \ | | _____| | | | | | | | | | | \ \ \_______ // \ | | | | |_____ | \_/ | | | | |_/ / _____ | -// \ _____| |__| |________| \_______/ |__| |______/ (_______/ +// \ _____| |__| |________| \_______/ |__| |______/ (_______/ // -// This file is part of VirtualFluids. VirtualFluids is free software: you can +// This file is part of VirtualFluids. VirtualFluids is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of +// License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. -// -// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// +// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License along // with VirtualFluids (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>. // @@ -30,9 +30,9 @@ //! \ingroup geometry3d //! \author Soeren Freudiger, Sebastian Geller //======================================================================================= +#include <GbCuboid3D.h> #include <GbLine3D.h> #include <GbSystem3D.h> -#include <GbCuboid3D.h> #include <GbTriangle3D.h> using namespace std; @@ -40,207 +40,232 @@ using namespace std; /*=======================================================*/ GbLine3D::GbLine3D() { - p1 = NULL; - p2 = NULL; - length = 0.0; + p1 = NULL; + p2 = NULL; + length = 0.0; } /*=======================================================*/ -GbLine3D::GbLine3D(GbPoint3D* point1, GbPoint3D* point2) +GbLine3D::GbLine3D(GbPoint3D *point1, GbPoint3D *point2) { - this->p1 = point1; - this->p2 = point2; - this->p1->addObserver(this); - this->p2->addObserver(this); - this->calculateValues(); + this->p1 = point1; + this->p2 = point2; + this->p1->addObserver(this); + this->p2->addObserver(this); + this->calculateValues(); } /*=======================================================*/ -GbLine3D::GbLine3D(GbLine3D* line) +GbLine3D::GbLine3D(GbLine3D *line) { - this->p1 = line->p1->clone(); - this->p2 = line->p2->clone(); - this->p1->addObserver(this); - this->p2->addObserver(this); - this->calculateValues(); + this->p1 = line->p1->clone(); + this->p2 = line->p2->clone(); + this->p1->addObserver(this); + this->p2->addObserver(this); + this->calculateValues(); } /*=======================================================*/ -GbLine3D::~GbLine3D() +GbLine3D::~GbLine3D() { - if(this->p1) this->p1->removeObserver(this); - if(this->p2) this->p2->removeObserver(this); + if (this->p1) + this->p1->removeObserver(this); + if (this->p2) + this->p2->removeObserver(this); } /*=======================================================*/ -void GbLine3D::finalize() -{ - if(this->p1) - { - this->p1->removeObserver(this); - this->p1->finalize(); - delete this->p1; - this->p1 = NULL; - } - if(this->p2) - { - this->p2->removeObserver(this); - this->p2->finalize(); - delete this->p2; - this->p2 = NULL; - } +void GbLine3D::finalize() +{ + if (this->p1) { + this->p1->removeObserver(this); + this->p1->finalize(); + delete this->p1; + this->p1 = NULL; + } + if (this->p2) { + this->p2->removeObserver(this); + this->p2->finalize(); + delete this->p2; + this->p2 = NULL; + } } /*=======================================================*/ -vector<GbTriangle3D*> GbLine3D::getSurfaceTriangleSet() +vector<GbTriangle3D *> GbLine3D::getSurfaceTriangleSet() { - vector<GbTriangle3D*> triangles; - GbPoint3D p1(getX1Minimum(),getX2Minimum(),getX3Minimum()); - GbPoint3D p2(getX1Centroid(),getX2Centroid(),getX3Centroid()); - GbPoint3D p3(getX1Maximum(),getX2Maximum(),getX3Maximum()); - - triangles.push_back(new GbTriangle3D(new GbPoint3D(p1),new GbPoint3D(p2),new GbPoint3D(p3))); - - return triangles; + vector<GbTriangle3D *> triangles; + GbPoint3D p1(getX1Minimum(), getX2Minimum(), getX3Minimum()); + GbPoint3D p2(getX1Centroid(), getX2Centroid(), getX3Centroid()); + GbPoint3D p3(getX1Maximum(), getX2Maximum(), getX3Maximum()); + + triangles.push_back(new GbTriangle3D(new GbPoint3D(p1), new GbPoint3D(p2), new GbPoint3D(p3))); + + return triangles; } /*=======================================================*/ -void GbLine3D::setPoint1(GbPoint3D* point1) -{ - if(this->p1) this->p1->removeObserver(this); - this->p1 = point1; - this->p1->addObserver(this); +void GbLine3D::setPoint1(GbPoint3D *point1) +{ + if (this->p1) + this->p1->removeObserver(this); + this->p1 = point1; + this->p1->addObserver(this); - if(this->p1 && this->p2) this->calculateValues(); + if (this->p1 && this->p2) + this->calculateValues(); } /*=======================================================*/ -void GbLine3D::setPoint2(GbPoint3D* point2) -{ - if(this->p2) this->p2->removeObserver(this); - this->p2 = point2; - this->p2->addObserver(this); +void GbLine3D::setPoint2(GbPoint3D *point2) +{ + if (this->p2) + this->p2->removeObserver(this); + this->p2 = point2; + this->p2->addObserver(this); - if(this->p1 && this->p2) this->calculateValues(); + if (this->p1 && this->p2) + this->calculateValues(); } /*=======================================================*/ -void GbLine3D::setPoints(GbPoint3D* point1, GbPoint3D* point2) -{ - if(this->p1) this->p1->removeObserver(this); - if(this->p2) this->p2->removeObserver(this); +void GbLine3D::setPoints(GbPoint3D *point1, GbPoint3D *point2) +{ + if (this->p1) + this->p1->removeObserver(this); + if (this->p2) + this->p2->removeObserver(this); - this->p1 = point1; - this->p2 = point2; + this->p1 = point1; + this->p2 = point2; - this->p1->addObserver(this); - this->p2->addObserver(this); + this->p1->addObserver(this); + this->p2->addObserver(this); - this->calculateValues(); + this->calculateValues(); } /*=======================================================*/ string GbLine3D::toString() { - stringstream ss; - ss<<"GbLine3D[p1="; - ss<<this->p1->toString()<<",p2="<<this->p2->toString()<<",l="<<this->getLength()<<"]"; - return(ss.str()); + stringstream ss; + ss << "GbLine3D[p1="; + ss << this->p1->toString() << ",p2=" << this->p2->toString() << ",l=" << this->getLength() << "]"; + return (ss.str()); } /*=======================================================*/ -GbPoint3D* GbLine3D::calculateIntersectionPoint3D(GbLine3D* /*line*/) +GbPoint3D *GbLine3D::calculateIntersectionPoint3D(GbLine3D * /*line*/) { - throw UbException(UB_EXARGS," not implemented"); - //return(GbSystem::calculateIntersectionPoint3D(*this->p1, *this->p2, *line->p1, *line->p2)); + throw UbException(UB_EXARGS, " not implemented"); + // return(GbSystem::calculateIntersectionPoint3D(*this->p1, *this->p2, *line->p1, *line->p2)); } /*======================================================================*/ -GbLine3D* GbLine3D::createClippedLine3D(GbCuboid3D* cuboid) +GbLine3D *GbLine3D::createClippedLine3D(GbCuboid3D *cuboid) { - return GbSystem3D::createClipLine3D(*this->p1, *this->p2, cuboid->getPoint1()->x1, cuboid->getPoint1()->x2, cuboid->getPoint1()->x3, cuboid->getPoint2()->x1, cuboid->getPoint2()->x2, cuboid->getPoint2()->x3); -} -/*======================================================================*/ -GbLine3D* GbLine3D::createClippedLine3D(GbPoint3D* pA, GbPoint3D* pE) -{ - return GbSystem3D::createClipLine3D(*this->p1, *this->p2, pA->x1, pA->x2, pA->x3, pE->x1, pE->x2, pE->x3); + return GbSystem3D::createClipLine3D(*this->p1, *this->p2, cuboid->getPoint1()->x1, cuboid->getPoint1()->x2, + cuboid->getPoint1()->x3, cuboid->getPoint2()->x1, cuboid->getPoint2()->x2, + cuboid->getPoint2()->x3); } /*======================================================================*/ -double GbLine3D::getDistance(const GbPoint3D& point) +GbLine3D *GbLine3D::createClippedLine3D(GbPoint3D *pA, GbPoint3D *pE) { - return this->getDistance(point.x1,point.x2,point.x3); + return GbSystem3D::createClipLine3D(*this->p1, *this->p2, pA->x1, pA->x2, pA->x3, pE->x1, pE->x2, pE->x3); } /*======================================================================*/ -double GbLine3D::getDistance(const double& x1,const double& x2,const double& x3) +double GbLine3D::getDistance(const GbPoint3D &point) { return this->getDistance(point.x1, point.x2, point.x3); } +/*======================================================================*/ +double GbLine3D::getDistance(const double &x1, const double &x2, const double &x3) { - double dx1 = this->p2->x1 - this->p1->x1; - double dx2 = this->p2->x2 - this->p1->x2; - double dx3 = this->p2->x3 - this->p1->x3; + double dx1 = this->p2->x1 - this->p1->x1; + double dx2 = this->p2->x2 - this->p1->x2; + double dx3 = this->p2->x3 - this->p1->x3; - //double vec[3]; - double a0 = x1 - p1->x1; - double a1 = x2 - p1->x2; - double a2 = x3 - p1->x3; + // double vec[3]; + double a0 = x1 - p1->x1; + double a1 = x2 - p1->x2; + double a2 = x3 - p1->x3; - double kreuzProd0 = a1 * dx3 - a2 * dx2; - double kreuzProd1 = a2 * dx1 - a0 * dx3; - double kreuzProd2 = a0 * dx2 - a1 * dx1; + double kreuzProd0 = a1 * dx3 - a2 * dx2; + double kreuzProd1 = a2 * dx1 - a0 * dx3; + double kreuzProd2 = a0 * dx2 - a1 * dx1; - return (std::sqrt(kreuzProd0*kreuzProd0+kreuzProd1*kreuzProd1+kreuzProd2*kreuzProd2))/length; + return (std::sqrt(kreuzProd0 * kreuzProd0 + kreuzProd1 * kreuzProd1 + kreuzProd2 * kreuzProd2)) / length; } /*=======================================================*/ void GbLine3D::calculateValues() { - double dx1 = this->p2->x1 - this->p1->x1; - double dx2 = this->p2->x2 - this->p1->x2; - double dx3 = this->p2->x3 - this->p1->x3; - this->length = std::sqrt(dx1*dx1+dx2*dx2+dx3*dx3); + double dx1 = this->p2->x1 - this->p1->x1; + double dx2 = this->p2->x2 - this->p1->x2; + double dx3 = this->p2->x3 - this->p1->x3; + this->length = std::sqrt(dx1 * dx1 + dx2 * dx2 + dx3 * dx3); } /*==========================================================*/ -void GbLine3D::objectChanged(UbObservable* changedObject) +void GbLine3D::objectChanged(UbObservable *changedObject) { - GbPoint3D* point = dynamic_cast<GbPoint3D*>(changedObject); - if(!point || (this->p1!=point && this->p2!=point)) return; + GbPoint3D *point = dynamic_cast<GbPoint3D *>(changedObject); + if (!point || (this->p1 != point && this->p2 != point)) + return; - this->calculateValues(); + this->calculateValues(); } /*==========================================================*/ -void GbLine3D::objectWillBeDeleted(UbObservable* objectForDeletion) -{ - if(this->p1) - { - UbObservable* observedObj = dynamic_cast<UbObservable*>(this->p1); - if(objectForDeletion == observedObj) { this->p1 = NULL; length = 0.0; } - } - if(this->p2) - { - UbObservable* observedObj = dynamic_cast<UbObservable*>(this->p2); - if(objectForDeletion == observedObj) { this->p2 = NULL; length = 0.0; } - } - //ACHTUNG: eigentlich muessten in allen methoden von GbLine if abfragen fuer NULL pointer hin... toDo +void GbLine3D::objectWillBeDeleted(UbObservable *objectForDeletion) +{ + if (this->p1) { + UbObservable *observedObj = dynamic_cast<UbObservable *>(this->p1); + if (objectForDeletion == observedObj) { + this->p1 = NULL; + length = 0.0; + } + } + if (this->p2) { + UbObservable *observedObj = dynamic_cast<UbObservable *>(this->p2); + if (objectForDeletion == observedObj) { + this->p2 = NULL; + length = 0.0; + } + } + // ACHTUNG: eigentlich muessten in allen methoden von GbLine if abfragen fuer NULL pointer hin... toDo } /*==========================================================*/ -void GbLine3D::scale(const double& sx1, const double& sx2, const double& sx3) -{ - double p1X1 = this->p1->getX1Coordinate(); - double p1X2 = this->p1->getX2Coordinate(); - double p1X3 = this->p1->getX3Coordinate(); - - double p2X1 = this->p2->getX1Coordinate(); - double p2X2 = this->p2->getX2Coordinate(); - double p2X3 = this->p2->getX3Coordinate(); - - double lenX1 = fabs( p1X1 - p2X1 ); - double lenX2 = fabs( p1X2 - p2X2 ); - double lenX3 = fabs( p1X3 - p2X3 ); - - double deltaX1 = lenX1*sx1 - lenX1; - double deltaX2 = lenX2*sx2 - lenX2; - double deltaX3 = lenX3*sx3 - lenX3; - - if(p1X1<p2X1) { p1X1 -= 0.5*deltaX1; p2X1 += 0.5*deltaX1; } - else { p1X1 += 0.5*deltaX1; p2X1 -= 0.5*deltaX1; } - if(p1X2<p2X2) { p1X2 -= 0.5*deltaX2; p2X2 += 0.5*deltaX2; } - else { p1X2 += 0.5*deltaX2; p2X2 -= 0.5*deltaX2; } - if(p1X3<p2X3) { p1X3 -= 0.5*deltaX3; p2X3 += 0.5*deltaX3; } - else { p1X3 += 0.5*deltaX3; p2X3 -= 0.5*deltaX3; } - - this->p1->setCoordinates(p1X1,p1X2,p1X3); - this->p2->setCoordinates(p2X1,p2X2,p2X3); +void GbLine3D::scale(const double &sx1, const double &sx2, const double &sx3) +{ + double p1X1 = this->p1->getX1Coordinate(); + double p1X2 = this->p1->getX2Coordinate(); + double p1X3 = this->p1->getX3Coordinate(); + + double p2X1 = this->p2->getX1Coordinate(); + double p2X2 = this->p2->getX2Coordinate(); + double p2X3 = this->p2->getX3Coordinate(); + + double lenX1 = fabs(p1X1 - p2X1); + double lenX2 = fabs(p1X2 - p2X2); + double lenX3 = fabs(p1X3 - p2X3); + + double deltaX1 = lenX1 * sx1 - lenX1; + double deltaX2 = lenX2 * sx2 - lenX2; + double deltaX3 = lenX3 * sx3 - lenX3; + + if (p1X1 < p2X1) { + p1X1 -= 0.5 * deltaX1; + p2X1 += 0.5 * deltaX1; + } else { + p1X1 += 0.5 * deltaX1; + p2X1 -= 0.5 * deltaX1; + } + if (p1X2 < p2X2) { + p1X2 -= 0.5 * deltaX2; + p2X2 += 0.5 * deltaX2; + } else { + p1X2 += 0.5 * deltaX2; + p2X2 -= 0.5 * deltaX2; + } + if (p1X3 < p2X3) { + p1X3 -= 0.5 * deltaX3; + p2X3 += 0.5 * deltaX3; + } else { + p1X3 += 0.5 * deltaX3; + p2X3 -= 0.5 * deltaX3; + } + + this->p1->setCoordinates(p1X1, p1X2, p1X3); + this->p2->setCoordinates(p2X1, p2X2, p2X3); } /*=======================================================*/ -void GbLine3D::translate(const double& tx1, const double& tx2, const double& tx3) -{ - this->p1->translate(tx1, tx2, tx3); - this->p2->translate(tx1, tx2, tx3); - //this->notifyObserversObjectChanged(); +void GbLine3D::translate(const double &tx1, const double &tx2, const double &tx3) +{ + this->p1->translate(tx1, tx2, tx3); + this->p2->translate(tx1, tx2, tx3); + // this->notifyObserversObjectChanged(); } diff --git a/src/basics/geometry3d/GbLine3D.h b/src/basics/geometry3d/GbLine3D.h index 25697f59b3cb04d61c3f5bcdbc16218315b9ef9b..29e0a3740cbe85fdae760e0234dbefa53617de1f 100644 --- a/src/basics/geometry3d/GbLine3D.h +++ b/src/basics/geometry3d/GbLine3D.h @@ -1,28 +1,28 @@ //======================================================================================= -// ____ ____ __ ______ __________ __ __ __ __ -// \ \ | | | | | _ \ |___ ___| | | | | / \ | | -// \ \ | | | | | |_) | | | | | | | / \ | | -// \ \ | | | | | _ / | | | | | | / /\ \ | | -// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ -// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| -// \ \ | | ________________________________________________________________ -// \ \ | | | ______________________________________________________________| -// \ \| | | | __ __ __ __ ______ _______ -// \ | | |_____ | | | | | | | | | _ \ / _____) -// \ | | _____| | | | | | | | | | | \ \ \_______ +// ____ ____ __ ______ __________ __ __ __ __ +// \ \ | | | | | _ \ |___ ___| | | | | / \ | | +// \ \ | | | | | |_) | | | | | | | / \ | | +// \ \ | | | | | _ / | | | | | | / /\ \ | | +// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ +// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| +// \ \ | | ________________________________________________________________ +// \ \ | | | ______________________________________________________________| +// \ \| | | | __ __ __ __ ______ _______ +// \ | | |_____ | | | | | | | | | _ \ / _____) +// \ | | _____| | | | | | | | | | | \ \ \_______ // \ | | | | |_____ | \_/ | | | | |_/ / _____ | -// \ _____| |__| |________| \_______/ |__| |______/ (_______/ +// \ _____| |__| |________| \_______/ |__| |______/ (_______/ // -// This file is part of VirtualFluids. VirtualFluids is free software: you can +// This file is part of VirtualFluids. VirtualFluids is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of +// License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. -// -// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// +// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License along // with VirtualFluids (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>. // @@ -33,9 +33,9 @@ #ifndef GBLINE3D_H #define GBLINE3D_H -#include <sstream> #include <cmath> - +#include <sstream> + #include <basics/utilities/UbObserver.h> #include <GbObject3D.h> @@ -46,90 +46,114 @@ class GbCuboid3D; #include <PointerDefinitions.h> ////////////////////////////////////////////////////////////////////////// -//! +//! //! \class GbLine3D -//! +//! //! \brief This Class provides basic 3D line objects. //! \details The describing points are observed by 3D line objects. //! ////////////////////////////////////////////////////////////////////////// -class GbLine3D : public GbObject3D , public UbObserver +class GbLine3D : public GbObject3D, public UbObserver { public: - GbLine3D(); - GbLine3D(GbPoint3D* point1, GbPoint3D* point2); - GbLine3D(GbLine3D* line); - ~GbLine3D() override; - - GbLine3D* clone() override { return new GbLine3D(this); } - void finalize() override; - - void setPoint1(GbPoint3D* point1); - void setPoint2(GbPoint3D* point2); - void setPoints(GbPoint3D* point1, GbPoint3D* point2); - - void deletePoint1() { if(this->p1) {this->p1->removeObserver(this); delete this->p1; this->p1=NULL;} } - void deletePoint2() { if(this->p2) {this->p2->removeObserver(this); delete this->p2; this->p2=NULL;} } - void deletePoints() { this->deletePoint1(); this->deletePoint2(); } - - GbPoint3D* getPoint1() { return this->p1; } - GbPoint3D* getPoint2() { return this->p2; } - - double getLength() { return(this->length); } - - double getX1Centroid() override { return((this->p1->x1+this->p2->x1)*0.5);} - double getX2Centroid() override { return((this->p1->x2+this->p2->x2)*0.5); }; - double getX3Centroid() override { return((this->p1->x3+this->p2->x3)*0.5); } - - double getX1Minimum() override { return(this->p1->x1 < this->p2->x1 ? this->p1->x1 : this->p2->x1); } - double getX2Minimum() override { return(this->p1->x2 < this->p2->x2 ? this->p1->x2 : this->p2->x2); } - double getX3Minimum() override { return(this->p1->x3 < this->p2->x3 ? this->p1->x3 : this->p2->x3); } - - double getX1Maximum() override { return(this->p1->x1 > this->p2->x1 ? this->p1->x1 : this->p2->x1); } - double getX2Maximum() override { return(this->p1->x2 > this->p2->x2 ? this->p1->x2 : this->p2->x2); } - double getX3Maximum() override { return(this->p1->x3 > this->p2->x3 ? this->p1->x3 : this->p2->x3); } - - void scale(const double& sx1, const double& sx2, const double& sx3) override; - void translate(const double& tx1, const double& tx2, const double& tx3) override; - - GbPoint3D* calculateIntersectionPoint3D(GbLine3D* line); - GbLine3D* createClippedLine3D(GbCuboid3D* cuboid); - GbLine3D* createClippedLine3D(GbPoint3D* pA, GbPoint3D* pE); - - double getDistance(const GbPoint3D& point); - double getDistance(const double& x1,const double& x2,const double& x3); - - std::vector<GbTriangle3D*> getSurfaceTriangleSet() override; - bool isPointInGbObject3D(const double& /*x1*/, const double& /*x2*/, const double& /*x3*/) override - { - throw UbException(UB_EXARGS,"not implemented"); - } - bool isPointInGbObject3D(const double& /*x1*/, const double& /*x2*/, const double& /*x3*/, bool& /*pointIsOnBoundary*/) override - { - throw UbException(UB_EXARGS,"not implemented"); - } - bool isCellInsideGbObject3D(const double& /*x11*/,const double& /*x21*/,const double& /*x31*/,const double& /*x12*/,const double& /*x22*/,const double& /*x32*/) override { return false; } - - GbLine3D* createClippedLine3D (GbPoint3D& /*point1*/, GbPoint3D& /*point2*/) override - { - throw UbException(UB_EXARGS,"not implemented"); - } - - //virtuelle Methoden von UbObserver - void objectChanged(UbObservable* changedObject) override; - void objectWillBeDeleted(UbObservable* objectForDeletion) override; - - std::string toString() override; - - using GbObject3D::isPointInGbObject3D; //Grund: dadurch muss man hier isPointInGbObject3D(GbPoint3D*) nicht ausprogrammieren, welche sonst hier "ueberdeckt" waere + GbLine3D(); + GbLine3D(GbPoint3D *point1, GbPoint3D *point2); + GbLine3D(GbLine3D *line); + ~GbLine3D() override; + + GbLine3D *clone() override { return new GbLine3D(this); } + void finalize() override; + + void setPoint1(GbPoint3D *point1); + void setPoint2(GbPoint3D *point2); + void setPoints(GbPoint3D *point1, GbPoint3D *point2); + + void deletePoint1() + { + if (this->p1) { + this->p1->removeObserver(this); + delete this->p1; + this->p1 = NULL; + } + } + void deletePoint2() + { + if (this->p2) { + this->p2->removeObserver(this); + delete this->p2; + this->p2 = NULL; + } + } + void deletePoints() + { + this->deletePoint1(); + this->deletePoint2(); + } + + GbPoint3D *getPoint1() { return this->p1; } + GbPoint3D *getPoint2() { return this->p2; } + + double getLength() { return (this->length); } + + double getX1Centroid() override { return ((this->p1->x1 + this->p2->x1) * 0.5); } + double getX2Centroid() override { return ((this->p1->x2 + this->p2->x2) * 0.5); }; + double getX3Centroid() override { return ((this->p1->x3 + this->p2->x3) * 0.5); } + + double getX1Minimum() override { return (this->p1->x1 < this->p2->x1 ? this->p1->x1 : this->p2->x1); } + double getX2Minimum() override { return (this->p1->x2 < this->p2->x2 ? this->p1->x2 : this->p2->x2); } + double getX3Minimum() override { return (this->p1->x3 < this->p2->x3 ? this->p1->x3 : this->p2->x3); } + + double getX1Maximum() override { return (this->p1->x1 > this->p2->x1 ? this->p1->x1 : this->p2->x1); } + double getX2Maximum() override { return (this->p1->x2 > this->p2->x2 ? this->p1->x2 : this->p2->x2); } + double getX3Maximum() override { return (this->p1->x3 > this->p2->x3 ? this->p1->x3 : this->p2->x3); } + + void scale(const double &sx1, const double &sx2, const double &sx3) override; + void translate(const double &tx1, const double &tx2, const double &tx3) override; + + GbPoint3D *calculateIntersectionPoint3D(GbLine3D *line); + GbLine3D *createClippedLine3D(GbCuboid3D *cuboid); + GbLine3D *createClippedLine3D(GbPoint3D *pA, GbPoint3D *pE); + + double getDistance(const GbPoint3D &point); + double getDistance(const double &x1, const double &x2, const double &x3); + + std::vector<GbTriangle3D *> getSurfaceTriangleSet() override; + bool isPointInGbObject3D(const double & /*x1*/, const double & /*x2*/, const double & /*x3*/) override + { + throw UbException(UB_EXARGS, "not implemented"); + } + bool isPointInGbObject3D(const double & /*x1*/, const double & /*x2*/, const double & /*x3*/, + bool & /*pointIsOnBoundary*/) override + { + throw UbException(UB_EXARGS, "not implemented"); + } + bool isCellInsideGbObject3D(const double & /*x11*/, const double & /*x21*/, const double & /*x31*/, + const double & /*x12*/, const double & /*x22*/, const double & /*x32*/) override + { + return false; + } + + GbLine3D *createClippedLine3D(GbPoint3D & /*point1*/, GbPoint3D & /*point2*/) override + { + throw UbException(UB_EXARGS, "not implemented"); + } + + // virtuelle Methoden von UbObserver + void objectChanged(UbObservable *changedObject) override; + void objectWillBeDeleted(UbObservable *objectForDeletion) override; + + std::string toString() override; + + using GbObject3D::isPointInGbObject3D; // Grund: dadurch muss man hier isPointInGbObject3D(GbPoint3D*) nicht + // ausprogrammieren, welche sonst hier "ueberdeckt" waere protected: - GbPoint3D* p1; - GbPoint3D* p2; - double length; + GbPoint3D *p1; + GbPoint3D *p2; + double length; private: - void calculateValues(); + void calculateValues(); }; #endif diff --git a/src/basics/geometry3d/GbMeshTools3D.h b/src/basics/geometry3d/GbMeshTools3D.h index 9805e33a6b57ec89b9bf62300cfa247616016c09..2a93319acb87011e0d63e60378e5db025c1e5a18 100644 --- a/src/basics/geometry3d/GbMeshTools3D.h +++ b/src/basics/geometry3d/GbMeshTools3D.h @@ -1,253 +1,316 @@ #ifndef GBMESHTOOLS3D_H #define GBMESHTOOLS3D_H -#include <sstream> #include <iostream> +#include <sstream> #include <vector> #include <basics/utilities/UbMath.h> namespace GbMeshTools3D { - inline int planeBoxOverlap(float normal[3], float vert[3], float maxbox[3]) // -NJMP- - { - int q; - float vmin[3],vmax[3],v; - - for(q=0;q<=2;q++) - { - v=vert[q]; // -NJMP- - if(normal[q]>0.0f) - { - vmin[q]=-maxbox[q] - v; // -NJMP- - vmax[q]= maxbox[q] - v; // -NJMP- - } - else - { - vmin[q]= maxbox[q] - v; // -NJMP- - vmax[q]=-maxbox[q] - v; // -NJMP- - } - } - if(( normal[0]*vmin[0] + normal[1]*vmin[1] + normal[2]*vmin[2] )>0.0f ) return 0; // -NJMP- - if(( normal[0]*vmax[0] + normal[1]*vmax[1] + normal[2]*vmax[2] )>=0.0f) return 1; // -NJMP- - return 0; - } - - //Testet auf schnittpunkt Box <-> Dreieck - //boxcenter = Mittelpunkt der Box - //boxhalfsize = Halbe Laenge/Hoehe/Breite der Box - //triverts = Koordinaten der Deickspunkte - inline int triBoxOverlap(float boxcenter[3],float boxhalfsize[3],float triverts[3][3]) - { - /* use separating axis theorem to test overlap between triangle and box */ - /* need to test for overlap in these directions: */ - /* 1) the {x,y,z}-directions (actually, since we use the AABB of the triangle */ - /* we do not even need to test these) */ - /* 2) normal of the triangle */ - /* 3) crossproduct(edge from tri, {x,y,z}-directin) */ - /* this gives 3x3=9 more tests */ - - float v0[3],v1[3],v2[3]; - - // float axis[3]; - - float min,max,p0,p1,p2,rad,fex,fey,fez; // -NJMP- "d" local variable removed - float normal[3],e0[3],e1[3],e2[3]; - - /* This is the fastest branch on Sun */ - /* move everything so that the boxcenter is in (0,0,0) */ - //SUB(v0,triverts[0],boxcenter); - //#define SUB(dest,v1,v2) - v0[0]=triverts[0][0]-boxcenter[0]; - v0[1]=triverts[0][1]-boxcenter[1]; - v0[2]=triverts[0][2]-boxcenter[2]; - - //SUB(v1,triverts[1],boxcenter); - //#define SUB(dest,v1,v2) - v1[0]=triverts[1][0]-boxcenter[0]; - v1[1]=triverts[1][1]-boxcenter[1]; - v1[2]=triverts[1][2]-boxcenter[2]; - - //SUB(v2,triverts[2],boxcenter); - //#define SUB(dest,v1,v2) - v2[0]=triverts[2][0]-boxcenter[0]; - v2[1]=triverts[2][1]-boxcenter[1]; - v2[2]=triverts[2][2]-boxcenter[2]; - - /* compute triangle edges */ - //SUB(e0,v1,v0); /* tri edge 0 */ - //#define SUB(dest,v1,v2) - e0[0]=v1[0]-v0[0]; - e0[1]=v1[1]-v0[1]; - e0[2]=v1[2]-v0[2]; - - //SUB(e1,v2,v1); /* tri edge 1 */ - //#define SUB(dest,v1,v2) - e1[0]=v2[0]-v1[0]; - e1[1]=v2[1]-v1[1]; - e1[2]=v2[2]-v1[2]; - - //SUB(e2,v0,v2); /* tri edge 2 */ - //#define SUB(dest,v1,v2) - e2[0]=v0[0]-v2[0]; - e2[1]=v0[1]-v2[1]; - e2[2]=v0[2]-v2[2]; - - /* Bullet 3: */ - /* test the 9 tests first (this was faster) */ - fex = fabsf(e0[0]); - fey = fabsf(e0[1]); - fez = fabsf(e0[2]); - - //AXISTEST_X01(e0[2], e0[1], fez, fey); - //#define AXISTEST_X01(a, b, fa, fb) - p0 = e0[2]*v0[1] - e0[1]*v0[2]; - p2 = e0[2]*v2[1] - e0[1]*v2[2]; - if(p0<p2) {min=p0; max=p2;} else {min=p2; max=p0;} - rad = fez * boxhalfsize[1] + fey * boxhalfsize[2]; - if(min>rad || max<-rad) return 0; - - //AXISTEST_Y02(e0[2], e0[0], fez, fex); - //#define AXISTEST_Y02(a, b, fa, fb) - p0 = -e0[2]*v0[0] + e0[0]*v0[2]; - p2 = -e0[2]*v2[0] + e0[0]*v2[2]; - if(p0<p2) {min=p0; max=p2;} else {min=p2; max=p0;} - rad = fez * boxhalfsize[0] + fex * boxhalfsize[2]; - if(min>rad || max<-rad) return 0; - - //AXISTEST_Z12(e0[1], e0[0], fey, fex); - //#define AXISTEST_Z12(a, b, fa, fb) - p1 = e0[1]*v1[0] - e0[0]*v1[1]; - p2 = e0[1]*v2[0] - e0[0]*v2[1]; - if(p2<p1) {min=p2; max=p1;} else {min=p1; max=p2;} - rad = fey * boxhalfsize[0] + fex * boxhalfsize[1]; - if(min>rad || max<-rad) return 0; - - fex = fabsf(e1[0]); - fey = fabsf(e1[1]); - fez = fabsf(e1[2]); - - //AXISTEST_X01(e1[2], e1[1], fez, fey); - //#define AXISTEST_X01(a, b, fa, fb) - p0 = e1[2]*v0[1] - e1[1]*v0[2]; - p2 = e1[2]*v2[1] - e1[1]*v2[2]; - if(p0<p2) {min=p0; max=p2;} else {min=p2; max=p0;} - rad = fez * boxhalfsize[1] + fey * boxhalfsize[2]; - if(min>rad || max<-rad) return 0; - - //AXISTEST_Y02(e1[2], e1[0], fez, fex); - //#define AXISTEST_Y02(a, b, fa, fb) - p0 = -e1[2]*v0[0] + e1[0]*v0[2]; - p2 = -e1[2]*v2[0] + e1[0]*v2[2]; - if(p0<p2) {min=p0; max=p2;} else {min=p2; max=p0;} - rad = fez * boxhalfsize[0] + fex * boxhalfsize[2]; - if(min>rad || max<-rad) return 0; - - //AXISTEST_Z0(e1[1], e1[0], fey, fex); - //#define AXISTEST_Z0(a, b, fa, fb) - p0 = e1[1]*v0[0] - e1[0]*v0[1]; - p1 = e1[1]*v1[0] - e1[0]*v1[1]; - if(p0<p1) {min=p0; max=p1;} else {min=p1; max=p0;} - rad = fey * boxhalfsize[0] + fex * boxhalfsize[2]; - if(min>rad || max<-rad) return 0; - - fex = fabsf(e2[0]); - fey = fabsf(e2[1]); - fez = fabsf(e2[2]); - //AXISTEST_X2(e2[2], e2[1], fez, fey); - //#define AXISTEST_X2(a, b, fa, fb) - p0 = e2[2]*v0[1] - e2[1]*v0[2]; - p1 = e2[2]*v1[1] - e2[1]*v1[2]; - if(p0<p1) {min=p0; max=p1;} else {min=p1; max=p0;} - rad = fez * boxhalfsize[1] + fey * boxhalfsize[2]; - if(min>rad || max<-rad) return 0; - - //AXISTEST_Y1(e2[2], e2[0], fez, fex); - //#define AXISTEST_Y1(a, b, fa, fb) - p0 = -e2[2]*v0[0] + e2[0]*v0[2]; - p1 = -e2[2]*v1[0] + e2[0]*v1[2]; - if(p0<p1) {min=p0; max=p1;} else {min=p1; max=p0;} - rad = fez * boxhalfsize[0] + fex * boxhalfsize[2]; - if(min>rad || max<-rad) return 0; - - //AXISTEST_Z12(e2[1], e2[0], fey, fex); - //#define AXISTEST_Z12(a, b, fa, fb) - p1 = e2[1]*v1[0] - e2[0]*v1[1]; - p2 = e2[1]*v2[0] - e2[0]*v2[1]; - if(p2<p1) {min=p2; max=p1;} else {min=p1; max=p2;} - rad = fey * boxhalfsize[0] + fex * boxhalfsize[1]; - if(min>rad || max<-rad) return 0; - - /* Bullet 1: */ - /* first test overlap in the {x,y,z}-directions */ - /* find min, max of the triangle each direction, and test for overlap in */ - /* that direction -- this is equivalent to testing a minimal AABB around */ - /* the triangle against the AABB */ - /* test in X-direction */ - //FINDMINMAX(v0[0],v1[0],v2[0],min,max); - min = (float)UbMath::min(v0[0],v1[0],v2[0]); - max = (float)UbMath::max(v0[0],v1[0],v2[0]); - if(min>boxhalfsize[0] || max<-boxhalfsize[0]) return 0; - - /* test in Y-direction */ - //FINDMINMAX(v0[1],v1[1],v2[1],min,max); - min = (float)UbMath::min(v0[1],v1[1],v2[1]); - max = (float)UbMath::max(v0[1],v1[1],v2[1]); - if(min>boxhalfsize[1] || max<-boxhalfsize[1]) return 0; - - /* test in Z-direction */ - //FINDMINMAX(v0[2],v1[2],v2[2],min,max); - min = (float)UbMath::min(v0[2],v1[2],v2[2]); - max = (float)UbMath::max(v0[2],v1[2],v2[2]); - - if(min>boxhalfsize[2] || max<-boxhalfsize[2]) return 0; - - /* Bullet 2: */ - /* test if the box intersects the plane of the triangle */ - /* compute plane equation of triangle: normal*x+d=0 */ - //CROSS(normal,e0,e1); - //#define CROSS(dest,v1,v2) - normal[0]=e0[1]*e1[2]-e0[2]*e1[1]; - normal[1]=e0[2]*e1[0]-e0[0]*e1[2]; - normal[2]=e0[0]*e1[1]-e0[1]*e1[0]; - - // -NJMP- (line removed here) - if(!planeBoxOverlap(normal,v0,boxhalfsize)) return 0; // -NJMP- - return 1; /* box and triangle overlaps */ - } - - - -}; +inline int planeBoxOverlap(float normal[3], float vert[3], float maxbox[3]) // -NJMP- +{ + int q; + float vmin[3], vmax[3], v; + + for (q = 0; q <= 2; q++) { + v = vert[q]; // -NJMP- + if (normal[q] > 0.0f) { + vmin[q] = -maxbox[q] - v; // -NJMP- + vmax[q] = maxbox[q] - v; // -NJMP- + } else { + vmin[q] = maxbox[q] - v; // -NJMP- + vmax[q] = -maxbox[q] - v; // -NJMP- + } + } + if ((normal[0] * vmin[0] + normal[1] * vmin[1] + normal[2] * vmin[2]) > 0.0f) + return 0; // -NJMP- + if ((normal[0] * vmax[0] + normal[1] * vmax[1] + normal[2] * vmax[2]) >= 0.0f) + return 1; // -NJMP- + return 0; +} + +// Testet auf schnittpunkt Box <-> Dreieck +// boxcenter = Mittelpunkt der Box +// boxhalfsize = Halbe Laenge/Hoehe/Breite der Box +// triverts = Koordinaten der Deickspunkte +inline int triBoxOverlap(float boxcenter[3], float boxhalfsize[3], float triverts[3][3]) +{ + /* use separating axis theorem to test overlap between triangle and box */ + /* need to test for overlap in these directions: */ + /* 1) the {x,y,z}-directions (actually, since we use the AABB of the triangle */ + /* we do not even need to test these) */ + /* 2) normal of the triangle */ + /* 3) crossproduct(edge from tri, {x,y,z}-directin) */ + /* this gives 3x3=9 more tests */ + + float v0[3], v1[3], v2[3]; + + // float axis[3]; + + float min, max, p0, p1, p2, rad, fex, fey, fez; // -NJMP- "d" local variable removed + float normal[3], e0[3], e1[3], e2[3]; + + /* This is the fastest branch on Sun */ + /* move everything so that the boxcenter is in (0,0,0) */ + // SUB(v0,triverts[0],boxcenter); + //#define SUB(dest,v1,v2) + v0[0] = triverts[0][0] - boxcenter[0]; + v0[1] = triverts[0][1] - boxcenter[1]; + v0[2] = triverts[0][2] - boxcenter[2]; + + // SUB(v1,triverts[1],boxcenter); + //#define SUB(dest,v1,v2) + v1[0] = triverts[1][0] - boxcenter[0]; + v1[1] = triverts[1][1] - boxcenter[1]; + v1[2] = triverts[1][2] - boxcenter[2]; + + // SUB(v2,triverts[2],boxcenter); + //#define SUB(dest,v1,v2) + v2[0] = triverts[2][0] - boxcenter[0]; + v2[1] = triverts[2][1] - boxcenter[1]; + v2[2] = triverts[2][2] - boxcenter[2]; + + /* compute triangle edges */ + // SUB(e0,v1,v0); /* tri edge 0 */ + //#define SUB(dest,v1,v2) + e0[0] = v1[0] - v0[0]; + e0[1] = v1[1] - v0[1]; + e0[2] = v1[2] - v0[2]; + + // SUB(e1,v2,v1); /* tri edge 1 */ + //#define SUB(dest,v1,v2) + e1[0] = v2[0] - v1[0]; + e1[1] = v2[1] - v1[1]; + e1[2] = v2[2] - v1[2]; + + // SUB(e2,v0,v2); /* tri edge 2 */ + //#define SUB(dest,v1,v2) + e2[0] = v0[0] - v2[0]; + e2[1] = v0[1] - v2[1]; + e2[2] = v0[2] - v2[2]; + + /* Bullet 3: */ + /* test the 9 tests first (this was faster) */ + fex = fabsf(e0[0]); + fey = fabsf(e0[1]); + fez = fabsf(e0[2]); + + // AXISTEST_X01(e0[2], e0[1], fez, fey); + //#define AXISTEST_X01(a, b, fa, fb) + p0 = e0[2] * v0[1] - e0[1] * v0[2]; + p2 = e0[2] * v2[1] - e0[1] * v2[2]; + if (p0 < p2) { + min = p0; + max = p2; + } else { + min = p2; + max = p0; + } + rad = fez * boxhalfsize[1] + fey * boxhalfsize[2]; + if (min > rad || max < -rad) + return 0; + + // AXISTEST_Y02(e0[2], e0[0], fez, fex); + //#define AXISTEST_Y02(a, b, fa, fb) + p0 = -e0[2] * v0[0] + e0[0] * v0[2]; + p2 = -e0[2] * v2[0] + e0[0] * v2[2]; + if (p0 < p2) { + min = p0; + max = p2; + } else { + min = p2; + max = p0; + } + rad = fez * boxhalfsize[0] + fex * boxhalfsize[2]; + if (min > rad || max < -rad) + return 0; + + // AXISTEST_Z12(e0[1], e0[0], fey, fex); + //#define AXISTEST_Z12(a, b, fa, fb) + p1 = e0[1] * v1[0] - e0[0] * v1[1]; + p2 = e0[1] * v2[0] - e0[0] * v2[1]; + if (p2 < p1) { + min = p2; + max = p1; + } else { + min = p1; + max = p2; + } + rad = fey * boxhalfsize[0] + fex * boxhalfsize[1]; + if (min > rad || max < -rad) + return 0; + + fex = fabsf(e1[0]); + fey = fabsf(e1[1]); + fez = fabsf(e1[2]); + + // AXISTEST_X01(e1[2], e1[1], fez, fey); + //#define AXISTEST_X01(a, b, fa, fb) + p0 = e1[2] * v0[1] - e1[1] * v0[2]; + p2 = e1[2] * v2[1] - e1[1] * v2[2]; + if (p0 < p2) { + min = p0; + max = p2; + } else { + min = p2; + max = p0; + } + rad = fez * boxhalfsize[1] + fey * boxhalfsize[2]; + if (min > rad || max < -rad) + return 0; + + // AXISTEST_Y02(e1[2], e1[0], fez, fex); + //#define AXISTEST_Y02(a, b, fa, fb) + p0 = -e1[2] * v0[0] + e1[0] * v0[2]; + p2 = -e1[2] * v2[0] + e1[0] * v2[2]; + if (p0 < p2) { + min = p0; + max = p2; + } else { + min = p2; + max = p0; + } + rad = fez * boxhalfsize[0] + fex * boxhalfsize[2]; + if (min > rad || max < -rad) + return 0; + + // AXISTEST_Z0(e1[1], e1[0], fey, fex); + //#define AXISTEST_Z0(a, b, fa, fb) + p0 = e1[1] * v0[0] - e1[0] * v0[1]; + p1 = e1[1] * v1[0] - e1[0] * v1[1]; + if (p0 < p1) { + min = p0; + max = p1; + } else { + min = p1; + max = p0; + } + rad = fey * boxhalfsize[0] + fex * boxhalfsize[2]; + if (min > rad || max < -rad) + return 0; + + fex = fabsf(e2[0]); + fey = fabsf(e2[1]); + fez = fabsf(e2[2]); + // AXISTEST_X2(e2[2], e2[1], fez, fey); + //#define AXISTEST_X2(a, b, fa, fb) + p0 = e2[2] * v0[1] - e2[1] * v0[2]; + p1 = e2[2] * v1[1] - e2[1] * v1[2]; + if (p0 < p1) { + min = p0; + max = p1; + } else { + min = p1; + max = p0; + } + rad = fez * boxhalfsize[1] + fey * boxhalfsize[2]; + if (min > rad || max < -rad) + return 0; + + // AXISTEST_Y1(e2[2], e2[0], fez, fex); + //#define AXISTEST_Y1(a, b, fa, fb) + p0 = -e2[2] * v0[0] + e2[0] * v0[2]; + p1 = -e2[2] * v1[0] + e2[0] * v1[2]; + if (p0 < p1) { + min = p0; + max = p1; + } else { + min = p1; + max = p0; + } + rad = fez * boxhalfsize[0] + fex * boxhalfsize[2]; + if (min > rad || max < -rad) + return 0; + + // AXISTEST_Z12(e2[1], e2[0], fey, fex); + //#define AXISTEST_Z12(a, b, fa, fb) + p1 = e2[1] * v1[0] - e2[0] * v1[1]; + p2 = e2[1] * v2[0] - e2[0] * v2[1]; + if (p2 < p1) { + min = p2; + max = p1; + } else { + min = p1; + max = p2; + } + rad = fey * boxhalfsize[0] + fex * boxhalfsize[1]; + if (min > rad || max < -rad) + return 0; + + /* Bullet 1: */ + /* first test overlap in the {x,y,z}-directions */ + /* find min, max of the triangle each direction, and test for overlap in */ + /* that direction -- this is equivalent to testing a minimal AABB around */ + /* the triangle against the AABB */ + /* test in X-direction */ + // FINDMINMAX(v0[0],v1[0],v2[0],min,max); + min = (float)UbMath::min(v0[0], v1[0], v2[0]); + max = (float)UbMath::max(v0[0], v1[0], v2[0]); + if (min > boxhalfsize[0] || max < -boxhalfsize[0]) + return 0; + + /* test in Y-direction */ + // FINDMINMAX(v0[1],v1[1],v2[1],min,max); + min = (float)UbMath::min(v0[1], v1[1], v2[1]); + max = (float)UbMath::max(v0[1], v1[1], v2[1]); + if (min > boxhalfsize[1] || max < -boxhalfsize[1]) + return 0; + + /* test in Z-direction */ + // FINDMINMAX(v0[2],v1[2],v2[2],min,max); + min = (float)UbMath::min(v0[2], v1[2], v2[2]); + max = (float)UbMath::max(v0[2], v1[2], v2[2]); + + if (min > boxhalfsize[2] || max < -boxhalfsize[2]) + return 0; + + /* Bullet 2: */ + /* test if the box intersects the plane of the triangle */ + /* compute plane equation of triangle: normal*x+d=0 */ + // CROSS(normal,e0,e1); + //#define CROSS(dest,v1,v2) + normal[0] = e0[1] * e1[2] - e0[2] * e1[1]; + normal[1] = e0[2] * e1[0] - e0[0] * e1[2]; + normal[2] = e0[0] * e1[1] - e0[1] * e1[0]; + + // -NJMP- (line removed here) + if (!planeBoxOverlap(normal, v0, boxhalfsize)) + return 0; // -NJMP- + return 1; /* box and triangle overlaps */ +} + +}; // namespace GbMeshTools3D #endif -//original - NICHT LOESCHEN - von kroete lynn +// original - NICHT LOESCHEN - von kroete lynn //#define X 0 //#define Y 1 //#define Z 2 // -//#define CROSS(dest,v1,v2) -// dest[0]=v1[1]*v2[2]-v1[2]*v2[1]; -// dest[1]=v1[2]*v2[0]-v1[0]*v2[2]; -// dest[2]=v1[0]*v2[1]-v1[1]*v2[0]; +//#define CROSS(dest,v1,v2) +// dest[0]=v1[1]*v2[2]-v1[2]*v2[1]; +// dest[1]=v1[2]*v2[0]-v1[0]*v2[2]; +// dest[2]=v1[0]*v2[1]-v1[1]*v2[0]; // //#define DOT(v1,v2) (v1[0]*v2[0]+v1[1]*v2[1]+v1[2]*v2[2]) // -//#define SUB(dest,v1,v2) -// dest[0]=v1[0]-v2[0]; -// dest[1]=v1[1]-v2[1]; -// dest[2]=v1[2]-v2[2]; +//#define SUB(dest,v1,v2) +// dest[0]=v1[0]-v2[0]; +// dest[1]=v1[1]-v2[1]; +// dest[2]=v1[2]-v2[2]; // -//#define FINDMINMAX(x0,x1,x2,min,max) -// min = max = x0; +//#define FINDMINMAX(x0,x1,x2,min,max) +// min = max = x0; // if(x1<min) min=x1; // if(x1>max) max=x1; // if(x2<min) min=x2; // if(x2>max) max=x2; // -//int planeBoxOverlap(float normal[3], float vert[3], float maxbox[3]) // -NJMP- +// int planeBoxOverlap(float normal[3], float vert[3], float maxbox[3]) // -NJMP- //{ // int q; // float vmin[3],vmax[3],v; @@ -273,63 +336,63 @@ namespace GbMeshTools3D // ///*======================== X-tests ======================== // -//#define AXISTEST_X01(a, b, fa, fb) -// p0 = a*v0[Y] - b*v0[Z]; -// p2 = a*v2[Y] - b*v2[Z]; -// if(p0<p2) {min=p0; max=p2;} else {min=p2; max=p0;} -// rad = fa * boxhalfsize[Y] + fb * boxhalfsize[Z]; +//#define AXISTEST_X01(a, b, fa, fb) +// p0 = a*v0[Y] - b*v0[Z]; +// p2 = a*v2[Y] - b*v2[Z]; +// if(p0<p2) {min=p0; max=p2;} else {min=p2; max=p0;} +// rad = fa * boxhalfsize[Y] + fb * boxhalfsize[Z]; // if(min>rad || max<-rad) return 0; // -//#define AXISTEST_X2(a, b, fa, fb) -// p0 = a*v0[Y] - b*v0[Z]; -// p1 = a*v1[Y] - b*v1[Z]; -// if(p0<p1) {min=p0; max=p1;} else {min=p1; max=p0;} -// rad = fa * boxhalfsize[Y] + fb * boxhalfsize[Z]; +//#define AXISTEST_X2(a, b, fa, fb) +// p0 = a*v0[Y] - b*v0[Z]; +// p1 = a*v1[Y] - b*v1[Z]; +// if(p0<p1) {min=p0; max=p1;} else {min=p1; max=p0;} +// rad = fa * boxhalfsize[Y] + fb * boxhalfsize[Z]; // if(min>rad || max<-rad) return 0; // // // ///*======================== Y-tests ======================== // -//#define AXISTEST_Y02(a, b, fa, fb) -// p0 = -a*v0[X] + b*v0[Z]; -// p2 = -a*v2[X] + b*v2[Z]; -// if(p0<p2) {min=p0; max=p2;} else {min=p2; max=p0;} -// rad = fa * boxhalfsize[X] + fb * boxhalfsize[Z]; +//#define AXISTEST_Y02(a, b, fa, fb) +// p0 = -a*v0[X] + b*v0[Z]; +// p2 = -a*v2[X] + b*v2[Z]; +// if(p0<p2) {min=p0; max=p2;} else {min=p2; max=p0;} +// rad = fa * boxhalfsize[X] + fb * boxhalfsize[Z]; // if(min>rad || max<-rad) return 0; // -//#define AXISTEST_Y1(a, b, fa, fb) -// p0 = -a*v0[X] + b*v0[Z]; -// p1 = -a*v1[X] + b*v1[Z]; -// if(p0<p1) {min=p0; max=p1;} else {min=p1; max=p0;} -// rad = fa * boxhalfsize[X] + fb * boxhalfsize[Z]; +//#define AXISTEST_Y1(a, b, fa, fb) +// p0 = -a*v0[X] + b*v0[Z]; +// p1 = -a*v1[X] + b*v1[Z]; +// if(p0<p1) {min=p0; max=p1;} else {min=p1; max=p0;} +// rad = fa * boxhalfsize[X] + fb * boxhalfsize[Z]; // if(min>rad || max<-rad) return 0; // //======================== Z-tests ======================== // -//#define AXISTEST_Z12(a, b, fa, fb) -// p1 = a*v1[X] - b*v1[Y]; -// p2 = a*v2[X] - b*v2[Y]; -// if(p2<p1) {min=p2; max=p1;} else {min=p1; max=p2;} -// rad = fa * boxhalfsize[X] + fb * boxhalfsize[Y]; +//#define AXISTEST_Z12(a, b, fa, fb) +// p1 = a*v1[X] - b*v1[Y]; +// p2 = a*v2[X] - b*v2[Y]; +// if(p2<p1) {min=p2; max=p1;} else {min=p1; max=p2;} +// rad = fa * boxhalfsize[X] + fb * boxhalfsize[Y]; // if(min>rad || max<-rad) return 0; // -//#define AXISTEST_Z0(a, b, fa, fb) -// p0 = a*v0[X] - b*v0[Y]; -// p1 = a*v1[X] - b*v1[Y]; +//#define AXISTEST_Z0(a, b, fa, fb) +// p0 = a*v0[X] - b*v0[Y]; +// p1 = a*v1[X] - b*v1[Y]; // if(p0<p1) {min=p0; max=p1;} else {min=p1; max=p0;} -// rad = fa * boxhalfsize[X] + fb * boxhalfsize[Y]; +// rad = fa * boxhalfsize[X] + fb * boxhalfsize[Y]; // if(min>rad || max<-rad) return 0; // -//int triBoxOverlap(float boxcenter[3],float boxhalfsize[3],float triverts[3][3]) +// int triBoxOverlap(float boxcenter[3],float boxhalfsize[3],float triverts[3][3]) //{ -// //use separating axis theorem to test overlap between triangle and box -// //need to test for overlap in these directions: -// //1) the {x,y,z}-directions (actually, since we use the AABB of the triangle -// // we do not even need to test these) -// //2) normal of the triangle -// //3) crossproduct(edge from tri, {x,y,z}-directin) -// // this gives 3x3=9 more tests +// //use separating axis theorem to test overlap between triangle and box +// //need to test for overlap in these directions: +// //1) the {x,y,z}-directions (actually, since we use the AABB of the triangle +// // we do not even need to test these) +// //2) normal of the triangle +// //3) crossproduct(edge from tri, {x,y,z}-directin) +// // this gives 3x3=9 more tests // // float v0[3],v1[3],v2[3]; // @@ -399,4 +462,3 @@ namespace GbMeshTools3D // if(!planeBoxOverlap(normal,v0,boxhalfsize)) return 0; // -NJMP- // return 1; /* box and triangle overlaps */ //} - diff --git a/src/basics/geometry3d/GbObject3D.cpp b/src/basics/geometry3d/GbObject3D.cpp index 1e96e72f3e00d8d24b717e670e2aff6f622b8413..b24831514c1168167f86a05a0c97714590e5a79a 100644 --- a/src/basics/geometry3d/GbObject3D.cpp +++ b/src/basics/geometry3d/GbObject3D.cpp @@ -1,28 +1,28 @@ //======================================================================================= -// ____ ____ __ ______ __________ __ __ __ __ -// \ \ | | | | | _ \ |___ ___| | | | | / \ | | -// \ \ | | | | | |_) | | | | | | | / \ | | -// \ \ | | | | | _ / | | | | | | / /\ \ | | -// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ -// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| -// \ \ | | ________________________________________________________________ -// \ \ | | | ______________________________________________________________| -// \ \| | | | __ __ __ __ ______ _______ -// \ | | |_____ | | | | | | | | | _ \ / _____) -// \ | | _____| | | | | | | | | | | \ \ \_______ +// ____ ____ __ ______ __________ __ __ __ __ +// \ \ | | | | | _ \ |___ ___| | | | | / \ | | +// \ \ | | | | | |_) | | | | | | | / \ | | +// \ \ | | | | | _ / | | | | | | / /\ \ | | +// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ +// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| +// \ \ | | ________________________________________________________________ +// \ \ | | | ______________________________________________________________| +// \ \| | | | __ __ __ __ ______ _______ +// \ | | |_____ | | | | | | | | | _ \ / _____) +// \ | | _____| | | | | | | | | | | \ \ \_______ // \ | | | | |_____ | \_/ | | | | |_/ / _____ | -// \ _____| |__| |________| \_______/ |__| |______/ (_______/ +// \ _____| |__| |________| \_______/ |__| |______/ (_______/ // -// This file is part of VirtualFluids. VirtualFluids is free software: you can +// This file is part of VirtualFluids. VirtualFluids is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of +// License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. -// -// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// +// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License along // with VirtualFluids (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>. // @@ -32,84 +32,66 @@ //======================================================================================= #include <GbObject3D.h> #include <GbPoint3D.h> -#include <basics/utilities/UbMath.h> +#include <basics/utilities/UbMath.h> using namespace std; /*======================================================================*/ -bool GbObject3D::isPointInGbObject3D(GbPoint3D* p) +bool GbObject3D::isPointInGbObject3D(GbPoint3D *p) { - return this->isPointInGbObject3D(p->getX1Centroid(),p->getX2Coordinate(),p->getX3Coordinate()); -} + return this->isPointInGbObject3D(p->getX1Centroid(), p->getX2Coordinate(), p->getX3Coordinate()); +} /*======================================================================*/ -bool GbObject3D::isCellInsideGbObject3D(const double& x1a,const double& x2a,const double& x3a,const double& x1b,const double& x2b,const double& x3b) +bool GbObject3D::isCellInsideGbObject3D(const double &x1a, const double &x2a, const double &x3a, const double &x1b, + const double &x2b, const double &x3b) { - if( this->isPointInGbObject3D(x1a, x2a, x3a) - && this->isPointInGbObject3D(x1b, x2a, x3a) - && this->isPointInGbObject3D(x1b, x2b, x3a) - && this->isPointInGbObject3D(x1a, x2b, x3a) - && this->isPointInGbObject3D(x1a, x2a, x3b) - && this->isPointInGbObject3D(x1b, x2a, x3b) - && this->isPointInGbObject3D(x1b, x2b, x3b) - && this->isPointInGbObject3D(x1a, x2b, x3b)) - { - return true; - } + if (this->isPointInGbObject3D(x1a, x2a, x3a) && this->isPointInGbObject3D(x1b, x2a, x3a) && + this->isPointInGbObject3D(x1b, x2b, x3a) && this->isPointInGbObject3D(x1a, x2b, x3a) && + this->isPointInGbObject3D(x1a, x2a, x3b) && this->isPointInGbObject3D(x1b, x2a, x3b) && + this->isPointInGbObject3D(x1b, x2b, x3b) && this->isPointInGbObject3D(x1a, x2b, x3b)) { + return true; + } - return false; + return false; } /*======================================================================*/ -bool GbObject3D::isCellCuttingGbObject3D(const double& x1a,const double& x2a,const double& x3a,const double& x1b,const double& x2b,const double& x3b) +bool GbObject3D::isCellCuttingGbObject3D(const double &x1a, const double &x2a, const double &x3a, const double &x1b, + const double &x2b, const double &x3b) { - if( this->isPointInGbObject3D(x1a, x2a, x3a) - || this->isPointInGbObject3D(x1b, x2a, x3a) - || this->isPointInGbObject3D(x1b, x2b, x3a) - || this->isPointInGbObject3D(x1a, x2b, x3a) - || this->isPointInGbObject3D(x1a, x2a, x3b) - || this->isPointInGbObject3D(x1b, x2a, x3b) - || this->isPointInGbObject3D(x1b, x2b, x3b) - || this->isPointInGbObject3D(x1a, x2b, x3b) ) - { - if( !this->isPointInGbObject3D(x1a, x2a, x3a) - || !this->isPointInGbObject3D(x1b, x2a, x3a) - || !this->isPointInGbObject3D(x1b, x2b, x3a) - || !this->isPointInGbObject3D(x1a, x2b, x3a) - || !this->isPointInGbObject3D(x1a, x2a, x3b) - || !this->isPointInGbObject3D(x1b, x2a, x3b) - || !this->isPointInGbObject3D(x1b, x2b, x3b) - || !this->isPointInGbObject3D(x1a, x2b, x3b)) return true; - } - return false; + if (this->isPointInGbObject3D(x1a, x2a, x3a) || this->isPointInGbObject3D(x1b, x2a, x3a) || + this->isPointInGbObject3D(x1b, x2b, x3a) || this->isPointInGbObject3D(x1a, x2b, x3a) || + this->isPointInGbObject3D(x1a, x2a, x3b) || this->isPointInGbObject3D(x1b, x2a, x3b) || + this->isPointInGbObject3D(x1b, x2b, x3b) || this->isPointInGbObject3D(x1a, x2b, x3b)) { + if (!this->isPointInGbObject3D(x1a, x2a, x3a) || !this->isPointInGbObject3D(x1b, x2a, x3a) || + !this->isPointInGbObject3D(x1b, x2b, x3a) || !this->isPointInGbObject3D(x1a, x2b, x3a) || + !this->isPointInGbObject3D(x1a, x2a, x3b) || !this->isPointInGbObject3D(x1b, x2a, x3b) || + !this->isPointInGbObject3D(x1b, x2b, x3b) || !this->isPointInGbObject3D(x1a, x2b, x3b)) + return true; + } + return false; } /*======================================================================*/ -bool GbObject3D::isCellInsideOrCuttingGbObject3D(const double& x1a,const double& x2a,const double& x3a,const double& x1b,const double& x2b,const double& x3b) +bool GbObject3D::isCellInsideOrCuttingGbObject3D(const double &x1a, const double &x2a, const double &x3a, + const double &x1b, const double &x2b, const double &x3b) { - if( this->isPointInGbObject3D(x1a, x2a, x3a) - || this->isPointInGbObject3D(x1b, x2a, x3a) - || this->isPointInGbObject3D(x1b, x2b, x3a) - || this->isPointInGbObject3D(x1a, x2b, x3a) - || this->isPointInGbObject3D(x1a, x2a, x3b) - || this->isPointInGbObject3D(x1b, x2a, x3b) - || this->isPointInGbObject3D(x1b, x2b, x3b) - || this->isPointInGbObject3D(x1a, x2b, x3b)) - { - return true; - } + if (this->isPointInGbObject3D(x1a, x2a, x3a) || this->isPointInGbObject3D(x1b, x2a, x3a) || + this->isPointInGbObject3D(x1b, x2b, x3a) || this->isPointInGbObject3D(x1a, x2b, x3a) || + this->isPointInGbObject3D(x1a, x2a, x3b) || this->isPointInGbObject3D(x1b, x2a, x3b) || + this->isPointInGbObject3D(x1b, x2b, x3b) || this->isPointInGbObject3D(x1a, x2b, x3b)) { + return true; + } - return false; + return false; } /*=======================================================*/ -bool GbObject3D::isInsideCell(const double& minX1,const double& minX2,const double& minX3,const double& maxX1,const double& maxX2,const double& maxX3) +bool GbObject3D::isInsideCell(const double &minX1, const double &minX2, const double &minX3, const double &maxX1, + const double &maxX2, const double &maxX3) { - if( UbMath::greaterEqual(this->getX1Minimum(),minX1) - && UbMath::greaterEqual(this->getX2Minimum(),minX2) - && UbMath::greaterEqual(this->getX3Minimum(),minX3) - && UbMath::lessEqual(this->getX1Maximum(),maxX1) - && UbMath::lessEqual(this->getX2Maximum(),maxX2) - && UbMath::lessEqual(this->getX2Maximum(),maxX3) ) return true; + if (UbMath::greaterEqual(this->getX1Minimum(), minX1) && UbMath::greaterEqual(this->getX2Minimum(), minX2) && + UbMath::greaterEqual(this->getX3Minimum(), minX3) && UbMath::lessEqual(this->getX1Maximum(), maxX1) && + UbMath::lessEqual(this->getX2Maximum(), maxX2) && UbMath::lessEqual(this->getX2Maximum(), maxX3)) + return true; - return false; + return false; } - - diff --git a/src/basics/geometry3d/GbObject3D.h b/src/basics/geometry3d/GbObject3D.h index be2191811bbf99c54998699073e90563d584db77..f60e64c8f95dfde84a389c422bbc6b9377e68187 100644 --- a/src/basics/geometry3d/GbObject3D.h +++ b/src/basics/geometry3d/GbObject3D.h @@ -1,28 +1,28 @@ //======================================================================================= -// ____ ____ __ ______ __________ __ __ __ __ -// \ \ | | | | | _ \ |___ ___| | | | | / \ | | -// \ \ | | | | | |_) | | | | | | | / \ | | -// \ \ | | | | | _ / | | | | | | / /\ \ | | -// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ -// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| -// \ \ | | ________________________________________________________________ -// \ \ | | | ______________________________________________________________| -// \ \| | | | __ __ __ __ ______ _______ -// \ | | |_____ | | | | | | | | | _ \ / _____) -// \ | | _____| | | | | | | | | | | \ \ \_______ +// ____ ____ __ ______ __________ __ __ __ __ +// \ \ | | | | | _ \ |___ ___| | | | | / \ | | +// \ \ | | | | | |_) | | | | | | | / \ | | +// \ \ | | | | | _ / | | | | | | / /\ \ | | +// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ +// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| +// \ \ | | ________________________________________________________________ +// \ \ | | | ______________________________________________________________| +// \ \| | | | __ __ __ __ ______ _______ +// \ | | |_____ | | | | | | | | | _ \ / _____) +// \ | | _____| | | | | | | | | | | \ \ \_______ // \ | | | | |_____ | \_/ | | | | |_/ / _____ | -// \ _____| |__| |________| \_______/ |__| |______/ (_______/ +// \ _____| |__| |________| \_______/ |__| |______/ (_______/ // -// This file is part of VirtualFluids. VirtualFluids is free software: you can +// This file is part of VirtualFluids. VirtualFluids is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of +// License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. -// -// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// +// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License along // with VirtualFluids (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>. // @@ -36,12 +36,11 @@ #include <string> #include <vector> - -#include <basics/utilities/UbSystem.h> +#include <basics/objects/ObObject.h> #include <basics/utilities/UbException.h> #include <basics/utilities/UbObservable.h> +#include <basics/utilities/UbSystem.h> #include <basics/utilities/UbTuple.h> -#include <basics/objects/ObObject.h> class GbPoint3D; class GbLine3D; @@ -51,99 +50,139 @@ class GbObject3DCreator; #include <PointerDefinitions.h> ////////////////////////////////////////////////////////////////////////// -//! +//! //! \class GbObject3D -//! +//! //! \brief This Interface provides basic 3D geometry objects methods. -//! +//! ////////////////////////////////////////////////////////////////////////// class GbObject3D : public ObObject { public: - //abstract Methods - virtual void finalize() = 0 ; //destroys also all dynamic objects (e.g. GbPoints in GbLine) - /** - * Returns the centroid x1 coordinate of this 3D object. - * @return the centroid x1 coordinate of this 3D object - */ - virtual double getX1Centroid()=0; - /** - * Returns the minimum x1 coordinate of this 3D object. - * @return the minimum x1 coordinate of this 3D object - */ - virtual double getX1Minimum()=0; - /** - * Returns the maximum x1 coordinate of this 3D object. - * @return the maximum x1 coordinate of this 3D object - */ - virtual double getX1Maximum()=0; - /** - * Returns the centroid x2 coordinate of this 3D object. - * @return the centroid x2 coordinate of this 3D object - */ - virtual double getX2Centroid()=0; - /** - * Returns the minimum x2 coordinate of this 3D object. - * @return the minimum x2 coordinate of this 3D object - */ - virtual double getX2Minimum()=0; - /** - * Returns the maximum x2 coordinate of this 3D object. - * @return the maximum x2 coordinate of this 3D object - */ - virtual double getX2Maximum()=0; - - virtual double getX3Centroid()=0; - /** - * Returns the minimum x2 coordinate of this 3D object. - * @return the minimum x2 coordinate of this 3D object - */ - virtual double getX3Minimum()=0; - /** - * Returns the maximum x2 coordinate of this 3D object. - * @return the maximum x2 coordinate of this 3D object - */ - virtual double getX3Maximum()=0; - - /*=======================================================*/ - double getLengthX1() { return (getX1Maximum()-getX1Minimum()); } - double getLengthX2() { return (getX2Maximum()-getX2Minimum()); } - double getLengthX3() { return (getX3Maximum()-getX3Minimum()); } - - virtual void setCenterX1Coordinate(const double& /*value*/) { throw UbException(UB_EXARGS,"not implemented for "+(std::string)typeid(*this).name() ); } - virtual void setCenterX2Coordinate(const double& /*value*/) { throw UbException(UB_EXARGS,"not implemented for "+(std::string)typeid(*this).name() ); } - virtual void setCenterX3Coordinate(const double& /*value*/) { throw UbException(UB_EXARGS,"not implemented for "+(std::string)typeid(*this).name() ); } - virtual void setCenterCoordinates(const double& /*x1*/, const double& /*x2*/, const double& /*x3*/) { throw UbException(UB_EXARGS, "not implemented for " + (std::string)typeid(*this).name()); } - virtual void setCenterCoordinates(const UbTupleDouble3& /*position*/) { throw UbException(UB_EXARGS,"not implemented for "+(std::string)typeid(*this).name() ); } - - //Rotates the Point in relation to the origen. - //Parameters must be radian measure. - virtual void rotate(const double& /*rx1*/, const double& /*rx2*/, const double& /*rx3*/) { throw UbException(UB_EXARGS,"not implemented for "+(std::string)typeid(*this).name() ); } - virtual void translate(const double& /*x1*/, const double& /*x2*/, const double& /*x3*/) { throw UbException(UB_EXARGS,"not implemented for "+(std::string)typeid(*this).name() ); } - virtual void scale(const double& /*sx1*/, const double& /*sx2*/, const double& /*sx3*/) { throw UbException(UB_EXARGS,"not implemented for "+(std::string)typeid(*this).name() ); } - - virtual bool isPointInGbObject3D(GbPoint3D* p); - virtual bool isPointInGbObject3D(const double& x1, const double& x2, const double& x3, bool& pointIsOnBoundary)=0; - virtual bool isPointInGbObject3D(const double& x1, const double& x2, const double& x3)=0; - - virtual bool isCellInsideGbObject3D(const double& x1a,const double& x2a,const double& x3a,const double& x1b,const double& x2b,const double& x3b); - virtual bool isCellCuttingGbObject3D(const double& x1a,const double& x2a,const double& x3a,const double& x1b,const double& x2b,const double& x3b); - virtual bool isCellInsideOrCuttingGbObject3D(const double& x1a,const double& x2a,const double& x3a,const double& x1b,const double& x2b,const double& x3b); - virtual double getCellVolumeInsideGbObject3D(const double& /*x1a*/,const double& /*x2a*/,const double& /*x3a*/,const double& /*x1b*/,const double& /*x2b*/,const double& /*x3b*/){ return -1.0;}; - - virtual bool isInsideCell(const double& minX1,const double& minX2,const double& minX3,const double& maxX1,const double& maxX2,const double& maxX3); - - virtual GbLine3D* createClippedLine3D (GbPoint3D &point1, GbPoint3D &point2) = 0; - virtual std::vector<GbTriangle3D*> getSurfaceTriangleSet()=0; - - virtual void addSurfaceTriangleSet(std::vector<UbTupleFloat3>& /*nodes*/, std::vector<UbTupleInt3>& /*triangles*/) { throw UbException("GbObject3D::addSurfaceTriangleSet - not implemented for "+(std::string)typeid(*this).name()); } - - virtual bool hasRaytracing() { return false; } - virtual bool raytracingSupportsPointsInside() { return false; } - //|r| must be 1! einheitsvector!! - //return negativ value oder zero if no intersection - virtual double getIntersectionRaytraceFactor(const double& /*x1*/, const double& /*x2*/, const double& /*x3*/, const double& /*rx1*/, const double& /*rx2*/, const double& /*rx3*/) { throw UbException("GbObject3D::getIntersectionRaytraceFactor - not implemented"); } + // abstract Methods + virtual void finalize() = 0; // destroys also all dynamic objects (e.g. GbPoints in GbLine) + /** + * Returns the centroid x1 coordinate of this 3D object. + * @return the centroid x1 coordinate of this 3D object + */ + virtual double getX1Centroid() = 0; + /** + * Returns the minimum x1 coordinate of this 3D object. + * @return the minimum x1 coordinate of this 3D object + */ + virtual double getX1Minimum() = 0; + /** + * Returns the maximum x1 coordinate of this 3D object. + * @return the maximum x1 coordinate of this 3D object + */ + virtual double getX1Maximum() = 0; + /** + * Returns the centroid x2 coordinate of this 3D object. + * @return the centroid x2 coordinate of this 3D object + */ + virtual double getX2Centroid() = 0; + /** + * Returns the minimum x2 coordinate of this 3D object. + * @return the minimum x2 coordinate of this 3D object + */ + virtual double getX2Minimum() = 0; + /** + * Returns the maximum x2 coordinate of this 3D object. + * @return the maximum x2 coordinate of this 3D object + */ + virtual double getX2Maximum() = 0; + + virtual double getX3Centroid() = 0; + /** + * Returns the minimum x2 coordinate of this 3D object. + * @return the minimum x2 coordinate of this 3D object + */ + virtual double getX3Minimum() = 0; + /** + * Returns the maximum x2 coordinate of this 3D object. + * @return the maximum x2 coordinate of this 3D object + */ + virtual double getX3Maximum() = 0; + + /*=======================================================*/ + double getLengthX1() { return (getX1Maximum() - getX1Minimum()); } + double getLengthX2() { return (getX2Maximum() - getX2Minimum()); } + double getLengthX3() { return (getX3Maximum() - getX3Minimum()); } + + virtual void setCenterX1Coordinate(const double & /*value*/) + { + throw UbException(UB_EXARGS, "not implemented for " + (std::string) typeid(*this).name()); + } + virtual void setCenterX2Coordinate(const double & /*value*/) + { + throw UbException(UB_EXARGS, "not implemented for " + (std::string) typeid(*this).name()); + } + virtual void setCenterX3Coordinate(const double & /*value*/) + { + throw UbException(UB_EXARGS, "not implemented for " + (std::string) typeid(*this).name()); + } + virtual void setCenterCoordinates(const double & /*x1*/, const double & /*x2*/, const double & /*x3*/) + { + throw UbException(UB_EXARGS, "not implemented for " + (std::string) typeid(*this).name()); + } + virtual void setCenterCoordinates(const UbTupleDouble3 & /*position*/) + { + throw UbException(UB_EXARGS, "not implemented for " + (std::string) typeid(*this).name()); + } + + // Rotates the Point in relation to the origen. + // Parameters must be radian measure. + virtual void rotate(const double & /*rx1*/, const double & /*rx2*/, const double & /*rx3*/) + { + throw UbException(UB_EXARGS, "not implemented for " + (std::string) typeid(*this).name()); + } + virtual void translate(const double & /*x1*/, const double & /*x2*/, const double & /*x3*/) + { + throw UbException(UB_EXARGS, "not implemented for " + (std::string) typeid(*this).name()); + } + virtual void scale(const double & /*sx1*/, const double & /*sx2*/, const double & /*sx3*/) + { + throw UbException(UB_EXARGS, "not implemented for " + (std::string) typeid(*this).name()); + } + + virtual bool isPointInGbObject3D(GbPoint3D *p); + virtual bool isPointInGbObject3D(const double &x1, const double &x2, const double &x3, bool &pointIsOnBoundary) = 0; + virtual bool isPointInGbObject3D(const double &x1, const double &x2, const double &x3) = 0; + + virtual bool isCellInsideGbObject3D(const double &x1a, const double &x2a, const double &x3a, const double &x1b, + const double &x2b, const double &x3b); + virtual bool isCellCuttingGbObject3D(const double &x1a, const double &x2a, const double &x3a, const double &x1b, + const double &x2b, const double &x3b); + virtual bool isCellInsideOrCuttingGbObject3D(const double &x1a, const double &x2a, const double &x3a, + const double &x1b, const double &x2b, const double &x3b); + virtual double getCellVolumeInsideGbObject3D(const double & /*x1a*/, const double & /*x2a*/, const double & /*x3a*/, + const double & /*x1b*/, const double & /*x2b*/, const double & /*x3b*/) + { + return -1.0; + }; + + virtual bool isInsideCell(const double &minX1, const double &minX2, const double &minX3, const double &maxX1, + const double &maxX2, const double &maxX3); + + virtual GbLine3D *createClippedLine3D(GbPoint3D &point1, GbPoint3D &point2) = 0; + virtual std::vector<GbTriangle3D *> getSurfaceTriangleSet() = 0; + + virtual void addSurfaceTriangleSet(std::vector<UbTupleFloat3> & /*nodes*/, std::vector<UbTupleInt3> & /*triangles*/) + { + throw UbException("GbObject3D::addSurfaceTriangleSet - not implemented for " + + (std::string) typeid(*this).name()); + } + + virtual bool hasRaytracing() { return false; } + virtual bool raytracingSupportsPointsInside() { return false; } + //|r| must be 1! einheitsvector!! + // return negativ value oder zero if no intersection + virtual double getIntersectionRaytraceFactor(const double & /*x1*/, const double & /*x2*/, const double & /*x3*/, + const double & /*rx1*/, const double & /*rx2*/, const double & /*rx3*/) + { + throw UbException("GbObject3D::getIntersectionRaytraceFactor - not implemented"); + } }; /*=========================================================================*/ diff --git a/src/basics/geometry3d/GbObjectGroup3D.cpp b/src/basics/geometry3d/GbObjectGroup3D.cpp index f96b9246aa80a4a37b51077b9956aee08c9ba4f4..e83ea5a605f8b77fdff45a8d17301c44f69614dd 100644 --- a/src/basics/geometry3d/GbObjectGroup3D.cpp +++ b/src/basics/geometry3d/GbObjectGroup3D.cpp @@ -1,133 +1,116 @@ +#include <geometry3d/GbLine3D.h> #include <geometry3d/GbObjectGroup3D.h> -#include <geometry3d/GbSystem3D.h> #include <geometry3d/GbPoint3D.h> -#include <geometry3d/GbLine3D.h> +#include <geometry3d/GbSystem3D.h> #include <geometry3d/GbTriangle3D.h> using namespace std; /*=====================================================*/ -GbObjectGroup3D::GbObjectGroup3D() -{ - this->setName("ObjectGroup"); -} +GbObjectGroup3D::GbObjectGroup3D() { this->setName("ObjectGroup"); } /*=====================================================*/ -GbObjectGroup3D::~GbObjectGroup3D() -= default; +GbObjectGroup3D::~GbObjectGroup3D() = default; /*=====================================================*/ -void GbObjectGroup3D::finalize() -{ - throw UbException(UB_EXARGS,"not implemented."); -} +void GbObjectGroup3D::finalize() { throw UbException(UB_EXARGS, "not implemented."); } /*=======================================================*/ -void GbObjectGroup3D::setCenterCoordinates(const double& /*x1*/, const double& /*x2*/, const double& /*x3*/) +void GbObjectGroup3D::setCenterCoordinates(const double & /*x1*/, const double & /*x2*/, const double & /*x3*/) { - throw UbException(UB_EXARGS,"not implemented."); + throw UbException(UB_EXARGS, "not implemented."); } /*=====================================================*/ -double GbObjectGroup3D::getDistance(GbPoint3D* /*p*/) -{ - throw UbException(UB_EXARGS,"not implemented."); -} +double GbObjectGroup3D::getDistance(GbPoint3D * /*p*/) { throw UbException(UB_EXARGS, "not implemented."); } /*=====================================================*/ -void GbObjectGroup3D::setCenterX1Coordinate(const double& /*value*/) +void GbObjectGroup3D::setCenterX1Coordinate(const double & /*value*/) { - throw UbException(UB_EXARGS,"not implemented."); + throw UbException(UB_EXARGS, "not implemented."); } /*=====================================================*/ -void GbObjectGroup3D::setCenterX2Coordinate(const double& /*value*/) +void GbObjectGroup3D::setCenterX2Coordinate(const double & /*value*/) { - throw UbException(UB_EXARGS,"not implemented."); + throw UbException(UB_EXARGS, "not implemented."); } /*=====================================================*/ -void GbObjectGroup3D::setCenterX3Coordinate(const double& /*value*/) +void GbObjectGroup3D::setCenterX3Coordinate(const double & /*value*/) { - throw UbException(UB_EXARGS,"not implemented."); + throw UbException(UB_EXARGS, "not implemented."); } /*=====================================================*/ -void GbObjectGroup3D::setRadius(const double& /*radius*/) -{ - throw UbException(UB_EXARGS,"not implemented."); -} +void GbObjectGroup3D::setRadius(const double & /*radius*/) { throw UbException(UB_EXARGS, "not implemented."); } /*=====================================================*/ -double GbObjectGroup3D::getDistance(const double& /*x1p*/, const double& /*x2p*/, const double& /*x3p*/) +double GbObjectGroup3D::getDistance(const double & /*x1p*/, const double & /*x2p*/, const double & /*x3p*/) { - throw UbException(UB_EXARGS,"not implemented."); + throw UbException(UB_EXARGS, "not implemented."); } /*=====================================================*/ -//true, wenn 'in Object' oder 'auf Boundary'! -bool GbObjectGroup3D::isPointInGbObject3D(const double& /*x1p*/, const double& /*x2p*/, const double& /*x3p*/) +// true, wenn 'in Object' oder 'auf Boundary'! +bool GbObjectGroup3D::isPointInGbObject3D(const double & /*x1p*/, const double & /*x2p*/, const double & /*x3p*/) { - return false; + return false; } /*=====================================================*/ -//true, wenn 'in Object' oder 'auf Boundary'! -bool GbObjectGroup3D::isPointInGbObject3D(const double& /*x1p*/, const double& /*x2p*/, const double& /*x3p*/, bool& /*pointIsOnBoundary*/) +// true, wenn 'in Object' oder 'auf Boundary'! +bool GbObjectGroup3D::isPointInGbObject3D(const double & /*x1p*/, const double & /*x2p*/, const double & /*x3p*/, + bool & /*pointIsOnBoundary*/) { - return false; + return false; } /*=====================================================*/ string GbObjectGroup3D::toString() { - stringstream ss; - ss<< "GbObjectGroup3D["; - ss <<"mid="<<midPoint->toString()<<", r="<<radius<<"]"; - return ss.str(); + stringstream ss; + ss << "GbObjectGroup3D["; + ss << "mid=" << midPoint->toString() << ", r=" << radius << "]"; + return ss.str(); } /*=====================================================*/ -GbLine3D* GbObjectGroup3D::createClippedLine3D(GbPoint3D& /*point1*/, GbPoint3D& /*point2*/) -{ - return NULL; -} +GbLine3D *GbObjectGroup3D::createClippedLine3D(GbPoint3D & /*point1*/, GbPoint3D & /*point2*/) { return NULL; } /*=========================================================================*/ -vector<GbTriangle3D*> GbObjectGroup3D::getSurfaceTriangleSet() +vector<GbTriangle3D *> GbObjectGroup3D::getSurfaceTriangleSet() { - vector<GbTriangle3D*> allTriangles; + vector<GbTriangle3D *> allTriangles; - //loop ueber alle objekte in der group - for( std::list< GbObject3D* >::iterator iter = this->geoobjects.begin(); - iter != this->geoobjects.end(); - iter++ ) - { - vector<GbTriangle3D*> triangles; - triangles = (*iter)->getSurfaceTriangleSet(); + // loop ueber alle objekte in der group + for (std::list<GbObject3D *>::iterator iter = this->geoobjects.begin(); iter != this->geoobjects.end(); iter++) { + vector<GbTriangle3D *> triangles; + triangles = (*iter)->getSurfaceTriangleSet(); - for( size_t i=0;i<triangles.size(); i++ ) - { - //kopieren... - allTriangles.push_back( triangles[i] ); - } - } - return allTriangles; + for (size_t i = 0; i < triangles.size(); i++) { + // kopieren... + allTriangles.push_back(triangles[i]); + } + } + return allTriangles; } /*=======================================================*/ -void GbObjectGroup3D::addSurfaceTriangleSet(vector<UbTupleFloat3>& nodes, vector<UbTupleInt3>& triangles) -{ -} +void GbObjectGroup3D::addSurfaceTriangleSet(vector<UbTupleFloat3> &nodes, vector<UbTupleInt3> &triangles) {} /*=======================================================*/ -bool GbObjectGroup3D::hasIntersectionWithDirectedLine(GbPoint3D /*origin*/, GbPoint3D /*direction*/) -{ - return false; -} +bool GbObjectGroup3D::hasIntersectionWithDirectedLine(GbPoint3D /*origin*/, GbPoint3D /*direction*/) { return false; } /*=======================================================*/ -bool GbObjectGroup3D::isCellCuttingGbObject3D(const double& /*x1a*/,const double& /*x2a*/,const double& /*x3a*/,const double& /*x1b*/,const double& /*x2b*/,const double& /*x3b*/) +bool GbObjectGroup3D::isCellCuttingGbObject3D(const double & /*x1a*/, const double & /*x2a*/, const double & /*x3a*/, + const double & /*x1b*/, const double & /*x2b*/, const double & /*x3b*/) { - return false; + return false; } /*=======================================================*/ -bool GbObjectGroup3D::isCellInsideOrCuttingGbObject3D(const double& /*x1a*/,const double& /*x2a*/,const double& /*x3a*/,const double& /*x1b*/,const double& /*x2b*/,const double& /*x3b*/) +bool GbObjectGroup3D::isCellInsideOrCuttingGbObject3D(const double & /*x1a*/, const double & /*x2a*/, + const double & /*x3a*/, const double & /*x1b*/, + const double & /*x2b*/, const double & /*x3b*/) { - return false; + return false; } /*==========================================================*/ -double GbObjectGroup3D::getCellVolumeInsideGbObject3D(const double& /*x1a*/,const double& /*x2a*/,const double& /*x3a*/,const double& /*x1b*/,const double& /*x2b*/,const double& /*x3b*/) +double GbObjectGroup3D::getCellVolumeInsideGbObject3D(const double & /*x1a*/, const double & /*x2a*/, + const double & /*x3a*/, const double & /*x1b*/, + const double & /*x2b*/, const double & /*x3b*/) { - return 0.0; + return 0.0; } /*==========================================================*/ -double GbObjectGroup3D::getIntersectionRaytraceFactor(const double& /*x1*/, const double& /*x2*/, const double& /*x3*/, const double& /*rx1*/, const double& /*rx2*/, const double& /*rx3*/) +double GbObjectGroup3D::getIntersectionRaytraceFactor(const double & /*x1*/, const double & /*x2*/, + const double & /*x3*/, const double & /*rx1*/, + const double & /*rx2*/, const double & /*rx3*/) { - return 0.0; + return 0.0; } /*=======================================================*/ diff --git a/src/basics/geometry3d/GbObjectGroup3D.h b/src/basics/geometry3d/GbObjectGroup3D.h index 380174f4750acbfc296fc5338c640eb13cc1ae1d..a94703dc18a42be5762a876bd03d799b725b0812 100644 --- a/src/basics/geometry3d/GbObjectGroup3D.h +++ b/src/basics/geometry3d/GbObjectGroup3D.h @@ -8,14 +8,14 @@ #define GBOBJECTGROUP3D_H #ifdef CAB_CTL - #include <ctl.h> -#endif //CAB_CTL +#include <ctl.h> +#endif // CAB_CTL -#include <vector> #include <cmath> +#include <vector> -#include <geometry3d/GbObject3D.h> #include <basics/utilities/UbObserver.h> +#include <geometry3d/GbObject3D.h> #include <geometry3d/GbPoint3D.h> #include <PointerDefinitions.h> @@ -25,110 +25,113 @@ class GbTriangle3D; class GbObject3DCreator; class GbObjectGroup3D : public GbObject3D, public UbObserver -{ +{ public: - enum TRIANGULATIONMODE { CUBOIDPROJECTION ,RAYPROJECTION }; - - ////////////////////////////////////////////////////////////////////////// - // Konstruktoren - GbObjectGroup3D(); - GbObjectGroup3D(GbObjectGroup3D * /*group*/){}; - ~GbObjectGroup3D() override; - - GbObjectGroup3D* clone() override {return new GbObjectGroup3D(this);} - void finalize() override; - - void addGbObject(GbObject3D* object) - { - this->geoobjects.push_back(object); - } - - double getRadius() const { return this->radius; } - - double getX1Centroid() override { return midPoint->getX1Coordinate();} - double getX1Minimum() override { return midPoint->getX1Coordinate()-radius;} - double getX1Maximum() override { return midPoint->getX1Coordinate()+radius;} - double getX2Centroid() override { return midPoint->getX2Coordinate();} - double getX2Minimum() override { return midPoint->getX2Coordinate()-radius;} - double getX2Maximum() override { return midPoint->getX2Coordinate()+radius;} - double getX3Centroid() override { return midPoint->getX3Coordinate();} - double getX3Minimum() override { return midPoint->getX3Coordinate()-radius;} - double getX3Maximum() override { return midPoint->getX3Coordinate()+radius;} - - void setCenterX1Coordinate(const double& value) override; - void setCenterX2Coordinate(const double& value) override; - void setCenterX3Coordinate(const double& value) override; - void setCenterCoordinates(const double& x1, const double& x2, const double& x3) override; - void setRadius(const double& radius); - - GbLine3D* createClippedLine3D(GbPoint3D& point1, GbPoint3D& point2) override; - double getDistance(GbPoint3D* p); - double getDistance(const double& x1p, const double& x2p, const double& x3p); - - bool isPointInGbObject3D(const double& x1, const double& x2, const double& x3) override; - bool isPointInGbObject3D(const double& x1p, const double& x2p, const double& x3p, bool& pointIsOnBoundary) override; - - bool isCellCuttingGbObject3D(const double& x1a,const double& x2a,const double& x3a,const double& x1b,const double& x2b,const double& x3b) override; - bool isCellInsideOrCuttingGbObject3D(const double& x1a,const double& x2a,const double& x3a,const double& x1b,const double& x2b,const double& x3b) override; - double getCellVolumeInsideGbObject3D(const double& x1a,const double& x2a,const double& x3a,const double& x1b,const double& x2b,const double& x3b) override; - - std::vector<GbTriangle3D*> getSurfaceTriangleSet() override; - void addSurfaceTriangleSet(std::vector<UbTupleFloat3>& nodes, std::vector<UbTupleInt3>& triangles) override; - - bool hasRaytracing() override { return true; } - /*|r| must be 1! einheitsvector!!*/ - double getIntersectionRaytraceFactor(const double& x1, const double& x2, const double& x3, const double& rx1, const double& rx2, const double& rx3) override; - - bool hasIntersectionWithDirectedLine(GbPoint3D origin, GbPoint3D direction); - - std::string toString() override; - - - void translate(const double& x1, const double& x2, const double& x3) override - { - this->midPoint->translate(x1, x2, x3); - this->notifyObserversObjectChanged(); - } - void rotate(const double& rx1, const double& rx2, const double& rx3) override {/* rotation makes no sense*/ } - void scale(const double& sx1, const double& /*sx2*/, const double& /*sx3*/) override { this->radius *= sx1; } - - TRIANGULATIONMODE getTriangulationMode() {return triangulationMode;} - void setTriangulationMode(TRIANGULATIONMODE mode) { this->triangulationMode = mode; } - - //virtuelle Methoden von UbObserver - void objectChanged(UbObservable* /*changedObject*/) override - { - this->notifyObserversObjectChanged(); - //std::cout<<"GbSphere:objectChanged() - toDo-);"; - } - void objectWillBeDeleted(UbObservable* /*objectForDeletion*/) override - { - std::cout<<"throw UbException(-GbObjectGroup3D::finalize() - toDo-);"; - } - - using GbObject3D::isPointInGbObject3D; //Grund: dadurch muss man hier isPointInGbObject3D(GbPoint3D*) nicht ausprogrammieren, welche sonst hier "ueberdeckt" waere, weil man eine - - std::list< GbObject3D* > getGbObject3DList() { return this->geoobjects; } + enum TRIANGULATIONMODE { CUBOIDPROJECTION, RAYPROJECTION }; + + ////////////////////////////////////////////////////////////////////////// + // Konstruktoren + GbObjectGroup3D(); + GbObjectGroup3D(GbObjectGroup3D * /*group*/){}; + ~GbObjectGroup3D() override; + + GbObjectGroup3D *clone() override { return new GbObjectGroup3D(this); } + void finalize() override; + + void addGbObject(GbObject3D *object) { this->geoobjects.push_back(object); } + + double getRadius() const { return this->radius; } + + double getX1Centroid() override { return midPoint->getX1Coordinate(); } + double getX1Minimum() override { return midPoint->getX1Coordinate() - radius; } + double getX1Maximum() override { return midPoint->getX1Coordinate() + radius; } + double getX2Centroid() override { return midPoint->getX2Coordinate(); } + double getX2Minimum() override { return midPoint->getX2Coordinate() - radius; } + double getX2Maximum() override { return midPoint->getX2Coordinate() + radius; } + double getX3Centroid() override { return midPoint->getX3Coordinate(); } + double getX3Minimum() override { return midPoint->getX3Coordinate() - radius; } + double getX3Maximum() override { return midPoint->getX3Coordinate() + radius; } + + void setCenterX1Coordinate(const double &value) override; + void setCenterX2Coordinate(const double &value) override; + void setCenterX3Coordinate(const double &value) override; + void setCenterCoordinates(const double &x1, const double &x2, const double &x3) override; + void setRadius(const double &radius); + + GbLine3D *createClippedLine3D(GbPoint3D &point1, GbPoint3D &point2) override; + double getDistance(GbPoint3D *p); + double getDistance(const double &x1p, const double &x2p, const double &x3p); + + bool isPointInGbObject3D(const double &x1, const double &x2, const double &x3) override; + bool isPointInGbObject3D(const double &x1p, const double &x2p, const double &x3p, bool &pointIsOnBoundary) override; + + bool isCellCuttingGbObject3D(const double &x1a, const double &x2a, const double &x3a, const double &x1b, + const double &x2b, const double &x3b) override; + bool isCellInsideOrCuttingGbObject3D(const double &x1a, const double &x2a, const double &x3a, const double &x1b, + const double &x2b, const double &x3b) override; + double getCellVolumeInsideGbObject3D(const double &x1a, const double &x2a, const double &x3a, const double &x1b, + const double &x2b, const double &x3b) override; + + std::vector<GbTriangle3D *> getSurfaceTriangleSet() override; + void addSurfaceTriangleSet(std::vector<UbTupleFloat3> &nodes, std::vector<UbTupleInt3> &triangles) override; + + bool hasRaytracing() override { return true; } + /*|r| must be 1! einheitsvector!!*/ + double getIntersectionRaytraceFactor(const double &x1, const double &x2, const double &x3, const double &rx1, + const double &rx2, const double &rx3) override; + + bool hasIntersectionWithDirectedLine(GbPoint3D origin, GbPoint3D direction); + + std::string toString() override; + + void translate(const double &x1, const double &x2, const double &x3) override + { + this->midPoint->translate(x1, x2, x3); + this->notifyObserversObjectChanged(); + } + void rotate(const double &rx1, const double &rx2, const double &rx3) override + { /* rotation makes no sense*/ + } + void scale(const double &sx1, const double & /*sx2*/, const double & /*sx3*/) override { this->radius *= sx1; } + + TRIANGULATIONMODE getTriangulationMode() { return triangulationMode; } + void setTriangulationMode(TRIANGULATIONMODE mode) { this->triangulationMode = mode; } + + // virtuelle Methoden von UbObserver + void objectChanged(UbObservable * /*changedObject*/) override + { + this->notifyObserversObjectChanged(); + // std::cout<<"GbSphere:objectChanged() - toDo-);"; + } + void objectWillBeDeleted(UbObservable * /*objectForDeletion*/) override + { + std::cout << "throw UbException(-GbObjectGroup3D::finalize() - toDo-);"; + } + + using GbObject3D::isPointInGbObject3D; // Grund: dadurch muss man hier isPointInGbObject3D(GbPoint3D*) nicht + // ausprogrammieren, welche sonst hier "ueberdeckt" waere, weil man eine + + std::list<GbObject3D *> getGbObject3DList() { return this->geoobjects; } #ifdef CAB_CTL - ctl::oStream &write(ctl::oStream &os) const - { - midPoint->write(os); - return os<<radius; - } - ctl::iStream &read(ctl::iStream &is) - { - midPoint->read(is); - return is>>radius; - } -#endif //CAB_CTL + ctl::oStream &write(ctl::oStream &os) const + { + midPoint->write(os); + return os << radius; + } + ctl::iStream &read(ctl::iStream &is) + { + midPoint->read(is); + return is >> radius; + } +#endif // CAB_CTL private: - GbPoint3D* midPoint; - double radius; // Radius des Kreises - TRIANGULATIONMODE triangulationMode; + GbPoint3D *midPoint; + double radius; // Radius des Kreises + TRIANGULATIONMODE triangulationMode; - std::list< GbObject3D* > geoobjects; + std::list<GbObject3D *> geoobjects; }; -#endif //GbObjectGroup3D_H +#endif // GbObjectGroup3D_H diff --git a/src/basics/geometry3d/GbPoint3D.cpp b/src/basics/geometry3d/GbPoint3D.cpp index ff6852e78ee176fb02633aa684dd3b7626e05930..c7780bb8be6f5b98c4b9c9e0c4266811af1bc9f7 100644 --- a/src/basics/geometry3d/GbPoint3D.cpp +++ b/src/basics/geometry3d/GbPoint3D.cpp @@ -1,28 +1,28 @@ //======================================================================================= -// ____ ____ __ ______ __________ __ __ __ __ -// \ \ | | | | | _ \ |___ ___| | | | | / \ | | -// \ \ | | | | | |_) | | | | | | | / \ | | -// \ \ | | | | | _ / | | | | | | / /\ \ | | -// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ -// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| -// \ \ | | ________________________________________________________________ -// \ \ | | | ______________________________________________________________| -// \ \| | | | __ __ __ __ ______ _______ -// \ | | |_____ | | | | | | | | | _ \ / _____) -// \ | | _____| | | | | | | | | | | \ \ \_______ +// ____ ____ __ ______ __________ __ __ __ __ +// \ \ | | | | | _ \ |___ ___| | | | | / \ | | +// \ \ | | | | | |_) | | | | | | | / \ | | +// \ \ | | | | | _ / | | | | | | / /\ \ | | +// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ +// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| +// \ \ | | ________________________________________________________________ +// \ \ | | | ______________________________________________________________| +// \ \| | | | __ __ __ __ ______ _______ +// \ | | |_____ | | | | | | | | | _ \ / _____) +// \ | | _____| | | | | | | | | | | \ \ \_______ // \ | | | | |_____ | \_/ | | | | |_/ / _____ | -// \ _____| |__| |________| \_______/ |__| |______/ (_______/ +// \ _____| |__| |________| \_______/ |__| |______/ (_______/ // -// This file is part of VirtualFluids. VirtualFluids is free software: you can +// This file is part of VirtualFluids. VirtualFluids is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of +// License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. -// -// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// +// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License along // with VirtualFluids (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>. // @@ -35,116 +35,120 @@ using namespace std; /*=======================================================*/ GbPoint3D::GbPoint3D() -{ - this->x1=0.0; - this->x2=0.0; - this->x3=0.0; -} +{ + this->x1 = 0.0; + this->x2 = 0.0; + this->x3 = 0.0; +} /*=======================================================*/ -GbPoint3D::GbPoint3D(const double& x1, const double& x2, const double& x3) -{ - this->x1=x1; - this->x2=x2; - this->x3=x3; +GbPoint3D::GbPoint3D(const double &x1, const double &x2, const double &x3) +{ + this->x1 = x1; + this->x2 = x2; + this->x3 = x3; } /*=======================================================*/ -GbPoint3D::GbPoint3D(GbPoint3D* point) +GbPoint3D::GbPoint3D(GbPoint3D *point) { - this->x1 = point->x1; - this->x2 = point->x2; - this->x3 = point->x3; -} + this->x1 = point->x1; + this->x2 = point->x2; + this->x3 = point->x3; +} /*=======================================================*/ -double GbPoint3D::getDistance(GbPoint3D* p) +double GbPoint3D::getDistance(GbPoint3D *p) { - double dx1 = this->x1 - p->x1; - double dx2 = this->x2 - p->x2; - double dx3 = this->x3 - p->x3; - return std::sqrt(dx1*dx1 + dx2*dx2 + dx3*dx3); + double dx1 = this->x1 - p->x1; + double dx2 = this->x2 - p->x2; + double dx3 = this->x3 - p->x3; + return std::sqrt(dx1 * dx1 + dx2 * dx2 + dx3 * dx3); } /*=======================================================*/ -bool GbPoint3D::equals(const GbPoint3D* point) const +bool GbPoint3D::equals(const GbPoint3D *point) const { - if(fabs(this->x1-point->x1)>1.E-10) return false; - if(fabs(this->x2-point->x2)>1.E-10) return false; - if(fabs(this->x3-point->x3)>1.E-10) return false; + if (fabs(this->x1 - point->x1) > 1.E-10) + return false; + if (fabs(this->x2 - point->x2) > 1.E-10) + return false; + if (fabs(this->x3 - point->x3) > 1.E-10) + return false; - return true; + return true; } /*=======================================================*/ void GbPoint3D::transform(const double matrix[4][4]) { - double tempX1 = x1; - double tempX2 = x2; - double tempX3 = x3; - x1 = matrix[0][0] * tempX1 + matrix[0][1] * tempX2 + matrix[0][2] * tempX3 + matrix[0][3] * 1.; - x2 = matrix[1][0] * tempX1 + matrix[1][1] * tempX2 + matrix[1][2] * tempX3 + matrix[1][3] * 1.; - x3 = matrix[2][0] * tempX1 + matrix[2][1] * tempX2 + matrix[2][2] * tempX3 + matrix[2][3] * 1.; + double tempX1 = x1; + double tempX2 = x2; + double tempX3 = x3; + x1 = matrix[0][0] * tempX1 + matrix[0][1] * tempX2 + matrix[0][2] * tempX3 + matrix[0][3] * 1.; + x2 = matrix[1][0] * tempX1 + matrix[1][1] * tempX2 + matrix[1][2] * tempX3 + matrix[1][3] * 1.; + x3 = matrix[2][0] * tempX1 + matrix[2][1] * tempX2 + matrix[2][2] * tempX3 + matrix[2][3] * 1.; } /*=======================================================*/ -bool GbPoint3D::isPointInGbObject3D(const double& x1, const double& x2, const double& x3) +bool GbPoint3D::isPointInGbObject3D(const double &x1, const double &x2, const double &x3) { - return (fabs(x1)<1.E-13 && fabs(x2)<1.E-13 && fabs(x3)<1.E-13 ); + return (fabs(x1) < 1.E-13 && fabs(x2) < 1.E-13 && fabs(x3) < 1.E-13); } /*=======================================================*/ -bool GbPoint3D::isPointInGbObject3D(const double& x1, const double& x2, const double& x3, bool& pointIsOnBoundary) +bool GbPoint3D::isPointInGbObject3D(const double &x1, const double &x2, const double &x3, bool &pointIsOnBoundary) { - pointIsOnBoundary = (fabs(x1)<1.E-13 && fabs(x2)<1.E-13 && fabs(x3)<1.E-13 ); - return pointIsOnBoundary; + pointIsOnBoundary = (fabs(x1) < 1.E-13 && fabs(x2) < 1.E-13 && fabs(x3) < 1.E-13); + return pointIsOnBoundary; } /*=======================================================*/ -vector<GbTriangle3D*> GbPoint3D::getSurfaceTriangleSet() -{ - cout<<"GbPoint3D::getSurfaceTriangleSet() - test ... if no exception occurs, everything is fine\n"; - vector<GbTriangle3D*> triangles; - return triangles; //<-empty vector! is okay! - - //old: - //to avoid unnecessary exceptions a point will generate a triangle with - //c3 point with same coordinates - //vector<GbTriangle3D*> triangles; - //GbPoint3D p1(getX1Coordinate(),getX2Coordinate(),getX3Coordinate()); - //triangles.push_back(new GbTriangle3D(new GbPoint3D(p1),new GbPoint3D(p1),new GbPoint3D(p1))); +vector<GbTriangle3D *> GbPoint3D::getSurfaceTriangleSet() +{ + cout << "GbPoint3D::getSurfaceTriangleSet() - test ... if no exception occurs, everything is fine\n"; + vector<GbTriangle3D *> triangles; + return triangles; //<-empty vector! is okay! + + // old: + // to avoid unnecessary exceptions a point will generate a triangle with + // c3 point with same coordinates + // vector<GbTriangle3D*> triangles; + // GbPoint3D p1(getX1Coordinate(),getX2Coordinate(),getX3Coordinate()); + // triangles.push_back(new GbTriangle3D(new GbPoint3D(p1),new GbPoint3D(p1),new GbPoint3D(p1))); } /*=======================================================*/ -GbLine3D* GbPoint3D::createClippedLine3D (GbPoint3D& /*point1*/, GbPoint3D& /*point2*/) +GbLine3D *GbPoint3D::createClippedLine3D(GbPoint3D & /*point1*/, GbPoint3D & /*point2*/) { - throw UbException(UB_EXARGS,"not implemented"); -} + throw UbException(UB_EXARGS, "not implemented"); +} /*=======================================================*/ string GbPoint3D::toString() { - stringstream ss; - ss<<"GbPoint3D["<<this->x1<<","<<this->x2<<","<<this->x3<<"]"; - return((ss.str()).c_str()); + stringstream ss; + ss << "GbPoint3D[" << this->x1 << "," << this->x2 << "," << this->x3 << "]"; + return ((ss.str()).c_str()); } /*=======================================================*/ -void GbPoint3D::translate(const double& dx1, const double& dx2, const double& dx3) -{ - this->x1 += dx1; - this->x2 += dx2; - this->x3 += dx3; - this->notifyObserversObjectChanged(); +void GbPoint3D::translate(const double &dx1, const double &dx2, const double &dx3) +{ + this->x1 += dx1; + this->x2 += dx2; + this->x3 += dx3; + this->notifyObserversObjectChanged(); } /*=======================================================*/ -void GbPoint3D::rotate(const double& rx1, const double& rx2, const double& rx3) -{ - double newX1 = cos(rx3)*cos(rx2)*x1-x2*sin(rx3)*cos(rx1)+x2*cos(rx3)*sin(rx2)*sin(rx1)+x3*sin(rx3)*sin(rx1)+x3*cos(rx3)*sin(rx2)*cos(rx1); - double newX2 = sin(rx3)*cos(rx2)*x1+x2*cos(rx3)*cos(rx1)+x2*sin(rx3)*sin(rx2)*sin(rx1)-x3*cos(rx3)*sin(rx1)+x3*sin(rx3)*sin(rx2)*cos(rx1); - double newX3 = -sin(rx2)*x1+cos(rx2)*sin(rx1)*x2+cos(rx2)*cos(rx1)*x3; +void GbPoint3D::rotate(const double &rx1, const double &rx2, const double &rx3) +{ + double newX1 = cos(rx3) * cos(rx2) * x1 - x2 * sin(rx3) * cos(rx1) + x2 * cos(rx3) * sin(rx2) * sin(rx1) + + x3 * sin(rx3) * sin(rx1) + x3 * cos(rx3) * sin(rx2) * cos(rx1); + double newX2 = sin(rx3) * cos(rx2) * x1 + x2 * cos(rx3) * cos(rx1) + x2 * sin(rx3) * sin(rx2) * sin(rx1) - + x3 * cos(rx3) * sin(rx1) + x3 * sin(rx3) * sin(rx2) * cos(rx1); + double newX3 = -sin(rx2) * x1 + cos(rx2) * sin(rx1) * x2 + cos(rx2) * cos(rx1) * x3; - this->x1 = newX1; - this->x2 = newX2; - this->x3 = newX3; - this->notifyObserversObjectChanged(); + this->x1 = newX1; + this->x2 = newX2; + this->x3 = newX3; + this->notifyObserversObjectChanged(); } /*=======================================================*/ -void GbPoint3D::scale(const double& sx1, const double& sx2, const double& sx3) -{ - this->x1 *= sx1; - this->x2 *= sx2; - this->x3 *= sx3; - this->notifyObserversObjectChanged(); +void GbPoint3D::scale(const double &sx1, const double &sx2, const double &sx3) +{ + this->x1 *= sx1; + this->x2 *= sx2; + this->x3 *= sx3; + this->notifyObserversObjectChanged(); } /*=======================================================*/ - diff --git a/src/basics/geometry3d/GbPoint3D.h b/src/basics/geometry3d/GbPoint3D.h index 68760d789b2271e999a94997f8557bab65c8adc5..ccb8a9ab64a971bf847db591d9d0c04d0abbfbb6 100644 --- a/src/basics/geometry3d/GbPoint3D.h +++ b/src/basics/geometry3d/GbPoint3D.h @@ -1,28 +1,28 @@ //======================================================================================= -// ____ ____ __ ______ __________ __ __ __ __ -// \ \ | | | | | _ \ |___ ___| | | | | / \ | | -// \ \ | | | | | |_) | | | | | | | / \ | | -// \ \ | | | | | _ / | | | | | | / /\ \ | | -// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ -// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| -// \ \ | | ________________________________________________________________ -// \ \ | | | ______________________________________________________________| -// \ \| | | | __ __ __ __ ______ _______ -// \ | | |_____ | | | | | | | | | _ \ / _____) -// \ | | _____| | | | | | | | | | | \ \ \_______ +// ____ ____ __ ______ __________ __ __ __ __ +// \ \ | | | | | _ \ |___ ___| | | | | / \ | | +// \ \ | | | | | |_) | | | | | | | / \ | | +// \ \ | | | | | _ / | | | | | | / /\ \ | | +// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ +// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| +// \ \ | | ________________________________________________________________ +// \ \ | | | ______________________________________________________________| +// \ \| | | | __ __ __ __ ______ _______ +// \ | | |_____ | | | | | | | | | _ \ / _____) +// \ | | _____| | | | | | | | | | | \ \ \_______ // \ | | | | |_____ | \_/ | | | | |_/ / _____ | -// \ _____| |__| |________| \_______/ |__| |______/ (_______/ +// \ _____| |__| |________| \_______/ |__| |______/ (_______/ // -// This file is part of VirtualFluids. VirtualFluids is free software: you can +// This file is part of VirtualFluids. VirtualFluids is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of +// License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. -// -// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// +// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License along // with VirtualFluids (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>. // @@ -33,9 +33,9 @@ #ifndef GBPOINT3D_H #define GBPOINT3D_H -#include <string> -#include <sstream> #include <cmath> +#include <sstream> +#include <string> #include <GbObject3D.h> @@ -47,63 +47,79 @@ class GbTriangle3D; class GbPoint3D : public GbObject3D { public: - GbPoint3D(); - GbPoint3D(const double& x1, const double& x2, const double& x3); - GbPoint3D(GbPoint3D *point); - ~GbPoint3D() override = default; - - GbPoint3D* clone() override {return new GbPoint3D(this);} - void finalize() override {} - - void setCoordinates(const double& x1, const double& x2, const double& x3) - { - this->x1=x1; - this->x2=x2; - this->x3=x3; - this->notifyObserversObjectChanged(); - } - void setX1(const double& x1) { this->x1=x1; this->notifyObserversObjectChanged(); } - void setX2(const double& x2) { this->x2=x2; this->notifyObserversObjectChanged(); } - void setX3(const double& x3) { this->x3=x3; this->notifyObserversObjectChanged(); } - - double getX1Coordinate() const { return this->x1; } - double getX2Coordinate() const { return this->x2; } - double getX3Coordinate() const { return this->x3; } - - void transform(const double matrix[4][4]); - - double getX1Centroid() override { return this->x1; } - double getX1Minimum() override { return this->x1; } - double getX1Maximum() override { return this->x1; } - double getX2Centroid() override { return this->x2; } - double getX2Minimum() override { return this->x2; } - double getX2Maximum() override { return this->x2; } - double getX3Centroid() override { return this->x3; } - double getX3Minimum() override { return this->x3; } - double getX3Maximum() override { return this->x3; } - - void translate(const double& x1, const double& x2, const double& x3) override; - void rotate(const double& rx1, const double& rx2, const double& rx3) override; - void scale(const double& sx1, const double& sx2, const double& sx3) override; - - double getDistance(GbPoint3D *p); - bool equals(const GbPoint3D* point) const; - bool isPointInGbObject3D(const double& x1, const double& x2, const double& x3, bool& pointIsOnBoundary) override; - bool isPointInGbObject3D(const double& x1, const double& x2, const double& x3) override; - bool isCellInsideGbObject3D(const double& /*x11*/,const double& /*x21*/,const double& /*x31*/,const double& /*x12*/,const double& /*x22*/,const double& /*x23*/) override { return false; } - - std::vector<GbTriangle3D*> getSurfaceTriangleSet() override; - GbLine3D* createClippedLine3D(GbPoint3D &point1, GbPoint3D &point2) override; - std::string toString() override; - - using GbObject3D::isPointInGbObject3D; //Grund: dadurch muss man hier isPointInGbObject3D(GbPoint3D*) nicht ausprogrammieren - //, welche sonst hier "ueberdeckt" waere,da es dieselbe methode mit anderen args gibt! - - //member - double x1; - double x2; - double x3; -}; + GbPoint3D(); + GbPoint3D(const double &x1, const double &x2, const double &x3); + GbPoint3D(GbPoint3D *point); + ~GbPoint3D() override = default; + + GbPoint3D *clone() override { return new GbPoint3D(this); } + void finalize() override {} + + void setCoordinates(const double &x1, const double &x2, const double &x3) + { + this->x1 = x1; + this->x2 = x2; + this->x3 = x3; + this->notifyObserversObjectChanged(); + } + void setX1(const double &x1) + { + this->x1 = x1; + this->notifyObserversObjectChanged(); + } + void setX2(const double &x2) + { + this->x2 = x2; + this->notifyObserversObjectChanged(); + } + void setX3(const double &x3) + { + this->x3 = x3; + this->notifyObserversObjectChanged(); + } + double getX1Coordinate() const { return this->x1; } + double getX2Coordinate() const { return this->x2; } + double getX3Coordinate() const { return this->x3; } + + void transform(const double matrix[4][4]); + + double getX1Centroid() override { return this->x1; } + double getX1Minimum() override { return this->x1; } + double getX1Maximum() override { return this->x1; } + double getX2Centroid() override { return this->x2; } + double getX2Minimum() override { return this->x2; } + double getX2Maximum() override { return this->x2; } + double getX3Centroid() override { return this->x3; } + double getX3Minimum() override { return this->x3; } + double getX3Maximum() override { return this->x3; } + + void translate(const double &x1, const double &x2, const double &x3) override; + void rotate(const double &rx1, const double &rx2, const double &rx3) override; + void scale(const double &sx1, const double &sx2, const double &sx3) override; + + double getDistance(GbPoint3D *p); + bool equals(const GbPoint3D *point) const; + bool isPointInGbObject3D(const double &x1, const double &x2, const double &x3, bool &pointIsOnBoundary) override; + bool isPointInGbObject3D(const double &x1, const double &x2, const double &x3) override; + bool isCellInsideGbObject3D(const double & /*x11*/, const double & /*x21*/, const double & /*x31*/, + const double & /*x12*/, const double & /*x22*/, const double & /*x23*/) override + { + return false; + } + + std::vector<GbTriangle3D *> getSurfaceTriangleSet() override; + GbLine3D *createClippedLine3D(GbPoint3D &point1, GbPoint3D &point2) override; + std::string toString() override; + + using GbObject3D::isPointInGbObject3D; // Grund: dadurch muss man hier isPointInGbObject3D(GbPoint3D*) nicht + // ausprogrammieren , welche sonst hier "ueberdeckt" waere,da es dieselbe + //methode mit anderen args gibt! + + // member + double x1; + double x2; + double x3; +}; #endif diff --git a/src/basics/geometry3d/GbPolygon3D.cpp b/src/basics/geometry3d/GbPolygon3D.cpp index 713ce56f072e7017066f7c5a9a1f922bf8d762cf..02138f75767420502d585842c7e05b9741df5b28 100644 --- a/src/basics/geometry3d/GbPolygon3D.cpp +++ b/src/basics/geometry3d/GbPolygon3D.cpp @@ -1,28 +1,28 @@ //======================================================================================= -// ____ ____ __ ______ __________ __ __ __ __ -// \ \ | | | | | _ \ |___ ___| | | | | / \ | | -// \ \ | | | | | |_) | | | | | | | / \ | | -// \ \ | | | | | _ / | | | | | | / /\ \ | | -// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ -// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| -// \ \ | | ________________________________________________________________ -// \ \ | | | ______________________________________________________________| -// \ \| | | | __ __ __ __ ______ _______ -// \ | | |_____ | | | | | | | | | _ \ / _____) -// \ | | _____| | | | | | | | | | | \ \ \_______ +// ____ ____ __ ______ __________ __ __ __ __ +// \ \ | | | | | _ \ |___ ___| | | | | / \ | | +// \ \ | | | | | |_) | | | | | | | / \ | | +// \ \ | | | | | _ / | | | | | | / /\ \ | | +// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ +// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| +// \ \ | | ________________________________________________________________ +// \ \ | | | ______________________________________________________________| +// \ \| | | | __ __ __ __ ______ _______ +// \ | | |_____ | | | | | | | | | _ \ / _____) +// \ | | _____| | | | | | | | | | | \ \ \_______ // \ | | | | |_____ | \_/ | | | | |_/ / _____ | -// \ _____| |__| |________| \_______/ |__| |______/ (_______/ +// \ _____| |__| |________| \_______/ |__| |______/ (_______/ // -// This file is part of VirtualFluids. VirtualFluids is free software: you can +// This file is part of VirtualFluids. VirtualFluids is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of +// License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. -// -// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// +// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License along // with VirtualFluids (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>. // @@ -38,319 +38,332 @@ int GbPolygon3D::counter = 0; GbPolygon3D::GbPolygon3D() { - init(); - counter++; - this->ps = new GbSystem3D::PointSet3(0); + init(); + counter++; + this->ps = new GbSystem3D::PointSet3(0); } void GbPolygon3D::init() { - x1s = 0.0; - x2s = 0.0; - x1min = 0.0; - x1max = 0.0; - x2min = 0.0; - x2max = 0.0; - // points = NULL; - consistent = false; - ps = NULL; + x1s = 0.0; + x2s = 0.0; + x1min = 0.0; + x1max = 0.0; + x2min = 0.0; + x2max = 0.0; + // points = NULL; + consistent = false; + ps = NULL; } /*! -* Creates an empty 3D polygon with the specified capacity. -* @param capacity the initial capacity -*/ + * Creates an empty 3D polygon with the specified capacity. + * @param capacity the initial capacity + */ GbPolygon3D::GbPolygon3D(int capacity) { - init(); - counter++; - this->ps = new GbSystem3D::PointSet3(capacity); - // this.po = new PointObserver(this); + init(); + counter++; + this->ps = new GbSystem3D::PointSet3(capacity); + // this.po = new PointObserver(this); } /** -* Creates a 3D polygon with the specified points. -* @param points the initial points of the polygon -*/ -GbPolygon3D::GbPolygon3D(vector<GbPoint3D>& points) + * Creates a 3D polygon with the specified points. + * @param points the initial points of the polygon + */ +GbPolygon3D::GbPolygon3D(vector<GbPoint3D> &points) { - init(); - counter++; - this->ps = new GbSystem3D::PointSet3((int)points.size()); - this->addPoints(points); + init(); + counter++; + this->ps = new GbSystem3D::PointSet3((int)points.size()); + this->addPoints(points); } /** -* Creates a 3D polygon as clone of the specified 3D polygon. -* @param polygon the 3D polygon to be cloned -*/ -GbPolygon3D::GbPolygon3D(GbPolygon3D* polygon) + * Creates a 3D polygon as clone of the specified 3D polygon. + * @param polygon the 3D polygon to be cloned + */ +GbPolygon3D::GbPolygon3D(GbPolygon3D *polygon) { - this->init(); - counter++; - this->ps = new GbSystem3D::PointSet3((int)polygon->size()); - vector<GbPoint3D> temp = polygon->getPoints(); - this->addPoints( temp ); + this->init(); + counter++; + this->ps = new GbSystem3D::PointSet3((int)polygon->size()); + vector<GbPoint3D> temp = polygon->getPoints(); + this->addPoints(temp); } GbPolygon3D::~GbPolygon3D() { - counter--; - //if(points) - //for(unsigned u=0; u<points->size(); u++) - //{ - // delete (*points)[u]; - //} - // delete this->points; - delete this->ps; + counter--; + // if(points) + // for(unsigned u=0; u<points->size(); u++) + //{ + // delete (*points)[u]; + //} + // delete this->points; + delete this->ps; } /*======================================================================*/ /** -* Returns the number of points. -* @return the number of points -*/ -int GbPolygon3D::size() -{ - return(this->ps->size()); -} + * Returns the number of points. + * @return the number of points + */ +int GbPolygon3D::size() { return (this->ps->size()); } /** -* Returns the number of times this 3D polygon contains the specified point. -* @param point the point -* @return the number of times this 3D polygon contains the specified point -*/ -int GbPolygon3D::contains(GbPoint3D* point) -{ - return(this->ps->contains(point)); -} + * Returns the number of times this 3D polygon contains the specified point. + * @param point the point + * @return the number of times this 3D polygon contains the specified point + */ +int GbPolygon3D::contains(GbPoint3D *point) { return (this->ps->contains(point)); } /** -* Returns the number of times this 3D polygon contains a point equal to the specified point. -* @param point the point -* @return the number of times this 3D polygon contains a point equal to the specified point -*/ -int GbPolygon3D::containsEqual(GbPoint3D* point) -{ - return(this->ps->containsEqual(point)); -} + * Returns the number of times this 3D polygon contains a point equal to the specified point. + * @param point the point + * @return the number of times this 3D polygon contains a point equal to the specified point + */ +int GbPolygon3D::containsEqual(GbPoint3D *point) { return (this->ps->containsEqual(point)); } /** -* Returns true, if this 3D polygon contains the specified line. -* @param point1 the first point -* @param point2 the second point -* @return true, if this 3D polygon contains the specified line -*/ -bool GbPolygon3D::containsLine(GbPoint3D* point1, GbPoint3D* point2) + * Returns true, if this 3D polygon contains the specified line. + * @param point1 the first point + * @param point2 the second point + * @return true, if this 3D polygon contains the specified line + */ +bool GbPolygon3D::containsLine(GbPoint3D *point1, GbPoint3D *point2) { - return(this->ps->containsLine(point1, point2)); + return (this->ps->containsLine(point1, point2)); } /** -* Returns true, if this 3D polygon contains the specified line. -* @param line the line -* @return true, if this 3D polygon contains the specified line -*/ -bool GbPolygon3D::containsLine(GbLine3D* line) + * Returns true, if this 3D polygon contains the specified line. + * @param line the line + * @return true, if this 3D polygon contains the specified line + */ +bool GbPolygon3D::containsLine(GbLine3D *line) { - return(this->ps->containsLine(line->getPoint1(), line->getPoint2())); + return (this->ps->containsLine(line->getPoint1(), line->getPoint2())); } /** -* Returns the first point. -* @return the first point -*/ -GbPoint3D* GbPolygon3D::getFirstPoint() -{ - return(this->ps->getFirstPoint()); -} + * Returns the first point. + * @return the first point + */ +GbPoint3D *GbPolygon3D::getFirstPoint() { return (this->ps->getFirstPoint()); } /** -* Returns the last point. -* @return the last point -*/ -GbPoint3D* GbPolygon3D::getLastPoint() -{ - return(this->ps->getLastPoint()); -} + * Returns the last point. + * @return the last point + */ +GbPoint3D *GbPolygon3D::getLastPoint() { return (this->ps->getLastPoint()); } /** -* Returns the specified point. -* @param index the index -* @return the specified point -* @exception ArrayIndexOutOfBoundsException if the specified index is not valid -*/ -GbPoint3D* GbPolygon3D::getPoint(const int& index) + * Returns the specified point. + * @param index the index + * @return the specified point + * @exception ArrayIndexOutOfBoundsException if the specified index is not valid + */ +GbPoint3D *GbPolygon3D::getPoint(const int &index) { - if(index < 0 || index > this->ps->size()) throw UbException(UB_EXARGS,"ArrayIndexOutOfBoundsException-GbPolygon3D.getPoint()"); - return(this->ps->getPoint(index)); + if (index < 0 || index > this->ps->size()) + throw UbException(UB_EXARGS, "ArrayIndexOutOfBoundsException-GbPolygon3D.getPoint()"); + return (this->ps->getPoint(index)); } /** -* Returns the points. -* @return the points -*/ + * Returns the points. + * @return the points + */ vector<GbPoint3D> GbPolygon3D::getPoints() { - if(!this->consistent) this->calculateValues(); - return(this->points); + if (!this->consistent) + this->calculateValues(); + return (this->points); } /** -* Returns the points within the specified rectangle. -* @param p1 the 1st point of the rectangle -* @param p2 the 2nd point of the rectangle -* @return the points within the specified rectangle -*/ -vector<GbPoint3D> GbPolygon3D::getPoints(GbPoint3D* p1, GbPoint3D* p2) + * Returns the points within the specified rectangle. + * @param p1 the 1st point of the rectangle + * @param p2 the 2nd point of the rectangle + * @return the points within the specified rectangle + */ +vector<GbPoint3D> GbPolygon3D::getPoints(GbPoint3D *p1, GbPoint3D *p2) { - return(this->getPoints(p1->x1, p1->x2, p1->x3, p2->x1, p2->x2, p2->x3)); + return (this->getPoints(p1->x1, p1->x2, p1->x3, p2->x1, p2->x2, p2->x3)); } /** -* Returns the points within the specified rectangle. -* @param p1x1 the 1st x1 coordinate of the rectangle -* @param p1x2 the 1st x2 coordinate of the rectangle -* @param p1x3 the 1st x3 coordinate of the rectangle -* @param p2x1 the 2nd x1 coordinate of the rectangle -* @param p2x2 the 2nd x2 coordinate of the rectangle -* @param p2x3 the 2nd x3 coordinate of the rectangle -* @return the points within the specified rectangle -*/ -vector<GbPoint3D> GbPolygon3D::getPoints(const double& p1x1, const double& p1x2, const double& p1x3, const double& p2x1, const double& p2x2, const double& p2x3) + * Returns the points within the specified rectangle. + * @param p1x1 the 1st x1 coordinate of the rectangle + * @param p1x2 the 1st x2 coordinate of the rectangle + * @param p1x3 the 1st x3 coordinate of the rectangle + * @param p2x1 the 2nd x1 coordinate of the rectangle + * @param p2x2 the 2nd x2 coordinate of the rectangle + * @param p2x3 the 2nd x3 coordinate of the rectangle + * @return the points within the specified rectangle + */ +vector<GbPoint3D> GbPolygon3D::getPoints(const double &p1x1, const double &p1x2, const double &p1x3, const double &p2x1, + const double &p2x2, const double &p2x3) { - double x1min, x1max, x2min, x2max, x3min, x3max; + double x1min, x1max, x2min, x2max, x3min, x3max; - if(UbMath::less(p1x1, p2x1)) { x1min = p1x1; x1max = p2x1; } - else { x1min = p2x1; x1max = p1x1; } - if(UbMath::less(p1x2, p2x2)) { x2min = p1x2; x2max = p2x2; } - else { x2min = p2x2; x2max = p1x2; } - if(UbMath::less(p1x3, p2x3)) { x3min = p1x3; x3max = p2x3; } - else { x3min = p2x3; x3max = p1x3; } + if (UbMath::less(p1x1, p2x1)) { + x1min = p1x1; + x1max = p2x1; + } else { + x1min = p2x1; + x1max = p1x1; + } + if (UbMath::less(p1x2, p2x2)) { + x2min = p1x2; + x2max = p2x2; + } else { + x2min = p2x2; + x2max = p1x2; + } + if (UbMath::less(p1x3, p2x3)) { + x3min = p1x3; + x3max = p2x3; + } else { + x3min = p2x3; + x3max = p1x3; + } - GbSystem3D::PointSet3 *pts = new GbSystem3D::PointSet3(1); + GbSystem3D::PointSet3 *pts = new GbSystem3D::PointSet3(1); - if(!this->consistent) this->calculateValues(); - for(int i=this->size()-1; i>=0; i--) - { - if(UbMath::lessEqual(x1min, (this->points)[i].x1) && UbMath::greaterEqual(x1max, (this->points)[i].x1) && - UbMath::lessEqual(x2min, (this->points)[i].x2) && UbMath::greaterEqual(x2max, (this->points)[i].x2) && - UbMath::lessEqual(x3min, (this->points)[i].x3) && UbMath::greaterEqual(x3max, (this->points)[i].x3)) pts->add((this->points)[i]); - } - return(pts->getPoints()); + if (!this->consistent) + this->calculateValues(); + for (int i = this->size() - 1; i >= 0; i--) { + if (UbMath::lessEqual(x1min, (this->points)[i].x1) && UbMath::greaterEqual(x1max, (this->points)[i].x1) && + UbMath::lessEqual(x2min, (this->points)[i].x2) && UbMath::greaterEqual(x2max, (this->points)[i].x2) && + UbMath::lessEqual(x3min, (this->points)[i].x3) && UbMath::greaterEqual(x3max, (this->points)[i].x3)) + pts->add((this->points)[i]); + } + return (pts->getPoints()); } /** -* Returns the area of this polygon. -* The area is positive for positive ordered points, otherwise negative. -* @return the area of this polygon -*/ -//double getArea() + * Returns the area of this polygon. + * The area is positive for positive ordered points, otherwise negative. + * @return the area of this polygon + */ +// double getArea() //{ // if(!this.consistent) this.calculateValues(); // return(this.area); //} double GbPolygon3D::getX1Centroid() { - if(!this->consistent) this->calculateValues(); - return(this->x1s); + if (!this->consistent) + this->calculateValues(); + return (this->x1s); } double GbPolygon3D::getX1Minimum() { - if(!this->consistent) this->calculateValues(); - return(this->x1min); + if (!this->consistent) + this->calculateValues(); + return (this->x1min); } double GbPolygon3D::getX1Maximum() { - if(!this->consistent) this->calculateValues(); - return(this->x1max); + if (!this->consistent) + this->calculateValues(); + return (this->x1max); } double GbPolygon3D::getX2Centroid() { - if(!this->consistent) this->calculateValues(); - return(this->x2s); + if (!this->consistent) + this->calculateValues(); + return (this->x2s); } double GbPolygon3D::getX2Minimum() { - if(!this->consistent) this->calculateValues(); - return(this->x2min); + if (!this->consistent) + this->calculateValues(); + return (this->x2min); } double GbPolygon3D::getX2Maximum() { - if(!this->consistent) this->calculateValues(); - return(this->x2max); + if (!this->consistent) + this->calculateValues(); + return (this->x2max); } double GbPolygon3D::getX3Centroid() { - if(!this->consistent) this->calculateValues(); - return(this->x3s); + if (!this->consistent) + this->calculateValues(); + return (this->x3s); } double GbPolygon3D::getX3Minimum() { - if(!this->consistent) this->calculateValues(); - return(this->x3min); + if (!this->consistent) + this->calculateValues(); + return (this->x3min); } double GbPolygon3D::getX3Maximum() { - if(!this->consistent) this->calculateValues(); - return(this->x3max); + if (!this->consistent) + this->calculateValues(); + return (this->x3max); } /** -* Adds a point to the end of this polygon. Notifies the observers of this 3D polygon. -* @param point the point -*/ -void GbPolygon3D::addPoint(GbPoint3D* point) + * Adds a point to the end of this polygon. Notifies the observers of this 3D polygon. + * @param point the point + */ +void GbPolygon3D::addPoint(GbPoint3D *point) { - //if((this instanceof GbPolygon3D) && !(point instanceof GbPoint3D)) throw new IllegalArgumentException("GbPolygon3D.addPoint(): points of 3D polygons have to be 3D points!"); + // if((this instanceof GbPolygon3D) && !(point instanceof GbPoint3D)) throw new + // IllegalArgumentException("GbPolygon3D.addPoint(): points of 3D polygons have to be 3D points!"); - this->ps->add(point); - //point.addObserver(this.po); - this->consistent = false; - //super.notifyObservers(); + this->ps->add(point); + // point.addObserver(this.po); + this->consistent = false; + // super.notifyObservers(); } /** -* Adds a number of points to the end of this polygon. Notifies the observers of this 3D polygon. -* @param points the points -*/ -void GbPolygon3D::addPoints(vector<GbPoint3D>& points) + * Adds a number of points to the end of this polygon. Notifies the observers of this 3D polygon. + * @param points the points + */ +void GbPolygon3D::addPoints(vector<GbPoint3D> &points) { - //if((this instanceof GbPolygon3D) && (points.getClass().getComponentType() != GbPoint3D.class)) throw new IllegalArgumentException("GbPolygon3D.addPoints(): points of 3D polygons have to be 3D points!"); + // if((this instanceof GbPolygon3D) && (points.getClass().getComponentType() != GbPoint3D.class)) throw new + // IllegalArgumentException("GbPolygon3D.addPoints(): points of 3D polygons have to be 3D points!"); - this->ps->add(points); - //for(int i=0; i<points.length; i++) points[i].addObserver(this.po); - this->consistent = false; - //super.notifyObservers(); + this->ps->add(points); + // for(int i=0; i<points.length; i++) points[i].addObserver(this.po); + this->consistent = false; + // super.notifyObservers(); } /** -* Removes all points from this polygon. Notifies the observers of this 3D polygon. -*/ + * Removes all points from this polygon. Notifies the observers of this 3D polygon. + */ void GbPolygon3D::clear() { - // delete this->points; - this->ps->clearAndTrim(); - delete this->ps; + // delete this->points; + this->ps->clearAndTrim(); + delete this->ps; - //for(int i=points.length-1; i>=0; i--) points[i].removeObserver(this.po); - this->consistent = false; - //super.notifyObservers(); + // for(int i=points.length-1; i>=0; i--) points[i].removeObserver(this.po); + this->consistent = false; + // super.notifyObservers(); } /** -* Returns a string representation of this 3D polygon. -* @return a string representation of this 3D polygon -*/ + * Returns a string representation of this 3D polygon. + * @return a string representation of this 3D polygon + */ string GbPolygon3D::toString() { - stringstream ss; - ss<<"GbPolygon3D["; - ss<<this->size()<<" points"; - ss<<"]"<<endl; - for(int u=0; u<this->size(); u++) - ss<<this->ps->getPoint(u)->toString()<<endl; + stringstream ss; + ss << "GbPolygon3D["; + ss << this->size() << " points"; + ss << "]" << endl; + for (int u = 0; u < this->size(); u++) + ss << this->ps->getPoint(u)->toString() << endl; - return(ss.str()); + return (ss.str()); } /*======================================================================*/ void GbPolygon3D::calculateValues() { - this->x1s = 0.0; - this->x2s = 0.0; - this->x3s = 0.0; - this->x1min = 0.0; - this->x1max = 0.0; - this->x2min = 0.0; - this->x2max = 0.0; - this->x3min = 0.0; - this->x3max = 0.0; - throw UbException(UB_EXARGS,"should be implemented"); + this->x1s = 0.0; + this->x2s = 0.0; + this->x3s = 0.0; + this->x1min = 0.0; + this->x1max = 0.0; + this->x2min = 0.0; + this->x2max = 0.0; + this->x3min = 0.0; + this->x3max = 0.0; + throw UbException(UB_EXARGS, "should be implemented"); } /*======================================================================*/ - - diff --git a/src/basics/geometry3d/GbPolygon3D.h b/src/basics/geometry3d/GbPolygon3D.h index 279b8bdb81c9460b9c3f35291652e1fc4900ff89..e4f44b5be5d31e3751be584c6623597229df5cd2 100644 --- a/src/basics/geometry3d/GbPolygon3D.h +++ b/src/basics/geometry3d/GbPolygon3D.h @@ -1,28 +1,28 @@ //======================================================================================= -// ____ ____ __ ______ __________ __ __ __ __ -// \ \ | | | | | _ \ |___ ___| | | | | / \ | | -// \ \ | | | | | |_) | | | | | | | / \ | | -// \ \ | | | | | _ / | | | | | | / /\ \ | | -// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ -// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| -// \ \ | | ________________________________________________________________ -// \ \ | | | ______________________________________________________________| -// \ \| | | | __ __ __ __ ______ _______ -// \ | | |_____ | | | | | | | | | _ \ / _____) -// \ | | _____| | | | | | | | | | | \ \ \_______ +// ____ ____ __ ______ __________ __ __ __ __ +// \ \ | | | | | _ \ |___ ___| | | | | / \ | | +// \ \ | | | | | |_) | | | | | | | / \ | | +// \ \ | | | | | _ / | | | | | | / /\ \ | | +// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ +// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| +// \ \ | | ________________________________________________________________ +// \ \ | | | ______________________________________________________________| +// \ \| | | | __ __ __ __ ______ _______ +// \ | | |_____ | | | | | | | | | _ \ / _____) +// \ | | _____| | | | | | | | | | | \ \ \_______ // \ | | | | |_____ | \_/ | | | | |_/ / _____ | -// \ _____| |__| |________| \_______/ |__| |______/ (_______/ +// \ _____| |__| |________| \_______/ |__| |______/ (_______/ // -// This file is part of VirtualFluids. VirtualFluids is free software: you can +// This file is part of VirtualFluids. VirtualFluids is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of +// License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. -// -// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// +// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License along // with VirtualFluids (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>. // @@ -33,254 +33,248 @@ #ifndef GBPOLYGON3D_H #define GBPOLYGON3D_H -#include <sstream> #include <iostream> +#include <sstream> - -#include <GbObject3D.h> #include <GbLine3D.h> -#include <GbTriangle3D.h> +#include <GbObject3D.h> #include <GbSystem3D.h> +#include <GbTriangle3D.h> #include <PointerDefinitions.h> - /*=========================================================================*/ -//! \class GbPolygon2D +//! \class GbPolygon2D /* */ //! \brief This Class provides basic 3D polygon objects. class GbPolygon3D : public GbObject3D { public: - using GbObject3D::isPointInGbObject3D; //Grund: dadurch muss man hier isPointInGbObject3D(GbPoint3D*) nicht ausprogrammieren, welche sonst hier "ueberdeckt" waere + using GbObject3D::isPointInGbObject3D; // Grund: dadurch muss man hier isPointInGbObject3D(GbPoint3D*) nicht + // ausprogrammieren, welche sonst hier "ueberdeckt" waere private: - /*======================================================================*/ - double x1s ; - double x2s ; - double x3s ; - double x1min; - double x1max; - double x2min; - double x2max; - double x3min; - double x3max; - - std::vector<GbPoint3D> points; - bool consistent; + /*======================================================================*/ + double x1s; + double x2s; + double x3s; + double x1min; + double x1max; + double x2min; + double x2max; + double x3min; + double x3max; - GbSystem3D::PointSet3 *ps; - //private PointObserver po = null; + std::vector<GbPoint3D> points; + bool consistent; - void init(); + GbSystem3D::PointSet3 *ps; + // private PointObserver po = null; - /*======================================================================*/ + void init(); + /*======================================================================*/ - /*======================================================================*/ - /* Construcrors */ - /* */ - /* - * Creates an empty 2D polygon. - */ + /*======================================================================*/ + /* Construcrors */ + /* */ + /* + * Creates an empty 2D polygon. + */ public: - static int counter; - GbPolygon3D(); - /* - * Creates an empty 2D polygon with the specified capacity. - * @param capacity the initial capacity - */ - GbPolygon3D(int capacity); - /* - * Creates a 2D polygon with the specified points. - * @param points the initial points of the polygon - */ - GbPolygon3D(std::vector<GbPoint3D> &points); - /* - * Creates a 2D polygon as clone of the specified 2D polygon. - * @param polygon the 2D polygon to be cloned - */ - GbPolygon3D(GbPolygon3D *polygon); - - ~GbPolygon3D() override; + static int counter; + GbPolygon3D(); + /* + * Creates an empty 2D polygon with the specified capacity. + * @param capacity the initial capacity + */ + GbPolygon3D(int capacity); + /* + * Creates a 2D polygon with the specified points. + * @param points the initial points of the polygon + */ + GbPolygon3D(std::vector<GbPoint3D> &points); + /* + * Creates a 2D polygon as clone of the specified 2D polygon. + * @param polygon the 2D polygon to be cloned + */ + GbPolygon3D(GbPolygon3D *polygon); - /*======================================================================*/ + ~GbPolygon3D() override; + /*======================================================================*/ - /*======================================================================*/ - /* Methoden */ - /* */ - /* - * Creates a 2D polygon as clone of this 2D polygon. - */ - GbPolygon3D* clone() override { return(new GbPolygon3D(this)); } - void finalize() override - { - throw UbException(UB_EXARGS,"toDo"); - } + /*======================================================================*/ + /* Methoden */ + /* */ + /* + * Creates a 2D polygon as clone of this 2D polygon. + */ + GbPolygon3D *clone() override { return (new GbPolygon3D(this)); } + void finalize() override { throw UbException(UB_EXARGS, "toDo"); } - /* - * Returns the number of points. - * @return the number of points - */ - int size(); - /* - * Returns the number of times this 2D polygon contains the specified point. - * @param point the point - * @return the number of times this 2D polygon contains the specified point - */ - int contains(GbPoint3D *point); - /* - * Returns the number of times this 2D polygon contains a point equal to the specified point. - * @param point the point - * @return the number of times this 2D polygon contains a point equal to the specified point - */ - int containsEqual(GbPoint3D* point); - /* - * Returns true, if this 2D polygon contains the specified line. - * @param point1 the first point - * @param point2 the second point - * @return true, if this 2D polygon contains the specified line - */ - bool containsLine(GbPoint3D* point1, GbPoint3D* point2); - /* - * Returns true, if this 2D polygon contains the specified line. - * @param line the line - * @return true, if this 2D polygon contains the specified line - */ - bool containsLine(GbLine3D* line); - /* - * Returns the first point. - * @return the first point - */ - GbPoint3D* getFirstPoint(); - /* - * Returns the last point. - * @return the last point - */ - GbPoint3D* getLastPoint(); - /* - * Returns the specified point. - * @param index the index - * @return the specified point - * @exception ArrayIndexOutOfBoundsException if the specified index is not valid - */ - GbPoint3D* getPoint(const int& index); - /* - * Returns the points. - * @return the points - */ - std::vector<GbPoint3D> getPoints(); - /* - * Returns the points within the specified rectangle. - * @param p1 the 1st point of the rectangle - * @param p2 the 2nd point of the rectangle - * @return the points within the specified rectangle - */ - std::vector<GbPoint3D> getPoints(GbPoint3D* p1, GbPoint3D* p2); - /* - * Returns the points within the specified rectangle. - * @param p1x1 the 1st x1 coordinate of the rectangle - * @param p1x2 the 1st x2 coordinate of the rectangle - * @param p2x1 the 2nd x1 coordinate of the rectangle - * @param p2x2 the 2nd x2 coordinate of the rectangle - * @return the points within the specified rectangle - */ - std::vector<GbPoint3D> getPoints(const double& p1x1, const double& p1x2, const double& p1x3, const double& p2x1, const double& p2x2, const double& p2x3); - /* - * Returns the area of this polygon. - * The area is positive for positive ordered points, otherwise negative. - * @return the area of this polygon - */ - //double getArea() - //{ - // if(!this.consistent) this.calculateValues(); - // return(this.area); - //} - double getX1Centroid() override; - double getX1Minimum() override; - double getX1Maximum() override; - double getX2Centroid() override; - double getX2Minimum() override; - double getX2Maximum() override; - double getX3Centroid() override; - double getX3Minimum() override; - double getX3Maximum() override; + /* + * Returns the number of points. + * @return the number of points + */ + int size(); + /* + * Returns the number of times this 2D polygon contains the specified point. + * @param point the point + * @return the number of times this 2D polygon contains the specified point + */ + int contains(GbPoint3D *point); + /* + * Returns the number of times this 2D polygon contains a point equal to the specified point. + * @param point the point + * @return the number of times this 2D polygon contains a point equal to the specified point + */ + int containsEqual(GbPoint3D *point); + /* + * Returns true, if this 2D polygon contains the specified line. + * @param point1 the first point + * @param point2 the second point + * @return true, if this 2D polygon contains the specified line + */ + bool containsLine(GbPoint3D *point1, GbPoint3D *point2); + /* + * Returns true, if this 2D polygon contains the specified line. + * @param line the line + * @return true, if this 2D polygon contains the specified line + */ + bool containsLine(GbLine3D *line); + /* + * Returns the first point. + * @return the first point + */ + GbPoint3D *getFirstPoint(); + /* + * Returns the last point. + * @return the last point + */ + GbPoint3D *getLastPoint(); + /* + * Returns the specified point. + * @param index the index + * @return the specified point + * @exception ArrayIndexOutOfBoundsException if the specified index is not valid + */ + GbPoint3D *getPoint(const int &index); + /* + * Returns the points. + * @return the points + */ + std::vector<GbPoint3D> getPoints(); + /* + * Returns the points within the specified rectangle. + * @param p1 the 1st point of the rectangle + * @param p2 the 2nd point of the rectangle + * @return the points within the specified rectangle + */ + std::vector<GbPoint3D> getPoints(GbPoint3D *p1, GbPoint3D *p2); + /* + * Returns the points within the specified rectangle. + * @param p1x1 the 1st x1 coordinate of the rectangle + * @param p1x2 the 1st x2 coordinate of the rectangle + * @param p2x1 the 2nd x1 coordinate of the rectangle + * @param p2x2 the 2nd x2 coordinate of the rectangle + * @return the points within the specified rectangle + */ + std::vector<GbPoint3D> getPoints(const double &p1x1, const double &p1x2, const double &p1x3, const double &p2x1, + const double &p2x2, const double &p2x3); + /* + * Returns the area of this polygon. + * The area is positive for positive ordered points, otherwise negative. + * @return the area of this polygon + */ + // double getArea() + //{ + // if(!this.consistent) this.calculateValues(); + // return(this.area); + //} + double getX1Centroid() override; + double getX1Minimum() override; + double getX1Maximum() override; + double getX2Centroid() override; + double getX2Minimum() override; + double getX2Maximum() override; + double getX3Centroid() override; + double getX3Minimum() override; + double getX3Maximum() override; - /* - * Adds a point to the end of this polygon. Notifies the observers of this 2D polygon. - * @param point the point - */ - void addPoint(GbPoint3D* point); - /* - * Adds a number of points to the end of this polygon. Notifies the observers of this 2D polygon. - * @param points the points - */ - void addPoints(std::vector<GbPoint3D>& points); - /* - * Removes all points from this polygon. Notifies the observers of this 2D polygon. - */ - void clear(); + /* + * Adds a point to the end of this polygon. Notifies the observers of this 2D polygon. + * @param point the point + */ + void addPoint(GbPoint3D *point); + /* + * Adds a number of points to the end of this polygon. Notifies the observers of this 2D polygon. + * @param points the points + */ + void addPoints(std::vector<GbPoint3D> &points); + /* + * Removes all points from this polygon. Notifies the observers of this 2D polygon. + */ + void clear(); - /* - * Returns true if this 2D polygon equals the specified object. - * Two polygon are equal, if their points are equal. - * <BR>Note that the order of points is recognized! - * @return true if this 2D polygon equals the specified object - * @see GbPoint2D#equals(java.lang.Object) - * @see GbPoint3D#equals(java.lang.Object) - */ - // bool equals(Object object) - // { - // try - // { - // GbPolygon2D polygon = (GbPolygon2D) object; - //int n = this.size(); + /* + * Returns true if this 2D polygon equals the specified object. + * Two polygon are equal, if their points are equal. + * <BR>Note that the order of points is recognized! + * @return true if this 2D polygon equals the specified object + * @see GbPoint2D#equals(java.lang.Object) + * @see GbPoint3D#equals(java.lang.Object) + */ + // bool equals(Object object) + // { + // try + // { + // GbPolygon2D polygon = (GbPolygon2D) object; + // int n = this.size(); - //if(n != polygon.size()) return(false); - //for(int i=0; i<n; i++) if(!this.getPoint(i).equals(polygon.getPoint(i))) return(false); - //return(true); - // } - // catch(Exception e){ return(false); } - // } - std::vector<GbTriangle3D*> getSurfaceTriangleSet() override - { - std::cout<<"GbPolygon3D::getSurfaceTriangleSet() - not implemented\n"; - std::vector<GbTriangle3D*> tmp; - return tmp; - } - bool isPointInGbObject3D(const double& /*x1*/, const double& /*x2*/, const double& /*x3*/) override - { - throw UbException(__FILE__, __LINE__, "GbPolygon3D::isPointInObject3D- not implemented"); - } - bool isPointInGbObject3D(const double& /*x1*/, const double& /*x2*/, const double& /*x3*/, bool& /*pointIsOnBoundary*/) override - { - throw UbException(__FILE__, __LINE__, "GbPolygon3D::isPointInObject3D- not implemented"); - } - bool isCellInsideGbObject3D(const double& /*x1a*/,const double& /*x2a*/,const double& /*x3a*/,const double& /*x1b*/,const double& /*x2b*/,const double& /*x3b*/) override { return false; } + // if(n != polygon.size()) return(false); + // for(int i=0; i<n; i++) if(!this.getPoint(i).equals(polygon.getPoint(i))) return(false); + // return(true); + // } + // catch(Exception e){ return(false); } + // } + std::vector<GbTriangle3D *> getSurfaceTriangleSet() override + { + std::cout << "GbPolygon3D::getSurfaceTriangleSet() - not implemented\n"; + std::vector<GbTriangle3D *> tmp; + return tmp; + } + bool isPointInGbObject3D(const double & /*x1*/, const double & /*x2*/, const double & /*x3*/) override + { + throw UbException(__FILE__, __LINE__, "GbPolygon3D::isPointInObject3D- not implemented"); + } + bool isPointInGbObject3D(const double & /*x1*/, const double & /*x2*/, const double & /*x3*/, + bool & /*pointIsOnBoundary*/) override + { + throw UbException(__FILE__, __LINE__, "GbPolygon3D::isPointInObject3D- not implemented"); + } + bool isCellInsideGbObject3D(const double & /*x1a*/, const double & /*x2a*/, const double & /*x3a*/, + const double & /*x1b*/, const double & /*x2b*/, const double & /*x3b*/) override + { + return false; + } - GbLine3D* createClippedLine3D (GbPoint3D& /*point1*/, GbPoint3D & /*point2*/) override - { - throw UbException(__FILE__, __LINE__, "GbPolygon3D::createClippedLine3D - not implemented"); - } + GbLine3D *createClippedLine3D(GbPoint3D & /*point1*/, GbPoint3D & /*point2*/) override + { + throw UbException(__FILE__, __LINE__, "GbPolygon3D::createClippedLine3D - not implemented"); + } -/* - * Returns a string representation of this 2D polygon. - * @return a string representation of this 2D polygon - */ - std::string toString() override; + /* + * Returns a string representation of this 2D polygon. + * @return a string representation of this 2D polygon + */ + std::string toString() override; - /*======================================================================*/ - /* Private Methoden */ - /* */ - void calculateValues(); - /*======================================================================*/ + /*======================================================================*/ + /* Private Methoden */ + /* */ + void calculateValues(); + /*======================================================================*/ }; /*=========================================================================*/ #endif - - - - - - diff --git a/src/basics/geometry3d/GbQuadFaceMesh3D.cpp b/src/basics/geometry3d/GbQuadFaceMesh3D.cpp index 8c7ccb1a076555732e147b150afd7c3c93f9d3f6..e525d710e6bf9f6d44fcb57a41ea7579e0667dd4 100644 --- a/src/basics/geometry3d/GbQuadFaceMesh3D.cpp +++ b/src/basics/geometry3d/GbQuadFaceMesh3D.cpp @@ -1,101 +1,102 @@ #include <geometry3d/GbQuadFaceMesh3D.h> -#include <geometry3d/GbHalfSpace3D.h> #include <geometry3d/GbCuboid3D.h> +#include <geometry3d/GbHalfSpace3D.h> - using namespace std; GbQuadFaceMesh3D::GbQuadFaceMesh3D() : GbObject3D() { - this->name = "new GbMesh"; - this->nodes = new vector<Vertex>; - this->quads = new vector<QuadFace>; - this->consistent = false; + this->name = "new GbMesh"; + this->nodes = new vector<Vertex>; + this->quads = new vector<QuadFace>; + this->consistent = false; } GbQuadFaceMesh3D::GbQuadFaceMesh3D(string name, vector<Vertex> *nodes, vector<QuadFace> *quads) : GbObject3D() { - if(name.size()==0 ) throw UbException(UB_EXARGS,"no name specified"); - if(!nodes ) throw UbException(UB_EXARGS,"no nodes specified"); - if(!quads ) throw UbException(UB_EXARGS,"no quads specified"); - - this->name = name; - this->nodes = nodes; - this->quads = quads; - this->consistent = false; + if (name.size() == 0) + throw UbException(UB_EXARGS, "no name specified"); + if (!nodes) + throw UbException(UB_EXARGS, "no nodes specified"); + if (!quads) + throw UbException(UB_EXARGS, "no quads specified"); + + this->name = name; + this->nodes = nodes; + this->quads = quads; + this->consistent = false; } /*=============================================================================================*/ GbQuadFaceMesh3D::~GbQuadFaceMesh3D() { - if(nodes) - { - // for(unsigned u=0; u<nodes->size(); u++) delete (*nodes)[u]; - delete nodes; - } - if(quads) - { - delete quads; - } + if (nodes) { + // for(unsigned u=0; u<nodes->size(); u++) delete (*nodes)[u]; + delete nodes; + } + if (quads) { + delete quads; + } } /*======================================================================*/ void GbQuadFaceMesh3D::init() { - nodes = NULL; - quads = NULL; - x1min = 0.0; - x1max = 0.0; - x2min = 0.0; - x2max = 0.0; - x3min = 0.0; - x3max = 0.0; - consistent = false; -} - /** - * Returns a string representation of this triangular mesh. - * @return a string representation of this triangular mesh - */ + nodes = NULL; + quads = NULL; + x1min = 0.0; + x1max = 0.0; + x2min = 0.0; + x2max = 0.0; + x3min = 0.0; + x3max = 0.0; + consistent = false; +} +/** + * Returns a string representation of this triangular mesh. + * @return a string representation of this triangular mesh + */ string GbQuadFaceMesh3D::toString() { - stringstream ss; - ss<<"GbQuadFaceMesh3D["; - ss<<(int)this->quads->size()<<"-Quadangles, "<<(int)this->nodes->size()<<"-Nodes, "<<endl; - //ss<<"\""<<this->name<<", Area=sollt mal berechnet werden ;-)"<<"\""; - //ss<<", x1min="<<this->x1min; - //ss<<", x1max="<<this->x1max; - //ss<<", x2min="<<this->x2min; - //ss<<", x2max="<<this->x2max; - //ss<<", x3min="<<this->x3min; - //ss<<", x3max="<<this->x3max; - ss<<"]"; - return(ss.str()); + stringstream ss; + ss << "GbQuadFaceMesh3D["; + ss << (int)this->quads->size() << "-Quadangles, " << (int)this->nodes->size() << "-Nodes, " << endl; + // ss<<"\""<<this->name<<", Area=sollt mal berechnet werden ;-)"<<"\""; + // ss<<", x1min="<<this->x1min; + // ss<<", x1max="<<this->x1max; + // ss<<", x2min="<<this->x2min; + // ss<<", x2max="<<this->x2max; + // ss<<", x3min="<<this->x3min; + // ss<<", x3max="<<this->x3max; + ss << "]"; + return (ss.str()); } /** * Returns the name of this triangular mesh. * @return the name of this triangular mesh */ -string GbQuadFaceMesh3D::getName(){ return(this->name); } +string GbQuadFaceMesh3D::getName() { return (this->name); } /** * Returns the nodes of this triangular mesh. * @return the nodes of this triangular mesh */ -vector<GbQuadFaceMesh3D::Vertex>* GbQuadFaceMesh3D::getNodes() { return(this->nodes); } +vector<GbQuadFaceMesh3D::Vertex> *GbQuadFaceMesh3D::getNodes() { return (this->nodes); } /** * Returns the quads of this triangular mesh. * @return the quads of this triangular mesh */ -vector<GbQuadFaceMesh3D::QuadFace>* GbQuadFaceMesh3D::getQuads() { return(this->quads); } +vector<GbQuadFaceMesh3D::QuadFace> *GbQuadFaceMesh3D::getQuads() { return (this->quads); } /** * Returns the center x1 coordinate of this triangular mesh. * @return the center x1 coordinate of this triangular mesh */ double GbQuadFaceMesh3D::getX1Centroid() { - if(!this->consistent) this->calculateValues(); - return(0.5*(this->x1min+this->x1max)); + if (!this->consistent) + this->calculateValues(); + return (0.5 * (this->x1min + this->x1max)); } /** * Returns the center x2 coordinate of this triangular mesh. @@ -103,17 +104,19 @@ double GbQuadFaceMesh3D::getX1Centroid() */ double GbQuadFaceMesh3D::getX2Centroid() { - if(!this->consistent) this->calculateValues(); - return(0.5*(this->x2min+this->x2max)); + if (!this->consistent) + this->calculateValues(); + return (0.5 * (this->x2min + this->x2max)); } /** -* Returns the center x3 coordinate of this triangular mesh. - * @return the center x3 coordinate of this triangular mesh - */ + * Returns the center x3 coordinate of this triangular mesh. + * @return the center x3 coordinate of this triangular mesh + */ double GbQuadFaceMesh3D::getX3Centroid() { - if(!this->consistent) this->calculateValues(); - return(0.5*(this->x3min+this->x3max)); + if (!this->consistent) + this->calculateValues(); + return (0.5 * (this->x3min + this->x3max)); } /** @@ -122,8 +125,9 @@ double GbQuadFaceMesh3D::getX3Centroid() */ double GbQuadFaceMesh3D::getX1Minimum() { - if(!this->consistent) this->calculateValues(); - return(this->x1min); + if (!this->consistent) + this->calculateValues(); + return (this->x1min); } /** * Returns the maximum x1 coordinate of this triangular mesh. @@ -131,8 +135,9 @@ double GbQuadFaceMesh3D::getX1Minimum() */ double GbQuadFaceMesh3D::getX1Maximum() { - if(!this->consistent) this->calculateValues(); - return(this->x1max); + if (!this->consistent) + this->calculateValues(); + return (this->x1max); } /** * Returns the minimum x2 coordinate of this triangular mesh. @@ -140,8 +145,9 @@ double GbQuadFaceMesh3D::getX1Maximum() */ double GbQuadFaceMesh3D::getX2Minimum() { - if(!this->consistent) this->calculateValues(); - return(this->x2min); + if (!this->consistent) + this->calculateValues(); + return (this->x2min); } /** * Returns the maximum x2 coordinate of this triangular mesh. @@ -149,8 +155,9 @@ double GbQuadFaceMesh3D::getX2Minimum() */ double GbQuadFaceMesh3D::getX2Maximum() { - if(!this->consistent) this->calculateValues(); - return(this->x2max); + if (!this->consistent) + this->calculateValues(); + return (this->x2max); } /** * Returns the minimum x3 coordinate of this triangular mesh. @@ -158,8 +165,9 @@ double GbQuadFaceMesh3D::getX2Maximum() */ double GbQuadFaceMesh3D::getX3Minimum() { - if(!this->consistent) this->calculateValues(); - return(this->x3min); + if (!this->consistent) + this->calculateValues(); + return (this->x3min); } /** * Returns the maximum x3 coordinate of this triangular mesh. @@ -167,47 +175,52 @@ double GbQuadFaceMesh3D::getX3Minimum() */ double GbQuadFaceMesh3D::getX3Maximum() { - if(!this->consistent) this->calculateValues(); - return(this->x3max); + if (!this->consistent) + this->calculateValues(); + return (this->x3max); } void GbQuadFaceMesh3D::calculateValues() { - double x1, x2, x3; + double x1, x2, x3; - this->x1min = (*this->nodes)[0].x; - this->x1max = (*this->nodes)[0].x; - this->x2min = (*this->nodes)[0].y; - this->x2max = (*this->nodes)[0].y; - this->x3min = (*this->nodes)[0].z; - this->x3max = (*this->nodes)[0].z; + this->x1min = (*this->nodes)[0].x; + this->x1max = (*this->nodes)[0].x; + this->x2min = (*this->nodes)[0].y; + this->x2max = (*this->nodes)[0].y; + this->x3min = (*this->nodes)[0].z; + this->x3max = (*this->nodes)[0].z; - for(int i=1; i<(int)this->nodes->size(); i++) - { - x1 = (*this->nodes)[i].x; - x2 = (*this->nodes)[i].y; - x3 = (*this->nodes)[i].z; - if(x1 < this->x1min) this->x1min = x1; - if(x1 > this->x1max) this->x1max = x1; - if(x2 < this->x2min) this->x2min = x2; - if(x2 > this->x2max) this->x2max = x2; - if(x3 < this->x3min) this->x3min = x3; - if(x3 > this->x3max) this->x3max = x3; - } - this->consistent = true; + for (int i = 1; i < (int)this->nodes->size(); i++) { + x1 = (*this->nodes)[i].x; + x2 = (*this->nodes)[i].y; + x3 = (*this->nodes)[i].z; + if (x1 < this->x1min) + this->x1min = x1; + if (x1 > this->x1max) + this->x1max = x1; + if (x2 < this->x2min) + this->x2min = x2; + if (x2 > this->x2max) + this->x2max = x2; + if (x3 < this->x3min) + this->x3min = x3; + if (x3 > this->x3max) + this->x3max = x3; + } + this->consistent = true; } - /*======================================================================*/ -vector<GbTriangle3D*> GbQuadFaceMesh3D::getSurfaceTriangleSet() +vector<GbTriangle3D *> GbQuadFaceMesh3D::getSurfaceTriangleSet() { - vector<GbTriangle3D*> triangles(0); - return triangles; - //throw UbException(__FILE__, __LINE__, "GbQuadFaceMesh3D::getSurfaceTriangelSet - not implemented"); + vector<GbTriangle3D *> triangles(0); + return triangles; + // throw UbException(__FILE__, __LINE__, "GbQuadFaceMesh3D::getSurfaceTriangelSet - not implemented"); } -//vector<GbQuad3D*> GbQuadFaceMesh3D::getSurfaceQuadSet() +// vector<GbQuad3D*> GbQuadFaceMesh3D::getSurfaceQuadSet() //{ -// throw UbException(__FILE__, __LINE__, "GbQuadFaceMesh3D::getSurfaceQuadSet - not implemented"); +// throw UbException(__FILE__, __LINE__, "GbQuadFaceMesh3D::getSurfaceQuadSet - not implemented"); // //vector<GbQuadangle3D*> tris; // //GbQuadangle3D* quad; // //GbPoint3D* p1; @@ -226,69 +239,72 @@ vector<GbTriangle3D*> GbQuadFaceMesh3D::getSurfaceTriangleSet() //} /*======================================================================*/ /* -* Function to determine if the point is inside the polyhedron defined as a 3D object -* using the Halfspace algorithm -* @param xp the x-coordinate of the point -* @param yp the y-coordinate of the point -* @param zp the z-coordinate of the point -* @return true if point is inside else return false -*/ -bool GbQuadFaceMesh3D::isPointInObject3DHalfSpace(const double& /*xp*/, const double& /*yp*/, const double& /*zp*/) -{ - throw UbException(UB_EXARGS,"not implemented"); - //vector<GbQuadangle3D*> *Quadangles = this->quads; - //int Quadanglesize = (int)Quadangles->size(); - //GbPoint3D Point(xp,yp,zp); - //for (int i=0; i<Quadanglesize; i++) - //{ - // GbPoint3D* point1 = (*Quadangles)[i]->getPoint1(); - // GbPoint3D* point2 = (*Quadangles)[i]->getPoint2(); - // GbPoint3D* point3 = (*Quadangles)[i]->getPoint3(); + * Function to determine if the point is inside the polyhedron defined as a 3D object + * using the Halfspace algorithm + * @param xp the x-coordinate of the point + * @param yp the y-coordinate of the point + * @param zp the z-coordinate of the point + * @return true if point is inside else return false + */ +bool GbQuadFaceMesh3D::isPointInObject3DHalfSpace(const double & /*xp*/, const double & /*yp*/, const double & /*zp*/) +{ + throw UbException(UB_EXARGS, "not implemented"); + // vector<GbQuadangle3D*> *Quadangles = this->quads; + // int Quadanglesize = (int)Quadangles->size(); + // GbPoint3D Point(xp,yp,zp); + // for (int i=0; i<Quadanglesize; i++) + //{ + // GbPoint3D* point1 = (*Quadangles)[i]->getPoint1(); + // GbPoint3D* point2 = (*Quadangles)[i]->getPoint2(); + // GbPoint3D* point3 = (*Quadangles)[i]->getPoint3(); - // GbHalfSpace3D halfspace(point1, point2, point3); - // if (halfspace.ptInside(&Point)) return false; - //} - //return true; + // GbHalfSpace3D halfspace(point1, point2, point3); + // if (halfspace.ptInside(&Point)) return false; + //} + // return true; } /*======================================================================*/ /*======================================================================*/ -bool GbQuadFaceMesh3D::isPointInGbObject3D(const double& x1, const double& x2, const double& x3) +bool GbQuadFaceMesh3D::isPointInGbObject3D(const double &x1, const double &x2, const double &x3) { - double xmin=this->getX1Minimum(); double xmax=this->getX1Maximum(); - double ymin=this->getX2Minimum(); double ymax=this->getX2Maximum(); - double zmin=this->getX3Minimum(); double zmax=this->getX3Maximum(); - double dX = (xmax-xmin)/100.; - double dY = (ymax-ymin)/100.; - double dZ = (zmax-zmin)/100.; - GbCuboid3D boundingCube(xmin-dX, ymin-dY, zmin-dZ, xmax+dX, ymax+dY, zmax+dZ); - if(!boundingCube.isPointInGbObject3D(x1, x2, x3)) - { - boundingCube.finalize(); - return false; - } - boundingCube.finalize(); + double xmin = this->getX1Minimum(); + double xmax = this->getX1Maximum(); + double ymin = this->getX2Minimum(); + double ymax = this->getX2Maximum(); + double zmin = this->getX3Minimum(); + double zmax = this->getX3Maximum(); + double dX = (xmax - xmin) / 100.; + double dY = (ymax - ymin) / 100.; + double dZ = (zmax - zmin) / 100.; + GbCuboid3D boundingCube(xmin - dX, ymin - dY, zmin - dZ, xmax + dX, ymax + dY, zmax + dZ); + if (!boundingCube.isPointInGbObject3D(x1, x2, x3)) { + boundingCube.finalize(); + return false; + } + boundingCube.finalize(); - // Halfspace algorithm, Area of spherical polygons algorithm or Ray crossing algorithm - GbVector3D bMin(boundingCube.getPoint1()); - GbVector3D bMax(boundingCube.getPoint2()); - bMin = bMax.Subtract(bMin); - //int radius = (int)bMin.Length(); + // Halfspace algorithm, Area of spherical polygons algorithm or Ray crossing algorithm + GbVector3D bMin(boundingCube.getPoint1()); + GbVector3D bMax(boundingCube.getPoint2()); + bMin = bMax.Subtract(bMin); + // int radius = (int)bMin.Length(); - //if(((GbQuadFaceMesh3D*)this->geoObject3D)->isPointInObject3DHalfSpace(x1,x2,x3) ) - //if(((GbQuadFaceMesh3D*)this->geoObject3D)->isPointInObject3Darea(x11,x12,x13,numQuadangles)) - //if(this->isPointInObject3DRayCrossing(x1,x2,x3,radius,(int)this->nodes->size(),(int)this->quads->size())) - // return true; - //else - return false; + // if(((GbQuadFaceMesh3D*)this->geoObject3D)->isPointInObject3DHalfSpace(x1,x2,x3) ) + // if(((GbQuadFaceMesh3D*)this->geoObject3D)->isPointInObject3Darea(x11,x12,x13,numQuadangles)) + // if(this->isPointInObject3DRayCrossing(x1,x2,x3,radius,(int)this->nodes->size(),(int)this->quads->size())) + // return true; + // else + return false; } /*======================================================================*/ -bool GbQuadFaceMesh3D::isPointInGbObject3D(const double& /*x1*/, const double& /*x2*/, const double& /*x3*/, bool& /*pointIsOnBoundary*/) +bool GbQuadFaceMesh3D::isPointInGbObject3D(const double & /*x1*/, const double & /*x2*/, const double & /*x3*/, + bool & /*pointIsOnBoundary*/) { - throw UbException(UB_EXARGS,"not implemented"); + throw UbException(UB_EXARGS, "not implemented"); } /*======================================================================*/ -GbLine3D* GbQuadFaceMesh3D::createClippedLine3D (GbPoint3D& /*point1*/, GbPoint3D& /*point2*/) +GbLine3D *GbQuadFaceMesh3D::createClippedLine3D(GbPoint3D & /*point1*/, GbPoint3D & /*point2*/) { - throw UbException(UB_EXARGS,"not implemented"); + throw UbException(UB_EXARGS, "not implemented"); } diff --git a/src/basics/geometry3d/GbQuadFaceMesh3D.h b/src/basics/geometry3d/GbQuadFaceMesh3D.h index 4a623b0f767d36a01568d489c745d606449d790d..d4f1c1310a07b673e2aab6a7a0526ad5aa79d5bd 100644 --- a/src/basics/geometry3d/GbQuadFaceMesh3D.h +++ b/src/basics/geometry3d/GbQuadFaceMesh3D.h @@ -7,12 +7,11 @@ #ifndef GBQUADFACEMESH3D_H #define GBQUADFACEMESH3D_H -#include <sstream> #include <iostream> +#include <sstream> - +#include <basics/utilities/UbException.h> #include <geometry3d/GbObject3D.h> -#include <basics/utilities/UbException.h> #include <PointerDefinitions.h> @@ -25,97 +24,100 @@ class UbFileInput; * This Class provides the triangular meshes. * Note, that up to now no methods for checking consistency are included. * in this context this class describes facettes from an 3D-object !!! -*/ -class GbQuadFaceMesh3D : public GbObject3D -{ + */ +class GbQuadFaceMesh3D : public GbObject3D +{ public: - // nested class start - class Vertex - { - public: - Vertex()= default; - Vertex(float x, float y, float z) - { - this->x=x; - this->y=y; - this->z=z; - } - float x, y, z; - }; - - class QuadFace - { - public: - QuadFace() = default; - QuadFace(int v1, int v2, int v3, int v4) - { - this->vertex1=v1; - this->vertex2=v2; - this->vertex3=v3; - this->vertex4=v4; - } - - int vertex1, vertex2, vertex3, vertex4; - }; - // nested class end + // nested class start + class Vertex + { + public: + Vertex() = default; + Vertex(float x, float y, float z) + { + this->x = x; + this->y = y; + this->z = z; + } + float x, y, z; + }; + + class QuadFace + { + public: + QuadFace() = default; + QuadFace(int v1, int v2, int v3, int v4) + { + this->vertex1 = v1; + this->vertex2 = v2; + this->vertex3 = v3; + this->vertex4 = v4; + } + + int vertex1, vertex2, vertex3, vertex4; + }; + // nested class end public: - GbQuadFaceMesh3D(); - GbQuadFaceMesh3D(std::string name, std::vector<Vertex> *nodes, std::vector<QuadFace> *quads); - ~GbQuadFaceMesh3D() override; - GbQuadFaceMesh3D* clone() override { throw UbException(UB_EXARGS,"clone() - not implemented"); } - void finalize() override { throw UbException(UB_EXARGS,"finalize() - not implemented");} - - std::string toString() override; - std::string getName() override; - std::vector<Vertex>* getNodes(); - std::vector<QuadFace>* getQuads(); - double getX1Centroid() override; - double getX2Centroid() override; - double getX3Centroid() override; - double getX1Minimum() override; - double getX1Maximum() override; - double getX2Minimum() override; - double getX2Maximum() override; - double getX3Minimum() override; - double getX3Maximum() override; - void calculateValues(); - - bool isPointInGbObject3D(const double& x1, const double& x2, const double& x3) override; - bool isPointInGbObject3D(const double& x1, const double& x2, const double& x3, bool& pointIsOnBoundary) override; - - bool isPointInObject3DHalfSpace(const double& xp, const double& yp, const double& zp); //based on Halfspace algorithm - //bool isPointInObject3DSpherical(const double& xp, const double& yp, const double& zp, int numQuads); //based on Spherical polygon area method - //bool isPointInObject3DRayCrossing(const double& xp, const double& yp, const double& zp, int radius, int numVertices, int numQuads); //based on Ray tracing algorithm - - //char SegPlaneInt(GbQuad3D *quad, GbVector3D &PointQ, GbVector3D &PointR, GbVector3D &Point, int *m); - //char SegQuadCross(GbQuad3D *quad, GbVector3D &PointQ, GbVector3D &PointR); - //till here !!! - - GbLine3D* createClippedLine3D (GbPoint3D &point1,GbPoint3D &point2) override; - //virtual std::vector<GbQuad3D*> getSurfaceQuadSet(); - std::vector<GbTriangle3D*> getSurfaceTriangleSet() override; - - virtual void write(UbFileOutput* /*out*/) { std::cout<<"GbQuadFaceMesh3D::write - sorry not implemented\n"; } - virtual void read(UbFileInput* /*in*/) { std::cout<<"GbQuadFaceMesh3D::read - sorry not implemented\n"; } - - void writeAVSMesh(UbFileOutput *out, bool normals=false); - - /*======================================================================*/ - using GbObject3D::isPointInGbObject3D; //Grund: dadurch muss man hier isPointInGbObject3D(GbPoint3D*) nicht ausprogrammieren, welche sonst hier "ueberdeckt" waere + GbQuadFaceMesh3D(); + GbQuadFaceMesh3D(std::string name, std::vector<Vertex> *nodes, std::vector<QuadFace> *quads); + ~GbQuadFaceMesh3D() override; + GbQuadFaceMesh3D *clone() override { throw UbException(UB_EXARGS, "clone() - not implemented"); } + void finalize() override { throw UbException(UB_EXARGS, "finalize() - not implemented"); } + + std::string toString() override; + std::string getName() override; + std::vector<Vertex> *getNodes(); + std::vector<QuadFace> *getQuads(); + double getX1Centroid() override; + double getX2Centroid() override; + double getX3Centroid() override; + double getX1Minimum() override; + double getX1Maximum() override; + double getX2Minimum() override; + double getX2Maximum() override; + double getX3Minimum() override; + double getX3Maximum() override; + void calculateValues(); + + bool isPointInGbObject3D(const double &x1, const double &x2, const double &x3) override; + bool isPointInGbObject3D(const double &x1, const double &x2, const double &x3, bool &pointIsOnBoundary) override; + + bool isPointInObject3DHalfSpace(const double &xp, const double &yp, + const double &zp); // based on Halfspace algorithm + // bool isPointInObject3DSpherical(const double& xp, const double& yp, const double& zp, int numQuads); //based + // on Spherical polygon area method bool isPointInObject3DRayCrossing(const double& xp, const double& yp, const + // double& zp, int radius, int numVertices, int numQuads); //based on Ray tracing algorithm + + // char SegPlaneInt(GbQuad3D *quad, GbVector3D &PointQ, GbVector3D &PointR, GbVector3D &Point, int *m); + // char SegQuadCross(GbQuad3D *quad, GbVector3D &PointQ, GbVector3D &PointR); + // till here !!! + + GbLine3D *createClippedLine3D(GbPoint3D &point1, GbPoint3D &point2) override; + // virtual std::vector<GbQuad3D*> getSurfaceQuadSet(); + std::vector<GbTriangle3D *> getSurfaceTriangleSet() override; + + virtual void write(UbFileOutput * /*out*/) { std::cout << "GbQuadFaceMesh3D::write - sorry not implemented\n"; } + virtual void read(UbFileInput * /*in*/) { std::cout << "GbQuadFaceMesh3D::read - sorry not implemented\n"; } + + void writeAVSMesh(UbFileOutput *out, bool normals = false); + + /*======================================================================*/ + using GbObject3D::isPointInGbObject3D; // Grund: dadurch muss man hier isPointInGbObject3D(GbPoint3D*) nicht + // ausprogrammieren, welche sonst hier "ueberdeckt" waere private: - void init(); - /*======================================================================*/ - std::string name; - std::vector<Vertex> *nodes; - std::vector<QuadFace> *quads; - double x1min; - double x1max; - double x2min; - double x2max; - double x3min; - double x3max; - bool consistent; + void init(); + /*======================================================================*/ + std::string name; + std::vector<Vertex> *nodes; + std::vector<QuadFace> *quads; + double x1min; + double x1max; + double x2min; + double x2max; + double x3min; + double x3max; + bool consistent; }; /*=========================================================================*/ diff --git a/src/basics/geometry3d/GbSphere3D.cpp b/src/basics/geometry3d/GbSphere3D.cpp index 670b37f5a30f3b954c53a093d324f2b4b7301382..da8aba0cb44e6f447266335874811425e17c8ef3 100644 --- a/src/basics/geometry3d/GbSphere3D.cpp +++ b/src/basics/geometry3d/GbSphere3D.cpp @@ -1,71 +1,69 @@ +#include <geometry3d/GbLine3D.h> +#include <geometry3d/GbPoint3D.h> #include <geometry3d/GbSphere3D.h> #include <geometry3d/GbSystem3D.h> -#include <geometry3d/GbPoint3D.h> -#include <geometry3d/GbLine3D.h> #include <geometry3d/GbTriangle3D.h> using namespace std; /*=====================================================*/ -GbSphere3D::GbSphere3D() - : GbObject3D(), UbObserver() +GbSphere3D::GbSphere3D() : GbObject3D(), UbObserver() { - this->setName("sphere"); - radius=0; - midPoint=new GbPoint3D(0,0,0); + this->setName("sphere"); + radius = 0; + midPoint = new GbPoint3D(0, 0, 0); } /*=====================================================*/ -GbSphere3D::GbSphere3D(const double& x1,const double& x2, const double& x3, const double& radius) - : GbObject3D(), UbObserver() +GbSphere3D::GbSphere3D(const double &x1, const double &x2, const double &x3, const double &radius) + : GbObject3D(), UbObserver() { - this->setName("sphere"); - midPoint = new GbPoint3D(x1,x2,x3); - midPoint->addObserver(this); + this->setName("sphere"); + midPoint = new GbPoint3D(x1, x2, x3); + midPoint->addObserver(this); - this->radius = radius; - triangulationMode = RAYPROJECTION; - //triangulationMode = CUBOIDPROJECTION; + this->radius = radius; + triangulationMode = RAYPROJECTION; + // triangulationMode = CUBOIDPROJECTION; } /*=====================================================*/ -GbSphere3D::GbSphere3D(const GbSphere3D& sphere) - : GbObject3D(sphere), UbObserver() +GbSphere3D::GbSphere3D(const GbSphere3D &sphere) : GbObject3D(sphere), UbObserver() { - this->setName("sphere"); + this->setName("sphere"); - this->midPoint = sphere.midPoint->clone(); - this->radius = sphere.radius; - triangulationMode = RAYPROJECTION; + this->midPoint = sphere.midPoint->clone(); + this->radius = sphere.radius; + triangulationMode = RAYPROJECTION; - this->midPoint->addObserver(this); + this->midPoint->addObserver(this); } /*=====================================================*/ -GbSphere3D::GbSphere3D(GbSphere3D* sphere) - : GbObject3D(), UbObserver() +GbSphere3D::GbSphere3D(GbSphere3D *sphere) : GbObject3D(), UbObserver() { - this->setName(sphere->getName()); - midPoint = sphere->midPoint->clone(); - midPoint->addObserver(this); + this->setName(sphere->getName()); + midPoint = sphere->midPoint->clone(); + midPoint->addObserver(this); - this->radius = sphere->getRadius(); - triangulationMode = RAYPROJECTION; + this->radius = sphere->getRadius(); + triangulationMode = RAYPROJECTION; } /*=====================================================*/ GbSphere3D::~GbSphere3D() { - if(this->midPoint) this->midPoint->removeObserver(this); + if (this->midPoint) + this->midPoint->removeObserver(this); } /*=====================================================*/ void GbSphere3D::finalize() { - if(this->midPoint) - { - this->midPoint->removeObserver(this); - this->midPoint->finalize(); - delete this->midPoint; - this->midPoint = NULL; - } - - if(this->midPoint) this->midPoint->removeObserver(this); + if (this->midPoint) { + this->midPoint->removeObserver(this); + this->midPoint->finalize(); + delete this->midPoint; + this->midPoint = NULL; + } + + if (this->midPoint) + this->midPoint->removeObserver(this); } /*=====================================================*/ bool GbSphere3D::intersects(SPtr<GbSphere3D> sphere) @@ -73,819 +71,855 @@ bool GbSphere3D::intersects(SPtr<GbSphere3D> sphere) return this->getDistance(sphere->midPoint) < radius + sphere->radius; } /*=======================================================*/ -void GbSphere3D::setCenterCoordinates(const double& x1, const double& x2, const double& x3) +void GbSphere3D::setCenterCoordinates(const double &x1, const double &x2, const double &x3) { - this->translate(x1-getX1Centroid(), x2-getX2Centroid(), x3-getX3Centroid() ); + this->translate(x1 - getX1Centroid(), x2 - getX2Centroid(), x3 - getX3Centroid()); } -void GbSphere3D::setCenterCoordinates(const UbTupleDouble3& position) +void GbSphere3D::setCenterCoordinates(const UbTupleDouble3 &position) { this->setCenterCoordinates(val<1>(position), val<2>(position), val<3>(position)); } /*=====================================================*/ -double GbSphere3D::getDistance(GbPoint3D* p) +double GbSphere3D::getDistance(GbPoint3D *p) { - return this->getDistance(p->getX1Centroid(),p->getX2Coordinate(),p->getX3Coordinate()); + return this->getDistance(p->getX1Centroid(), p->getX2Coordinate(), p->getX3Coordinate()); } /*=====================================================*/ -void GbSphere3D::setCenterX1Coordinate(const double& value) +void GbSphere3D::setCenterX1Coordinate(const double &value) { - if(this->midPoint) this->midPoint->setX1(value); - else throw UbException(UB_EXARGS,"Sphere has no midPoint"); - //kein notifyObserver(), da der knoten notifyObserver() ausfuehrt und die GbSphere dieses event - //abfaengt und dann selbst notifyObservers ausfuehrt ;-) + if (this->midPoint) + this->midPoint->setX1(value); + else + throw UbException(UB_EXARGS, "Sphere has no midPoint"); + // kein notifyObserver(), da der knoten notifyObserver() ausfuehrt und die GbSphere dieses event + // abfaengt und dann selbst notifyObservers ausfuehrt ;-) } /*=====================================================*/ -void GbSphere3D::setCenterX2Coordinate(const double& value) +void GbSphere3D::setCenterX2Coordinate(const double &value) { - if(this->midPoint) this->midPoint->setX2(value); - else throw UbException(UB_EXARGS,"Sphere has no midPoint"); - //kein notifyObserver(), da der knoten notifyObserver() ausfuehrt und die GbSphere dieses event - //abfaengt und dann selbst notifyObservers ausfuehrt ;-) + if (this->midPoint) + this->midPoint->setX2(value); + else + throw UbException(UB_EXARGS, "Sphere has no midPoint"); + // kein notifyObserver(), da der knoten notifyObserver() ausfuehrt und die GbSphere dieses event + // abfaengt und dann selbst notifyObservers ausfuehrt ;-) } /*=====================================================*/ -void GbSphere3D::setCenterX3Coordinate(const double& value) +void GbSphere3D::setCenterX3Coordinate(const double &value) { - if(this->midPoint) this->midPoint->setX3(value); - else throw UbException(UB_EXARGS,"sphere has no midPoint"); - //kein notifyObserver(), da der knoten notifyObserver() ausfuehrt und die GbSphere dieses event - //abfaengt und dann selbst notifyObservers ausfuehrt ;-) + if (this->midPoint) + this->midPoint->setX3(value); + else + throw UbException(UB_EXARGS, "sphere has no midPoint"); + // kein notifyObserver(), da der knoten notifyObserver() ausfuehrt und die GbSphere dieses event + // abfaengt und dann selbst notifyObservers ausfuehrt ;-) } /*=====================================================*/ -void GbSphere3D::setRadius(const double& radius) +void GbSphere3D::setRadius(const double &radius) { - if (radius != this->radius) - { - this->radius=radius; - this->notifyObserversObjectChanged(); -} + if (radius != this->radius) { + this->radius = radius; + this->notifyObserversObjectChanged(); + } } /*=====================================================*/ -double GbSphere3D::getDistance(const double& x1p, const double& x2p, const double& x3p) +double GbSphere3D::getDistance(const double &x1p, const double &x2p, const double &x3p) { - double deltaX1 = x1p - midPoint->getX1Coordinate(); - double deltaX2 = x2p - midPoint->getX2Coordinate(); - double deltaX3 = x3p - midPoint->getX3Coordinate(); - return sqrt(deltaX1*deltaX1+deltaX2*deltaX2+deltaX3*deltaX3)-this->radius; + double deltaX1 = x1p - midPoint->getX1Coordinate(); + double deltaX2 = x2p - midPoint->getX2Coordinate(); + double deltaX3 = x3p - midPoint->getX3Coordinate(); + return sqrt(deltaX1 * deltaX1 + deltaX2 * deltaX2 + deltaX3 * deltaX3) - this->radius; } /*=====================================================*/ -//true, wenn 'in Object' oder 'auf Boundary'! -bool GbSphere3D::isPointInGbObject3D(const double& x1p, const double& x2p, const double& x3p) +// true, wenn 'in Object' oder 'auf Boundary'! +bool GbSphere3D::isPointInGbObject3D(const double &x1p, const double &x2p, const double &x3p) { - double deltaX1 = x1p - midPoint->getX1Coordinate(); - double deltaX2 = x2p - midPoint->getX2Coordinate(); - double deltaX3 = x3p - midPoint->getX3Coordinate(); + double deltaX1 = x1p - midPoint->getX1Coordinate(); + double deltaX2 = x2p - midPoint->getX2Coordinate(); + double deltaX3 = x3p - midPoint->getX3Coordinate(); - return UbMath::lessEqual(deltaX1*deltaX1+deltaX2*deltaX2+deltaX3*deltaX3, this->radius*this->radius); + return UbMath::lessEqual(deltaX1 * deltaX1 + deltaX2 * deltaX2 + deltaX3 * deltaX3, this->radius * this->radius); } /*=====================================================*/ -//true, wenn 'in Object' oder 'auf Boundary'! -bool GbSphere3D::isPointInGbObject3D(const double& x1p, const double& x2p, const double& x3p, bool& pointIsOnBoundary) +// true, wenn 'in Object' oder 'auf Boundary'! +bool GbSphere3D::isPointInGbObject3D(const double &x1p, const double &x2p, const double &x3p, bool &pointIsOnBoundary) { - double deltaX1 = x1p - midPoint->getX1Coordinate(); - double deltaX2 = x2p - midPoint->getX2Coordinate(); - double deltaX3 = x3p - midPoint->getX3Coordinate(); + double deltaX1 = x1p - midPoint->getX1Coordinate(); + double deltaX2 = x2p - midPoint->getX2Coordinate(); + double deltaX3 = x3p - midPoint->getX3Coordinate(); - double distanceSquare = deltaX1*deltaX1+deltaX2*deltaX2+deltaX3*deltaX3; - double radiusSquare = this->radius*this->radius; + double distanceSquare = deltaX1 * deltaX1 + deltaX2 * deltaX2 + deltaX3 * deltaX3; + double radiusSquare = this->radius * this->radius; - pointIsOnBoundary = UbMath::equal(distanceSquare,radiusSquare); + pointIsOnBoundary = UbMath::equal(distanceSquare, radiusSquare); - return UbMath::lessEqual(distanceSquare,radiusSquare); + return UbMath::lessEqual(distanceSquare, radiusSquare); } /*=====================================================*/ -//bool GbSphere3D::crossCellCrossSection(double x11,double x21,double x12,double x22, double ra) +// bool GbSphere3D::crossCellCrossSection(double x11,double x21,double x12,double x22, double ra) //{ -// if(this->isPointInCrossection(x11, x12) || this->isPointInCrossection(x21, x22) || this->isPointInCrossection(x11, x22) || this->isPointInCrossection(x21, x12)) +// if(this->isPointInCrossection(x11, x12) || this->isPointInCrossection(x21, x22) || this->isPointInCrossection(x11, +// x22) || this->isPointInCrossection(x21, x12)) // { -// if(!this->isPointInCrossection(x11, x12) || !this->isPointInCrossection(x21, x22) || !this->isPointInCrossection(x11, x22) || !this->isPointInCrossection(x21, x12)) return true; +// if(!this->isPointInCrossection(x11, x12) || !this->isPointInCrossection(x21, x22) || +//!this->isPointInCrossection(x11, x22) || !this->isPointInCrossection(x21, x12)) return true; // } // return false; //} // ///*=====================================================*/ -//bool GbSphere3D::cellCrossAndInsideCrossSection(double x11,double x21,double x12,double x22, double ra) +// bool GbSphere3D::cellCrossAndInsideCrossSection(double x11,double x21,double x12,double x22, double ra) //{ -// if(this->isPointInCrossection(x11, x12) || this->isPointInCrossection(x21, x22) || this->isPointInCrossection(x11, x22) || this->isPointInCrossection(x21, x12)) return true; -// return false; +// if(this->isPointInCrossection(x11, x12) || this->isPointInCrossection(x21, x22) || this->isPointInCrossection(x11, +// x22) || this->isPointInCrossection(x21, x12)) return true; return false; //} /*=====================================================*/ string GbSphere3D::toString() { - stringstream ss; - ss<< "GbSphere3D["; - ss <<"mid="<<midPoint->toString()<<", r="<<radius<<"]"; - return ss.str(); + stringstream ss; + ss << "GbSphere3D["; + ss << "mid=" << midPoint->toString() << ", r=" << radius << "]"; + return ss.str(); } /*=====================================================*/ -GbLine3D* GbSphere3D::createClippedLine3D(GbPoint3D& point1, GbPoint3D& point2) +GbLine3D *GbSphere3D::createClippedLine3D(GbPoint3D &point1, GbPoint3D &point2) { - double factor = 100.0; //um rundungsfehler beim wurzelterm zu minimieren - double xa = factor*point1.getX1Coordinate(); - double ya = factor*point1.getX2Coordinate(); - double za = factor*point1.getX3Coordinate(); - double xb = factor*point2.getX1Coordinate(); - double yb = factor*point2.getX2Coordinate(); - double zb = factor*point2.getX3Coordinate(); - double xm = factor*this->midPoint->getX1Coordinate(); - double ym = factor*this->midPoint->getX2Coordinate(); - double zm = factor*this->midPoint->getX3Coordinate(); - double r = factor*this->radius; - - double xa2 = xa*xa; - double ya2 = ya*ya; - double za2 = za*za; - double xb2 = xb*xb; - double yb2 = yb*yb; - double zb2 = zb*zb; - double xm2 = xm*xm; - double ym2 = ym*ym; - double zm2 = zm*zm; - double r2 = r*r; - - double wurzel = 2.0*xa*xb*ym2-2.0*ya*yb*r2+2.0*ya*ym*xb2+2.0*yb*ym*za2 - +2.0*ya*ym*zb2+2.0*xb*xm*za2+2.0*za*zb*ym2+2.0*xb*xm*ya2+2.0*xa*xm*yb2 - +2.0*yb*ym*xa2+2.0*zb*zm*ya2+2.0*xa*xm*zb2+2.0*za*zm*xb2+2.0*za*zm*yb2 - +2.0*xa*xb*zm2-2.0*xa*xb*r2-2.0*za*zb*r2+2.0*za*zb*xm2-2.0*ya*yb*xa*xm - +2.0*ya*yb*xa*xb+2.0*zb*zm*xa2-2.0*ya*yb*xb*xm+2.0*ya*yb*xm2-2.0*ya*yb*zb*zm - +2.0*ya*yb*zm2+2.0*zb*zm*yb*ym-2.0*zb*zm*ya*ym+2.0*zb*zm*xb*xm-2.0*xa*xm*yb*ym - +2.0*xa*xm*za*zm+2.0*xa*xm*ya*ym-2.0*yb*ym*za*zm+2.0*yb*ym*xb*xm+2.0*za*zm*ya*ym - -2.0*za*zm*xb*xm-2.0*ya*ym*xb*xm+2.0*za*zb*xa*xb-2.0*za*zb*xa*xm-2.0*za*zb*xb*xm - +2.0*za*zb*ya*yb-2.0*za*zb*ya*ym-2.0*za*zb*yb*ym-2.0*ya*yb*za*zm-xa2*zb2 - -xa2*yb2-zb2*ya2-za2*xb2-za2*yb2-xb2*ya2-2.0*zb*zm*xa*xm - -2.0*xa*xb*za*zm-2.0*xa*xb*zb*zm-2.0*xa*xb*ya*ym-2.0*xa*xb*yb*ym+za2*r2 - -za2*xm2-za2*ym2+zb2*r2-zb2*xm2-zb2*ym2+xa2*r2-xa2*zm2 - -xa2*ym2+xb2*r2-xb2*zm2-xb2*ym2+ya2*r2-ya2*zm2-ya2*xm2 - +yb2*r2-yb2*zm2-yb2*xm2; - double nenner = -2.0*za*zb-2.0*ya*yb-2.0*xa*xb+za2+zb2+xa2+xb2+ya2+yb2; - double zaehler = 2.0*zb*zm-2.0*xa*xm+2.0*yb*ym-2.0*za*zm+xa2-2.0*ya*ym - +2.0*xb*xm-zb2+za2-xb2+ya2-yb2; - - vector<GbPoint3D*> schnittpunkte; - - if(fabs(nenner)>1.E-13 && UbMath::greaterEqual(wurzel,0.0)) - { - double t1 = (zaehler+2.0*sqrt(wurzel))/nenner; - double t2 = (zaehler-2.0*sqrt(wurzel))/nenner; - - if(UbMath::inClosedInterval(t1,-1.0,1.0)) - { - double x = ( xa*(0.5-0.5*t1)+xb*(0.5+0.5*t1) )/factor; - double y = ( ya*(0.5-0.5*t1)+yb*(0.5+0.5*t1) )/factor; - double z = ( za*(0.5-0.5*t1)+zb*(0.5+0.5*t1) )/factor; - - schnittpunkte.push_back(new GbPoint3D(x,y,z)); - } - if(fabs(t2-t1)>1.E-13 && UbMath::inClosedInterval(t2,-1.0,1.0)) - { - double x = ( xa*(0.5-0.5*t2)+xb*(0.5+0.5*t2) )/factor; - double y = ( ya*(0.5-0.5*t2)+yb*(0.5+0.5*t2) )/factor; - double z = ( za*(0.5-0.5*t2)+zb*(0.5+0.5*t2) )/factor; - - schnittpunkte.push_back(new GbPoint3D(x,y,z)); - } - } - - int nofSchnittpunkte = (int)schnittpunkte.size(); - if(nofSchnittpunkte==1) - { - if (this->isPointInGbObject3D(&point1)) return new GbLine3D(schnittpunkte[0],new GbPoint3D(point1)); - else if(this->isPointInGbObject3D(&point2)) return new GbLine3D(schnittpunkte[0],new GbPoint3D(point2)); - else //line beruehrt kugel! -> clippedLine reduziert sich zu einem Punkt! - { - if(std::fabs(this->getDistance(schnittpunkte[0])-this->radius)<1.E-13) - throw UbException(UB_EXARGS,"Beide LinenPunkte ausserhalb des Kreises, der berechnete Punkt ist jedoch KEIN Beruhrungspunkt der Sphere..."); - return new GbLine3D(schnittpunkte[0],new GbPoint3D(*(schnittpunkte[0]))); - } - } - else if(nofSchnittpunkte==2) return new GbLine3D(schnittpunkte[0],schnittpunkte[1]); - - return NULL; + double factor = 100.0; // um rundungsfehler beim wurzelterm zu minimieren + double xa = factor * point1.getX1Coordinate(); + double ya = factor * point1.getX2Coordinate(); + double za = factor * point1.getX3Coordinate(); + double xb = factor * point2.getX1Coordinate(); + double yb = factor * point2.getX2Coordinate(); + double zb = factor * point2.getX3Coordinate(); + double xm = factor * this->midPoint->getX1Coordinate(); + double ym = factor * this->midPoint->getX2Coordinate(); + double zm = factor * this->midPoint->getX3Coordinate(); + double r = factor * this->radius; + + double xa2 = xa * xa; + double ya2 = ya * ya; + double za2 = za * za; + double xb2 = xb * xb; + double yb2 = yb * yb; + double zb2 = zb * zb; + double xm2 = xm * xm; + double ym2 = ym * ym; + double zm2 = zm * zm; + double r2 = r * r; + + double wurzel = + 2.0 * xa * xb * ym2 - 2.0 * ya * yb * r2 + 2.0 * ya * ym * xb2 + 2.0 * yb * ym * za2 + 2.0 * ya * ym * zb2 + + 2.0 * xb * xm * za2 + 2.0 * za * zb * ym2 + 2.0 * xb * xm * ya2 + 2.0 * xa * xm * yb2 + 2.0 * yb * ym * xa2 + + 2.0 * zb * zm * ya2 + 2.0 * xa * xm * zb2 + 2.0 * za * zm * xb2 + 2.0 * za * zm * yb2 + 2.0 * xa * xb * zm2 - + 2.0 * xa * xb * r2 - 2.0 * za * zb * r2 + 2.0 * za * zb * xm2 - 2.0 * ya * yb * xa * xm + + 2.0 * ya * yb * xa * xb + 2.0 * zb * zm * xa2 - 2.0 * ya * yb * xb * xm + 2.0 * ya * yb * xm2 - + 2.0 * ya * yb * zb * zm + 2.0 * ya * yb * zm2 + 2.0 * zb * zm * yb * ym - 2.0 * zb * zm * ya * ym + + 2.0 * zb * zm * xb * xm - 2.0 * xa * xm * yb * ym + 2.0 * xa * xm * za * zm + 2.0 * xa * xm * ya * ym - + 2.0 * yb * ym * za * zm + 2.0 * yb * ym * xb * xm + 2.0 * za * zm * ya * ym - 2.0 * za * zm * xb * xm - + 2.0 * ya * ym * xb * xm + 2.0 * za * zb * xa * xb - 2.0 * za * zb * xa * xm - 2.0 * za * zb * xb * xm + + 2.0 * za * zb * ya * yb - 2.0 * za * zb * ya * ym - 2.0 * za * zb * yb * ym - 2.0 * ya * yb * za * zm - + xa2 * zb2 - xa2 * yb2 - zb2 * ya2 - za2 * xb2 - za2 * yb2 - xb2 * ya2 - 2.0 * zb * zm * xa * xm - + 2.0 * xa * xb * za * zm - 2.0 * xa * xb * zb * zm - 2.0 * xa * xb * ya * ym - 2.0 * xa * xb * yb * ym + + za2 * r2 - za2 * xm2 - za2 * ym2 + zb2 * r2 - zb2 * xm2 - zb2 * ym2 + xa2 * r2 - xa2 * zm2 - xa2 * ym2 + + xb2 * r2 - xb2 * zm2 - xb2 * ym2 + ya2 * r2 - ya2 * zm2 - ya2 * xm2 + yb2 * r2 - yb2 * zm2 - yb2 * xm2; + double nenner = -2.0 * za * zb - 2.0 * ya * yb - 2.0 * xa * xb + za2 + zb2 + xa2 + xb2 + ya2 + yb2; + double zaehler = 2.0 * zb * zm - 2.0 * xa * xm + 2.0 * yb * ym - 2.0 * za * zm + xa2 - 2.0 * ya * ym + + 2.0 * xb * xm - zb2 + za2 - xb2 + ya2 - yb2; + + vector<GbPoint3D *> schnittpunkte; + + if (fabs(nenner) > 1.E-13 && UbMath::greaterEqual(wurzel, 0.0)) { + double t1 = (zaehler + 2.0 * sqrt(wurzel)) / nenner; + double t2 = (zaehler - 2.0 * sqrt(wurzel)) / nenner; + + if (UbMath::inClosedInterval(t1, -1.0, 1.0)) { + double x = (xa * (0.5 - 0.5 * t1) + xb * (0.5 + 0.5 * t1)) / factor; + double y = (ya * (0.5 - 0.5 * t1) + yb * (0.5 + 0.5 * t1)) / factor; + double z = (za * (0.5 - 0.5 * t1) + zb * (0.5 + 0.5 * t1)) / factor; + + schnittpunkte.push_back(new GbPoint3D(x, y, z)); + } + if (fabs(t2 - t1) > 1.E-13 && UbMath::inClosedInterval(t2, -1.0, 1.0)) { + double x = (xa * (0.5 - 0.5 * t2) + xb * (0.5 + 0.5 * t2)) / factor; + double y = (ya * (0.5 - 0.5 * t2) + yb * (0.5 + 0.5 * t2)) / factor; + double z = (za * (0.5 - 0.5 * t2) + zb * (0.5 + 0.5 * t2)) / factor; + + schnittpunkte.push_back(new GbPoint3D(x, y, z)); + } + } + + int nofSchnittpunkte = (int)schnittpunkte.size(); + if (nofSchnittpunkte == 1) { + if (this->isPointInGbObject3D(&point1)) + return new GbLine3D(schnittpunkte[0], new GbPoint3D(point1)); + else if (this->isPointInGbObject3D(&point2)) + return new GbLine3D(schnittpunkte[0], new GbPoint3D(point2)); + else // line beruehrt kugel! -> clippedLine reduziert sich zu einem Punkt! + { + if (std::fabs(this->getDistance(schnittpunkte[0]) - this->radius) < 1.E-13) + throw UbException(UB_EXARGS, "Beide LinenPunkte ausserhalb des Kreises, der berechnete Punkt ist " + "jedoch KEIN Beruhrungspunkt der Sphere..."); + return new GbLine3D(schnittpunkte[0], new GbPoint3D(*(schnittpunkte[0]))); + } + } else if (nofSchnittpunkte == 2) + return new GbLine3D(schnittpunkte[0], schnittpunkte[1]); + + return NULL; } /*=========================================================================*/ -vector<GbTriangle3D*> GbSphere3D::getSurfaceTriangleSet() +vector<GbTriangle3D *> GbSphere3D::getSurfaceTriangleSet() { - if(triangulationMode==RAYPROJECTION) - { - double x1m = midPoint->getX1Coordinate(); - double x2m = midPoint->getX2Coordinate(); - double x3m = midPoint->getX3Coordinate(); - - vector<GbTriangle3D*> triangles; - - int segments =30; - double deltaPhi = UbMath::PI/(double)segments; - double phiX1a,phiX1b,phiX3a,phiX3b; - double x1a,x2a,x3a,x1b,x2b,x3b,x1c,x2c,x3c,x1d,x2d,x3d; - - for(phiX3a=0.5*UbMath::PI; phiX3a>-1.5*UbMath::PI; phiX3a-=deltaPhi) - { - for(phiX1a=0.0; phiX1a<UbMath::PI; phiX1a+=deltaPhi) - { - phiX1b = phiX1a+deltaPhi; - phiX3b = phiX3a+deltaPhi; - - x1a = x1m+radius*cos(phiX3a)*std::cos(phiX1a); - x2a = x2m+radius*cos(phiX3a)*std::sin(phiX1a); - x3a = x3m+radius*sin(phiX3a); - x1b = x1m+radius*cos(phiX3a)*std::cos(phiX1b); - x2b = x2m+radius*cos(phiX3a)*std::sin(phiX1b); - x3b = x3m+radius*sin(phiX3a); - x1c = x1m+radius*cos(phiX3b)*std::cos(phiX1b); - x2c = x2m+radius*cos(phiX3b)*std::sin(phiX1b); - x3c = x3m+radius*sin(phiX3b); - x1d = x1m+radius*cos(phiX3b)*std::cos(phiX1a); - x2d = x2m+radius*cos(phiX3b)*std::sin(phiX1a); - x3d = x3m+radius*sin(phiX3b); - - if(UbMath::greater(phiX3b,-0.5*UbMath::PI) && UbMath::less(phiX3a,0.5*UbMath::PI)) - { - triangles.push_back(new GbTriangle3D(new GbPoint3D(x1a,x2a,x3a),new GbPoint3D(x1b,x2b,x3b),new GbPoint3D(x1c,x2c,x3c))); - triangles.push_back(new GbTriangle3D(new GbPoint3D(x1a,x2a,x3a),new GbPoint3D(x1c,x2c,x3c),new GbPoint3D(x1d,x2d,x3d))); + if (triangulationMode == RAYPROJECTION) { + double x1m = midPoint->getX1Coordinate(); + double x2m = midPoint->getX2Coordinate(); + double x3m = midPoint->getX3Coordinate(); + + vector<GbTriangle3D *> triangles; + + int segments = 30; + double deltaPhi = UbMath::PI / (double)segments; + double phiX1a, phiX1b, phiX3a, phiX3b; + double x1a, x2a, x3a, x1b, x2b, x3b, x1c, x2c, x3c, x1d, x2d, x3d; + + for (phiX3a = 0.5 * UbMath::PI; phiX3a > -1.5 * UbMath::PI; phiX3a -= deltaPhi) { + for (phiX1a = 0.0; phiX1a < UbMath::PI; phiX1a += deltaPhi) { + phiX1b = phiX1a + deltaPhi; + phiX3b = phiX3a + deltaPhi; + + x1a = x1m + radius * cos(phiX3a) * std::cos(phiX1a); + x2a = x2m + radius * cos(phiX3a) * std::sin(phiX1a); + x3a = x3m + radius * sin(phiX3a); + x1b = x1m + radius * cos(phiX3a) * std::cos(phiX1b); + x2b = x2m + radius * cos(phiX3a) * std::sin(phiX1b); + x3b = x3m + radius * sin(phiX3a); + x1c = x1m + radius * cos(phiX3b) * std::cos(phiX1b); + x2c = x2m + radius * cos(phiX3b) * std::sin(phiX1b); + x3c = x3m + radius * sin(phiX3b); + x1d = x1m + radius * cos(phiX3b) * std::cos(phiX1a); + x2d = x2m + radius * cos(phiX3b) * std::sin(phiX1a); + x3d = x3m + radius * sin(phiX3b); + + if (UbMath::greater(phiX3b, -0.5 * UbMath::PI) && UbMath::less(phiX3a, 0.5 * UbMath::PI)) { + triangles.push_back(new GbTriangle3D(new GbPoint3D(x1a, x2a, x3a), new GbPoint3D(x1b, x2b, x3b), + new GbPoint3D(x1c, x2c, x3c))); + triangles.push_back(new GbTriangle3D(new GbPoint3D(x1a, x2a, x3a), new GbPoint3D(x1c, x2c, x3c), + new GbPoint3D(x1d, x2d, x3d))); + } else { + triangles.push_back(new GbTriangle3D(new GbPoint3D(x1d, x2d, x3d), new GbPoint3D(x1c, x2c, x3c), + new GbPoint3D(x1a, x2a, x3a))); + triangles.push_back(new GbTriangle3D(new GbPoint3D(x1c, x2c, x3c), new GbPoint3D(x1b, x2b, x3b), + new GbPoint3D(x1a, x2a, x3a))); + } } - else - { - triangles.push_back(new GbTriangle3D(new GbPoint3D(x1d,x2d,x3d),new GbPoint3D(x1c,x2c,x3c),new GbPoint3D(x1a,x2a,x3a))); - triangles.push_back(new GbTriangle3D(new GbPoint3D(x1c,x2c,x3c),new GbPoint3D(x1b,x2b,x3b),new GbPoint3D(x1a,x2a,x3a))); + } + return triangles; + } else if (triangulationMode == CUBOIDPROJECTION) { + vector<GbTriangle3D *> triangles; + vector<GbPoint3D *> points; + double x1min = this->getX1Minimum(); + double x2min = this->getX2Minimum(); + double x3min = this->getX3Minimum(); + double x1max = this->getX1Maximum(); + double x2max = this->getX2Maximum(); + double x3max = this->getX3Maximum(); + double ax1 = x1min; + double bx2 = x2min; + double cx1 = x1min; + double ax2 = x2min; + double bx3 = x3min; + double cx3 = x3min; + + int anzahl = 20; + double dx1 = (x1max - x1min) / (double)(anzahl - 1); + double dx2 = (x2max - x2min) / (double)(anzahl - 1); + double dx3 = (x3max - x3min) / (double)(anzahl - 1); + + for (int u = 0; u < anzahl; u++) { + ax2 = x2min; + bx2 = x2min; + cx3 = x3min; + for (int v = 0; v < anzahl; v++) { + GbPoint3D p1 = GbPoint3D(ax1, ax2, x3max); + GbPoint3D p2 = GbPoint3D(ax1, ax2, x3min); + GbPoint3D p3 = GbPoint3D(cx1, x2min, cx3); + GbPoint3D p4 = GbPoint3D(cx1, x2max, cx3); + GbPoint3D p5 = GbPoint3D(x1min, bx2, bx3); + GbPoint3D p6 = GbPoint3D(x1max, bx2, bx3); + + GbLine3D *clippedline1 = this->createClippedLine3D(*this->midPoint, p1); + GbLine3D *clippedline2 = this->createClippedLine3D(*this->midPoint, p2); + GbLine3D *clippedline3 = this->createClippedLine3D(*this->midPoint, p3); + GbLine3D *clippedline4 = this->createClippedLine3D(*this->midPoint, p4); + GbLine3D *clippedline5 = this->createClippedLine3D(*this->midPoint, p5); + GbLine3D *clippedline6 = this->createClippedLine3D(*this->midPoint, p6); + points.push_back(new GbPoint3D(clippedline1->getPoint1())); + points.push_back(new GbPoint3D(clippedline2->getPoint1())); + points.push_back(new GbPoint3D(clippedline3->getPoint1())); + points.push_back(new GbPoint3D(clippedline4->getPoint1())); + points.push_back(new GbPoint3D(clippedline5->getPoint1())); + points.push_back(new GbPoint3D(clippedline6->getPoint1())); + clippedline1->deletePoints(); + delete clippedline1; + clippedline2->deletePoints(); + delete clippedline2; + clippedline3->deletePoints(); + delete clippedline3; + clippedline4->deletePoints(); + delete clippedline4; + clippedline5->deletePoints(); + delete clippedline5; + clippedline6->deletePoints(); + delete clippedline6; + ax2 += dx2; + cx3 += dx3; + bx2 += dx2; } - } - } - return triangles; - } - else if(triangulationMode==CUBOIDPROJECTION) - { - vector<GbTriangle3D*> triangles; - vector<GbPoint3D*> points; - double x1min = this->getX1Minimum(); - double x2min = this->getX2Minimum(); - double x3min = this->getX3Minimum(); - double x1max = this->getX1Maximum(); - double x2max = this->getX2Maximum(); - double x3max = this->getX3Maximum(); - double ax1 = x1min; double bx2 = x2min; double cx1 = x1min; - double ax2 = x2min; double bx3 = x3min; double cx3 = x3min; - - int anzahl = 20; - double dx1 = (x1max-x1min)/(double)(anzahl-1); - double dx2 = (x2max-x2min)/(double)(anzahl-1); - double dx3 = (x3max-x3min)/(double)(anzahl-1); - - for (int u=0; u<anzahl; u++) - { - ax2 = x2min; - bx2 = x2min; - cx3 = x3min; - for (int v=0; v<anzahl; v++) - { - GbPoint3D p1 = GbPoint3D(ax1, ax2, x3max); - GbPoint3D p2 = GbPoint3D(ax1, ax2, x3min); - GbPoint3D p3 = GbPoint3D(cx1, x2min, cx3); - GbPoint3D p4 = GbPoint3D(cx1, x2max, cx3); - GbPoint3D p5 = GbPoint3D(x1min, bx2, bx3); - GbPoint3D p6 = GbPoint3D(x1max, bx2, bx3); - - GbLine3D* clippedline1 = this->createClippedLine3D(*this->midPoint, p1); - GbLine3D* clippedline2 = this->createClippedLine3D(*this->midPoint, p2); - GbLine3D* clippedline3 = this->createClippedLine3D(*this->midPoint, p3); - GbLine3D* clippedline4 = this->createClippedLine3D(*this->midPoint, p4); - GbLine3D* clippedline5 = this->createClippedLine3D(*this->midPoint, p5); - GbLine3D* clippedline6 = this->createClippedLine3D(*this->midPoint, p6); - points.push_back(new GbPoint3D(clippedline1->getPoint1())); - points.push_back(new GbPoint3D(clippedline2->getPoint1())); - points.push_back(new GbPoint3D(clippedline3->getPoint1())); - points.push_back(new GbPoint3D(clippedline4->getPoint1())); - points.push_back(new GbPoint3D(clippedline5->getPoint1())); - points.push_back(new GbPoint3D(clippedline6->getPoint1())); - clippedline1->deletePoints(); delete clippedline1; - clippedline2->deletePoints(); delete clippedline2; - clippedline3->deletePoints(); delete clippedline3; - clippedline4->deletePoints(); delete clippedline4; - clippedline5->deletePoints(); delete clippedline5; - clippedline6->deletePoints(); delete clippedline6; - ax2 +=dx2; - cx3 +=dx3; - bx2 +=dx2; - } - ax1 +=dx1; - cx1 +=dx1; - bx3 +=dx3; - } - - int anz = anzahl*anzahl*6; - GbPoint3D* point1 = NULL; - GbPoint3D* point2 = NULL; - GbPoint3D* point3 = NULL; - int anzahl2 = anzahl*6; - int anzahl3 = anzahl2+6; - for (int u=0; u<anz-anzahl3; u++) - { - point1 = new GbPoint3D(points[u+6]); - point2 = new GbPoint3D(points[u]); - point3 = new GbPoint3D(points[u+anzahl2]); - if(u%2 == 0) triangles.push_back(new GbTriangle3D(point1, point2, point3)); - else triangles.push_back(new GbTriangle3D(point2, point1, point3)); - - point1 = new GbPoint3D(points[u+6]); - point2 = new GbPoint3D(points[u+anzahl2]); - point3 = new GbPoint3D(points[u+anzahl3]); - if(u%2 == 0) triangles.push_back(new GbTriangle3D(point1, point2, point3)); - else triangles.push_back(new GbTriangle3D(point2, point1, point3)); - } - for (int u=0; u<anz; u++) delete points[u]; - - return triangles; - } - else throw UbException(UB_EXARGS,"undefined triangulationmode"); + ax1 += dx1; + cx1 += dx1; + bx3 += dx3; + } + + int anz = anzahl * anzahl * 6; + GbPoint3D *point1 = NULL; + GbPoint3D *point2 = NULL; + GbPoint3D *point3 = NULL; + int anzahl2 = anzahl * 6; + int anzahl3 = anzahl2 + 6; + for (int u = 0; u < anz - anzahl3; u++) { + point1 = new GbPoint3D(points[u + 6]); + point2 = new GbPoint3D(points[u]); + point3 = new GbPoint3D(points[u + anzahl2]); + if (u % 2 == 0) + triangles.push_back(new GbTriangle3D(point1, point2, point3)); + else + triangles.push_back(new GbTriangle3D(point2, point1, point3)); + + point1 = new GbPoint3D(points[u + 6]); + point2 = new GbPoint3D(points[u + anzahl2]); + point3 = new GbPoint3D(points[u + anzahl3]); + if (u % 2 == 0) + triangles.push_back(new GbTriangle3D(point1, point2, point3)); + else + triangles.push_back(new GbTriangle3D(point2, point1, point3)); + } + for (int u = 0; u < anz; u++) + delete points[u]; + + return triangles; + } else + throw UbException(UB_EXARGS, "undefined triangulationmode"); } /*=======================================================*/ -void GbSphere3D::addSurfaceTriangleSet(vector<UbTupleFloat3>& nodes, vector<UbTupleInt3>& triangles) +void GbSphere3D::addSurfaceTriangleSet(vector<UbTupleFloat3> &nodes, vector<UbTupleInt3> &triangles) { - //wenn ich viele Kugeln bei der PE rausschreibe sollten die vektoren nicht geresized werden - //nodes.resize(0); - //triangles.resize(0); - - if(triangulationMode==RAYPROJECTION) - { - float x1m = (float)midPoint->getX1Coordinate(); - float x2m = (float)midPoint->getX2Coordinate(); - float x3m = (float)midPoint->getX3Coordinate(); - - int segments =30; - float deltaPhi = (float)UbMath::PI/(float)segments; - float phiX1a,phiX1b,phiX3a,phiX3b; - float x1a,x2a,x3a,x1b,x2b,x3b,x1c,x2c,x3c,x1d,x2d,x3d; - int nodeNr = int(nodes.size()); - for(phiX3a=(float)(0.5*UbMath::PI); phiX3a > (float)(-1.5*UbMath::PI); phiX3a-=deltaPhi) - { - for(phiX1a=0.0; phiX1a<UbMath::PI; phiX1a+=deltaPhi) - { - phiX1b = phiX1a+deltaPhi; - phiX3b = phiX3a+deltaPhi; - - x1a = x1m+(float)(radius*cos(phiX3a)*std::cos(phiX1a)); - x2a = x2m+(float)(radius*cos(phiX3a)*std::sin(phiX1a)); - x3a = x3m+(float)(radius*sin(phiX3a)); - x1b = x1m+(float)(radius*cos(phiX3a)*std::cos(phiX1b)); - x2b = x2m+(float)(radius*cos(phiX3a)*std::sin(phiX1b)); - x3b = x3m+(float)(radius*sin(phiX3a)); - x1c = x1m+(float)(radius*cos(phiX3b)*std::cos(phiX1b)); - x2c = x2m+(float)(radius*cos(phiX3b)*std::sin(phiX1b)); - x3c = x3m+(float)(radius*sin(phiX3b)); - x1d = x1m+(float)(radius*cos(phiX3b)*std::cos(phiX1a)); - x2d = x2m+(float)(radius*cos(phiX3b)*std::sin(phiX1a)); - x3d = x3m+(float)(radius*sin(phiX3b)); - - if(UbMath::greater(phiX3b,-0.5*UbMath::PI) && UbMath::less(phiX3a,0.5*UbMath::PI)) - { - nodes.push_back( makeUbTuple(x1a,x2a,x3a) ); - nodes.push_back( makeUbTuple(x1b,x2b,x3b) ); - nodes.push_back( makeUbTuple(x1c,x2c,x3c) ); - - nodes.push_back( makeUbTuple(x1a,x2a,x3a) ); - nodes.push_back( makeUbTuple(x1c,x2c,x3c) ); - nodes.push_back( makeUbTuple(x1d,x2d,x3d) ); + // wenn ich viele Kugeln bei der PE rausschreibe sollten die vektoren nicht geresized werden + // nodes.resize(0); + // triangles.resize(0); + + if (triangulationMode == RAYPROJECTION) { + float x1m = (float)midPoint->getX1Coordinate(); + float x2m = (float)midPoint->getX2Coordinate(); + float x3m = (float)midPoint->getX3Coordinate(); + + int segments = 30; + float deltaPhi = (float)UbMath::PI / (float)segments; + float phiX1a, phiX1b, phiX3a, phiX3b; + float x1a, x2a, x3a, x1b, x2b, x3b, x1c, x2c, x3c, x1d, x2d, x3d; + int nodeNr = int(nodes.size()); + for (phiX3a = (float)(0.5 * UbMath::PI); phiX3a > (float)(-1.5 * UbMath::PI); phiX3a -= deltaPhi) { + for (phiX1a = 0.0; phiX1a < UbMath::PI; phiX1a += deltaPhi) { + phiX1b = phiX1a + deltaPhi; + phiX3b = phiX3a + deltaPhi; + + x1a = x1m + (float)(radius * cos(phiX3a) * std::cos(phiX1a)); + x2a = x2m + (float)(radius * cos(phiX3a) * std::sin(phiX1a)); + x3a = x3m + (float)(radius * sin(phiX3a)); + x1b = x1m + (float)(radius * cos(phiX3a) * std::cos(phiX1b)); + x2b = x2m + (float)(radius * cos(phiX3a) * std::sin(phiX1b)); + x3b = x3m + (float)(radius * sin(phiX3a)); + x1c = x1m + (float)(radius * cos(phiX3b) * std::cos(phiX1b)); + x2c = x2m + (float)(radius * cos(phiX3b) * std::sin(phiX1b)); + x3c = x3m + (float)(radius * sin(phiX3b)); + x1d = x1m + (float)(radius * cos(phiX3b) * std::cos(phiX1a)); + x2d = x2m + (float)(radius * cos(phiX3b) * std::sin(phiX1a)); + x3d = x3m + (float)(radius * sin(phiX3b)); + + if (UbMath::greater(phiX3b, -0.5 * UbMath::PI) && UbMath::less(phiX3a, 0.5 * UbMath::PI)) { + nodes.push_back(makeUbTuple(x1a, x2a, x3a)); + nodes.push_back(makeUbTuple(x1b, x2b, x3b)); + nodes.push_back(makeUbTuple(x1c, x2c, x3c)); + + nodes.push_back(makeUbTuple(x1a, x2a, x3a)); + nodes.push_back(makeUbTuple(x1c, x2c, x3c)); + nodes.push_back(makeUbTuple(x1d, x2d, x3d)); + } else { + nodes.push_back(makeUbTuple(x1d, x2d, x3d)); + nodes.push_back(makeUbTuple(x1c, x2c, x3c)); + nodes.push_back(makeUbTuple(x1a, x2a, x3a)); + + nodes.push_back(makeUbTuple(x1c, x2c, x3c)); + nodes.push_back(makeUbTuple(x1b, x2b, x3b)); + nodes.push_back(makeUbTuple(x1a, x2a, x3a)); + } + triangles.push_back(makeUbTuple(nodeNr, nodeNr + 1, nodeNr + 2)); + triangles.push_back(makeUbTuple(nodeNr + 3, nodeNr + 4, nodeNr + 5)); + nodeNr += 6; } - else - { - nodes.push_back( makeUbTuple(x1d,x2d,x3d) ); - nodes.push_back( makeUbTuple(x1c,x2c,x3c) ); - nodes.push_back( makeUbTuple(x1a,x2a,x3a) ); - - nodes.push_back( makeUbTuple(x1c,x2c,x3c) ); - nodes.push_back( makeUbTuple(x1b,x2b,x3b) ); - nodes.push_back( makeUbTuple(x1a,x2a,x3a) ); + } + } else if (triangulationMode == CUBOIDPROJECTION) { + vector<GbPoint3D *> points; + double x1min = this->getX1Minimum(); + double x2min = this->getX2Minimum(); + double x3min = this->getX3Minimum(); + double x1max = this->getX1Maximum(); + double x2max = this->getX2Maximum(); + double x3max = this->getX3Maximum(); + double ax1 = x1min; + double bx2 = x2min; + double cx1 = x1min; + double ax2 = x2min; + double bx3 = x3min; + double cx3 = x3min; + + int anzahl = 20; + double dx1 = (x1max - x1min) / (double)(anzahl - 1); + double dx2 = (x2max - x2min) / (double)(anzahl - 1); + double dx3 = (x3max - x3min) / (double)(anzahl - 1); + + for (int u = 0; u < anzahl; u++) { + ax2 = x2min; + bx2 = x2min; + cx3 = x3min; + for (int v = 0; v < anzahl; v++) { + GbPoint3D p1 = GbPoint3D(ax1, ax2, x3max); + GbPoint3D p2 = GbPoint3D(ax1, ax2, x3min); + GbPoint3D p3 = GbPoint3D(cx1, x2min, cx3); + GbPoint3D p4 = GbPoint3D(cx1, x2max, cx3); + GbPoint3D p5 = GbPoint3D(x1min, bx2, bx3); + GbPoint3D p6 = GbPoint3D(x1max, bx2, bx3); + + GbLine3D *clippedline1 = this->createClippedLine3D(*this->midPoint, p1); + GbLine3D *clippedline2 = this->createClippedLine3D(*this->midPoint, p2); + GbLine3D *clippedline3 = this->createClippedLine3D(*this->midPoint, p3); + GbLine3D *clippedline4 = this->createClippedLine3D(*this->midPoint, p4); + GbLine3D *clippedline5 = this->createClippedLine3D(*this->midPoint, p5); + GbLine3D *clippedline6 = this->createClippedLine3D(*this->midPoint, p6); + points.push_back(new GbPoint3D(clippedline1->getPoint1())); + points.push_back(new GbPoint3D(clippedline2->getPoint1())); + points.push_back(new GbPoint3D(clippedline3->getPoint1())); + points.push_back(new GbPoint3D(clippedline4->getPoint1())); + points.push_back(new GbPoint3D(clippedline5->getPoint1())); + points.push_back(new GbPoint3D(clippedline6->getPoint1())); + clippedline1->deletePoints(); + delete clippedline1; + clippedline2->deletePoints(); + delete clippedline2; + clippedline3->deletePoints(); + delete clippedline3; + clippedline4->deletePoints(); + delete clippedline4; + clippedline5->deletePoints(); + delete clippedline5; + clippedline6->deletePoints(); + delete clippedline6; + ax2 += dx2; + cx3 += dx3; + bx2 += dx2; } - triangles.push_back( makeUbTuple(nodeNr, nodeNr+1, nodeNr+2) ); - triangles.push_back( makeUbTuple(nodeNr+3, nodeNr+4, nodeNr+5) ); - nodeNr+=6; - } - } - } - else if(triangulationMode==CUBOIDPROJECTION) - { - vector<GbPoint3D*> points; - double x1min = this->getX1Minimum(); - double x2min = this->getX2Minimum(); - double x3min = this->getX3Minimum(); - double x1max = this->getX1Maximum(); - double x2max = this->getX2Maximum(); - double x3max = this->getX3Maximum(); - double ax1 = x1min; double bx2 = x2min; double cx1 = x1min; - double ax2 = x2min; double bx3 = x3min; double cx3 = x3min; - - int anzahl = 20; - double dx1 = (x1max-x1min)/(double)(anzahl-1); - double dx2 = (x2max-x2min)/(double)(anzahl-1); - double dx3 = (x3max-x3min)/(double)(anzahl-1); - - for (int u=0; u<anzahl; u++) - { - ax2 = x2min; - bx2 = x2min; - cx3 = x3min; - for (int v=0; v<anzahl; v++) - { - GbPoint3D p1 = GbPoint3D(ax1, ax2, x3max); - GbPoint3D p2 = GbPoint3D(ax1, ax2, x3min); - GbPoint3D p3 = GbPoint3D(cx1, x2min, cx3); - GbPoint3D p4 = GbPoint3D(cx1, x2max, cx3); - GbPoint3D p5 = GbPoint3D(x1min, bx2, bx3); - GbPoint3D p6 = GbPoint3D(x1max, bx2, bx3); - - GbLine3D* clippedline1 = this->createClippedLine3D(*this->midPoint, p1); - GbLine3D* clippedline2 = this->createClippedLine3D(*this->midPoint, p2); - GbLine3D* clippedline3 = this->createClippedLine3D(*this->midPoint, p3); - GbLine3D* clippedline4 = this->createClippedLine3D(*this->midPoint, p4); - GbLine3D* clippedline5 = this->createClippedLine3D(*this->midPoint, p5); - GbLine3D* clippedline6 = this->createClippedLine3D(*this->midPoint, p6); - points.push_back(new GbPoint3D(clippedline1->getPoint1())); - points.push_back(new GbPoint3D(clippedline2->getPoint1())); - points.push_back(new GbPoint3D(clippedline3->getPoint1())); - points.push_back(new GbPoint3D(clippedline4->getPoint1())); - points.push_back(new GbPoint3D(clippedline5->getPoint1())); - points.push_back(new GbPoint3D(clippedline6->getPoint1())); - clippedline1->deletePoints(); delete clippedline1; - clippedline2->deletePoints(); delete clippedline2; - clippedline3->deletePoints(); delete clippedline3; - clippedline4->deletePoints(); delete clippedline4; - clippedline5->deletePoints(); delete clippedline5; - clippedline6->deletePoints(); delete clippedline6; - ax2 +=dx2; - cx3 +=dx3; - bx2 +=dx2; - } - ax1 +=dx1; - cx1 +=dx1; - bx3 +=dx3; - } - - int anz = anzahl*anzahl*6; - int anzahl2 = anzahl*6; - int anzahl3 = anzahl2+6; - int nodeNr = 0; - for (int u=0; u<anz-anzahl3; u++) - { - nodes.push_back( makeUbTuple((float)points[u+6]->x1 , (float)points[u+6]->x2 , (float)points[u+6]->x3) ); - nodes.push_back( makeUbTuple((float)points[u]->x1 , (float)points[u]->x2 , (float)points[u]->x3) ); - nodes.push_back( makeUbTuple((float)points[u+anzahl2]->x1, (float)points[u+anzahl2]->x2, (float)points[u+anzahl2]->x3) ); - - if(u%2 == 0) triangles.push_back( makeUbTuple(nodeNr , nodeNr+1, nodeNr+2) ); - else triangles.push_back( makeUbTuple(nodeNr , nodeNr+1, nodeNr+2) ); - - nodes.push_back( makeUbTuple((float)points[u+6]->x1 , (float)points[u+6]->x2 , (float)points[u+6]->x3) ); - nodes.push_back( makeUbTuple((float)points[u+anzahl2]->x1, (float)points[u+anzahl2]->x2, (float)points[u+anzahl2]->x3) ); - nodes.push_back( makeUbTuple((float)points[u+anzahl3]->x1, (float)points[u+anzahl3]->x2, (float)points[u+anzahl3]->x3) ); - if(u%2 == 0) triangles.push_back( makeUbTuple(nodeNr+3, nodeNr+4, nodeNr+5) ); - else triangles.push_back( makeUbTuple(nodeNr+3, nodeNr+4, nodeNr+5) ); - - nodeNr+=6; - } - for(int u=0; u<anz; u++) delete points[u]; - } - else throw UbException(UB_EXARGS,"undefined triangulationmode"); + ax1 += dx1; + cx1 += dx1; + bx3 += dx3; + } + + int anz = anzahl * anzahl * 6; + int anzahl2 = anzahl * 6; + int anzahl3 = anzahl2 + 6; + int nodeNr = 0; + for (int u = 0; u < anz - anzahl3; u++) { + nodes.push_back(makeUbTuple((float)points[u + 6]->x1, (float)points[u + 6]->x2, (float)points[u + 6]->x3)); + nodes.push_back(makeUbTuple((float)points[u]->x1, (float)points[u]->x2, (float)points[u]->x3)); + nodes.push_back(makeUbTuple((float)points[u + anzahl2]->x1, (float)points[u + anzahl2]->x2, + (float)points[u + anzahl2]->x3)); + + if (u % 2 == 0) + triangles.push_back(makeUbTuple(nodeNr, nodeNr + 1, nodeNr + 2)); + else + triangles.push_back(makeUbTuple(nodeNr, nodeNr + 1, nodeNr + 2)); + + nodes.push_back(makeUbTuple((float)points[u + 6]->x1, (float)points[u + 6]->x2, (float)points[u + 6]->x3)); + nodes.push_back(makeUbTuple((float)points[u + anzahl2]->x1, (float)points[u + anzahl2]->x2, + (float)points[u + anzahl2]->x3)); + nodes.push_back(makeUbTuple((float)points[u + anzahl3]->x1, (float)points[u + anzahl3]->x2, + (float)points[u + anzahl3]->x3)); + if (u % 2 == 0) + triangles.push_back(makeUbTuple(nodeNr + 3, nodeNr + 4, nodeNr + 5)); + else + triangles.push_back(makeUbTuple(nodeNr + 3, nodeNr + 4, nodeNr + 5)); + + nodeNr += 6; + } + for (int u = 0; u < anz; u++) + delete points[u]; + } else + throw UbException(UB_EXARGS, "undefined triangulationmode"); } /*=======================================================*/ void GbSphere3D::transform(const double matrix[4][4]) { - midPoint->transform(matrix); - this->setRadius(this->getRadius()*matrix[0][0]); - this->notifyObserversObjectChanged(); + midPoint->transform(matrix); + this->setRadius(this->getRadius() * matrix[0][0]); + this->notifyObserversObjectChanged(); } /*=======================================================*/ bool GbSphere3D::hasIntersectionWithDirectedLine(GbPoint3D origin, GbPoint3D direction) { - GbVector3D vecOrigin(origin.getX1Coordinate(),origin.getX2Coordinate(), origin.getX3Coordinate()) ; - GbVector3D vecDirection(direction.getX1Coordinate(),direction.getX2Coordinate(), direction.getX3Coordinate()); - GbVector3D vecSfereCenter(getX1Centroid(), getX2Centroid(), getX3Centroid()); - GbVector3D diff = vecOrigin - vecSfereCenter; - float a = (float)(vecDirection.Dot(vecDirection)); - float b = (float)(2.0 * vecDirection.Dot(diff)); - float c = (float)(diff.Dot(diff) - this->getRadius()*this->getRadius()); - - // use 'abc'-formula for finding root t_1,2 = (-b +/- sqrt(b^2-4ac))/(2a) - float inRoot = (float)(b*b - 4.0*a*c); - if (inRoot < 0) return false; - float root = sqrt(inRoot); - - float dist = (float)((-b - root)/(2.0*a)); - - double infinity = DBL_MAX; - double eps = 1E-4; - - if (dist > infinity) - return false; - - if (dist < eps) - { - dist = (float)((-b + root)/(2.0*a)); - if (dist < eps || dist > infinity) - return false; - } - return true; + GbVector3D vecOrigin(origin.getX1Coordinate(), origin.getX2Coordinate(), origin.getX3Coordinate()); + GbVector3D vecDirection(direction.getX1Coordinate(), direction.getX2Coordinate(), direction.getX3Coordinate()); + GbVector3D vecSfereCenter(getX1Centroid(), getX2Centroid(), getX3Centroid()); + GbVector3D diff = vecOrigin - vecSfereCenter; + float a = (float)(vecDirection.Dot(vecDirection)); + float b = (float)(2.0 * vecDirection.Dot(diff)); + float c = (float)(diff.Dot(diff) - this->getRadius() * this->getRadius()); + + // use 'abc'-formula for finding root t_1,2 = (-b +/- sqrt(b^2-4ac))/(2a) + float inRoot = (float)(b * b - 4.0 * a * c); + if (inRoot < 0) + return false; + float root = sqrt(inRoot); + + float dist = (float)((-b - root) / (2.0 * a)); + + double infinity = DBL_MAX; + double eps = 1E-4; + + if (dist > infinity) + return false; + + if (dist < eps) { + dist = (float)((-b + root) / (2.0 * a)); + if (dist < eps || dist > infinity) + return false; + } + return true; } /*=======================================================*/ -bool GbSphere3D::isCellCuttingGbObject3D(const double& x1a,const double& x2a,const double& x3a,const double& x1b,const double& x2b,const double& x3b) -//Merksatz: cell oder deren Volumen schneidet oder beinhaltet komplette oder Teile der SphereUmrandung -//returns true: +bool GbSphere3D::isCellCuttingGbObject3D(const double &x1a, const double &x2a, const double &x3a, const double &x1b, + const double &x2b, const double &x3b) +// Merksatz: cell oder deren Volumen schneidet oder beinhaltet komplette oder Teile der SphereUmrandung +// returns true: // - cell cuts sphere3D // - cell boxes sphere3D -//returns false: +// returns false: // - cell completely inside sphere3D ( = sphere3D boxes cell) // - cell und sphere3D haben kein gemeinsames Volumen { - double midX[] = { this->getX1Centroid() - , this->getX2Centroid() - , this->getX3Centroid() }; - - double Bmin[] = { UbMath::min(x1a, x1b) - , UbMath::min(x2a, x2b) - , UbMath::min(x3a, x3b) }; - - double Bmax[] = { UbMath::max(x1a, x1b) - , UbMath::max(x2a, x2b) - , UbMath::max(x3a, x3b) }; - - /* Solid Box - Hollow Sphere */ - double dmin = 0.0; - double dmax = 0.0; - double r2 = radius*radius; - - for( int i=0; i<3; i++ ) - { - double a = pow( midX[i] - Bmin[i], 2.0 ); - double b = pow( midX[i] - Bmax[i], 2.0 ); - dmax += UbMath::max( a, b ); - if ( UbMath::less ( midX[i], Bmin[i] ) ) dmin += a; - else if( UbMath::greater( midX[i], Bmax[i] ) ) dmin += b; - } - if( UbMath::lessEqual(dmin, r2 ) - && UbMath::lessEqual(r2 , dmax ) ) - { - return true; - } - return false; + double midX[] = { this->getX1Centroid(), this->getX2Centroid(), this->getX3Centroid() }; + + double Bmin[] = { UbMath::min(x1a, x1b), UbMath::min(x2a, x2b), UbMath::min(x3a, x3b) }; + + double Bmax[] = { UbMath::max(x1a, x1b), UbMath::max(x2a, x2b), UbMath::max(x3a, x3b) }; + + /* Solid Box - Hollow Sphere */ + double dmin = 0.0; + double dmax = 0.0; + double r2 = radius * radius; + + for (int i = 0; i < 3; i++) { + double a = pow(midX[i] - Bmin[i], 2.0); + double b = pow(midX[i] - Bmax[i], 2.0); + dmax += UbMath::max(a, b); + if (UbMath::less(midX[i], Bmin[i])) + dmin += a; + else if (UbMath::greater(midX[i], Bmax[i])) + dmin += b; + } + if (UbMath::lessEqual(dmin, r2) && UbMath::lessEqual(r2, dmax)) { + return true; + } + return false; } /*=======================================================*/ -bool GbSphere3D::isCellInsideOrCuttingGbObject3D(const double& x1a,const double& x2a,const double& x3a,const double& x1b,const double& x2b,const double& x3b) -//returns true: +bool GbSphere3D::isCellInsideOrCuttingGbObject3D(const double &x1a, const double &x2a, const double &x3a, + const double &x1b, const double &x2b, const double &x3b) +// returns true: // - cell completely inside sphere3D ( = sphere3D boxes cell) // - cell cuts sphere3D // - cell boxes sphere3D -//returns false: +// returns false: // - cell und sphere3D haben kein gemeinsames Volumen { - //URL: http://tog.acm.org/GraphicsGems/gems/BoxSphere.c (mode=4, beides solids!!!) - // solid - solid - //this routine tests for intersection between an 3-dimensional - //axis-aligned box and an 3-dimensional sphere. - - //true: - // - wenn Schnitt - // - Cell komplett innerhalb GbSphere3D - // - Cell umhuellt GbSphere3D - - - double midX1 = this->getX1Centroid(); - double midX2 = this->getX2Centroid(); - double midX3 = this->getX3Centroid(); - - double dmin = 0.0; - - if ( UbMath::less ( midX1, x1a ) ) dmin += std::pow( midX1 - x1a, 2.0 ); - else if( UbMath::greater( midX1, x1b ) ) dmin += std::pow( midX1 - x1b, 2.0 ); - - if ( UbMath::less ( midX2, x2a ) ) dmin += std::pow( midX2 - x2a, 2.0 ); - else if( UbMath::greater( midX2, x2b ) ) dmin += std::pow( midX2 - x2b, 2.0 ); - - if ( UbMath::less ( midX3, x3a ) ) dmin += std::pow( midX3 - x3a, 2.0 ); - else if( UbMath::greater( midX3, x3b ) ) dmin += std::pow( midX3 - x3b, 2.0 ); - - if( UbMath::lessEqual( dmin, radius*radius ) ) - { - return true; - } - - return false; + // URL: http://tog.acm.org/GraphicsGems/gems/BoxSphere.c (mode=4, beides solids!!!) + // solid - solid + // this routine tests for intersection between an 3-dimensional + // axis-aligned box and an 3-dimensional sphere. + + // true: + // - wenn Schnitt + // - Cell komplett innerhalb GbSphere3D + // - Cell umhuellt GbSphere3D + + double midX1 = this->getX1Centroid(); + double midX2 = this->getX2Centroid(); + double midX3 = this->getX3Centroid(); + + double dmin = 0.0; + + if (UbMath::less(midX1, x1a)) + dmin += std::pow(midX1 - x1a, 2.0); + else if (UbMath::greater(midX1, x1b)) + dmin += std::pow(midX1 - x1b, 2.0); + + if (UbMath::less(midX2, x2a)) + dmin += std::pow(midX2 - x2a, 2.0); + else if (UbMath::greater(midX2, x2b)) + dmin += std::pow(midX2 - x2b, 2.0); + + if (UbMath::less(midX3, x3a)) + dmin += std::pow(midX3 - x3a, 2.0); + else if (UbMath::greater(midX3, x3b)) + dmin += std::pow(midX3 - x3b, 2.0); + + if (UbMath::lessEqual(dmin, radius * radius)) { + return true; + } + + return false; } /*==========================================================*/ -double GbSphere3D::getCellVolumeInsideGbObject3D(const double& x1a,const double& x2a,const double& x3a,const double& x1b,const double& x2b,const double& x3b) +double GbSphere3D::getCellVolumeInsideGbObject3D(const double &x1a, const double &x2a, const double &x3a, + const double &x1b, const double &x2b, const double &x3b) { - double deltaX1 = (x1b-x1a); - double deltaX2 = (x2b-x2a); - double deltaX3 = (x3b-x3a); - - if( this->isCellInsideGbObject3D(x1a,x2a,x3a,x1b,x2b,x3b) ) return 1.0*deltaX1*deltaX2*deltaX3; - if( !(this->isCellCuttingGbObject3D(x1a,x2a,x3a,x1b,x2b,x3b)) ) return 0.0; - - double tempResult = 0.0; - - int iMax = 10; - int jMax = 10; - int kMax = 10; - - for( int i=0; i<iMax; i++){ - for( int j=0; j<jMax; j++){ - for( int k=0; k<kMax; k++){ - - tempResult += getCellVolumeInsideGbObject3DHelperFunction( - x1a+((double) i )*deltaX1/((double)iMax), x2a+((double) j )*deltaX2/((double)jMax), x3a+((double) k )*deltaX3/((double)kMax), - x1a+((double)(i+1))*deltaX1/((double)iMax), x2a+((double)(j+1))*deltaX2/((double)jMax), x3a+((double)(k+1))*deltaX3/((double)kMax) ); - } - } - } - - - // double resultWithOneCell = getCellVolumeInsideGbObject3DHelperFunction( x1a, x2a, x3a, x1b, x2b, x3b ); - // cout << tempResult << " vs. " << resultWithOneCell << endl; + double deltaX1 = (x1b - x1a); + double deltaX2 = (x2b - x2a); + double deltaX3 = (x3b - x3a); + + if (this->isCellInsideGbObject3D(x1a, x2a, x3a, x1b, x2b, x3b)) + return 1.0 * deltaX1 * deltaX2 * deltaX3; + if (!(this->isCellCuttingGbObject3D(x1a, x2a, x3a, x1b, x2b, x3b))) + return 0.0; + + double tempResult = 0.0; + + int iMax = 10; + int jMax = 10; + int kMax = 10; + + for (int i = 0; i < iMax; i++) { + for (int j = 0; j < jMax; j++) { + for (int k = 0; k < kMax; k++) { + + tempResult += getCellVolumeInsideGbObject3DHelperFunction( + x1a + ((double)i) * deltaX1 / ((double)iMax), x2a + ((double)j) * deltaX2 / ((double)jMax), + x3a + ((double)k) * deltaX3 / ((double)kMax), x1a + ((double)(i + 1)) * deltaX1 / ((double)iMax), + x2a + ((double)(j + 1)) * deltaX2 / ((double)jMax), + x3a + ((double)(k + 1)) * deltaX3 / ((double)kMax)); + } + } + } - return tempResult; + // double resultWithOneCell = getCellVolumeInsideGbObject3DHelperFunction( x1a, x2a, x3a, x1b, x2b, x3b ); + // cout << tempResult << " vs. " << resultWithOneCell << endl; + return tempResult; } /*==========================================================*/ -double GbSphere3D::getCellVolumeInsideGbObject3DHelperFunction(const double& x1a,const double& x2a,const double& x3a,const double& x1b,const double& x2b,const double& x3b) +double GbSphere3D::getCellVolumeInsideGbObject3DHelperFunction(const double &x1a, const double &x2a, const double &x3a, + const double &x1b, const double &x2b, const double &x3b) { - double deltaX1 = x1b-x1a; - double deltaX2 = x2b-x2a; - double deltaX3 = x3b-x3a; - - if( this->isCellInsideGbObject3D(x1a,x2a,x3a,x1b,x2b,x3b) ) return 1.0*deltaX1*deltaX2*deltaX3; - if( !(this->isCellCuttingGbObject3D(x1a,x2a,x3a,x1b,x2b,x3b)) ) return 0.0; - - double alpha=0.0; - double internX1,internX2,internX3; - - for(int x1vers=0;x1vers<2;x1vers++){ - for(int x2vers=0;x2vers<2;x2vers++){ - for(int x3vers=0;x3vers<2;x3vers++){ - internX1 = x1a + (x1b-x1a)*x1vers; - internX2 = x2a + (x2b-x2a)*x2vers; - internX3 = x3a + (x3b-x3a)*x3vers; - - if( UbMath::lessEqual(this->getDistance(internX1,internX2,internX3),alpha) ) - alpha = this->getDistance(internX1,internX2,internX3); - //cout<<zelltyp<<" "<<kugel->getDistance(internX1,internX2,internX3)<<" "<<alpha<<endl; - }//end first for - }//end second for - }//end third for - - alpha = (-1)*alpha; - - - - double n[3]; - n[0] = 0.5*(x1b+x1a) - this->getX1Centroid(); - n[1] = 0.5*(x2b+x2a) - this->getX2Centroid(); - n[2] = 0.5*(x3b+x3a) - this->getX3Centroid(); - - //cout << "Koordinaten: "<<x1<<" "<<x2<<" "<<x3<<endl; - //cout << "Deltas: "<<deltaX1<<" "<<deltaX2<<" "<<deltaX3<<endl; - //cout << "Halbe Zelle: "<<halfcelldelta<<endl; - - //cout<<"Centroid: "<<kugel->getX1Centroid()<<" "<<kugel->getX2Centroid()<<" "<<kugel->getX3Centroid()<<endl; - - //cout<<"Normals: "<<n[0]<<" "<<n[1]<<" "<<n[2]<<endl; - - double normLength; - normLength = sqrt(n[0]*n[0] + n[1]*n[1] + n[2]*n[2]); - n[0] /= normLength; - n[1] /= normLength; - n[2] /= normLength; - - if( UbMath::less(n[0],0.0) ) n[0] = -n[0]; - if( UbMath::less(n[1],0.0) ) n[1] = -n[1]; - if( UbMath::less(n[2],0.0) ) n[2] = -n[2]; - - //cout<<"Normals: "<<n[0]<<" "<<n[1]<<" "<<n[2]<<endl; - - double dummy; - if( UbMath::greater(n[0],n[1])) {dummy=n[1]; n[1]=n[0]; n[0]=dummy;} - if( UbMath::greater(n[1],n[2])) {dummy=n[2]; n[2]=n[1]; n[1]=dummy;} - if( UbMath::greater(n[0],n[1])) {dummy=n[1]; n[1]=n[0]; n[0]=dummy;} - - //cout<<"Normals: "<<n[0]<<" "<<n[1]<<" "<<n[2]<<endl; - - double n1,n2,n3; - n1=n[0]; - n2=n[1]; - n3=n[2]; - - double maxVol = deltaX1*deltaX2*deltaX3; - - double result = 0.0, preresult = 0.0; - - if( UbMath::lessEqual( maxVol, 0.000001 ) ) - return 0.0; - - // 1D Check - if ( UbMath::lessEqual(n1,0.001)&&UbMath::lessEqual(n2,0.001) ) - { - result = alpha*deltaX1*deltaX2; - } - // 2D Check - else if ( UbMath::lessEqual(n1,0.001) ) - { - preresult = (2*n2*n3); - result = (alpha*alpha)/preresult; - - if( UbMath::greater(alpha,n2*deltaX2) ) - { - result += -(alpha-n2*deltaX2)*(alpha-n2*deltaX2)/preresult; - } - if( UbMath::greater(alpha,n3*deltaX3) ) - { - result += -(alpha-n3*deltaX3)*(alpha-n3*deltaX3)/preresult; - } - if( UbMath::greater(alpha,n2*deltaX2+n3*deltaX3) ) - { - result += (alpha-n2*deltaX2-n3*deltaX3)*(alpha-n2*deltaX2-n3*deltaX3)/preresult; - } - - // tiefenrichtung mit einmultiplizieren... - result *= deltaX1; - } - // 3D Check - else - { - preresult =6*n1*n2*n3; - - result = alpha*alpha*alpha; - - if ( UbMath::greaterEqual(alpha,n1*deltaX1)) - { - result+=-((alpha-n1*deltaX1)*(alpha-n1*deltaX1)*(alpha-n1*deltaX1)); - } - if (UbMath::greaterEqual(alpha,n2*deltaX2)) - { - result+=-((alpha-n2*deltaX2)*(alpha-n2*deltaX2)*(alpha-n2*deltaX2)); - } - if (UbMath::greaterEqual(alpha,n3*deltaX3)) - { - result+=-((alpha-n3*deltaX3)*(alpha-n3*deltaX3)*(alpha-n3*deltaX3)); - } - if (UbMath::greaterEqual(alpha,(n1*deltaX1+n2*deltaX2))) - { - result+=((alpha-(n1*deltaX1+n2*deltaX2))*(alpha-(n1*deltaX1+n2*deltaX2))*(alpha-(n1*deltaX1+n2*deltaX2))); - } - if (UbMath::greaterEqual(alpha,(n1*deltaX1+n3*deltaX3))) - { - result+=((alpha-(n1*deltaX1+n3*deltaX3))*(alpha-(n1*deltaX1+n3*deltaX3))*(alpha-(n1*deltaX1+n3*deltaX3))); - } - if (UbMath::greaterEqual(alpha,(n2*deltaX2+n3*deltaX3))) - { - result+=((alpha-(n2*deltaX2+n3*deltaX3))*(alpha-(n2*deltaX2+n3*deltaX3))*(alpha-(n2*deltaX2+n3*deltaX3))); - } - - //NEW - if (UbMath::greaterEqual(alpha,(n1*deltaX1+n2*deltaX2+n3*deltaX3))) - { - result+= -((alpha-(n1*deltaX1+n2*deltaX2+n3*deltaX3))*(alpha-(n1*deltaX1+n2*deltaX2+n3*deltaX3))*(alpha-(n1*deltaX1+n2*deltaX2+n3*deltaX3))); - } - - result = result / preresult; - - } - return(result) ; - - //cout << "alpha ist " << alpha << endl; - //cout << "fillLevel ist " << eps << endl; + double deltaX1 = x1b - x1a; + double deltaX2 = x2b - x2a; + double deltaX3 = x3b - x3a; + + if (this->isCellInsideGbObject3D(x1a, x2a, x3a, x1b, x2b, x3b)) + return 1.0 * deltaX1 * deltaX2 * deltaX3; + if (!(this->isCellCuttingGbObject3D(x1a, x2a, x3a, x1b, x2b, x3b))) + return 0.0; + + double alpha = 0.0; + double internX1, internX2, internX3; + + for (int x1vers = 0; x1vers < 2; x1vers++) { + for (int x2vers = 0; x2vers < 2; x2vers++) { + for (int x3vers = 0; x3vers < 2; x3vers++) { + internX1 = x1a + (x1b - x1a) * x1vers; + internX2 = x2a + (x2b - x2a) * x2vers; + internX3 = x3a + (x3b - x3a) * x3vers; + + if (UbMath::lessEqual(this->getDistance(internX1, internX2, internX3), alpha)) + alpha = this->getDistance(internX1, internX2, internX3); + // cout<<zelltyp<<" "<<kugel->getDistance(internX1,internX2,internX3)<<" "<<alpha<<endl; + } // end first for + } // end second for + } // end third for + + alpha = (-1) * alpha; + + double n[3]; + n[0] = 0.5 * (x1b + x1a) - this->getX1Centroid(); + n[1] = 0.5 * (x2b + x2a) - this->getX2Centroid(); + n[2] = 0.5 * (x3b + x3a) - this->getX3Centroid(); + + // cout << "Koordinaten: "<<x1<<" "<<x2<<" "<<x3<<endl; + // cout << "Deltas: "<<deltaX1<<" "<<deltaX2<<" "<<deltaX3<<endl; + // cout << "Halbe Zelle: "<<halfcelldelta<<endl; + + // cout<<"Centroid: "<<kugel->getX1Centroid()<<" "<<kugel->getX2Centroid()<<" "<<kugel->getX3Centroid()<<endl; + + // cout<<"Normals: "<<n[0]<<" "<<n[1]<<" "<<n[2]<<endl; + + double normLength; + normLength = sqrt(n[0] * n[0] + n[1] * n[1] + n[2] * n[2]); + n[0] /= normLength; + n[1] /= normLength; + n[2] /= normLength; + + if (UbMath::less(n[0], 0.0)) + n[0] = -n[0]; + if (UbMath::less(n[1], 0.0)) + n[1] = -n[1]; + if (UbMath::less(n[2], 0.0)) + n[2] = -n[2]; + + // cout<<"Normals: "<<n[0]<<" "<<n[1]<<" "<<n[2]<<endl; + + double dummy; + if (UbMath::greater(n[0], n[1])) { + dummy = n[1]; + n[1] = n[0]; + n[0] = dummy; + } + if (UbMath::greater(n[1], n[2])) { + dummy = n[2]; + n[2] = n[1]; + n[1] = dummy; + } + if (UbMath::greater(n[0], n[1])) { + dummy = n[1]; + n[1] = n[0]; + n[0] = dummy; + } + + // cout<<"Normals: "<<n[0]<<" "<<n[1]<<" "<<n[2]<<endl; + + double n1, n2, n3; + n1 = n[0]; + n2 = n[1]; + n3 = n[2]; + + double maxVol = deltaX1 * deltaX2 * deltaX3; + + double result = 0.0, preresult = 0.0; + + if (UbMath::lessEqual(maxVol, 0.000001)) + return 0.0; + + // 1D Check + if (UbMath::lessEqual(n1, 0.001) && UbMath::lessEqual(n2, 0.001)) { + result = alpha * deltaX1 * deltaX2; + } + // 2D Check + else if (UbMath::lessEqual(n1, 0.001)) { + preresult = (2 * n2 * n3); + result = (alpha * alpha) / preresult; + + if (UbMath::greater(alpha, n2 * deltaX2)) { + result += -(alpha - n2 * deltaX2) * (alpha - n2 * deltaX2) / preresult; + } + if (UbMath::greater(alpha, n3 * deltaX3)) { + result += -(alpha - n3 * deltaX3) * (alpha - n3 * deltaX3) / preresult; + } + if (UbMath::greater(alpha, n2 * deltaX2 + n3 * deltaX3)) { + result += (alpha - n2 * deltaX2 - n3 * deltaX3) * (alpha - n2 * deltaX2 - n3 * deltaX3) / preresult; + } + + // tiefenrichtung mit einmultiplizieren... + result *= deltaX1; + } + // 3D Check + else { + preresult = 6 * n1 * n2 * n3; + + result = alpha * alpha * alpha; + + if (UbMath::greaterEqual(alpha, n1 * deltaX1)) { + result += -((alpha - n1 * deltaX1) * (alpha - n1 * deltaX1) * (alpha - n1 * deltaX1)); + } + if (UbMath::greaterEqual(alpha, n2 * deltaX2)) { + result += -((alpha - n2 * deltaX2) * (alpha - n2 * deltaX2) * (alpha - n2 * deltaX2)); + } + if (UbMath::greaterEqual(alpha, n3 * deltaX3)) { + result += -((alpha - n3 * deltaX3) * (alpha - n3 * deltaX3) * (alpha - n3 * deltaX3)); + } + if (UbMath::greaterEqual(alpha, (n1 * deltaX1 + n2 * deltaX2))) { + result += ((alpha - (n1 * deltaX1 + n2 * deltaX2)) * (alpha - (n1 * deltaX1 + n2 * deltaX2)) * + (alpha - (n1 * deltaX1 + n2 * deltaX2))); + } + if (UbMath::greaterEqual(alpha, (n1 * deltaX1 + n3 * deltaX3))) { + result += ((alpha - (n1 * deltaX1 + n3 * deltaX3)) * (alpha - (n1 * deltaX1 + n3 * deltaX3)) * + (alpha - (n1 * deltaX1 + n3 * deltaX3))); + } + if (UbMath::greaterEqual(alpha, (n2 * deltaX2 + n3 * deltaX3))) { + result += ((alpha - (n2 * deltaX2 + n3 * deltaX3)) * (alpha - (n2 * deltaX2 + n3 * deltaX3)) * + (alpha - (n2 * deltaX2 + n3 * deltaX3))); + } + + // NEW + if (UbMath::greaterEqual(alpha, (n1 * deltaX1 + n2 * deltaX2 + n3 * deltaX3))) { + result += -((alpha - (n1 * deltaX1 + n2 * deltaX2 + n3 * deltaX3)) * + (alpha - (n1 * deltaX1 + n2 * deltaX2 + n3 * deltaX3)) * + (alpha - (n1 * deltaX1 + n2 * deltaX2 + n3 * deltaX3))); + } + + result = result / preresult; + } + return (result); + + // cout << "alpha ist " << alpha << endl; + // cout << "fillLevel ist " << eps << endl; } /*==========================================================*/ -double GbSphere3D::getIntersectionRaytraceFactor(const double& x1, const double& x2, const double& x3, const double& rx1, const double& rx2, const double& rx3) +double GbSphere3D::getIntersectionRaytraceFactor(const double &x1, const double &x2, const double &x3, + const double &rx1, const double &rx2, const double &rx3) { - double lx1 = midPoint->x1 - x1; - double lx2 = midPoint->x2 - x2; - double lx3 = midPoint->x3 - x3; - double l_sq = lx1*lx1 + lx2*lx2 + lx3*lx3; //l = abstand Punkt(x1,x2,x3)<->kreismittelpunkt - - double s = lx1*rx1 + lx2*rx2 + lx3*rx3; //s= l*ray_dir) - double r_sq = this->radius * this->radius; // r� =r*r - //if (d<0 (fuer die Richtung falls sie gegen das Kreis dann haben wir ein negativer Zahl) - // && l� > r� (point outside )) - //wenn s<0->Punkt liegt rechts vom mittelpunkt, wenn nun punkt ausserhalb des kreises liegt, kann es keinen SP mehr geben - if( s<-1.E-10 && l_sq>r_sq+1.E-10 ) - return -1.0; - //Pythagor on Triangle Rectangle (point, center of the cercle, intersection of the direction on point and m) - // l� = m� + d� - double m_sq = l_sq - s*s; - // if (m� > r� (dann gibt es kein schnittpunt zwischen direction und circle)) - if( m_sq > r_sq+1.E-10 ) return -1.0; - // Pythagoras on Triangle Rectangle in cercle (direction , m, r) - // r� = m� + h� - - //patch: rundungsfehler bei kleinen delta!!! - //-> wenn wurzel minimal null-> - double wurzelTerm = r_sq - m_sq; - if(wurzelTerm<0.0) - { - if(wurzelTerm<-1E-10) return -1.0; //definitiv kein SP - else return s; //im rundungsfehler-bereich. SP liegt dierkt auf sphere umrandung - } - - //if point outside of the circle - if(l_sq>r_sq) return s-sqrt(wurzelTerm); - - return s+sqrt(wurzelTerm); + double lx1 = midPoint->x1 - x1; + double lx2 = midPoint->x2 - x2; + double lx3 = midPoint->x3 - x3; + double l_sq = lx1 * lx1 + lx2 * lx2 + lx3 * lx3; // l = abstand Punkt(x1,x2,x3)<->kreismittelpunkt + + double s = lx1 * rx1 + lx2 * rx2 + lx3 * rx3; // s= l*ray_dir) + double r_sq = this->radius * this->radius; // r� =r*r + // if (d<0 (fuer die Richtung falls sie gegen das Kreis dann haben wir ein negativer Zahl) + // && l� > r� (point outside )) + // wenn s<0->Punkt liegt rechts vom mittelpunkt, wenn nun punkt ausserhalb des kreises liegt, kann es keinen SP mehr + // geben + if (s < -1.E-10 && l_sq > r_sq + 1.E-10) + return -1.0; + // Pythagor on Triangle Rectangle (point, center of the cercle, intersection of the direction on point and m) + // l� = m� + d� + double m_sq = l_sq - s * s; + // if (m� > r� (dann gibt es kein schnittpunt zwischen direction und circle)) + if (m_sq > r_sq + 1.E-10) + return -1.0; + // Pythagoras on Triangle Rectangle in cercle (direction , m, r) + // r� = m� + h� + + // patch: rundungsfehler bei kleinen delta!!! + //-> wenn wurzel minimal null-> + double wurzelTerm = r_sq - m_sq; + if (wurzelTerm < 0.0) { + if (wurzelTerm < -1E-10) + return -1.0; // definitiv kein SP + else + return s; // im rundungsfehler-bereich. SP liegt dierkt auf sphere umrandung + } + + // if point outside of the circle + if (l_sq > r_sq) + return s - sqrt(wurzelTerm); + + return s + sqrt(wurzelTerm); } /*=======================================================*/ diff --git a/src/basics/geometry3d/GbSphere3D.h b/src/basics/geometry3d/GbSphere3D.h index 9fb4ae98aa278ea5256d3695c8a4feb04e876e9c..738a122a185f8a10eddce64d035cea73b96e8b07 100644 --- a/src/basics/geometry3d/GbSphere3D.h +++ b/src/basics/geometry3d/GbSphere3D.h @@ -8,11 +8,11 @@ #define GBSPHERE3D_H #ifdef CAB_CTL - #include <ctl.h> -#endif //CAB_CTL +#include <ctl.h> +#endif // CAB_CTL -#include <vector> #include <cmath> +#include <vector> #include <basics/utilities/UbObserver.h> @@ -26,115 +26,121 @@ class GbTriangle3D; class GbObject3DCreator; class GbSphere3D : public GbObject3D, public UbObserver -{ +{ public: - enum TRIANGULATIONMODE { CUBOIDPROJECTION ,RAYPROJECTION }; - - ////////////////////////////////////////////////////////////////////////// - // Konstruktoren - GbSphere3D(); - GbSphere3D(const double& x1,const double& x2, const double& x3, const double& radius); - GbSphere3D(const GbSphere3D& sphere); - GbSphere3D(GbSphere3D* sphere); //<-unschoen! - - ~GbSphere3D() override; - - GbSphere3D* clone() override { return new GbSphere3D(*this);} - void finalize() override; - - - bool intersects(SPtr<GbSphere3D> sphere); - - double getRadius() const { return this->radius; } - - double getX1Centroid() override { return midPoint->getX1Coordinate();} - double getX1Minimum() override { return midPoint->getX1Coordinate()-radius;} - double getX1Maximum() override { return midPoint->getX1Coordinate()+radius;} - double getX2Centroid() override { return midPoint->getX2Coordinate();} - double getX2Minimum() override { return midPoint->getX2Coordinate()-radius;} - double getX2Maximum() override { return midPoint->getX2Coordinate()+radius;} - double getX3Centroid() override { return midPoint->getX3Coordinate();} - double getX3Minimum() override { return midPoint->getX3Coordinate()-radius;} - double getX3Maximum() override { return midPoint->getX3Coordinate()+radius;} - - void setCenterX1Coordinate(const double& value) override; - void setCenterX2Coordinate(const double& value) override; - void setCenterX3Coordinate(const double& value) override; - void setCenterCoordinates(const double& x1, const double& x2, const double& x3) override; - void setCenterCoordinates(const UbTupleDouble3& position) override; - void setRadius(const double& radius); - - GbLine3D* createClippedLine3D(GbPoint3D& point1, GbPoint3D& point2) override; - double getDistance(GbPoint3D* p); - double getDistance(const double& x1p, const double& x2p, const double& x3p); - - bool isPointInGbObject3D(const double& x1, const double& x2, const double& x3) override; - bool isPointInGbObject3D(const double& x1p, const double& x2p, const double& x3p, bool& pointIsOnBoundary) override; - - bool isCellCuttingGbObject3D(const double& x1a,const double& x2a,const double& x3a,const double& x1b,const double& x2b,const double& x3b) override; - bool isCellInsideOrCuttingGbObject3D(const double& x1a,const double& x2a,const double& x3a,const double& x1b,const double& x2b,const double& x3b) override; - double getCellVolumeInsideGbObject3D(const double& x1a,const double& x2a,const double& x3a,const double& x1b,const double& x2b,const double& x3b) override; - double getCellVolumeInsideGbObject3DHelperFunction(const double& x1a,const double& x2a,const double& x3a,const double& x1b,const double& x2b,const double& x3b); - - std::vector<GbTriangle3D*> getSurfaceTriangleSet() override; - void addSurfaceTriangleSet(std::vector<UbTupleFloat3>& nodes, std::vector<UbTupleInt3>& triangles) override; - - bool hasRaytracing() override { return true; } - /*|r| must be 1! einheitsvector!!*/ - double getIntersectionRaytraceFactor(const double& x1, const double& x2, const double& x3, const double& rx1, const double& rx2, const double& rx3) override; - - bool hasIntersectionWithDirectedLine(GbPoint3D origin, GbPoint3D direction); - - std::string toString() override; - - void translate(const double& x1, const double& x2, const double& x3) override - { - this->midPoint->translate(x1, x2, x3); - this->notifyObserversObjectChanged(); - } - void rotate(const double& rx1, const double& rx2, const double& rx3) override {/* rotation makes no sense*/ } - void scale(const double& sx1, const double& /*sx2*/, const double& /*sx3*/) override - { - this->radius *= sx1; - this->notifyObserversObjectChanged(); - } - - void transform(const double matrix[4][4]); - - TRIANGULATIONMODE getTriangulationMode() {return triangulationMode;} - void setTriangulationMode(TRIANGULATIONMODE mode) { this->triangulationMode = mode; } - - //virtuelle Methoden von UbObserver - void objectChanged(UbObservable* /*changedObject*/) override - { - this->notifyObserversObjectChanged(); - //std::cout<<"GbSphere:objectChanged() - toDo-);"; - } - void objectWillBeDeleted(UbObservable* /*objectForDeletion*/) override - { - throw UbException(UB_EXARGS,"not implemented"); - } - - using GbObject3D::isPointInGbObject3D; //Grund: dadurch muss man hier isPointInGbObject3D(GbPoint3D*) nicht ausprogrammieren, welche sonst hier "ueberdeckt" waere, weil man eine + enum TRIANGULATIONMODE { CUBOIDPROJECTION, RAYPROJECTION }; + + ////////////////////////////////////////////////////////////////////////// + // Konstruktoren + GbSphere3D(); + GbSphere3D(const double &x1, const double &x2, const double &x3, const double &radius); + GbSphere3D(const GbSphere3D &sphere); + GbSphere3D(GbSphere3D *sphere); //<-unschoen! + + ~GbSphere3D() override; + + GbSphere3D *clone() override { return new GbSphere3D(*this); } + void finalize() override; + + bool intersects(SPtr<GbSphere3D> sphere); + + double getRadius() const { return this->radius; } + + double getX1Centroid() override { return midPoint->getX1Coordinate(); } + double getX1Minimum() override { return midPoint->getX1Coordinate() - radius; } + double getX1Maximum() override { return midPoint->getX1Coordinate() + radius; } + double getX2Centroid() override { return midPoint->getX2Coordinate(); } + double getX2Minimum() override { return midPoint->getX2Coordinate() - radius; } + double getX2Maximum() override { return midPoint->getX2Coordinate() + radius; } + double getX3Centroid() override { return midPoint->getX3Coordinate(); } + double getX3Minimum() override { return midPoint->getX3Coordinate() - radius; } + double getX3Maximum() override { return midPoint->getX3Coordinate() + radius; } + + void setCenterX1Coordinate(const double &value) override; + void setCenterX2Coordinate(const double &value) override; + void setCenterX3Coordinate(const double &value) override; + void setCenterCoordinates(const double &x1, const double &x2, const double &x3) override; + void setCenterCoordinates(const UbTupleDouble3 &position) override; + void setRadius(const double &radius); + + GbLine3D *createClippedLine3D(GbPoint3D &point1, GbPoint3D &point2) override; + double getDistance(GbPoint3D *p); + double getDistance(const double &x1p, const double &x2p, const double &x3p); + + bool isPointInGbObject3D(const double &x1, const double &x2, const double &x3) override; + bool isPointInGbObject3D(const double &x1p, const double &x2p, const double &x3p, bool &pointIsOnBoundary) override; + + bool isCellCuttingGbObject3D(const double &x1a, const double &x2a, const double &x3a, const double &x1b, + const double &x2b, const double &x3b) override; + bool isCellInsideOrCuttingGbObject3D(const double &x1a, const double &x2a, const double &x3a, const double &x1b, + const double &x2b, const double &x3b) override; + double getCellVolumeInsideGbObject3D(const double &x1a, const double &x2a, const double &x3a, const double &x1b, + const double &x2b, const double &x3b) override; + double getCellVolumeInsideGbObject3DHelperFunction(const double &x1a, const double &x2a, const double &x3a, + const double &x1b, const double &x2b, const double &x3b); + + std::vector<GbTriangle3D *> getSurfaceTriangleSet() override; + void addSurfaceTriangleSet(std::vector<UbTupleFloat3> &nodes, std::vector<UbTupleInt3> &triangles) override; + + bool hasRaytracing() override { return true; } + /*|r| must be 1! einheitsvector!!*/ + double getIntersectionRaytraceFactor(const double &x1, const double &x2, const double &x3, const double &rx1, + const double &rx2, const double &rx3) override; + + bool hasIntersectionWithDirectedLine(GbPoint3D origin, GbPoint3D direction); + + std::string toString() override; + + void translate(const double &x1, const double &x2, const double &x3) override + { + this->midPoint->translate(x1, x2, x3); + this->notifyObserversObjectChanged(); + } + void rotate(const double &rx1, const double &rx2, const double &rx3) override + { /* rotation makes no sense*/ + } + void scale(const double &sx1, const double & /*sx2*/, const double & /*sx3*/) override + { + this->radius *= sx1; + this->notifyObserversObjectChanged(); + } + + void transform(const double matrix[4][4]); + + TRIANGULATIONMODE getTriangulationMode() { return triangulationMode; } + void setTriangulationMode(TRIANGULATIONMODE mode) { this->triangulationMode = mode; } + + // virtuelle Methoden von UbObserver + void objectChanged(UbObservable * /*changedObject*/) override + { + this->notifyObserversObjectChanged(); + // std::cout<<"GbSphere:objectChanged() - toDo-);"; + } + void objectWillBeDeleted(UbObservable * /*objectForDeletion*/) override + { + throw UbException(UB_EXARGS, "not implemented"); + } + + using GbObject3D::isPointInGbObject3D; // Grund: dadurch muss man hier isPointInGbObject3D(GbPoint3D*) nicht + // ausprogrammieren, welche sonst hier "ueberdeckt" waere, weil man eine #ifdef CAB_CTL - ctl::oStream &write(ctl::oStream &os) const - { - midPoint->write(os); - return os<<radius; - } - ctl::iStream &read(ctl::iStream &is) - { - midPoint->read(is); - return is>>radius; - } -#endif //CAB_CTL + ctl::oStream &write(ctl::oStream &os) const + { + midPoint->write(os); + return os << radius; + } + ctl::iStream &read(ctl::iStream &is) + { + midPoint->read(is); + return is >> radius; + } +#endif // CAB_CTL private: - GbPoint3D* midPoint; - double radius; // Radius des Kreises - TRIANGULATIONMODE triangulationMode; + GbPoint3D *midPoint; + double radius; // Radius des Kreises + TRIANGULATIONMODE triangulationMode; }; - -#endif //GBSPHERE3D_H +#endif // GBSPHERE3D_H diff --git a/src/basics/geometry3d/GbSystem3D.cpp b/src/basics/geometry3d/GbSystem3D.cpp index 142b584f36e441ae7d668b0b153704563ce8d93e..2a49aff7d55cb3f18ff316eb6310c96b92bbc721 100644 --- a/src/basics/geometry3d/GbSystem3D.cpp +++ b/src/basics/geometry3d/GbSystem3D.cpp @@ -1,28 +1,28 @@ //======================================================================================= -// ____ ____ __ ______ __________ __ __ __ __ -// \ \ | | | | | _ \ |___ ___| | | | | / \ | | -// \ \ | | | | | |_) | | | | | | | / \ | | -// \ \ | | | | | _ / | | | | | | / /\ \ | | -// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ -// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| -// \ \ | | ________________________________________________________________ -// \ \ | | | ______________________________________________________________| -// \ \| | | | __ __ __ __ ______ _______ -// \ | | |_____ | | | | | | | | | _ \ / _____) -// \ | | _____| | | | | | | | | | | \ \ \_______ +// ____ ____ __ ______ __________ __ __ __ __ +// \ \ | | | | | _ \ |___ ___| | | | | / \ | | +// \ \ | | | | | |_) | | | | | | | / \ | | +// \ \ | | | | | _ / | | | | | | / /\ \ | | +// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ +// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| +// \ \ | | ________________________________________________________________ +// \ \ | | | ______________________________________________________________| +// \ \| | | | __ __ __ __ ______ _______ +// \ | | |_____ | | | | | | | | | _ \ / _____) +// \ | | _____| | | | | | | | | | | \ \ \_______ // \ | | | | |_____ | \_/ | | | | |_/ / _____ | -// \ _____| |__| |________| \_______/ |__| |______/ (_______/ +// \ _____| |__| |________| \_______/ |__| |______/ (_______/ // -// This file is part of VirtualFluids. VirtualFluids is free software: you can +// This file is part of VirtualFluids. VirtualFluids is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of +// License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. -// -// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// +// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License along // with VirtualFluids (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>. // @@ -30,143 +30,161 @@ //! \ingroup geometry3d //! \author Soeren Freudiger, Sebastian Geller //======================================================================================= -#include <GbSystem3D.h> -#include <GbPolygon3D.h> #include <GbCuboid3D.h> +#include <GbPolygon3D.h> +#include <GbSystem3D.h> using namespace std; -double GbSystem3D::getDistance(const GbPoint3D& p11, const GbPoint3D& p12) +double GbSystem3D::getDistance(const GbPoint3D &p11, const GbPoint3D &p12) { - double dx1 = p11.x1 - p12.x1; - double dx2 = p11.x2 - p12.x2; - double dx3 = p11.x3 - p12.x3; - return std::sqrt(dx1*dx1+dx2*dx2+dx3*dx3); + double dx1 = p11.x1 - p12.x1; + double dx2 = p11.x2 - p12.x2; + double dx3 = p11.x3 - p12.x3; + return std::sqrt(dx1 * dx1 + dx2 * dx2 + dx3 * dx3); } -GbPoint3D* GbSystem3D::calculateIntersectionPoint3D(GbPoint3D& p11, GbPoint3D& p12, GbPoint3D& p21, GbPoint3D& p22) +GbPoint3D *GbSystem3D::calculateIntersectionPoint3D(GbPoint3D &p11, GbPoint3D &p12, GbPoint3D &p21, GbPoint3D &p22) { - if(UbMath::less2(p11.x1, p12.x1, p21.x1, p22.x1)) return NULL; - if(UbMath::less2(p11.x2, p12.x2, p21.x2, p22.x2)) return NULL; - if(UbMath::less2(p11.x3, p12.x3, p21.x3, p22.x3)) return NULL; - if(UbMath::greater2(p11.x1, p12.x1, p21.x1, p22.x1)) return NULL; - if(UbMath::greater2(p11.x2, p12.x2, p21.x2, p22.x2)) return NULL; - if(UbMath::greater2(p11.x3, p12.x3, p21.x3, p22.x3)) return NULL; - - double a11 = p12.x1 - p11.x1; //..HOW PARAMETERS ARE USED......... - double a12 = p12.x2 - p11.x2; // - double a13 = p12.x3 - p11.x3; // p11 and p12 represent line 1 - double a21 = p21.x1 - p22.x1; // p21 and p22 represent line 2 - double a22 = p21.x2 - p22.x2; // - double a23 = p21.x3 - p22.x3; //.................................. - double b1 = p21.x1 - p11.x1; - double b2 = p21.x2 - p11.x2; - double b3 = p21.x3 - p11.x3; - double d1 = a11*a22 - a12*a21; - double d2 = a11*a23 - a13*a21; - double d3 = a12*a23 - a13*a22; - double t; - - if(UbMath::zero(d1) && UbMath::zero(d2) && UbMath::zero(d3)) return NULL; - if(UbMath::zero(d1)) - { - if(!UbMath::zero(d2)) t = (a23*b1-a21*b3)/d2; - else t = (a23*b2-a22*b3)/d3; - } - else if(UbMath::zero(d2)) - { - if(!UbMath::zero(d1)) t = (a22*b1-a21*b2)/d1; - else t = (a23*b2-a22*b3)/d3; - } - else if(UbMath::zero(d3)) - { - if(!UbMath::zero(d1)) t = (a22*b1-a21*b2)/d1; - else t = (a23*b1-a21*b3)/d2; - } - else return NULL; - - double x1 = p11.x1 + t*a11; - double x2 = p11.x2 + t*a12; - double x3 = p11.x3 + t*a13; - - if(UbMath::inClosedInterval(x1, p11.x1, p12.x1) && UbMath::inClosedInterval(x1, p21.x1, p22.x1) && - UbMath::inClosedInterval(x2, p11.x2, p12.x2) && UbMath::inClosedInterval(x2, p21.x2, p22.x2) && - UbMath::inClosedInterval(x3, p11.x3, p12.x3) && UbMath::inClosedInterval(x3, p21.x3, p22.x3) ) return new GbPoint3D(x1, x2, x3); - - return NULL; + if (UbMath::less2(p11.x1, p12.x1, p21.x1, p22.x1)) + return NULL; + if (UbMath::less2(p11.x2, p12.x2, p21.x2, p22.x2)) + return NULL; + if (UbMath::less2(p11.x3, p12.x3, p21.x3, p22.x3)) + return NULL; + if (UbMath::greater2(p11.x1, p12.x1, p21.x1, p22.x1)) + return NULL; + if (UbMath::greater2(p11.x2, p12.x2, p21.x2, p22.x2)) + return NULL; + if (UbMath::greater2(p11.x3, p12.x3, p21.x3, p22.x3)) + return NULL; + + double a11 = p12.x1 - p11.x1; //..HOW PARAMETERS ARE USED......... + double a12 = p12.x2 - p11.x2; // + double a13 = p12.x3 - p11.x3; // p11 and p12 represent line 1 + double a21 = p21.x1 - p22.x1; // p21 and p22 represent line 2 + double a22 = p21.x2 - p22.x2; // + double a23 = p21.x3 - p22.x3; //.................................. + double b1 = p21.x1 - p11.x1; + double b2 = p21.x2 - p11.x2; + double b3 = p21.x3 - p11.x3; + double d1 = a11 * a22 - a12 * a21; + double d2 = a11 * a23 - a13 * a21; + double d3 = a12 * a23 - a13 * a22; + double t; + + if (UbMath::zero(d1) && UbMath::zero(d2) && UbMath::zero(d3)) + return NULL; + if (UbMath::zero(d1)) { + if (!UbMath::zero(d2)) + t = (a23 * b1 - a21 * b3) / d2; + else + t = (a23 * b2 - a22 * b3) / d3; + } else if (UbMath::zero(d2)) { + if (!UbMath::zero(d1)) + t = (a22 * b1 - a21 * b2) / d1; + else + t = (a23 * b2 - a22 * b3) / d3; + } else if (UbMath::zero(d3)) { + if (!UbMath::zero(d1)) + t = (a22 * b1 - a21 * b2) / d1; + else + t = (a23 * b1 - a21 * b3) / d2; + } else + return NULL; + + double x1 = p11.x1 + t * a11; + double x2 = p11.x2 + t * a12; + double x3 = p11.x3 + t * a13; + + if (UbMath::inClosedInterval(x1, p11.x1, p12.x1) && UbMath::inClosedInterval(x1, p21.x1, p22.x1) && + UbMath::inClosedInterval(x2, p11.x2, p12.x2) && UbMath::inClosedInterval(x2, p21.x2, p22.x2) && + UbMath::inClosedInterval(x3, p11.x3, p12.x3) && UbMath::inClosedInterval(x3, p21.x3, p22.x3)) + return new GbPoint3D(x1, x2, x3); + + return NULL; } /*=================================================================*/ -//Line1: p11 -> p12 and Line2: p21 -> p22 -bool GbSystem3D::hasIntersectionPoint3D(GbPoint3D& p11, GbPoint3D& p12, GbPoint3D& p21, GbPoint3D& p22) +// Line1: p11 -> p12 and Line2: p21 -> p22 +bool GbSystem3D::hasIntersectionPoint3D(GbPoint3D &p11, GbPoint3D &p12, GbPoint3D &p21, GbPoint3D &p22) { - if(UbMath::less2(p11.x1, p12.x1, p21.x1, p22.x1)) return false; - if(UbMath::less2(p11.x2, p12.x2, p21.x2, p22.x2)) return false; - if(UbMath::less2(p11.x3, p12.x3, p21.x3, p22.x3)) return false; - if(UbMath::greater2(p11.x1, p12.x1, p21.x1, p22.x1)) return false; - if(UbMath::greater2(p11.x2, p12.x2, p21.x2, p22.x2)) return false; - if(UbMath::greater2(p11.x3, p12.x3, p21.x3, p22.x3)) return false; - - double a11 = p12.x1 - p11.x1; //..HOW PARAMETERS ARE USED......... - double a12 = p12.x2 - p11.x2; // - double a13 = p12.x3 - p11.x3; // p11 and p12 represent line 1 - double a21 = p21.x1 - p22.x1; // p21 and p22 represent line 2 - double a22 = p21.x2 - p22.x2; // - double a23 = p21.x3 - p22.x3; //.................................. - double b1 = p21.x1 - p11.x1; - double b2 = p21.x2 - p11.x2; - double b3 = p21.x3 - p11.x3; - double d1 = a11*a22 - a12*a21; - double d2 = a11*a23 - a13*a21; - double d3 = a12*a23 - a13*a22; - double t; - - if(UbMath::zero(d1) && UbMath::zero(d2) && UbMath::zero(d3)) return false; - if(UbMath::zero(d1)) - { - if(!UbMath::zero(d2)) t = (a23*b1-a21*b3)/d2; - else t = (a23*b2-a22*b3)/d3; - } - else if(UbMath::zero(d2)) - { - if(!UbMath::zero(d1)) t = (a22*b1-a21*b2)/d1; - else t = (a23*b2-a22*b3)/d3; - } - else if(UbMath::zero(d3)) - { - if(!UbMath::zero(d1)) t = (a22*b1-a21*b2)/d1; - else t = (a23*b1-a21*b3)/d2; - } - else return false; - - double x1 = p11.x1 + t*a11; - double x2 = p11.x2 + t*a12; - double x3 = p11.x3 + t*a13; - - if(UbMath::inClosedInterval(x1, p11.x1, p12.x1) && UbMath::inClosedInterval(x1, p21.x1, p22.x1) && - UbMath::inClosedInterval(x2, p11.x2, p12.x2) && UbMath::inClosedInterval(x2, p21.x2, p22.x2) && - UbMath::inClosedInterval(x3, p11.x3, p12.x3) && UbMath::inClosedInterval(x3, p21.x3, p22.x3)) return true; - return false; + if (UbMath::less2(p11.x1, p12.x1, p21.x1, p22.x1)) + return false; + if (UbMath::less2(p11.x2, p12.x2, p21.x2, p22.x2)) + return false; + if (UbMath::less2(p11.x3, p12.x3, p21.x3, p22.x3)) + return false; + if (UbMath::greater2(p11.x1, p12.x1, p21.x1, p22.x1)) + return false; + if (UbMath::greater2(p11.x2, p12.x2, p21.x2, p22.x2)) + return false; + if (UbMath::greater2(p11.x3, p12.x3, p21.x3, p22.x3)) + return false; + + double a11 = p12.x1 - p11.x1; //..HOW PARAMETERS ARE USED......... + double a12 = p12.x2 - p11.x2; // + double a13 = p12.x3 - p11.x3; // p11 and p12 represent line 1 + double a21 = p21.x1 - p22.x1; // p21 and p22 represent line 2 + double a22 = p21.x2 - p22.x2; // + double a23 = p21.x3 - p22.x3; //.................................. + double b1 = p21.x1 - p11.x1; + double b2 = p21.x2 - p11.x2; + double b3 = p21.x3 - p11.x3; + double d1 = a11 * a22 - a12 * a21; + double d2 = a11 * a23 - a13 * a21; + double d3 = a12 * a23 - a13 * a22; + double t; + + if (UbMath::zero(d1) && UbMath::zero(d2) && UbMath::zero(d3)) + return false; + if (UbMath::zero(d1)) { + if (!UbMath::zero(d2)) + t = (a23 * b1 - a21 * b3) / d2; + else + t = (a23 * b2 - a22 * b3) / d3; + } else if (UbMath::zero(d2)) { + if (!UbMath::zero(d1)) + t = (a22 * b1 - a21 * b2) / d1; + else + t = (a23 * b2 - a22 * b3) / d3; + } else if (UbMath::zero(d3)) { + if (!UbMath::zero(d1)) + t = (a22 * b1 - a21 * b2) / d1; + else + t = (a23 * b1 - a21 * b3) / d2; + } else + return false; + + double x1 = p11.x1 + t * a11; + double x2 = p11.x2 + t * a12; + double x3 = p11.x3 + t * a13; + + if (UbMath::inClosedInterval(x1, p11.x1, p12.x1) && UbMath::inClosedInterval(x1, p21.x1, p22.x1) && + UbMath::inClosedInterval(x2, p11.x2, p12.x2) && UbMath::inClosedInterval(x2, p21.x2, p22.x2) && + UbMath::inClosedInterval(x3, p11.x3, p12.x3) && UbMath::inClosedInterval(x3, p21.x3, p22.x3)) + return true; + return false; } - /*======================================================================*/ +/*======================================================================*/ // // // /*======================================================================*/ // /* Private Methoden (Parallelism) */ // /* */ -bool GbSystem3D::isParallelIn3D(GbPoint3D& p11, GbPoint3D& p12, GbPoint3D& p21, GbPoint3D& p22) +bool GbSystem3D::isParallelIn3D(GbPoint3D &p11, GbPoint3D &p12, GbPoint3D &p21, GbPoint3D &p22) { - double a11 = p12.x1 - p11.x1; //..HOW PARAMETERS ARE USED......... - double a12 = p12.x2 - p11.x2; // - double a13 = p12.x3 - p11.x3; // p11 and p12 represent line 1 - double a21 = p21.x1 - p22.x1; // p21 and p22 represent line 2 - double a22 = p21.x2 - p22.x2; // - double a23 = p21.x3 - p22.x3; //.................................. - - return (UbMath::zero(a11*a22 - a12*a21) && UbMath::zero(a11*a23 - a13*a21) && UbMath::zero(a12*a23 - a13*a22)); + double a11 = p12.x1 - p11.x1; //..HOW PARAMETERS ARE USED......... + double a12 = p12.x2 - p11.x2; // + double a13 = p12.x3 - p11.x3; // p11 and p12 represent line 1 + double a21 = p21.x1 - p22.x1; // p21 and p22 represent line 2 + double a22 = p21.x2 - p22.x2; // + double a23 = p21.x3 - p22.x3; //.................................. + + return (UbMath::zero(a11 * a22 - a12 * a21) && UbMath::zero(a11 * a23 - a13 * a21) && + UbMath::zero(a12 * a23 - a13 * a22)); } /*======================================================================*/ - /*======================================================================*/ /* General Clipping Methods */ //......................................................................*/ @@ -181,134 +199,152 @@ bool GbSystem3D::isParallelIn3D(GbPoint3D& p11, GbPoint3D& p12, GbPoint3D& p21, /*======================================================================*/ /* Private Methoden (Clipping Lines) */ /* */ -GbLine3D* GbSystem3D::createClipLine3D(GbPoint3D &pA, GbPoint3D &pB, double x1a, double x2a, double x3a, double x1b, double x2b, double x3b) +GbLine3D *GbSystem3D::createClipLine3D(GbPoint3D &pA, GbPoint3D &pB, double x1a, double x2a, double x3a, double x1b, + double x2b, double x3b) { - GbPoint3D *p1 = new GbPoint3D(pA); - GbPoint3D *p2 = new GbPoint3D(pB); - - if(UbMath::greater(x1a, x1b)) { double x1 = x1a; x1a = x1b; x1b = x1; } - if(UbMath::greater(x2a, x2b)) { double x2 = x2a; x2a = x2b; x2b = x2; } - if(UbMath::greater(x3a, x3b)) { double x3 = x3a; x3a = x3b; x3b = x3; } - - double f; - - /*-------------------------------------------------------------------*/ - /* Schneiden an vorderer Kante */ - /* */ - if(UbMath::less(p1->x3, x3a)) - { - if(UbMath::less(p2->x3, x3a)) { delete p1; delete p2; return NULL; } - - f = (x3a-p1->x3)/(p1->x3-p2->x3); - p1->x1 += (p1->x1-p2->x1)*f; - p1->x2 += (p1->x2-p2->x2)*f; - p1->x3 = x3a; - } - else if(UbMath::less(p2->x3, x3a)) - { - f = (x3a-p2->x3)/(p2->x3-p1->x3); - p2->x1 += (p2->x1-p1->x1)*f; - p2->x2 += (p2->x2-p1->x2)*f; - p2->x3 = x3a; - } - /*-------------------------------------------------------------------*/ - /* Schneiden an unterer Kante */ - /* */ - if(UbMath::less(p1->x2, x2a)) - { - if(UbMath::less(p2->x2, x2a)) { delete p1; delete p2; return NULL; - } - - f = (x2a-p1->x2)/(p1->x2-p2->x2); - p1->x1 += (p1->x1-p2->x1)*f; - p1->x3 += (p1->x3-p2->x3)*f; - p1->x2 = x2a; - } - else if(UbMath::less(p2->x2, x2a)) - { - f = (x2a-p2->x2)/(p2->x2-p1->x2); - p2->x1 += (p2->x1-p1->x1)*f; - p2->x3 += (p2->x3-p1->x3)*f; - p2->x2 = x2a; - } - /*-------------------------------------------------------------------*/ - /* Schneiden an rechter Kante */ - /* */ - if(UbMath::greater(p1->x1, x1b)) - { - if(UbMath::greater(p2->x1, x1b)) { delete p1;delete p2; return NULL;} - - f = (x1b-p1->x1)/(p1->x1-p2->x1); - p1->x2 += (p1->x2-p2->x2)*f; - p1->x3 += (p1->x3-p2->x3)*f; - p1->x1 = x1b; - } - else if(UbMath::greater(p2->x1, x1b)) - { - f = (x1b-p2->x1)/(p2->x1-p1->x1); - p2->x2 += (p2->x2-p1->x2)*f; - p2->x3 += (p2->x3-p1->x3)*f; - p2->x1 = x1b; - } - /*-------------------------------------------------------------------*/ - /* Schneiden an hinterer Kante */ - /* */ - if(UbMath::greater(p1->x3, x3b)) - { - if(UbMath::greater(p2->x3, x3b)) { delete p1;delete p2; return NULL;} - - f = (x3b-p1->x3)/(p1->x3-p2->x3); - p1->x1 += (p1->x1-p2->x1)*f; - p1->x2 += (p1->x2-p2->x2)*f; - p1->x3 = x3b; - } - else if(UbMath::greater(p2->x3, x3b)) - { - f = (x3b-p2->x3)/(p2->x3-p1->x3); - p2->x1 += (p2->x1-p1->x1)*f; - p2->x2 += (p2->x2-p1->x2)*f; - p2->x3 = x3b; - } - /*-------------------------------------------------------------------*/ - /* Schneiden an oberer Kante */ - /* */ - if(UbMath::greater(p1->x2, x2b)) - { - if(UbMath::greater(p2->x2, x2b)) { delete p1;delete p2; return NULL;} - - f = (x2b-p1->x2)/(p1->x2-p2->x2); - p1->x1 += (p1->x1-p2->x1)*f; - p1->x3 += (p1->x3-p2->x3)*f; - p1->x2 = x2b; - } - else if(UbMath::greater(p2->x2, x2b)) - { - f = (x2b-p2->x2)/(p2->x2-p1->x2); - p2->x1 += (p2->x1-p1->x1)*f; - p2->x3 += (p2->x3-p1->x3)*f; - p2->x2 = x2b; - } - /*-------------------------------------------------------------------*/ - /* Schneiden an linker Kante */ - /* */ - if(UbMath::less(p1->x1, x1a)) - { - if(UbMath::less(p2->x1, x1a)) { delete p1;delete p2; return NULL;} - - f = (x1a-p1->x1)/(p1->x1-p2->x1); - p1->x2 += (p1->x2-p2->x2)*f; - p1->x3 += (p1->x3-p2->x3)*f; - p1->x1 = x1a; - } - else if(UbMath::less(p2->x1, x1a)) - { - f = (x1a-p2->x1)/(p2->x1-p1->x1); - p2->x2 += (p2->x2-p1->x2)*f; - p2->x3 += (p2->x3-p1->x3)*f; - p2->x1 = x1a; - } - /*-------------------------------------------------------------------*/ - return new GbLine3D(p1, p2); + GbPoint3D *p1 = new GbPoint3D(pA); + GbPoint3D *p2 = new GbPoint3D(pB); + + if (UbMath::greater(x1a, x1b)) { + double x1 = x1a; + x1a = x1b; + x1b = x1; + } + if (UbMath::greater(x2a, x2b)) { + double x2 = x2a; + x2a = x2b; + x2b = x2; + } + if (UbMath::greater(x3a, x3b)) { + double x3 = x3a; + x3a = x3b; + x3b = x3; + } + + double f; + + /*-------------------------------------------------------------------*/ + /* Schneiden an vorderer Kante */ + /* */ + if (UbMath::less(p1->x3, x3a)) { + if (UbMath::less(p2->x3, x3a)) { + delete p1; + delete p2; + return NULL; + } + + f = (x3a - p1->x3) / (p1->x3 - p2->x3); + p1->x1 += (p1->x1 - p2->x1) * f; + p1->x2 += (p1->x2 - p2->x2) * f; + p1->x3 = x3a; + } else if (UbMath::less(p2->x3, x3a)) { + f = (x3a - p2->x3) / (p2->x3 - p1->x3); + p2->x1 += (p2->x1 - p1->x1) * f; + p2->x2 += (p2->x2 - p1->x2) * f; + p2->x3 = x3a; + } + /*-------------------------------------------------------------------*/ + /* Schneiden an unterer Kante */ + /* */ + if (UbMath::less(p1->x2, x2a)) { + if (UbMath::less(p2->x2, x2a)) { + delete p1; + delete p2; + return NULL; + } + + f = (x2a - p1->x2) / (p1->x2 - p2->x2); + p1->x1 += (p1->x1 - p2->x1) * f; + p1->x3 += (p1->x3 - p2->x3) * f; + p1->x2 = x2a; + } else if (UbMath::less(p2->x2, x2a)) { + f = (x2a - p2->x2) / (p2->x2 - p1->x2); + p2->x1 += (p2->x1 - p1->x1) * f; + p2->x3 += (p2->x3 - p1->x3) * f; + p2->x2 = x2a; + } + /*-------------------------------------------------------------------*/ + /* Schneiden an rechter Kante */ + /* */ + if (UbMath::greater(p1->x1, x1b)) { + if (UbMath::greater(p2->x1, x1b)) { + delete p1; + delete p2; + return NULL; + } + + f = (x1b - p1->x1) / (p1->x1 - p2->x1); + p1->x2 += (p1->x2 - p2->x2) * f; + p1->x3 += (p1->x3 - p2->x3) * f; + p1->x1 = x1b; + } else if (UbMath::greater(p2->x1, x1b)) { + f = (x1b - p2->x1) / (p2->x1 - p1->x1); + p2->x2 += (p2->x2 - p1->x2) * f; + p2->x3 += (p2->x3 - p1->x3) * f; + p2->x1 = x1b; + } + /*-------------------------------------------------------------------*/ + /* Schneiden an hinterer Kante */ + /* */ + if (UbMath::greater(p1->x3, x3b)) { + if (UbMath::greater(p2->x3, x3b)) { + delete p1; + delete p2; + return NULL; + } + + f = (x3b - p1->x3) / (p1->x3 - p2->x3); + p1->x1 += (p1->x1 - p2->x1) * f; + p1->x2 += (p1->x2 - p2->x2) * f; + p1->x3 = x3b; + } else if (UbMath::greater(p2->x3, x3b)) { + f = (x3b - p2->x3) / (p2->x3 - p1->x3); + p2->x1 += (p2->x1 - p1->x1) * f; + p2->x2 += (p2->x2 - p1->x2) * f; + p2->x3 = x3b; + } + /*-------------------------------------------------------------------*/ + /* Schneiden an oberer Kante */ + /* */ + if (UbMath::greater(p1->x2, x2b)) { + if (UbMath::greater(p2->x2, x2b)) { + delete p1; + delete p2; + return NULL; + } + + f = (x2b - p1->x2) / (p1->x2 - p2->x2); + p1->x1 += (p1->x1 - p2->x1) * f; + p1->x3 += (p1->x3 - p2->x3) * f; + p1->x2 = x2b; + } else if (UbMath::greater(p2->x2, x2b)) { + f = (x2b - p2->x2) / (p2->x2 - p1->x2); + p2->x1 += (p2->x1 - p1->x1) * f; + p2->x3 += (p2->x3 - p1->x3) * f; + p2->x2 = x2b; + } + /*-------------------------------------------------------------------*/ + /* Schneiden an linker Kante */ + /* */ + if (UbMath::less(p1->x1, x1a)) { + if (UbMath::less(p2->x1, x1a)) { + delete p1; + delete p2; + return NULL; + } + + f = (x1a - p1->x1) / (p1->x1 - p2->x1); + p1->x2 += (p1->x2 - p2->x2) * f; + p1->x3 += (p1->x3 - p2->x3) * f; + p1->x1 = x1a; + } else if (UbMath::less(p2->x1, x1a)) { + f = (x1a - p2->x1) / (p2->x1 - p1->x1); + p2->x2 += (p2->x2 - p1->x2) * f; + p2->x3 += (p2->x3 - p1->x3) * f; + p2->x1 = x1a; + } + /*-------------------------------------------------------------------*/ + return new GbLine3D(p1, p2); } // /*======================================================================*/ // /* Private Methoden (Clipping Rectangles) */ @@ -346,7 +382,8 @@ GbLine3D* GbSystem3D::createClipLine3D(GbPoint3D &pA, GbPoint3D &pB, double x1a, // if(flag) // { // f = (x12-(*points)[i]->x2)/((*points)[i]->x2-last->x2); -// ps.add(new GbPoint3D((*points)[i]->x1 + ((*points)[i]->x1-last->x1)*f, x12, (*points)[i]->x3 + ((*points)[i]->x3-last->x3)*f)); +// ps.add(new GbPoint3D((*points)[i]->x1 + ((*points)[i]->x1-last->x1)*f, x12, (*points)[i]->x3 + +//((*points)[i]->x3-last->x3)*f)); // } // flag = false; // } @@ -355,7 +392,8 @@ GbLine3D* GbSystem3D::createClipLine3D(GbPoint3D &pA, GbPoint3D &pB, double x1a, // if(!flag) // { // f = (x12-(*points)[i]->x2)/((*points)[i]->x2-last->x2); -// ps.add(new GbPoint3D((*points)[i]->x1 + ((*points)[i]->x1-last->x1)*f, x12, (*points)[i]->x3 + ((*points)[i]->x3-last->x3)*f)); +// ps.add(new GbPoint3D((*points)[i]->x1 + ((*points)[i]->x1-last->x1)*f, x12, (*points)[i]->x3 + +//((*points)[i]->x3-last->x3)*f)); // } // ps.add((*points)[i]); // flag = true; @@ -393,7 +431,8 @@ GbLine3D* GbSystem3D::createClipLine3D(GbPoint3D &pA, GbPoint3D &pB, double x1a, // if(flag) // { // f = (x21-(*points)[i]->x1)/((*points)[i]->x1-last->x1); -// ps.add(new GbPoint3D(x21, (*points)[i]->x2 + ((*points)[i]->x2-last->x2)*f, (*points)[i]->x3 + ((*points)[i]->x3-last->x3)*f)); +// ps.add(new GbPoint3D(x21, (*points)[i]->x2 + ((*points)[i]->x2-last->x2)*f, (*points)[i]->x3 + +//((*points)[i]->x3-last->x3)*f)); // } // flag = false; // } @@ -402,7 +441,8 @@ GbLine3D* GbSystem3D::createClipLine3D(GbPoint3D &pA, GbPoint3D &pB, double x1a, // if(!flag) // { // f = (x21-(*points)[i]->x1)/((*points)[i]->x1-last->x1); -// ps.add(new GbPoint3D(x21, (*points)[i]->x2 + ((*points)[i]->x2-last->x2)*f, (*points)[i]->x3 + ((*points)[i]->x3-last->x3)*f)); +// ps.add(new GbPoint3D(x21, (*points)[i]->x2 + ((*points)[i]->x2-last->x2)*f, (*points)[i]->x3 + +//((*points)[i]->x3-last->x3)*f)); // } // ps.add(points[i]); // flag = true; @@ -440,7 +480,8 @@ GbLine3D* GbSystem3D::createClipLine3D(GbPoint3D &pA, GbPoint3D &pB, double x1a, // if(flag) // { // f = (x22-(*points)[i]->x2)/(points[i].x2-last.x2); -// ps.add(new GbPoint3D(points[i].x1 + (points[i].x1-last.x1)*f, x22, points[i].x3 + (points[i].x3-last.x3)*f)); +// ps.add(new GbPoint3D(points[i].x1 + (points[i].x1-last.x1)*f, x22, points[i].x3 + +//(points[i].x3-last.x3)*f)); // } // flag = false; // } @@ -449,7 +490,8 @@ GbLine3D* GbSystem3D::createClipLine3D(GbPoint3D &pA, GbPoint3D &pB, double x1a, // if(!flag) // { // f = (x22-points[i].x2)/(points[i].x2-last.x2); -// ps.add(new GbPoint3D(points[i].x1 + (points[i].x1-last.x1)*f, x22, points[i].x3 + (points[i].x3-last.x3)*f)); +// ps.add(new GbPoint3D(points[i].x1 + (points[i].x1-last.x1)*f, x22, points[i].x3 + +//(points[i].x3-last.x3)*f)); // } // ps.add(points[i]); // flag = true; @@ -487,7 +529,8 @@ GbLine3D* GbSystem3D::createClipLine3D(GbPoint3D &pA, GbPoint3D &pB, double x1a, // if(flag) // { // f = (x11-points[i].x1)/(points[i].x1-last.x1); -// ps.add(new GbPoint3D(x11, points[i].x2 + (points[i].x2-last.x2)*f, points[i].x3 + (points[i].x3-last.x3)*f)); +// ps.add(new GbPoint3D(x11, points[i].x2 + (points[i].x2-last.x2)*f, points[i].x3 + +//(points[i].x3-last.x3)*f)); // } // flag = false; // } @@ -496,7 +539,8 @@ GbLine3D* GbSystem3D::createClipLine3D(GbPoint3D &pA, GbPoint3D &pB, double x1a, // if(!flag) // { // f = (x11-points[i].x1)/(points[i].x1-last.x1); -// ps.add(new GbPoint3D(x11, points[i].x2 + (points[i].x2-last.x2)*f, points[i].x3 + (points[i].x3-last.x3)*f)); +// ps.add(new GbPoint3D(x11, points[i].x2 + (points[i].x2-last.x2)*f, points[i].x3 + +//(points[i].x3-last.x3)*f)); // } // ps.add(points[i]); // flag = true; @@ -557,7 +601,8 @@ GbLine3D* GbSystem3D::createClipLine3D(GbPoint3D &pA, GbPoint3D &pB, double x1a, // if(flag) // { // f = (x13-points[i].x3)/(points[i].x3-last.x3); -// ps.add(new GbPoint3D(points[i].x1 + (points[i].x1-last.x1)*f, points[i].x2 + (points[i].x2-last.x2)*f, x13)); +// ps.add(new GbPoint3D(points[i].x1 + (points[i].x1-last.x1)*f, points[i].x2 + (points[i].x2-last.x2)*f, +//x13)); // } // flag = false; // } @@ -566,7 +611,8 @@ GbLine3D* GbSystem3D::createClipLine3D(GbPoint3D &pA, GbPoint3D &pB, double x1a, // if(!flag) // { // f = (x13-points[i].x3)/(points[i].x3-last.x3); -// ps.add(new GbPoint3D(points[i].x1 + (points[i].x1-last.x1)*f, points[i].x2 + (points[i].x2-last.x2)*f, x13)); +// ps.add(new GbPoint3D(points[i].x1 + (points[i].x1-last.x1)*f, points[i].x2 + (points[i].x2-last.x2)*f, +//x13)); // } // ps.add(points[i]); // flag = true; @@ -604,7 +650,8 @@ GbLine3D* GbSystem3D::createClipLine3D(GbPoint3D &pA, GbPoint3D &pB, double x1a, // if(flag) // { // f = (x23-points[i].x3)/(points[i].x3-last.x3); -// ps.add(new GbPoint3D(points[i].x1 + (points[i].x1-last.x1)*f, points[i].x2 + (points[i].x2-last.x2)*f, x23)); +// ps.add(new GbPoint3D(points[i].x1 + (points[i].x1-last.x1)*f, points[i].x2 + (points[i].x2-last.x2)*f, +//x23)); // } // flag = false; // } @@ -613,7 +660,8 @@ GbLine3D* GbSystem3D::createClipLine3D(GbPoint3D &pA, GbPoint3D &pB, double x1a, // if(!flag) // { // f = (x23-points[i].x3)/(points[i].x3-last.x3); -// ps.add(new GbPoint3D(points[i].x1 + ((*points)[i]->x1-last.x1)*f, (*points)[i]->x2 + ((*points)[i]->x2-last.x2)*f, x23)); +// ps.add(new GbPoint3D(points[i].x1 + ((*points)[i]->x1-last.x1)*f, (*points)[i]->x2 + +//((*points)[i]->x2-last.x2)*f, x23)); // } // ps.add(points[i]); // flag = true; @@ -636,404 +684,420 @@ GbLine3D* GbSystem3D::createClipLine3D(GbPoint3D &pA, GbPoint3D &pB, double x1a, // // return(polygon); // } -GbPolygon3D* GbSystem3D::clipPolygon3D(vector<GbPoint3D> points, double x11, double x12, double x13, double x21, double x22, double x23) +GbPolygon3D *GbSystem3D::clipPolygon3D(vector<GbPoint3D> points, double x11, double x12, double x13, double x21, + double x22, double x23) { - GbPoint3D last; - PointSet3 ps(points); - bool flag = false; - int n = (int)points.size(); - int i; - double f; - - if(n == 0) return NULL; - if(UbMath::greater(x11, x21)) { double ax = x11; x11 = x21; x21 = ax; } - if(UbMath::greater(x12, x22)) { double ay = x12; x12 = x22; x22 = ay; } - if(UbMath::greater(x13, x23)) { double az = x13; x13 = x23; x23 = az; } - - /*-------------------------------------------------------------------*/ - /* Schneiden an vorderer Kante */ - /* */ - if(UbMath::less(ps.getX3Minimum(), x13)) - { - ps.clear(); - last = (points)[0]; - if(UbMath::less((points)[0].x3, x13)) flag = false; - else - { - ps.add((points)[0]); - flag = true; - } - for(i=1; i<n; i++) - { - if(UbMath::less((points)[i].x3, x13)) - { - if(flag) - { - f = (x13-(points)[i].x3)/((points)[i].x3-last.x3); - ps.add(GbPoint3D((points)[i].x1 + ((points)[i].x1-last.x1)*f, (points)[i].x2 + ((points)[i].x2-last.x2)*f, x13)); - } - flag = false; - } - else - { - if(!flag) - { - f = (x13-(points)[i].x3)/((points)[i].x3-last.x3); - ps.add(GbPoint3D((points)[i].x1 + ((points)[i].x1-last.x1)*f, (points)[i].x2 + ((points)[i].x2-last.x2)*f, x13)); - } - ps.add((points)[i]); - flag = true; - } - last = (points)[i]; - } - if(!((UbMath::less((points)[0].x3, x13)) ^ flag)) - { - f = (x13-(points)[0].x3)/((points)[0].x3-last.x3); - ps.add(GbPoint3D((points)[0].x1 + ((points)[0].x1-last.x1)*f, (points)[0].x2 + ((points)[0].x2-last.x2)*f, x13)); - } - - points = ps.getPoints(); - n = (int)points.size(); - - if(n == 0) return NULL; - } - - /*-------------------------------------------------------------------*/ - /* Schneiden an unterer Kante */ - /* */ - if(UbMath::less(ps.getX2Minimum(), x12)) - { - ps.clear(); - last = (points)[0]; - if(UbMath::less((points)[0].x2, x12)) flag = false; - else - { - ps.add((points)[0]); - flag = true; - } - for(i=1; i<n; i++) - { - if(UbMath::less((points)[i].x2, x12)) - { - if(flag) - { - f = (x12-(points)[i].x2)/((points)[i].x2-last.x2); - ps.add(GbPoint3D((points)[i].x1 + ((points)[i].x1-last.x1)*f, x12, (points)[i].x3 + ((points)[i].x3-last.x3)*f)); - } - flag = false; - } - else - { - if(!flag) - { - f = (x12-(points)[i].x2)/((points)[i].x2-last.x2); - ps.add(GbPoint3D((points)[i].x1 + ((points)[i].x1-last.x1)*f, x12, (points)[i].x3 + ((points)[i].x3-last.x3)*f)); - } - ps.add((points)[i]); - flag = true; - } - last = (points)[i]; - } - if(!((UbMath::less((points)[0].x2, x12)) ^ flag)) - { - f = (x12-(points)[0].x2)/((points)[0].x2-last.x2); - ps.add(GbPoint3D((points)[0].x1 + ((points)[0].x1-last.x1)*f, x12, (points)[0].x3 + ((points)[0].x3-last.x3)*f)); - } - - points = ps.getPoints(); - n = (int)points.size(); - - if(n == 0) return NULL; - } - /*-------------------------------------------------------------------*/ - /* Schneiden an rechter Kante */ - /* */ - - if(UbMath::greater(ps.getX1Maximum(), x21)) - { - ps.clear(); - last = (points)[0]; - if(UbMath::greater((points)[0].x1, x21)) flag = false; - else - { - ps.add((points)[0]); - flag = true; - } - for(i=1; i<n; i++) - { - if(UbMath::greater((points)[i].x1, x21)) - { - if(flag) - { - f = (x21-(points)[i].x1)/((points)[i].x1-last.x1); - ps.add(GbPoint3D(x21, (points)[i].x2 + ((points)[i].x2-last.x2)*f, (points)[i].x3 + ((points)[i].x3-last.x3)*f)); - } - flag = false; - } - else - { - if(!flag) - { - f = (x21-(points)[i].x1)/((points)[i].x1-last.x1); - ps.add(GbPoint3D(x21, (points)[i].x2 + ((points)[i].x2-last.x2)*f, (points)[i].x3 + ((points)[i].x3-last.x3)*f)); - } - ps.add((points)[i]); - flag = true; - } - last = (points)[i]; - } - if(!((UbMath::greater((points)[0].x1, x21)) ^ flag)) - { - f = (x21-(points)[0].x1)/((points)[0].x1-last.x1); - ps.add(GbPoint3D(x21, (points)[0].x2 + ((points)[0].x2-last.x2)*f, (points)[0].x3 + ((points)[0].x3-last.x3)*f)); - } - - points = ps.getPoints(); - n = (int)points.size(); - - if(n == 0) return NULL; - } - /*-------------------------------------------------------------------*/ - /* Schneiden an hinterer Kante */ - /* */ - if(UbMath::greater(ps.getX3Maximum(), x23)) - { - ps.clear(); - last = (points)[0]; - if(UbMath::greater((points)[0].x3, x23)) flag = false; - else - { - ps.add((points)[0]); - flag = true; - } - for(i=1; i<n; i++) - { - if(UbMath::greater((points)[i].x3, x23)) - { - if(flag) - { - f = (x23-(points)[i].x3)/((points)[i].x3-last.x3); - ps.add(GbPoint3D((points)[i].x1 + ((points)[i].x1-last.x1)*f, (points)[i].x2 + ((points)[i].x2-last.x2)*f, x23)); - } - flag = false; - } - else - { - if(!flag) - { - f = (x23-(points)[i].x3)/((points)[i].x3-last.x3); - ps.add(GbPoint3D((points)[i].x1 + ((points)[i].x1-last.x1)*f, (points)[i].x2 + ((points)[i].x2-last.x2)*f, x23)); - } - ps.add((points)[i]); - flag = true; - } - last = (points)[i]; - } - if(!((UbMath::greater((points)[0].x3, x23)) ^ flag)) - { - f = (x23-(points)[0].x3)/((points)[0].x3-last.x3); - ps.add(GbPoint3D((points)[0].x1 + ((points)[0].x1-last.x1)*f, (points)[0].x2 + ((points)[0].x2-last.x2)*f, x23)); - } - - points = ps.getPoints(); - n = (int)points.size(); - - if(n == 0) return NULL; - } - /*-------------------------------------------------------------------*/ - /* Schneiden an oberer Kante */ - /* */ - - if(UbMath::greater(ps.getX2Maximum(), x22)) - { - ps.clear(); - last = (points)[0]; - if(UbMath::greater((points)[0].x2, x22)) flag = false; - else - { - ps.add((points)[0]); - flag = true; - } - for(i=1; i<n; i++) - { - if(UbMath::greater((points)[i].x2, x22)) - { - if(flag) - { - f = (x22-(points)[i].x2)/((points)[i].x2-last.x2); - ps.add(GbPoint3D((points)[i].x1 + ((points)[i].x1-last.x1)*f, x22, (points)[i].x3 + ((points)[i].x3-last.x3)*f)); - } - flag = false; - } - else - { - if(!flag) - { - f = (x22-(points)[i].x2)/((points)[i].x2-last.x2); - ps.add(GbPoint3D((points)[i].x1 + ((points)[i].x1-last.x1)*f, x22, (points)[i].x3 + ((points)[i].x3-last.x3)*f)); - } - ps.add((points)[i]); - flag = true; - } - last = (points)[i]; - } - if(!((UbMath::greater((points)[0].x2, x22)) ^ flag)) - { - f = (x22-(points)[0].x2)/((points)[0].x2-last.x2); - ps.add(GbPoint3D((points)[0].x1 + ((points)[0].x1-last.x1)*f, x22, (points)[0].x3 + ((points)[0].x3-last.x3)*f)); - } - - points = ps.getPoints(); - n = (int)points.size(); - - if(n == 0) return NULL; - } - /*-------------------------------------------------------------------*/ - /* Schneiden an linker Kante */ - /* */ - if(UbMath::less(ps.getX1Minimum(), x11)) - { - ps.clear(); - last = (points)[0]; - if(UbMath::less((points)[0].x1, x11)) flag = false; - else - { - ps.add((points)[0]); - flag = true; - } - for(i=1; i<n; i++) - { - if(UbMath::less((points)[i].x1, x11)) - { - if(flag) - { - f = (x11-(points)[i].x1)/((points)[i].x1-last.x1); - ps.add(GbPoint3D(x11, (points)[i].x2 + ((points)[i].x2-last.x2)*f, (points)[i].x3 + ((points)[i].x3-last.x3)*f)); - - } - flag = false; - } - else - { - if(!flag) - { - f = (x11-(points)[i].x1)/((points)[i].x1-last.x1); - ps.add(GbPoint3D(x11, (points)[i].x2 + ((points)[i].x2-last.x2)*f, (points)[i].x3 + ((points)[i].x3-last.x3)*f)); - } - ps.add((points)[i]); - flag = true; - } - last = (points)[i]; - } - if(!((UbMath::less((points)[0].x1, x11)) ^ flag)) - { - f = (x11-(points)[0].x1)/((points)[0].x1-last.x1); - ps.add(GbPoint3D(x11, (points)[0].x2 + ((points)[0].x2-last.x2)*f, (points)[0].x3 + ((points)[0].x3-last.x3)*f)); - } - - points = ps.getPoints(); - n = (int)points.size(); - - if(n == 0) return NULL; - } - /*-------------------------------------------------------------------*/ - return new GbPolygon3D(points); + GbPoint3D last; + PointSet3 ps(points); + bool flag = false; + int n = (int)points.size(); + int i; + double f; + + if (n == 0) + return NULL; + if (UbMath::greater(x11, x21)) { + double ax = x11; + x11 = x21; + x21 = ax; + } + if (UbMath::greater(x12, x22)) { + double ay = x12; + x12 = x22; + x22 = ay; + } + if (UbMath::greater(x13, x23)) { + double az = x13; + x13 = x23; + x23 = az; + } + + /*-------------------------------------------------------------------*/ + /* Schneiden an vorderer Kante */ + /* */ + if (UbMath::less(ps.getX3Minimum(), x13)) { + ps.clear(); + last = (points)[0]; + if (UbMath::less((points)[0].x3, x13)) + flag = false; + else { + ps.add((points)[0]); + flag = true; + } + for (i = 1; i < n; i++) { + if (UbMath::less((points)[i].x3, x13)) { + if (flag) { + f = (x13 - (points)[i].x3) / ((points)[i].x3 - last.x3); + ps.add(GbPoint3D((points)[i].x1 + ((points)[i].x1 - last.x1) * f, + (points)[i].x2 + ((points)[i].x2 - last.x2) * f, x13)); + } + flag = false; + } else { + if (!flag) { + f = (x13 - (points)[i].x3) / ((points)[i].x3 - last.x3); + ps.add(GbPoint3D((points)[i].x1 + ((points)[i].x1 - last.x1) * f, + (points)[i].x2 + ((points)[i].x2 - last.x2) * f, x13)); + } + ps.add((points)[i]); + flag = true; + } + last = (points)[i]; + } + if (!((UbMath::less((points)[0].x3, x13)) ^ flag)) { + f = (x13 - (points)[0].x3) / ((points)[0].x3 - last.x3); + ps.add(GbPoint3D((points)[0].x1 + ((points)[0].x1 - last.x1) * f, + (points)[0].x2 + ((points)[0].x2 - last.x2) * f, x13)); + } + + points = ps.getPoints(); + n = (int)points.size(); + + if (n == 0) + return NULL; + } + + /*-------------------------------------------------------------------*/ + /* Schneiden an unterer Kante */ + /* */ + if (UbMath::less(ps.getX2Minimum(), x12)) { + ps.clear(); + last = (points)[0]; + if (UbMath::less((points)[0].x2, x12)) + flag = false; + else { + ps.add((points)[0]); + flag = true; + } + for (i = 1; i < n; i++) { + if (UbMath::less((points)[i].x2, x12)) { + if (flag) { + f = (x12 - (points)[i].x2) / ((points)[i].x2 - last.x2); + ps.add(GbPoint3D((points)[i].x1 + ((points)[i].x1 - last.x1) * f, x12, + (points)[i].x3 + ((points)[i].x3 - last.x3) * f)); + } + flag = false; + } else { + if (!flag) { + f = (x12 - (points)[i].x2) / ((points)[i].x2 - last.x2); + ps.add(GbPoint3D((points)[i].x1 + ((points)[i].x1 - last.x1) * f, x12, + (points)[i].x3 + ((points)[i].x3 - last.x3) * f)); + } + ps.add((points)[i]); + flag = true; + } + last = (points)[i]; + } + if (!((UbMath::less((points)[0].x2, x12)) ^ flag)) { + f = (x12 - (points)[0].x2) / ((points)[0].x2 - last.x2); + ps.add(GbPoint3D((points)[0].x1 + ((points)[0].x1 - last.x1) * f, x12, + (points)[0].x3 + ((points)[0].x3 - last.x3) * f)); + } + + points = ps.getPoints(); + n = (int)points.size(); + + if (n == 0) + return NULL; + } + /*-------------------------------------------------------------------*/ + /* Schneiden an rechter Kante */ + /* */ + + if (UbMath::greater(ps.getX1Maximum(), x21)) { + ps.clear(); + last = (points)[0]; + if (UbMath::greater((points)[0].x1, x21)) + flag = false; + else { + ps.add((points)[0]); + flag = true; + } + for (i = 1; i < n; i++) { + if (UbMath::greater((points)[i].x1, x21)) { + if (flag) { + f = (x21 - (points)[i].x1) / ((points)[i].x1 - last.x1); + ps.add(GbPoint3D(x21, (points)[i].x2 + ((points)[i].x2 - last.x2) * f, + (points)[i].x3 + ((points)[i].x3 - last.x3) * f)); + } + flag = false; + } else { + if (!flag) { + f = (x21 - (points)[i].x1) / ((points)[i].x1 - last.x1); + ps.add(GbPoint3D(x21, (points)[i].x2 + ((points)[i].x2 - last.x2) * f, + (points)[i].x3 + ((points)[i].x3 - last.x3) * f)); + } + ps.add((points)[i]); + flag = true; + } + last = (points)[i]; + } + if (!((UbMath::greater((points)[0].x1, x21)) ^ flag)) { + f = (x21 - (points)[0].x1) / ((points)[0].x1 - last.x1); + ps.add(GbPoint3D(x21, (points)[0].x2 + ((points)[0].x2 - last.x2) * f, + (points)[0].x3 + ((points)[0].x3 - last.x3) * f)); + } + + points = ps.getPoints(); + n = (int)points.size(); + + if (n == 0) + return NULL; + } + /*-------------------------------------------------------------------*/ + /* Schneiden an hinterer Kante */ + /* */ + if (UbMath::greater(ps.getX3Maximum(), x23)) { + ps.clear(); + last = (points)[0]; + if (UbMath::greater((points)[0].x3, x23)) + flag = false; + else { + ps.add((points)[0]); + flag = true; + } + for (i = 1; i < n; i++) { + if (UbMath::greater((points)[i].x3, x23)) { + if (flag) { + f = (x23 - (points)[i].x3) / ((points)[i].x3 - last.x3); + ps.add(GbPoint3D((points)[i].x1 + ((points)[i].x1 - last.x1) * f, + (points)[i].x2 + ((points)[i].x2 - last.x2) * f, x23)); + } + flag = false; + } else { + if (!flag) { + f = (x23 - (points)[i].x3) / ((points)[i].x3 - last.x3); + ps.add(GbPoint3D((points)[i].x1 + ((points)[i].x1 - last.x1) * f, + (points)[i].x2 + ((points)[i].x2 - last.x2) * f, x23)); + } + ps.add((points)[i]); + flag = true; + } + last = (points)[i]; + } + if (!((UbMath::greater((points)[0].x3, x23)) ^ flag)) { + f = (x23 - (points)[0].x3) / ((points)[0].x3 - last.x3); + ps.add(GbPoint3D((points)[0].x1 + ((points)[0].x1 - last.x1) * f, + (points)[0].x2 + ((points)[0].x2 - last.x2) * f, x23)); + } + + points = ps.getPoints(); + n = (int)points.size(); + + if (n == 0) + return NULL; + } + /*-------------------------------------------------------------------*/ + /* Schneiden an oberer Kante */ + /* */ + + if (UbMath::greater(ps.getX2Maximum(), x22)) { + ps.clear(); + last = (points)[0]; + if (UbMath::greater((points)[0].x2, x22)) + flag = false; + else { + ps.add((points)[0]); + flag = true; + } + for (i = 1; i < n; i++) { + if (UbMath::greater((points)[i].x2, x22)) { + if (flag) { + f = (x22 - (points)[i].x2) / ((points)[i].x2 - last.x2); + ps.add(GbPoint3D((points)[i].x1 + ((points)[i].x1 - last.x1) * f, x22, + (points)[i].x3 + ((points)[i].x3 - last.x3) * f)); + } + flag = false; + } else { + if (!flag) { + f = (x22 - (points)[i].x2) / ((points)[i].x2 - last.x2); + ps.add(GbPoint3D((points)[i].x1 + ((points)[i].x1 - last.x1) * f, x22, + (points)[i].x3 + ((points)[i].x3 - last.x3) * f)); + } + ps.add((points)[i]); + flag = true; + } + last = (points)[i]; + } + if (!((UbMath::greater((points)[0].x2, x22)) ^ flag)) { + f = (x22 - (points)[0].x2) / ((points)[0].x2 - last.x2); + ps.add(GbPoint3D((points)[0].x1 + ((points)[0].x1 - last.x1) * f, x22, + (points)[0].x3 + ((points)[0].x3 - last.x3) * f)); + } + + points = ps.getPoints(); + n = (int)points.size(); + + if (n == 0) + return NULL; + } + /*-------------------------------------------------------------------*/ + /* Schneiden an linker Kante */ + /* */ + if (UbMath::less(ps.getX1Minimum(), x11)) { + ps.clear(); + last = (points)[0]; + if (UbMath::less((points)[0].x1, x11)) + flag = false; + else { + ps.add((points)[0]); + flag = true; + } + for (i = 1; i < n; i++) { + if (UbMath::less((points)[i].x1, x11)) { + if (flag) { + f = (x11 - (points)[i].x1) / ((points)[i].x1 - last.x1); + ps.add(GbPoint3D(x11, (points)[i].x2 + ((points)[i].x2 - last.x2) * f, + (points)[i].x3 + ((points)[i].x3 - last.x3) * f)); + } + flag = false; + } else { + if (!flag) { + f = (x11 - (points)[i].x1) / ((points)[i].x1 - last.x1); + ps.add(GbPoint3D(x11, (points)[i].x2 + ((points)[i].x2 - last.x2) * f, + (points)[i].x3 + ((points)[i].x3 - last.x3) * f)); + } + ps.add((points)[i]); + flag = true; + } + last = (points)[i]; + } + if (!((UbMath::less((points)[0].x1, x11)) ^ flag)) { + f = (x11 - (points)[0].x1) / ((points)[0].x1 - last.x1); + ps.add(GbPoint3D(x11, (points)[0].x2 + ((points)[0].x2 - last.x2) * f, + (points)[0].x3 + ((points)[0].x3 - last.x3) * f)); + } + + points = ps.getPoints(); + n = (int)points.size(); + + if (n == 0) + return NULL; + } + /*-------------------------------------------------------------------*/ + return new GbPolygon3D(points); } /*=========================================================================*/ -GbCuboid3D* GbSystem3D::clipRectangle3D(GbPoint3D& p1, GbPoint3D& p2, double x11, double x12, double x13, double x21, double x22, double x23) +GbCuboid3D *GbSystem3D::clipRectangle3D(GbPoint3D &p1, GbPoint3D &p2, double x11, double x12, double x13, double x21, + double x22, double x23) { - double r11 = p1.x1; - double r12 = p1.x2; - double r13 = p1.x3; - double r21 = p2.x1; - double r22 = p2.x2; - double r23 = p2.x3; - - if(UbMath::greater(x11, x21)) { double ax = x11; x11 = x21; x21 = ax; } - if(UbMath::greater(x12, x22)) { double ay = x12; x12 = x22; x22 = ay; } - if(UbMath::greater(x13, x23)) { double az = x13; x13 = x23; x23 = az; } - if(UbMath::greater(r11, r21)) { double bx = r11; r11 = r21; r21 = bx; } - if(UbMath::greater(r12, r22)) { double by = r12; r12 = r22; r22 = by; } - if(UbMath::greater(r13, r23)) { double bz = r13; r13 = r23; r23 = bz; } - - double m11 = UbMath::greater(x11, r11) ? x11 : r11; - double m12 = UbMath::greater(x12, r12) ? x12 : r12; - double m13 = UbMath::greater(x13, r13) ? x13 : r13; - double m21 = UbMath::greater(x21, r21) ? r21 : x21; - double m22 = UbMath::greater(x22, r22) ? r22 : x22; - double m23 = UbMath::greater(x23, r23) ? r23 : x23; - - if(UbMath::lessEqual(m11, m21) && UbMath::lessEqual(m12, m22) && UbMath::lessEqual(m13, m23)) - return(new GbCuboid3D(new GbPoint3D(m11, m12, m13), new GbPoint3D(m21, m22, m23))); - else - return(NULL); + double r11 = p1.x1; + double r12 = p1.x2; + double r13 = p1.x3; + double r21 = p2.x1; + double r22 = p2.x2; + double r23 = p2.x3; + + if (UbMath::greater(x11, x21)) { + double ax = x11; + x11 = x21; + x21 = ax; + } + if (UbMath::greater(x12, x22)) { + double ay = x12; + x12 = x22; + x22 = ay; + } + if (UbMath::greater(x13, x23)) { + double az = x13; + x13 = x23; + x23 = az; + } + if (UbMath::greater(r11, r21)) { + double bx = r11; + r11 = r21; + r21 = bx; + } + if (UbMath::greater(r12, r22)) { + double by = r12; + r12 = r22; + r22 = by; + } + if (UbMath::greater(r13, r23)) { + double bz = r13; + r13 = r23; + r23 = bz; + } + + double m11 = UbMath::greater(x11, r11) ? x11 : r11; + double m12 = UbMath::greater(x12, r12) ? x12 : r12; + double m13 = UbMath::greater(x13, r13) ? x13 : r13; + double m21 = UbMath::greater(x21, r21) ? r21 : x21; + double m22 = UbMath::greater(x22, r22) ? r22 : x22; + double m23 = UbMath::greater(x23, r23) ? r23 : x23; + + if (UbMath::lessEqual(m11, m21) && UbMath::lessEqual(m12, m22) && UbMath::lessEqual(m13, m23)) + return (new GbCuboid3D(new GbPoint3D(m11, m12, m13), new GbPoint3D(m21, m22, m23))); + else + return (NULL); } /*=========================================================================*/ /*=========================================================================*/ /*=========================================================================*/ - GbSystem3D::PointSet3::PointSet3(int n) { - this->init(); - this->points.reserve(n); //reserves n elements! but the size of the vector ist still "0" + this->init(); + this->points.reserve(n); // reserves n elements! but the size of the vector ist still "0" } /*=======================================================*/ -GbSystem3D::PointSet3::PointSet3(const vector<GbPoint3D>& points) +GbSystem3D::PointSet3::PointSet3(const vector<GbPoint3D> &points) { - this->init(); - this->add(points); + this->init(); + this->add(points); } /*=======================================================*/ -void GbSystem3D::PointSet3::add(const GbPoint3D& point) +void GbSystem3D::PointSet3::add(const GbPoint3D &point) { - //is point equal to last point in points then return - if(!this->points.empty() && point.equals(&this->points.back())) return; //WHY??? + // is point equal to last point in points then return + if (!this->points.empty() && point.equals(&this->points.back())) + return; // WHY??? - //push point to vector - this->points.push_back(point); + // push point to vector + this->points.push_back(point); - this->consistent = false; + this->consistent = false; } /*=======================================================*/ -void GbSystem3D::PointSet3::addUnequal(const GbPoint3D& point) +void GbSystem3D::PointSet3::addUnequal(const GbPoint3D &point) { - if(this->containsEqual(point) > 0) return; - - this->points.push_back(point); - this->consistent = false; + if (this->containsEqual(point) > 0) + return; + + this->points.push_back(point); + this->consistent = false; } /*=======================================================*/ -void GbSystem3D::PointSet3::add(const vector<GbPoint3D>& pointVector) +void GbSystem3D::PointSet3::add(const vector<GbPoint3D> &pointVector) { - for(int pos=0; pos<(int)pointVector.size(); pos++ ) - this->points.push_back(pointVector[pos]); + for (int pos = 0; pos < (int)pointVector.size(); pos++) + this->points.push_back(pointVector[pos]); - this->consistent = false; + this->consistent = false; } /*=======================================================*/ -void GbSystem3D::PointSet3::insert(const GbPoint3D& point, int index) +void GbSystem3D::PointSet3::insert(const GbPoint3D &point, int index) { - if(index<0 || index>=(int)this->points.size()) - throw UbException(UB_EXARGS,"index out of range"); + if (index < 0 || index >= (int)this->points.size()) + throw UbException(UB_EXARGS, "index out of range"); - //get iterator for index-position - vector<GbPoint3D>::iterator pos=this->points.begin(); - for(int i=1; i<=index; i++) ++pos; + // get iterator for index-position + vector<GbPoint3D>::iterator pos = this->points.begin(); + for (int i = 1; i <= index; i++) + ++pos; - //insert point - this->points.insert(pos,point); + // insert point + this->points.insert(pos, point); - this->consistent = false; + this->consistent = false; } /*=======================================================*/ -//void delete(GbPoint3D point) +// void delete(GbPoint3D point) //{ // for(int i=this.size-1; i>=0; i--) if(this.points[i] == point) this.delete(i); //} /*=======================================================*/ -//void delete(int index) +// void delete(int index) //{ // int j = this.size - index - 1; // if(j > 0) System.arraycopy(this.points, index + 1, this.points, index, j); @@ -1043,176 +1107,177 @@ void GbSystem3D::PointSet3::insert(const GbPoint3D& point, int index) /*=======================================================*/ void GbSystem3D::PointSet3::clear() { - //clears points (size==0 but capacity is the old c1) - this->points.clear(); - this->consistent = false; + // clears points (size==0 but capacity is the old c1) + this->points.clear(); + this->consistent = false; } /*=======================================================*/ void GbSystem3D::PointSet3::clearAndTrim() { - //clears points (size==0 AND capacity==0) - this->points.resize(0); - this->consistent = false; + // clears points (size==0 AND capacity==0) + this->points.resize(0); + this->consistent = false; } /*=======================================================*/ double GbSystem3D::PointSet3::getX1Minimum() { - if(!this->consistent) this->calculateValues(); - return this->x1min; + if (!this->consistent) + this->calculateValues(); + return this->x1min; } /*=======================================================*/ double GbSystem3D::PointSet3::getX1Maximum() { - if(!this->consistent) this->calculateValues(); - return this->x1max; + if (!this->consistent) + this->calculateValues(); + return this->x1max; } /*=======================================================*/ double GbSystem3D::PointSet3::getX2Minimum() { - if(!this->consistent) this->calculateValues(); - return this->x2min; + if (!this->consistent) + this->calculateValues(); + return this->x2min; } /*=======================================================*/ double GbSystem3D::PointSet3::getX2Maximum() { - if(!this->consistent) this->calculateValues(); - return this->x2max; + if (!this->consistent) + this->calculateValues(); + return this->x2max; } /*=======================================================*/ double GbSystem3D::PointSet3::getX3Minimum() { - if(!this->consistent) this->calculateValues(); - return this->x3min; + if (!this->consistent) + this->calculateValues(); + return this->x3min; } /*=======================================================*/ double GbSystem3D::PointSet3::getX3Maximum() { - if(!this->consistent) this->calculateValues(); - return this->x3max; + if (!this->consistent) + this->calculateValues(); + return this->x3max; } /*=======================================================*/ -int GbSystem3D::PointSet3::contains(GbPoint3D* point) +int GbSystem3D::PointSet3::contains(GbPoint3D *point) { - //returns number of points which has the same adress (this should be 0 or 1!!!) - int n=0; + // returns number of points which has the same adress (this should be 0 or 1!!!) + int n = 0; - for(int pos=(int)this->points.size()-1; pos>=0; pos--) - if(&this->points[pos]==point) n++; + for (int pos = (int)this->points.size() - 1; pos >= 0; pos--) + if (&this->points[pos] == point) + n++; - return n; + return n; } /*=======================================================*/ -int GbSystem3D::PointSet3::containsEqual(const GbPoint3D& point) +int GbSystem3D::PointSet3::containsEqual(const GbPoint3D &point) { - //returns number of points which have the same coordinates with point (could be 0,1 or even more) - int n=0; + // returns number of points which have the same coordinates with point (could be 0,1 or even more) + int n = 0; - for(int pos=(int)this->points.size()-1; pos>=0; pos--) - if(this->points[pos].equals(&point)) n++; + for (int pos = (int)this->points.size() - 1; pos >= 0; pos--) + if (this->points[pos].equals(&point)) + n++; - return n; + return n; } /*=======================================================*/ bool GbSystem3D::PointSet3::containsLine(GbPoint3D *point1, GbPoint3D *point2) { - //returns true if pointset has c2 in "this->points"vector neighboured points - //wich have the same adress as point1 or point2 - vector<GbPoint3D>::iterator pos1=this->points.begin(); - vector<GbPoint3D>::iterator pos2; + // returns true if pointset has c2 in "this->points"vector neighboured points + // wich have the same adress as point1 or point2 + vector<GbPoint3D>::iterator pos1 = this->points.begin(); + vector<GbPoint3D>::iterator pos2; - for(pos2=pos1++; pos2!=this->points.end(); ++pos2) - { - if (&(*pos1)==point1 && &(*pos2)==point2) return true; - else if(&(*pos1)==point2 && &(*pos2)==point1) return true; + for (pos2 = pos1++; pos2 != this->points.end(); ++pos2) { + if (&(*pos1) == point1 && &(*pos2) == point2) + return true; + else if (&(*pos1) == point2 && &(*pos2) == point1) + return true; - pos1=pos2; - } + pos1 = pos2; + } - return false; + return false; } /*=======================================================*/ -bool GbSystem3D::PointSet3::containsEqualLine(const GbPoint3D& point1, const GbPoint3D& point2) +bool GbSystem3D::PointSet3::containsEqualLine(const GbPoint3D &point1, const GbPoint3D &point2) { - //returns true if pointset has c2 in "this->points"vector neighboured points - //wich have the same coordinates as point1 or point2 - vector<GbPoint3D>::iterator pos1=this->points.begin(); - vector<GbPoint3D>::iterator pos2; + // returns true if pointset has c2 in "this->points"vector neighboured points + // wich have the same coordinates as point1 or point2 + vector<GbPoint3D>::iterator pos1 = this->points.begin(); + vector<GbPoint3D>::iterator pos2; - for(pos2=pos1++; pos2!=this->points.end(); ++pos2) - { - if ((*pos1).equals(&point1) && (*pos2).equals(&point2)) return true; - else if((*pos1).equals(&point2) && (*pos2).equals(&point1)) return true; + for (pos2 = pos1++; pos2 != this->points.end(); ++pos2) { + if ((*pos1).equals(&point1) && (*pos2).equals(&point2)) + return true; + else if ((*pos1).equals(&point2) && (*pos2).equals(&point1)) + return true; - pos1=pos2; - } + pos1 = pos2; + } - return false; + return false; } /*=======================================================*/ -GbPoint3D* GbSystem3D::PointSet3::getPoint(int index) +GbPoint3D *GbSystem3D::PointSet3::getPoint(int index) { - if(index<0 || index>=(int)this->points.size()) throw UbException(UB_EXARGS,"index out of range"); - return &(this->points)[index]; + if (index < 0 || index >= (int)this->points.size()) + throw UbException(UB_EXARGS, "index out of range"); + return &(this->points)[index]; } /*=======================================================*/ -GbPoint3D* GbSystem3D::PointSet3::getFirstPoint() -{ - return &(this->points.front()); -} +GbPoint3D *GbSystem3D::PointSet3::getFirstPoint() { return &(this->points.front()); } /*=======================================================*/ -GbPoint3D* GbSystem3D::PointSet3::getLastPoint() -{ - return &(this->points.back()); -} +GbPoint3D *GbSystem3D::PointSet3::getLastPoint() { return &(this->points.back()); } /*=======================================================*/ -int GbSystem3D::PointSet3::size() -{ - return (int)this->points.size(); -} +int GbSystem3D::PointSet3::size() { return (int)this->points.size(); } /*=======================================================*/ vector<GbPoint3D> GbSystem3D::PointSet3::getPoints() { - //is this right? it's another effect as at GbPoint3D* getNode(index)!!! - //or do we want to have the next uncommented getPoints() funktion - return this->points; + // is this right? it's another effect as at GbPoint3D* getNode(index)!!! + // or do we want to have the next uncommented getPoints() funktion + return this->points; } ///*=======================================================*/ -//vector<GbPoint3D*> GbSystem3D::PointSet3::getPoints() +// vector<GbPoint3D*> GbSystem3D::PointSet3::getPoints() //{ // vector<GbPoint3D*> tmp; // for(int pos=0; pos<(int)this->points.size();pos++) tmp.push_back(&this->points[pos]); -// +// // return tmp; //} /*=======================================================*/ void GbSystem3D::PointSet3::calculateValues() { - if(this->points.empty()) - { - this->x1min = this->x2min = this->x3min = 0.0; - this->x1max = this->x2max = this->x3max = 0.0; - } - else - { - this->x1min = (this->points)[0].x1; - this->x1max = (this->points)[0].x1; - this->x2min = (this->points)[0].x2; - this->x2max = (this->points)[0].x2; - this->x3min = (this->points)[0].x3; - this->x3max = (this->points)[0].x3; - - for(int i=(int)this->points.size()-1; i>0; --i) - { - if((this->points)[i].x1 < this->x1min) this->x1min = (this->points)[i].x1; - if((this->points)[i].x1 > this->x1max) this->x1max = (this->points)[i].x1; - if((this->points)[i].x2 < this->x2min) this->x2min = (this->points)[i].x2; - if((this->points)[i].x2 > this->x2max) this->x2max = (this->points)[i].x2; - if((this->points)[i].x3 < this->x3min) this->x3min = (this->points)[i].x3; - if((this->points)[i].x3 > this->x3max) this->x3max = (this->points)[i].x3; - } - } - this->consistent = true; + if (this->points.empty()) { + this->x1min = this->x2min = this->x3min = 0.0; + this->x1max = this->x2max = this->x3max = 0.0; + } else { + this->x1min = (this->points)[0].x1; + this->x1max = (this->points)[0].x1; + this->x2min = (this->points)[0].x2; + this->x2max = (this->points)[0].x2; + this->x3min = (this->points)[0].x3; + this->x3max = (this->points)[0].x3; + + for (int i = (int)this->points.size() - 1; i > 0; --i) { + if ((this->points)[i].x1 < this->x1min) + this->x1min = (this->points)[i].x1; + if ((this->points)[i].x1 > this->x1max) + this->x1max = (this->points)[i].x1; + if ((this->points)[i].x2 < this->x2min) + this->x2min = (this->points)[i].x2; + if ((this->points)[i].x2 > this->x2max) + this->x2max = (this->points)[i].x2; + if ((this->points)[i].x3 < this->x3min) + this->x3min = (this->points)[i].x3; + if ((this->points)[i].x3 > this->x3max) + this->x3max = (this->points)[i].x3; + } + } + this->consistent = true; } - - - diff --git a/src/basics/geometry3d/GbSystem3D.h b/src/basics/geometry3d/GbSystem3D.h index b448335caafc372bdca7ab103b213a631afa8442..239a4c30da2c15d3a07355716c1160e79016f128 100644 --- a/src/basics/geometry3d/GbSystem3D.h +++ b/src/basics/geometry3d/GbSystem3D.h @@ -1,28 +1,28 @@ //======================================================================================= -// ____ ____ __ ______ __________ __ __ __ __ -// \ \ | | | | | _ \ |___ ___| | | | | / \ | | -// \ \ | | | | | |_) | | | | | | | / \ | | -// \ \ | | | | | _ / | | | | | | / /\ \ | | -// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ -// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| -// \ \ | | ________________________________________________________________ -// \ \ | | | ______________________________________________________________| -// \ \| | | | __ __ __ __ ______ _______ -// \ | | |_____ | | | | | | | | | _ \ / _____) -// \ | | _____| | | | | | | | | | | \ \ \_______ +// ____ ____ __ ______ __________ __ __ __ __ +// \ \ | | | | | _ \ |___ ___| | | | | / \ | | +// \ \ | | | | | |_) | | | | | | | / \ | | +// \ \ | | | | | _ / | | | | | | / /\ \ | | +// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ +// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| +// \ \ | | ________________________________________________________________ +// \ \ | | | ______________________________________________________________| +// \ \| | | | __ __ __ __ ______ _______ +// \ | | |_____ | | | | | | | | | _ \ / _____) +// \ | | _____| | | | | | | | | | | \ \ \_______ // \ | | | | |_____ | \_/ | | | | |_/ / _____ | -// \ _____| |__| |________| \_______/ |__| |______/ (_______/ +// \ _____| |__| |________| \_______/ |__| |______/ (_______/ // -// This file is part of VirtualFluids. VirtualFluids is free software: you can +// This file is part of VirtualFluids. VirtualFluids is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of +// License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. -// -// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// +// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License along // with VirtualFluids (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>. // @@ -33,12 +33,12 @@ #ifndef GBSYSTEM3D_H #define GBSYSTEM3D_H -#include <iostream> #include <cmath> +#include <iostream> #include <vector> -#include <GbPoint3D.h> #include <GbObject3D.h> +#include <GbPoint3D.h> #include <basics/utilities/UbMath.h> #include <basics/writer/WbWriter.h> @@ -48,372 +48,393 @@ class GbLine3D; namespace GbSystem3D { - extern double getDistance(const GbPoint3D& p11, const GbPoint3D& p12); - extern GbPoint3D* calculateIntersectionPoint3D(GbPoint3D& p11, GbPoint3D& p12, GbPoint3D& p21, GbPoint3D& p22); - extern GbPolygon3D* clipPolygon3D(std::vector<GbPoint3D> points, double x11, double x12, double x13, double x21, double x22, double x23); - extern GbLine3D* createClipLine3D(GbPoint3D& p1, GbPoint3D& p2, double x11, double x12, double x13, double x21, double x22, double x23); - extern bool hasIntersectionPoint3D(GbPoint3D& p11, GbPoint3D& p12, GbPoint3D& p21, GbPoint3D& p22); - extern bool isParallelIn3D(GbPoint3D& p11, GbPoint3D& p12, GbPoint3D& p21, GbPoint3D& p22); - extern GbCuboid3D* clipRectangle3D(GbPoint3D& p1, GbPoint3D& p2, double x11, double x12, double x13, double x21, double x22, double x23); +extern double getDistance(const GbPoint3D &p11, const GbPoint3D &p12); +extern GbPoint3D *calculateIntersectionPoint3D(GbPoint3D &p11, GbPoint3D &p12, GbPoint3D &p21, GbPoint3D &p22); +extern GbPolygon3D *clipPolygon3D(std::vector<GbPoint3D> points, double x11, double x12, double x13, double x21, + double x22, double x23); +extern GbLine3D *createClipLine3D(GbPoint3D &p1, GbPoint3D &p2, double x11, double x12, double x13, double x21, + double x22, double x23); +extern bool hasIntersectionPoint3D(GbPoint3D &p11, GbPoint3D &p12, GbPoint3D &p21, GbPoint3D &p22); +extern bool isParallelIn3D(GbPoint3D &p11, GbPoint3D &p12, GbPoint3D &p21, GbPoint3D &p22); +extern GbCuboid3D *clipRectangle3D(GbPoint3D &p1, GbPoint3D &p2, double x11, double x12, double x13, double x21, + double x22, double x23); - /*========================================================================================*/ - inline static std::string writeGeoObject(GbObject3D* gbobject, const std::string& filename, WbWriter* writer) - { - std::vector<UbTupleFloat3> nodes; - std::vector<UbTupleInt3> triangles; - gbobject->addSurfaceTriangleSet(nodes, triangles); +/*========================================================================================*/ +inline static std::string writeGeoObject(GbObject3D *gbobject, const std::string &filename, WbWriter *writer) +{ + std::vector<UbTupleFloat3> nodes; + std::vector<UbTupleInt3> triangles; + gbobject->addSurfaceTriangleSet(nodes, triangles); - std::string outFilename = writer->writeTriangles(filename,nodes,triangles); - return outFilename; - } - //the same as before - /*========================================================================================*/ - inline static std::string writeGeoObject(SPtr<GbObject3D> gbobject, const std::string& filename, WbWriter* writer) - { - std::vector<UbTupleFloat3> nodes; - std::vector<UbTupleInt3> triangles; - gbobject->addSurfaceTriangleSet(nodes, triangles); + std::string outFilename = writer->writeTriangles(filename, nodes, triangles); + return outFilename; +} +// the same as before +/*========================================================================================*/ +inline static std::string writeGeoObject(SPtr<GbObject3D> gbobject, const std::string &filename, WbWriter *writer) +{ + std::vector<UbTupleFloat3> nodes; + std::vector<UbTupleInt3> triangles; + gbobject->addSurfaceTriangleSet(nodes, triangles); - std::string outFilename = writer->writeTriangles(filename,nodes,triangles); - return outFilename; - } - /*========================================================================================*/ - inline static std::vector< std::string > writeGeoObject(GbObject3D* gbobject, const std::string& filename, std::vector< WbWriter* > writer ) - { - std::vector<UbTupleFloat3> nodes; - std::vector<UbTupleInt3> triangles; - gbobject->addSurfaceTriangleSet(nodes, triangles); + std::string outFilename = writer->writeTriangles(filename, nodes, triangles); + return outFilename; +} +/*========================================================================================*/ +inline static std::vector<std::string> writeGeoObject(GbObject3D *gbobject, const std::string &filename, + std::vector<WbWriter *> writer) +{ + std::vector<UbTupleFloat3> nodes; + std::vector<UbTupleInt3> triangles; + gbobject->addSurfaceTriangleSet(nodes, triangles); - std::vector< std::string > outFilenames; - for(std::size_t i=0; i<writer.size(); ++i) - outFilenames.push_back( writer[i]->writeTriangles(filename,nodes,triangles) ); - return outFilenames; - } - /*========================================================================================*/ - inline static std::string writeGeoObjects(std::vector< GbObject3D* > gbobjects, const std::string& filename, WbWriter* writer) - { - std::vector<UbTupleFloat3> nodes; - std::vector<UbTupleInt3> triangles; + std::vector<std::string> outFilenames; + for (std::size_t i = 0; i < writer.size(); ++i) + outFilenames.push_back(writer[i]->writeTriangles(filename, nodes, triangles)); + return outFilenames; +} +/*========================================================================================*/ +inline static std::string writeGeoObjects(std::vector<GbObject3D *> gbobjects, const std::string &filename, + WbWriter *writer) +{ + std::vector<UbTupleFloat3> nodes; + std::vector<UbTupleInt3> triangles; - for(std::size_t i=0; i<gbobjects.size(); ++i) - { - //std::cout<<i<<", "<<gbobjects[i]<<std::endl; - gbobjects[i]->addSurfaceTriangleSet(nodes, triangles); - } + for (std::size_t i = 0; i < gbobjects.size(); ++i) { + // std::cout<<i<<", "<<gbobjects[i]<<std::endl; + gbobjects[i]->addSurfaceTriangleSet(nodes, triangles); + } - std::string outFilename = writer->writeTriangles(filename,nodes,triangles); - return outFilename; - } - /*========================================================================================*/ + std::string outFilename = writer->writeTriangles(filename, nodes, triangles); + return outFilename; +} +/*========================================================================================*/ - ////////////////////////////////////////////////////////////////////////// - class PointSet3 - { - public: - PointSet3(int n); - PointSet3(const std::vector<GbPoint3D>& points); - ~PointSet3()= default; - void add(const GbPoint3D& point); - void addUnequal(const GbPoint3D& point); - void add(const std::vector<GbPoint3D>& p); - int contains(GbPoint3D* point); - void insert(const GbPoint3D& point, int index); - void clear(); - void clearAndTrim(); - int containsEqual(const GbPoint3D& point); - bool containsLine(GbPoint3D* point1, GbPoint3D* point2); - bool containsEqualLine(const GbPoint3D& point1, const GbPoint3D& point2); - double getX1Minimum(); - double getX1Maximum(); - double getX2Minimum(); - double getX2Maximum(); - double getX3Minimum(); - double getX3Maximum(); - void calculateValues(); - int size(); - GbPoint3D* getPoint(int index); - GbPoint3D* getFirstPoint(); - GbPoint3D* getLastPoint() ; - std::vector<GbPoint3D> getPoints(); +////////////////////////////////////////////////////////////////////////// +class PointSet3 +{ +public: + PointSet3(int n); + PointSet3(const std::vector<GbPoint3D> &points); + ~PointSet3() = default; + void add(const GbPoint3D &point); + void addUnequal(const GbPoint3D &point); + void add(const std::vector<GbPoint3D> &p); + int contains(GbPoint3D *point); + void insert(const GbPoint3D &point, int index); + void clear(); + void clearAndTrim(); + int containsEqual(const GbPoint3D &point); + bool containsLine(GbPoint3D *point1, GbPoint3D *point2); + bool containsEqualLine(const GbPoint3D &point1, const GbPoint3D &point2); + double getX1Minimum(); + double getX1Maximum(); + double getX2Minimum(); + double getX2Maximum(); + double getX3Minimum(); + double getX3Maximum(); + void calculateValues(); + int size(); + GbPoint3D *getPoint(int index); + GbPoint3D *getFirstPoint(); + GbPoint3D *getLastPoint(); + std::vector<GbPoint3D> getPoints(); - private: - double x1min; - double x1max; - double x2min; - double x2max; - double x3min; - double x3max; - bool consistent; - std::vector<GbPoint3D> points; +private: + double x1min; + double x1max; + double x2min; + double x2max; + double x3min; + double x3max; + bool consistent; + std::vector<GbPoint3D> points; - void init() - { - consistent = false; - x1min = x2min = x3min = 0.0; - x1max = x2max = x3max = 0.0; - } - }; - /*=================================================================*/ - class OldPointSet3 - { - private: - int sizet; - double x1min; - double x1max; - double x2min; - double x2max; - double x3min; - double x3max; - bool consistent; - std::vector<GbPoint3D> points; + void init() + { + consistent = false; + x1min = x2min = x3min = 0.0; + x1max = x2max = x3max = 0.0; + } +}; +/*=================================================================*/ +class OldPointSet3 +{ +private: + int sizet; + double x1min; + double x1max; + double x2min; + double x2max; + double x3min; + double x3max; + bool consistent; + std::vector<GbPoint3D> points; - void init() - { - sizet = 0; - x1min = 0.0; - x1max = 0.0; - x2min = 0.0; - x2max = 0.0; - x3min = 0.0; - x3max = 0.0; - consistent = false; - //points = NULL; - }; + void init() + { + sizet = 0; + x1min = 0.0; + x1max = 0.0; + x2min = 0.0; + x2max = 0.0; + x3min = 0.0; + x3max = 0.0; + consistent = false; + // points = NULL; + }; - public: - OldPointSet3(int n) - { - this->init(); - this->points.resize(n); - } - OldPointSet3(std::vector<GbPoint3D> &points) - { - this->init(); - this->points.resize(0);//, NULL); - this->add(points); - }; - ~OldPointSet3() = default; - void add(GbPoint3D point) - { - if(this->sizet>0 && point.equals(&(this->points)[this->sizet-1])) return; - if(this->sizet == (int)this->points.size()) - { - std::vector<GbPoint3D> a; - a.resize(1+(this->sizet<<1)); - for(int u=0; u<this->sizet; u++) { (a)[u] = (points)[u]; } - this->points = a; +public: + OldPointSet3(int n) + { + this->init(); + this->points.resize(n); + } + OldPointSet3(std::vector<GbPoint3D> &points) + { + this->init(); + this->points.resize(0); //, NULL); + this->add(points); + }; + ~OldPointSet3() = default; + void add(GbPoint3D point) + { + if (this->sizet > 0 && point.equals(&(this->points)[this->sizet - 1])) + return; + if (this->sizet == (int)this->points.size()) { + std::vector<GbPoint3D> a; + a.resize(1 + (this->sizet << 1)); + for (int u = 0; u < this->sizet; u++) { + (a)[u] = (points)[u]; } - (this->points)[this->sizet] = point; - this->consistent = false; - this->sizet++; - } - void addUnequal(GbPoint3D *point) - { - if(this->containsEqual(point) > 0) return; - if(this->sizet == (int)this->points.size()) - { - std::vector<GbPoint3D> a; - a.resize(1+(this->sizet<<1)); - for(int u=0; u<this->sizet; u++) { (a)[u] = (points)[u]; } - this->points = a; + this->points = a; + } + (this->points)[this->sizet] = point; + this->consistent = false; + this->sizet++; + } + void addUnequal(GbPoint3D *point) + { + if (this->containsEqual(point) > 0) + return; + if (this->sizet == (int)this->points.size()) { + std::vector<GbPoint3D> a; + a.resize(1 + (this->sizet << 1)); + for (int u = 0; u < this->sizet; u++) { + (a)[u] = (points)[u]; } - (this->points)[this->sizet] = point; - this->consistent = false; - this->sizet++; - } - void add(std::vector<GbPoint3D> &p) - { - if(this->sizet+p.size() >= this->points.size()) - { - std::vector<GbPoint3D> a; - a.resize(this->sizet+p.size()); - for(int u=0; u<(int)this->points.size(); u++) { (a)[u] = (this->points)[u]; } - this->points = a; + this->points = a; + } + (this->points)[this->sizet] = point; + this->consistent = false; + this->sizet++; + } + void add(std::vector<GbPoint3D> &p) + { + if (this->sizet + p.size() >= this->points.size()) { + std::vector<GbPoint3D> a; + a.resize(this->sizet + p.size()); + for (int u = 0; u < (int)this->points.size(); u++) { + (a)[u] = (this->points)[u]; } - int u = this->sizet;// (int)this->points->size(); - for(int b=0; b<(int)p.size(); b++) (this->points)[u++] = (p)[b]; - //u = this->sizet; - //for(int b=0; b<(int)p->size(); b++) - // cout<<(this->points)[u++].toString()<<endl; - this->consistent = false; - this->sizet += (int)p.size(); - }; - // void insert(GbPoint3D *point, int index) - // { - // if(this.size == this.points.length) - // { - // GbPoint3D a[] = new GbPoint3D[1+(this.size<<1)]; - // System.arraycopy(this.points, 0, a, 0, this.size); - // this.points = a; - // } - // System.arraycopy(this.points, index, this.points, index+1, this.size-index); - // this.points[index] = point; - // this.consistent = false; - // this.size++; - // } - // void delete(GbPoint3D point) - // { - // for(int i=this.size-1; i>=0; i--) if(this.points[i] == point) this.delete(i); - // } - // void delete(int index) - // { - // int j = this.size - index - 1; - // if(j > 0) System.arraycopy(this.points, index + 1, this.points, index, j); - // this.consistent = false; - // this.size--; - // } - void clear() - { - this->sizet = 0; - this->consistent = false; - } - void clearAndTrim() - { - this->sizet = 0; - this->points.resize(0); - this->consistent = false; - } + this->points = a; + } + int u = this->sizet; // (int)this->points->size(); + for (int b = 0; b < (int)p.size(); b++) + (this->points)[u++] = (p)[b]; + // u = this->sizet; + // for(int b=0; b<(int)p->size(); b++) + // cout<<(this->points)[u++].toString()<<endl; + this->consistent = false; + this->sizet += (int)p.size(); + }; + // void insert(GbPoint3D *point, int index) + // { + // if(this.size == this.points.length) + // { + // GbPoint3D a[] = new GbPoint3D[1+(this.size<<1)]; + // System.arraycopy(this.points, 0, a, 0, this.size); + // this.points = a; + // } + // System.arraycopy(this.points, index, this.points, index+1, this.size-index); + // this.points[index] = point; + // this.consistent = false; + // this.size++; + // } + // void delete(GbPoint3D point) + // { + // for(int i=this.size-1; i>=0; i--) if(this.points[i] == point) this.delete(i); + // } + // void delete(int index) + // { + // int j = this.size - index - 1; + // if(j > 0) System.arraycopy(this.points, index + 1, this.points, index, j); + // this.consistent = false; + // this.size--; + // } + void clear() + { + this->sizet = 0; + this->consistent = false; + } + void clearAndTrim() + { + this->sizet = 0; + this->points.resize(0); + this->consistent = false; + } - double getX1Minimum() - { - if(!this->consistent) this->calculateValues(); - return(this->x1min); - } - double getX1Maximum() - { - if(!this->consistent) this->calculateValues(); - return(this->x1max); - } - double getX2Minimum() - { - if(!this->consistent) this->calculateValues(); - return(this->x2min); - } - double getX2Maximum() - { - if(!this->consistent) this->calculateValues(); - return(this->x2max); - } - double getX3Minimum() - { - if(!this->consistent) this->calculateValues(); - return(this->x3min); - } - double getX3Maximum() - { - if(!this->consistent) this->calculateValues(); - return(this->x3max); - } - void calculateValues() - { - this->x1min = 0.0; - this->x1max = 0.0; - this->x2min = 0.0; - this->x2max = 0.0; - this->x3min = 0.0; - this->x3max = 0.0; - this->consistent = true; + double getX1Minimum() + { + if (!this->consistent) + this->calculateValues(); + return (this->x1min); + } + double getX1Maximum() + { + if (!this->consistent) + this->calculateValues(); + return (this->x1max); + } + double getX2Minimum() + { + if (!this->consistent) + this->calculateValues(); + return (this->x2min); + } + double getX2Maximum() + { + if (!this->consistent) + this->calculateValues(); + return (this->x2max); + } + double getX3Minimum() + { + if (!this->consistent) + this->calculateValues(); + return (this->x3min); + } + double getX3Maximum() + { + if (!this->consistent) + this->calculateValues(); + return (this->x3max); + } + void calculateValues() + { + this->x1min = 0.0; + this->x1max = 0.0; + this->x2min = 0.0; + this->x2max = 0.0; + this->x3min = 0.0; + this->x3max = 0.0; + this->consistent = true; - if(this->sizet == 0) return; + if (this->sizet == 0) + return; - this->x1min = (this->points)[0].x1; - this->x1max = (this->points)[0].x1; - this->x2min = (this->points)[0].x2; - this->x2max = (this->points)[0].x2; - this->x3min = (this->points)[0].x3; - this->x3max = (this->points)[0].x3; + this->x1min = (this->points)[0].x1; + this->x1max = (this->points)[0].x1; + this->x2min = (this->points)[0].x2; + this->x2max = (this->points)[0].x2; + this->x3min = (this->points)[0].x3; + this->x3max = (this->points)[0].x3; - for(int i=this->sizet-1; i>0; i--) - { - if((this->points)[i].x1 < this->x1min) this->x1min = (this->points)[i].x1; - if((this->points)[i].x1 > this->x1max) this->x1max = (this->points)[i].x1; - if((this->points)[i].x2 < this->x2min) this->x2min = (this->points)[i].x2; - if((this->points)[i].x2 > this->x2max) this->x2max = (this->points)[i].x2; - if((this->points)[i].x3 < this->x3min) this->x3min = (this->points)[i].x3; - if((this->points)[i].x3 > this->x3max) this->x3max = (this->points)[i].x3; - } - }; + for (int i = this->sizet - 1; i > 0; i--) { + if ((this->points)[i].x1 < this->x1min) + this->x1min = (this->points)[i].x1; + if ((this->points)[i].x1 > this->x1max) + this->x1max = (this->points)[i].x1; + if ((this->points)[i].x2 < this->x2min) + this->x2min = (this->points)[i].x2; + if ((this->points)[i].x2 > this->x2max) + this->x2max = (this->points)[i].x2; + if ((this->points)[i].x3 < this->x3min) + this->x3min = (this->points)[i].x3; + if ((this->points)[i].x3 > this->x3max) + this->x3max = (this->points)[i].x3; + } + }; - int contains(GbPoint3D *point) - { - int n = 0; - for(int i=this->sizet-1; i>=0; i--) if(&(this->points)[i] == point) n++; - return(n); - }; - int containsEqual(GbPoint3D *point) - { - int n = 0; - for(int i=this->sizet-1; i>=0; i--) if((this->points)[i].equals(point)) n++; - return(n); - } - bool containsLine(GbPoint3D *point1, GbPoint3D *point2) - { - for(int i=this->sizet-1; i>=0; i--) if(&(this->points)[i] == point1) - { - if(i == 0) - { - if(&(this->points)[i+1] == point2) return(true); - if(&(this->points)[this->sizet-1] == point2) return(true); - } - else if(i == this->sizet-1) - { - if(&(this->points)[0] == point2) return(true); - if(&(this->points)[i-1] == point2) return(true); - } - else - { - if(&(this->points)[i+1] == point2) return(true); - if(&(this->points)[i-1] == point2) return(true); - } + int contains(GbPoint3D *point) + { + int n = 0; + for (int i = this->sizet - 1; i >= 0; i--) + if (&(this->points)[i] == point) + n++; + return (n); + }; + int containsEqual(GbPoint3D *point) + { + int n = 0; + for (int i = this->sizet - 1; i >= 0; i--) + if ((this->points)[i].equals(point)) + n++; + return (n); + } + bool containsLine(GbPoint3D *point1, GbPoint3D *point2) + { + for (int i = this->sizet - 1; i >= 0; i--) + if (&(this->points)[i] == point1) { + if (i == 0) { + if (&(this->points)[i + 1] == point2) + return (true); + if (&(this->points)[this->sizet - 1] == point2) + return (true); + } else if (i == this->sizet - 1) { + if (&(this->points)[0] == point2) + return (true); + if (&(this->points)[i - 1] == point2) + return (true); + } else { + if (&(this->points)[i + 1] == point2) + return (true); + if (&(this->points)[i - 1] == point2) + return (true); + } } - return(false); - }; - // boolean containsEqualLine(GbPoint2D point1, GbPoint2D point2) - // { - // for(int i=this.size-1; i>=0; i--) if(this.points[i].equals(point1)) - // { - // if(i == 0) - // { - // if(this.points[i+1].equals(point2)) return(true); - // if(this.points[this.size-1].equals(point2)) return(true); - // } - // else if(i == this.size-1) - // { - // if(this.points[0].equals(point2)) return(true); - // if(this.points[i-1].equals(point2)) return(true); - // } - // else - // { - // if(this.points[i+1].equals(point2)) return(true); - // if(this.points[i-1].equals(point2)) return(true); - // } - // } - // return(false); - // } - GbPoint3D *getPoint(int index) - { - return(&(this->points)[index]); - } - GbPoint3D *getFirstPoint() - { - return(&(this->points)[0]); - } - GbPoint3D *getLastPoint() { return(&(this->points)[this->sizet-1]); } - int size() { return(this->sizet); } - std::vector<GbPoint3D> getPoints() - { - points.resize(sizet); - return points; - //int l = this->sizet; - //if(l > 1 && (this->points)[0].equals(&(this->points)[l-1])) l--; + return (false); + }; + // boolean containsEqualLine(GbPoint2D point1, GbPoint2D point2) + // { + // for(int i=this.size-1; i>=0; i--) if(this.points[i].equals(point1)) + // { + // if(i == 0) + // { + // if(this.points[i+1].equals(point2)) return(true); + // if(this.points[this.size-1].equals(point2)) return(true); + // } + // else if(i == this.size-1) + // { + // if(this.points[0].equals(point2)) return(true); + // if(this.points[i-1].equals(point2)) return(true); + // } + // else + // { + // if(this.points[i+1].equals(point2)) return(true); + // if(this.points[i-1].equals(point2)) return(true); + // } + // } + // return(false); + // } + GbPoint3D *getPoint(int index) { return (&(this->points)[index]); } + GbPoint3D *getFirstPoint() { return (&(this->points)[0]); } + GbPoint3D *getLastPoint() { return (&(this->points)[this->sizet - 1]); } + int size() { return (this->sizet); } + std::vector<GbPoint3D> getPoints() + { + points.resize(sizet); + return points; + // int l = this->sizet; + // if(l > 1 && (this->points)[0].equals(&(this->points)[l-1])) l--; - //vector<GbPoint3D*> *a = new vector<GbPoint3D*>; - //a->resize(l, NULL); - //for(int u=0; u<l; u++) { (*a)[u] = &((points)[u]); } - //return(a); - } - }; - /*=================================================================*/ -} + // vector<GbPoint3D*> *a = new vector<GbPoint3D*>; + // a->resize(l, NULL); + // for(int u=0; u<l; u++) { (*a)[u] = &((points)[u]); } + // return(a); + } +}; +/*=================================================================*/ +} // namespace GbSystem3D -#endif //GBSYSTEM3D_H +#endif // GBSYSTEM3D_H diff --git a/src/basics/geometry3d/GbTriFaceMesh3D.cpp b/src/basics/geometry3d/GbTriFaceMesh3D.cpp index e883f59564efb02bfc9729e04d7652da55eb2002..61940c0d7a4bfaaf62ac51556ead5ca1573383fe 100644 --- a/src/basics/geometry3d/GbTriFaceMesh3D.cpp +++ b/src/basics/geometry3d/GbTriFaceMesh3D.cpp @@ -1,176 +1,178 @@ #include <geometry3d/GbTriFaceMesh3D.h> -#include <geometry3d/GbCuboid3D.h> -#include <geometry3d/GbHalfSpace3D.h> -#include <geometry3d/CoordinateTransformation3D.h> +#include <basics/utilities/UbFileInputASCII.h> +#include <basics/utilities/UbLogger.h> #include <basics/utilities/UbRandom.h> #include <basics/utilities/UbTiming.h> -#include <basics/utilities/UbLogger.h> -#include <basics/utilities/UbFileInputASCII.h> #include <basics/writer/WbWriter.h> +#include <geometry3d/CoordinateTransformation3D.h> +#include <geometry3d/GbCuboid3D.h> +#include <geometry3d/GbHalfSpace3D.h> #include <geometry3d/KdTree/KdTree.h> -#include <geometry3d/KdTree/splitalgorithms/KdSpatiallMedianSplit.h> -#include <geometry3d/KdTree/splitalgorithms/KdSAHSplit.h> #include <geometry3d/KdTree/intersectionhandler/KdCountLineIntersectionHandler.h> #include <geometry3d/KdTree/intersectionhandler/KdCountRayIntersectionHandler.h> +#include <geometry3d/KdTree/splitalgorithms/KdSAHSplit.h> +#include <geometry3d/KdTree/splitalgorithms/KdSpatiallMedianSplit.h> #define MAX_ITER 10 using namespace std; -GbTriFaceMesh3D::GbTriFaceMesh3D() - : GbObject3D() +GbTriFaceMesh3D::GbTriFaceMesh3D() : GbObject3D() { - this->setName("CAB_GbTriFaceMesh3D"); - this->nodes = new vector<Vertex>; - this->triangles = new vector<TriFace>; - this->consistent = false; - this->kdtreeSplitAlg = KDTREE_SAHPLIT; + this->setName("CAB_GbTriFaceMesh3D"); + this->nodes = new vector<Vertex>; + this->triangles = new vector<TriFace>; + this->consistent = false; + this->kdtreeSplitAlg = KDTREE_SAHPLIT; } /*=======================================================================*/ -GbTriFaceMesh3D::GbTriFaceMesh3D(string name, vector<Vertex>* nodes, vector<TriFace>* triangles, KDTREE_SPLITAGORITHM splitAlg, bool removeRedundantNodes) - : GbObject3D() - , nodes(nodes) - , triangles(triangles) - , kdtreeSplitAlg(splitAlg) +GbTriFaceMesh3D::GbTriFaceMesh3D(string name, vector<Vertex> *nodes, vector<TriFace> *triangles, + KDTREE_SPLITAGORITHM splitAlg, bool removeRedundantNodes) + : GbObject3D(), nodes(nodes), triangles(triangles), kdtreeSplitAlg(splitAlg) { - if( name.empty() ) throw UbException(UB_EXARGS,"no name specified"); - if( !nodes ) throw UbException(UB_EXARGS,"no nodes specified"); - if( !triangles ) throw UbException(UB_EXARGS,"no triangles specified"); - - this->setName(name); - - if(removeRedundantNodes) - { - this->deleteRedundantNodes(); //dort wird autoamtisch calculateValues() aufgerufen - } - else - { - this->calculateValues(); - } + if (name.empty()) + throw UbException(UB_EXARGS, "no name specified"); + if (!nodes) + throw UbException(UB_EXARGS, "no nodes specified"); + if (!triangles) + throw UbException(UB_EXARGS, "no triangles specified"); + + this->setName(name); + + if (removeRedundantNodes) { + this->deleteRedundantNodes(); // dort wird autoamtisch calculateValues() aufgerufen + } else { + this->calculateValues(); + } } /*=======================================================================*/ GbTriFaceMesh3D::~GbTriFaceMesh3D() { - if( nodes ) { delete nodes; nodes = NULL; } - if( triangles ) { delete triangles; triangles = NULL; } - if( kdTree ) { delete kdTree; kdTree = NULL; } + if (nodes) { + delete nodes; + nodes = NULL; + } + if (triangles) { + delete triangles; + triangles = NULL; + } + if (kdTree) { + delete kdTree; + kdTree = NULL; + } } /*======================================================================*/ void GbTriFaceMesh3D::init() { - nodes = NULL; - triangles = NULL; - x1min = 0.0; - x1max = 0.0; - x1center = 0.0; - x2min = 0.0; - x2max = 0.0; - x2center = 0.0; - x3min = 0.0; - x3max = 0.0; - x3center = 0.0; - consistent = false; + nodes = NULL; + triangles = NULL; + x1min = 0.0; + x1max = 0.0; + x1center = 0.0; + x2min = 0.0; + x2max = 0.0; + x2center = 0.0; + x3min = 0.0; + x3max = 0.0; + x3center = 0.0; + consistent = false; } /*======================================================================*/ -GbTriFaceMesh3D* GbTriFaceMesh3D::clone() +GbTriFaceMesh3D *GbTriFaceMesh3D::clone() { - vector<GbTriFaceMesh3D::Vertex> *newNodes = new vector<GbTriFaceMesh3D::Vertex>; - vector<GbTriFaceMesh3D::TriFace> *newTriangles = new vector<GbTriFaceMesh3D::TriFace>; - - int numberNodes = (int)this->nodes->size(); - - double x,y,z; - for(int u=0;u<numberNodes;u++) - { - x=(*nodes)[u].x; - y=(*nodes)[u].y; - z=(*nodes)[u].z; - newNodes->push_back(GbTriFaceMesh3D::Vertex((float)x,(float)y,(float)z)); - } - int numberTris = (int)this->triangles->size(); - UBLOG(logDEBUG1,"numberTris:"<<numberTris); - - int id1,id2,id3; - for(int u=0;u<numberTris;u++) - { - id1 = (*this->triangles)[u].v1; - id2 = (*this->triangles)[u].v2; - id3 = (*this->triangles)[u].v3; - newTriangles->push_back(GbTriFaceMesh3D::TriFace(id1,id2,id3)); - //cout<<u<<" - id1,id2,id3:"<<id1<<","<<id2<<","<<id3<<endl; - } - UBLOG(logDEBUG1,"Tris gelesen"); - - GbTriFaceMesh3D* mesh = new GbTriFaceMesh3D("no name", newNodes, newTriangles); - UBLOG(logDEBUG1,"mesh cloned ..."); - - return mesh; + vector<GbTriFaceMesh3D::Vertex> *newNodes = new vector<GbTriFaceMesh3D::Vertex>; + vector<GbTriFaceMesh3D::TriFace> *newTriangles = new vector<GbTriFaceMesh3D::TriFace>; + + int numberNodes = (int)this->nodes->size(); + + double x, y, z; + for (int u = 0; u < numberNodes; u++) { + x = (*nodes)[u].x; + y = (*nodes)[u].y; + z = (*nodes)[u].z; + newNodes->push_back(GbTriFaceMesh3D::Vertex((float)x, (float)y, (float)z)); + } + int numberTris = (int)this->triangles->size(); + UBLOG(logDEBUG1, "numberTris:" << numberTris); + + int id1, id2, id3; + for (int u = 0; u < numberTris; u++) { + id1 = (*this->triangles)[u].v1; + id2 = (*this->triangles)[u].v2; + id3 = (*this->triangles)[u].v3; + newTriangles->push_back(GbTriFaceMesh3D::TriFace(id1, id2, id3)); + // cout<<u<<" - id1,id2,id3:"<<id1<<","<<id2<<","<<id3<<endl; + } + UBLOG(logDEBUG1, "Tris gelesen"); + + GbTriFaceMesh3D *mesh = new GbTriFaceMesh3D("no name", newNodes, newTriangles); + UBLOG(logDEBUG1, "mesh cloned ..."); + + return mesh; } /*======================================================================*/ -//checks for doppelt nodes und fixed Dreicke die zweimal denselben Knoten haben +// checks for doppelt nodes und fixed Dreicke die zweimal denselben Knoten haben void GbTriFaceMesh3D::deleteRedundantNodes() { - UBLOG(logDEBUG1,"GbTriFaceMesh3D::deleteRedundantNodes - Nodes before deleting redundant: "<<this->nodes->size()); - - map<Vertex,size_t/*new vecIndex*/> vertexMap; - map<Vertex,size_t/*new vecIndex*/>::iterator pos; - map<Vertex,size_t/*new vecIndex*/>::iterator it; - - vector<TriFace>& tris = *this->triangles; - vector<Vertex>& oldNodes = *this->nodes; - vector<Vertex> newNodes; - - for(size_t t=0; t<tris.size(); t++) - { - if(t%100==0) { UBLOG(logDEBUG5,"GbTriFaceMesh3D::deleteRedundantNodes - tri: "<<(t)<<" von "<<tris.size()); } - TriFace& tri = tris[t]; - //Knoten bereits in neuem node vector? - for(int v=0; v<=2; v++) - { - Vertex& vert = tri.getNode(v,oldNodes); - //pos=vertexMap.find( vert ); - //if( pos==vertexMap.end() ) - { - for(pos=vertexMap.begin();pos!=vertexMap.end();pos++) - { - Vertex rhs = pos->first; - //if(UbMath::inClosedInterval(vert.z,0.01999, 0.02001)) - if ( fabs(vert.x-rhs.x)<1.E-5 && fabs(vert.y-rhs.y)<1.E-5 && fabs(vert.z-rhs.z)<1.E-5 ) - { - break; - } - } - } - if( pos!=vertexMap.end() ) tri.setNode(v, (int)pos->second); - else - { - newNodes.push_back(vert); - int index = (int)newNodes.size()-1; - vertexMap[vert] = index; - tri.setNode(v,index); - } - } + UBLOG(logDEBUG1, + "GbTriFaceMesh3D::deleteRedundantNodes - Nodes before deleting redundant: " << this->nodes->size()); + + map<Vertex, size_t /*new vecIndex*/> vertexMap; + map<Vertex, size_t /*new vecIndex*/>::iterator pos; + map<Vertex, size_t /*new vecIndex*/>::iterator it; + + vector<TriFace> &tris = *this->triangles; + vector<Vertex> &oldNodes = *this->nodes; + vector<Vertex> newNodes; + + for (size_t t = 0; t < tris.size(); t++) { + if (t % 100 == 0) { + UBLOG(logDEBUG5, "GbTriFaceMesh3D::deleteRedundantNodes - tri: " << (t) << " von " << tris.size()); + } + TriFace &tri = tris[t]; + // Knoten bereits in neuem node vector? + for (int v = 0; v <= 2; v++) { + Vertex &vert = tri.getNode(v, oldNodes); + // pos=vertexMap.find( vert ); + // if( pos==vertexMap.end() ) + { + for (pos = vertexMap.begin(); pos != vertexMap.end(); pos++) { + Vertex rhs = pos->first; + // if(UbMath::inClosedInterval(vert.z,0.01999, 0.02001)) + if (fabs(vert.x - rhs.x) < 1.E-5 && fabs(vert.y - rhs.y) < 1.E-5 && fabs(vert.z - rhs.z) < 1.E-5) { + break; + } + } + } + if (pos != vertexMap.end()) + tri.setNode(v, (int)pos->second); + else { + newNodes.push_back(vert); + int index = (int)newNodes.size() - 1; + vertexMap[vert] = index; + tri.setNode(v, index); + } + } } - std::swap(*nodes,newNodes); + std::swap(*nodes, newNodes); - UBLOG(logDEBUG1,"GbTriFaceMesh3D::deleteRedundantNodes - Nodes after deleting redundant:"<<this->nodes->size()); + UBLOG(logDEBUG1, "GbTriFaceMesh3D::deleteRedundantNodes - Nodes after deleting redundant:" << this->nodes->size()); // - //Das geht irgendwie nicht ... + // Das geht irgendwie nicht ... // - //UBLOG(logDEBUG1,"GbTriFaceMesh3D::deleteRedundantNodes - checking for double triangles !!!"); - //UBLOG(logDEBUG1,"GbTriFaceMesh3D::deleteRedundantNodes - Triangles before deleting redundant: "<<this->triangles->size()); - //vector<TriFace> newSingleTris; - //newSingleTris.reserve( this->triangles->size() ); - //for(size_t t=0; t<tris.size(); t++) + // UBLOG(logDEBUG1,"GbTriFaceMesh3D::deleteRedundantNodes - checking for double triangles !!!"); + // UBLOG(logDEBUG1,"GbTriFaceMesh3D::deleteRedundantNodes - Triangles before deleting redundant: + // "<<this->triangles->size()); vector<TriFace> newSingleTris; newSingleTris.reserve( this->triangles->size() ); + // for(size_t t=0; t<tris.size(); t++) //{ - // Vertex& v1 = tris[t].getNode(0,*nodes); - // Vertex& v2 = tris[t].getNode(1,*nodes); - // Vertex& v3 = tris[t].getNode(2,*nodes); + // Vertex& v1 = tris[t].getNode(0,*nodes); + // Vertex& v2 = tris[t].getNode(1,*nodes); + // Vertex& v3 = tris[t].getNode(2,*nodes); // if(UbMath::greater(std::fabs(v1.x), 0.0634) && UbMath::inClosedInterval(v1.z, 0.01999, 0.02001)) // { @@ -188,9 +190,9 @@ void GbTriFaceMesh3D::deleteRedundantNodes() // bool inList = false; // for(size_t u=0; u<newSingleTris.size(); u++) // { - // Vertex& vn1 = newSingleTris[t].getNode(0,*nodes); - // Vertex& vn2 = newSingleTris[t].getNode(1,*nodes); - // Vertex& vn3 = newSingleTris[t].getNode(2,*nodes); + // Vertex& vn1 = newSingleTris[t].getNode(0,*nodes); + // Vertex& vn2 = newSingleTris[t].getNode(1,*nodes); + // Vertex& vn3 = newSingleTris[t].getNode(2,*nodes); // if(v1==vn1 && v2==vn2 && v3==vn3) inList = true; // else if(v1==vn1 && v2==vn3 && v3==vn2) inList = true; @@ -200,393 +202,409 @@ void GbTriFaceMesh3D::deleteRedundantNodes() // else if(v1==vn3 && v2==vn2 && v3==vn1) inList = true; // } // if(!inList) newSingleTris.push_back(tris[t]); - // else + // else // UBLOG(logDEBUG1,"GbTriFaceMesh3D::deleteRedundantNodes - inList !!!!"); - + //} - //swap(tris,newSingleTris); + // swap(tris,newSingleTris); - //UBLOG(logDEBUG1,"GbTriFaceMesh3D::deleteRedundantNodes - Triangles after deleting redundant:"<<this->triangles->size()); - UBLOG(logDEBUG1,"GbTriFaceMesh3D::deleteRedundantNodes - checking for triangles that have same node several times or are lines!!!"); + // UBLOG(logDEBUG1,"GbTriFaceMesh3D::deleteRedundantNodes - Triangles after deleting + // redundant:"<<this->triangles->size()); + UBLOG(logDEBUG1, "GbTriFaceMesh3D::deleteRedundantNodes - checking for triangles that have same node several times " + "or are lines!!!"); int counter1 = 0; int counter2 = 0; vector<TriFace> newTris; - newTris.reserve( this->triangles->size() ); - for(size_t t=0; t<tris.size(); t++) - { - Vertex& v1 = tris[t].getNode(0,*nodes); - Vertex& v2 = tris[t].getNode(1,*nodes); - Vertex& v3 = tris[t].getNode(2,*nodes); - if( v1==v2 || v1==v3 || v2==v3 ) - { - counter1++; - } - else if( tris[t].getArea(*nodes)<1.0E-8 ) - { - counter2++; - } - else newTris.push_back(tris[t]); + newTris.reserve(this->triangles->size()); + for (size_t t = 0; t < tris.size(); t++) { + Vertex &v1 = tris[t].getNode(0, *nodes); + Vertex &v2 = tris[t].getNode(1, *nodes); + Vertex &v3 = tris[t].getNode(2, *nodes); + if (v1 == v2 || v1 == v3 || v2 == v3) { + counter1++; + } else if (tris[t].getArea(*nodes) < 1.0E-8) { + counter2++; + } else + newTris.push_back(tris[t]); } - if(counter1) - { - UBLOG(logDEBUG1,"GbTriFaceMesh3D::deleteRedundantNodes - ### Warning ###: found and removed "<<counter1<<" triangle with double nodes!"); + if (counter1) { + UBLOG(logDEBUG1, "GbTriFaceMesh3D::deleteRedundantNodes - ### Warning ###: found and removed " + << counter1 << " triangle with double nodes!"); } - if(counter2) - { - UBLOG(logDEBUG1,"GbTriFaceMesh3D::deleteRedundantNodes - ### Warning ###: found and removed "<<counter2<<" triangle that are lines!") ; + if (counter2) { + UBLOG(logDEBUG1, "GbTriFaceMesh3D::deleteRedundantNodes - ### Warning ###: found and removed " + << counter2 << " triangle that are lines!"); } - if(!counter1 && !counter2) { UBLOG(logDEBUG1,"GbTriFaceMesh3D::deleteRedundantNodes - alles gut... nix doppelt"); } - else swap(tris,newTris); - - UBLOG(logDEBUG1,"GbTriFaceMesh3D::deleteRedundantNodes - done" ); + if (!counter1 && !counter2) { + UBLOG(logDEBUG1, "GbTriFaceMesh3D::deleteRedundantNodes - alles gut... nix doppelt"); + } else + swap(tris, newTris); + + UBLOG(logDEBUG1, "GbTriFaceMesh3D::deleteRedundantNodes - done"); this->calculateValues(); } /*======================================================================*/ -void GbTriFaceMesh3D::setKdTreeSplitAlgorithm(KDTREE_SPLITAGORITHM mode) -{ - if(kdTree && mode != this->kdtreeSplitAlg) { delete kdTree; kdTree = NULL; } - this->kdtreeSplitAlg = mode; +void GbTriFaceMesh3D::setKdTreeSplitAlgorithm(KDTREE_SPLITAGORITHM mode) +{ + if (kdTree && mode != this->kdtreeSplitAlg) { + delete kdTree; + kdTree = NULL; + } + this->kdtreeSplitAlg = mode; } /*======================================================================*/ - /** - * Returns a string representation of this triangular mesh. - * @return a string representation of this triangular mesh - */ +/** + * Returns a string representation of this triangular mesh. + * @return a string representation of this triangular mesh + */ string GbTriFaceMesh3D::toString() { - stringstream ss; - ss<<"GbTriFaceMesh3D["; - ss<<(int)this->triangles->size()<<"-Triangles, "<<(int)this->nodes->size()<<"-Nodes, "<<endl; - ss<<"]"; - return(ss.str()); + stringstream ss; + ss << "GbTriFaceMesh3D["; + ss << (int)this->triangles->size() << "-Triangles, " << (int)this->nodes->size() << "-Nodes, " << endl; + ss << "]"; + return (ss.str()); } /** * Returns the nodes of this triangular mesh. * @return the nodes of this triangular mesh */ -vector<GbTriFaceMesh3D::Vertex>* GbTriFaceMesh3D::getNodes() { return this->nodes; } +vector<GbTriFaceMesh3D::Vertex> *GbTriFaceMesh3D::getNodes() { return this->nodes; } /** * Returns the triangles of this triangular mesh. * @return the triangles of this triangular mesh */ -vector<GbTriFaceMesh3D::TriFace>* GbTriFaceMesh3D::getTriangles() { return this->triangles; } +vector<GbTriFaceMesh3D::TriFace> *GbTriFaceMesh3D::getTriangles() { return this->triangles; } /** * Returns the center x1 coordinate of this triangular mesh. * @return the center x1 coordinate of this triangular mesh */ double GbTriFaceMesh3D::getVolume() { - vector<Vertex>& vertices = *nodes; - vector<TriFace>& tris = *triangles; - - double x1,x2,x3,y1,y2,y3,z1,z2,z3, G3i; - //double rSP1 = 0.0;double rSP2 = 0.0;double rSP3 = 0.0; - double volume = 0.0; - for(size_t t=0; t<tris.size(); t++) - { - TriFace& triangle = tris[t]; - x1 = triangle.getV1x(vertices); y1 = triangle.getV1y(vertices); z1 = triangle.getV1z(vertices); - x2 = triangle.getV2x(vertices); y2 = triangle.getV2y(vertices); z2 = triangle.getV2z(vertices); - x3 = triangle.getV3x(vertices); y3 = triangle.getV3y(vertices); z3 = triangle.getV3z(vertices); - G3i = x1*(y2*z3-z2*y3)+y1*(z2*x3-x2*z3)+z1*(x2*y3-y2*x3); - volume = volume+G3i/6.0; - } - return volume; + vector<Vertex> &vertices = *nodes; + vector<TriFace> &tris = *triangles; + + double x1, x2, x3, y1, y2, y3, z1, z2, z3, G3i; + // double rSP1 = 0.0;double rSP2 = 0.0;double rSP3 = 0.0; + double volume = 0.0; + for (size_t t = 0; t < tris.size(); t++) { + TriFace &triangle = tris[t]; + x1 = triangle.getV1x(vertices); + y1 = triangle.getV1y(vertices); + z1 = triangle.getV1z(vertices); + x2 = triangle.getV2x(vertices); + y2 = triangle.getV2y(vertices); + z2 = triangle.getV2z(vertices); + x3 = triangle.getV3x(vertices); + y3 = triangle.getV3y(vertices); + z3 = triangle.getV3z(vertices); + G3i = x1 * (y2 * z3 - z2 * y3) + y1 * (z2 * x3 - x2 * z3) + z1 * (x2 * y3 - y2 * x3); + volume = volume + G3i / 6.0; + } + return volume; } /*===============================================*/ UbTupleDouble3 GbTriFaceMesh3D::calculateCenterOfGravity() { - vector<Vertex>& vertices = *nodes; - vector<TriFace>& tris = *triangles; - - double x1,x2,x3,y1,y2,y3,z1,z2,z3; - double G3i; - double rSP1 = 0.0, rSP2 = 0.0, rSP3 = 0.0, volume = 0.0; - - for(size_t t=0; t<tris.size(); t++) - { - TriFace& triangle = tris[t]; - x1 = triangle.getV1x(vertices); y1 = triangle.getV1y(vertices); z1 = triangle.getV1z(vertices); - x2 = triangle.getV2x(vertices); y2 = triangle.getV2y(vertices); z2 = triangle.getV2z(vertices); - x3 = triangle.getV3x(vertices); y3 = triangle.getV3y(vertices); z3 = triangle.getV3z(vertices); - G3i = x1*(y2*z3-z2*y3)+y1*(z2*x3-x2*z3)+z1*(x2*y3-y2*x3); - volume = volume+G3i/6.0; - rSP1 = rSP1+G3i*(x1+x2+x3); - rSP2 = rSP2+G3i*(y1+y2+y3); - rSP3 = rSP3+G3i*(z1+z2+z3); - } - rSP1 = rSP1/(24.0*volume); - rSP2 = rSP2/(24.0*volume); - rSP3 = rSP3/(24.0*volume); - - return {rSP1, rSP2, rSP3}; + vector<Vertex> &vertices = *nodes; + vector<TriFace> &tris = *triangles; + + double x1, x2, x3, y1, y2, y3, z1, z2, z3; + double G3i; + double rSP1 = 0.0, rSP2 = 0.0, rSP3 = 0.0, volume = 0.0; + + for (size_t t = 0; t < tris.size(); t++) { + TriFace &triangle = tris[t]; + x1 = triangle.getV1x(vertices); + y1 = triangle.getV1y(vertices); + z1 = triangle.getV1z(vertices); + x2 = triangle.getV2x(vertices); + y2 = triangle.getV2y(vertices); + z2 = triangle.getV2z(vertices); + x3 = triangle.getV3x(vertices); + y3 = triangle.getV3y(vertices); + z3 = triangle.getV3z(vertices); + G3i = x1 * (y2 * z3 - z2 * y3) + y1 * (z2 * x3 - x2 * z3) + z1 * (x2 * y3 - y2 * x3); + volume = volume + G3i / 6.0; + rSP1 = rSP1 + G3i * (x1 + x2 + x3); + rSP2 = rSP2 + G3i * (y1 + y2 + y3); + rSP3 = rSP3 + G3i * (z1 + z2 + z3); + } + rSP1 = rSP1 / (24.0 * volume); + rSP2 = rSP2 / (24.0 * volume); + rSP3 = rSP3 / (24.0 * volume); + + return { rSP1, rSP2, rSP3 }; } /*===============================================*/ UbTupleDouble6 GbTriFaceMesh3D::calculateMomentOfInertia(double rhoP) { - vector<Vertex>& vertices = *nodes; - - double x1,x2,x3,y1,y2,y3,z1,z2,z3; - double G3i; - double xx,yy,zz,xy,yz,zx; - double rSP1 = 0.0;double rSP2 = 0.0;double rSP3 = 0.0; - double volume = 0.0; - double top11 = 0.0;double top22 = 0.0;double top33 = 0.0; - double top12 = 0.0;double top23 = 0.0;double top13 = 0.0; - int size = (int)this->triangles->size(); - for(int u=0; u<size;u++) - { - TriFace& triangle = (*this->triangles)[u]; - x1 = triangle.getV1x(vertices); y1 = triangle.getV1y(vertices); z1 = triangle.getV1z(vertices); - x2 = triangle.getV2x(vertices); y2 = triangle.getV2y(vertices); z2 = triangle.getV2z(vertices); - x3 = triangle.getV3x(vertices); y3 = triangle.getV3y(vertices); z3 = triangle.getV3z(vertices); - G3i = x1*(y2*z3-z2*y3)+y1*(z2*x3-x2*z3)+z1*(x2*y3-y2*x3); - volume = volume+G3i/6.0; - rSP1 = rSP1+G3i*(x1+x2+x3); - rSP2 = rSP2+G3i*(y1+y2+y3); - rSP3 = rSP3+G3i*(z1+z2+z3); - } - rSP1 = rSP1/(24.0*volume); - rSP2 = rSP2/(24.0*volume); - rSP3 = rSP3/(24.0*volume); - - double x1s = 0.0;//rSP1;//0.0;// - double x2s = 0.0;//rSP2;//0.0;// - double x3s = 0.0;//rSP3;//0.0;// - - for(int u=0; u<size;u++) - { - TriFace& triangle = (*this->triangles)[u]; - x1 = triangle.getV1x(vertices)-x1s; - y1 = triangle.getV1y(vertices)-x2s; - z1 = triangle.getV1z(vertices)-x3s; - x2 = triangle.getV2x(vertices)-x1s; - y2 = triangle.getV2y(vertices)-x2s; - z2 = triangle.getV2z(vertices)-x3s; - x3 = triangle.getV3x(vertices)-x1s; - y3 = triangle.getV3y(vertices)-x2s; - z3 = triangle.getV3z(vertices)-x3s; - G3i = x1*(y2*z3-z2*y3)+y1*(z2*x3-x2*z3)+z1*(x2*y3-y2*x3); - //rSP1 = rSP1+G3i*(x1+x2+x3)/(24.0*volume); - //rSP2 = rSP2+G3i*(y1+y2+y3)/(24.0*volume); - //rSP3 = rSP3+G3i*(z1+z2+z3)/(24.0*volume); - xx = x1*x1+x2*x2+x3*x3+x1*x2+x2*x3+x3*x1; - yy = y1*y1+y2*y2+y3*y3+y1*y2+y2*y3+y3*y1; - zz = z1*z1+z2*z2+z3*z3+z1*z2+z2*z3+z3*z1; - top11 = top11+(yy+zz)*rhoP*G3i/60.; - top22 = top22+(xx+zz)*rhoP*G3i/60.; - top33 = top33+(yy+xx)*rhoP*G3i/60.; - xy = 2.0*(x1*y1+x2*y2+x3*y3)+x2*y3+x3*y1+x1*y2+x3*y2+x1*y3+x2*y1; - yz = 2.0*(y1*z1+y2*z2+y3*z3)+y2*z3+y3*z1+y1*z2+y3*z2+y1*z3+y2*z1; - zx = 2.0*(z1*x1+z2*x2+z3*x3)+z2*x3+z3*x1+z1*x2+z3*x2+z1*x3+z2*x1; - top12 = top12-xy*rhoP*G3i/120.; - top23 = top23-yz*rhoP*G3i/120.; - top13 = top13-zx*rhoP*G3i/120.; - } - //Satz von Steiner ... - top11 = top11-rhoP*volume*(rSP2*rSP2+rSP3+rSP3); - top22 = top22-rhoP*volume*(rSP3*rSP3+rSP1*rSP1); - top33 = top33-rhoP*volume*(rSP1*rSP1+rSP2*rSP2); - top12 = top12+rhoP*volume*rSP1*rSP2; - top23 = top23+rhoP*volume*rSP2*rSP3; - top13 = top13+rhoP*volume*rSP3*rSP1; - - cout<<"Volume:"<<volume<<"\n Traegheitsmomente:\n"; - cout<<" top11:"<<top11<<" top22:"<<top22<<" top33:"<<top33<<endl; - cout<<" top12:"<<top12<<" top23:"<<top23<<" top13:"<<top13<<endl; - - return {top11,top22,top33,top12,top23,top13}; + vector<Vertex> &vertices = *nodes; + + double x1, x2, x3, y1, y2, y3, z1, z2, z3; + double G3i; + double xx, yy, zz, xy, yz, zx; + double rSP1 = 0.0; + double rSP2 = 0.0; + double rSP3 = 0.0; + double volume = 0.0; + double top11 = 0.0; + double top22 = 0.0; + double top33 = 0.0; + double top12 = 0.0; + double top23 = 0.0; + double top13 = 0.0; + int size = (int)this->triangles->size(); + for (int u = 0; u < size; u++) { + TriFace &triangle = (*this->triangles)[u]; + x1 = triangle.getV1x(vertices); + y1 = triangle.getV1y(vertices); + z1 = triangle.getV1z(vertices); + x2 = triangle.getV2x(vertices); + y2 = triangle.getV2y(vertices); + z2 = triangle.getV2z(vertices); + x3 = triangle.getV3x(vertices); + y3 = triangle.getV3y(vertices); + z3 = triangle.getV3z(vertices); + G3i = x1 * (y2 * z3 - z2 * y3) + y1 * (z2 * x3 - x2 * z3) + z1 * (x2 * y3 - y2 * x3); + volume = volume + G3i / 6.0; + rSP1 = rSP1 + G3i * (x1 + x2 + x3); + rSP2 = rSP2 + G3i * (y1 + y2 + y3); + rSP3 = rSP3 + G3i * (z1 + z2 + z3); + } + rSP1 = rSP1 / (24.0 * volume); + rSP2 = rSP2 / (24.0 * volume); + rSP3 = rSP3 / (24.0 * volume); + + double x1s = 0.0; // rSP1;//0.0;// + double x2s = 0.0; // rSP2;//0.0;// + double x3s = 0.0; // rSP3;//0.0;// + + for (int u = 0; u < size; u++) { + TriFace &triangle = (*this->triangles)[u]; + x1 = triangle.getV1x(vertices) - x1s; + y1 = triangle.getV1y(vertices) - x2s; + z1 = triangle.getV1z(vertices) - x3s; + x2 = triangle.getV2x(vertices) - x1s; + y2 = triangle.getV2y(vertices) - x2s; + z2 = triangle.getV2z(vertices) - x3s; + x3 = triangle.getV3x(vertices) - x1s; + y3 = triangle.getV3y(vertices) - x2s; + z3 = triangle.getV3z(vertices) - x3s; + G3i = x1 * (y2 * z3 - z2 * y3) + y1 * (z2 * x3 - x2 * z3) + z1 * (x2 * y3 - y2 * x3); + // rSP1 = rSP1+G3i*(x1+x2+x3)/(24.0*volume); + // rSP2 = rSP2+G3i*(y1+y2+y3)/(24.0*volume); + // rSP3 = rSP3+G3i*(z1+z2+z3)/(24.0*volume); + xx = x1 * x1 + x2 * x2 + x3 * x3 + x1 * x2 + x2 * x3 + x3 * x1; + yy = y1 * y1 + y2 * y2 + y3 * y3 + y1 * y2 + y2 * y3 + y3 * y1; + zz = z1 * z1 + z2 * z2 + z3 * z3 + z1 * z2 + z2 * z3 + z3 * z1; + top11 = top11 + (yy + zz) * rhoP * G3i / 60.; + top22 = top22 + (xx + zz) * rhoP * G3i / 60.; + top33 = top33 + (yy + xx) * rhoP * G3i / 60.; + xy = 2.0 * (x1 * y1 + x2 * y2 + x3 * y3) + x2 * y3 + x3 * y1 + x1 * y2 + x3 * y2 + x1 * y3 + x2 * y1; + yz = 2.0 * (y1 * z1 + y2 * z2 + y3 * z3) + y2 * z3 + y3 * z1 + y1 * z2 + y3 * z2 + y1 * z3 + y2 * z1; + zx = 2.0 * (z1 * x1 + z2 * x2 + z3 * x3) + z2 * x3 + z3 * x1 + z1 * x2 + z3 * x2 + z1 * x3 + z2 * x1; + top12 = top12 - xy * rhoP * G3i / 120.; + top23 = top23 - yz * rhoP * G3i / 120.; + top13 = top13 - zx * rhoP * G3i / 120.; + } + // Satz von Steiner ... + top11 = top11 - rhoP * volume * (rSP2 * rSP2 + rSP3 + rSP3); + top22 = top22 - rhoP * volume * (rSP3 * rSP3 + rSP1 * rSP1); + top33 = top33 - rhoP * volume * (rSP1 * rSP1 + rSP2 * rSP2); + top12 = top12 + rhoP * volume * rSP1 * rSP2; + top23 = top23 + rhoP * volume * rSP2 * rSP3; + top13 = top13 + rhoP * volume * rSP3 * rSP1; + + cout << "Volume:" << volume << "\n Traegheitsmomente:\n"; + cout << " top11:" << top11 << " top22:" << top22 << " top33:" << top33 << endl; + cout << " top12:" << top12 << " top23:" << top23 << " top13:" << top13 << endl; + + return { top11, top22, top33, top12, top23, top13 }; } /*==============================================================*/ void GbTriFaceMesh3D::calculateValues() { - relationVertTris.clear(); - - if( nodes->empty() ) - { - x1min = x1max = x2min = x2max = x3min = x3max = 0.0; - } - else - { - Vertex& v = (*nodes)[0]; - x1min = x1max = v.x; - x2min = x2max = v.y; - x3min = x3max = v.z; - - for(size_t i=1; i<this->nodes->size(); i++) - { - Vertex& v1 = (*nodes)[i]; - - x1min = UbMath::min<double>(x1min,v1.x); - x2min = UbMath::min<double>(x2min,v1.y); - x3min = UbMath::min<double>(x3min,v1.z); - - x1max = UbMath::max<double>(x1max,v1.x); - x2max = UbMath::max<double>(x2max,v1.y); - x3max = UbMath::max<double>(x3max,v1.z); - } - x1center = 0.5 * (x1min + x1max ); - x2center = 0.5 * (x2min + x2max ); - x3center = 0.5 * (x3min + x3max ); - - vector<TriFace>& tris = *this->triangles; - vector<Vertex>& verts = *this->nodes; - for(size_t i=0; i<this->triangles->size(); i++) - { - tris[i].calculateNormal(verts); - } - //relation Vertex <-> Triangle ermitteln - if(buildVertTriRelationMap) - { - for(size_t t=0; t<tris.size(); t++) - { - TriFace& tri = tris[t]; - relationVertTris.insert( make_pair( &verts[tri.v1], &tri) ); - relationVertTris.insert( make_pair( &verts[tri.v2], &tri) ); - relationVertTris.insert( make_pair( &verts[tri.v3], &tri) ); - } - } - } - if(kdTree) - { - delete kdTree; - kdTree=NULL; - } - - this->consistent = true; + relationVertTris.clear(); + + if (nodes->empty()) { + x1min = x1max = x2min = x2max = x3min = x3max = 0.0; + } else { + Vertex &v = (*nodes)[0]; + x1min = x1max = v.x; + x2min = x2max = v.y; + x3min = x3max = v.z; + + for (size_t i = 1; i < this->nodes->size(); i++) { + Vertex &v1 = (*nodes)[i]; + + x1min = UbMath::min<double>(x1min, v1.x); + x2min = UbMath::min<double>(x2min, v1.y); + x3min = UbMath::min<double>(x3min, v1.z); + + x1max = UbMath::max<double>(x1max, v1.x); + x2max = UbMath::max<double>(x2max, v1.y); + x3max = UbMath::max<double>(x3max, v1.z); + } + x1center = 0.5 * (x1min + x1max); + x2center = 0.5 * (x2min + x2max); + x3center = 0.5 * (x3min + x3max); + + vector<TriFace> &tris = *this->triangles; + vector<Vertex> &verts = *this->nodes; + for (size_t i = 0; i < this->triangles->size(); i++) { + tris[i].calculateNormal(verts); + } + // relation Vertex <-> Triangle ermitteln + if (buildVertTriRelationMap) { + for (size_t t = 0; t < tris.size(); t++) { + TriFace &tri = tris[t]; + relationVertTris.insert(make_pair(&verts[tri.v1], &tri)); + relationVertTris.insert(make_pair(&verts[tri.v2], &tri)); + relationVertTris.insert(make_pair(&verts[tri.v3], &tri)); + } + } + } + if (kdTree) { + delete kdTree; + kdTree = NULL; + } + + this->consistent = true; } /*=========================================================================*/ -std::vector<GbTriFaceMesh3D::TriFace*> GbTriFaceMesh3D::getTrianglesForVertex(Vertex* vertex) +std::vector<GbTriFaceMesh3D::TriFace *> GbTriFaceMesh3D::getTrianglesForVertex(Vertex *vertex) { - if(!buildVertTriRelationMap) { buildVertTriRelationMap=true; consistent = false;} - if(!consistent) this->calculateValues(); + if (!buildVertTriRelationMap) { + buildVertTriRelationMap = true; + consistent = false; + } + if (!consistent) + this->calculateValues(); - typedef std::multimap<Vertex*,TriFace*>::iterator Iterator; - pair<Iterator,Iterator> objRange = relationVertTris.equal_range(vertex); + typedef std::multimap<Vertex *, TriFace *>::iterator Iterator; + pair<Iterator, Iterator> objRange = relationVertTris.equal_range(vertex); - std::vector<TriFace*> tmpTris; - for(Iterator pos=objRange.first; pos!=objRange.second; ++pos) - tmpTris.push_back( pos->second ); + std::vector<TriFace *> tmpTris; + for (Iterator pos = objRange.first; pos != objRange.second; ++pos) + tmpTris.push_back(pos->second); - return tmpTris; + return tmpTris; } /*=======================================================*/ -void GbTriFaceMesh3D::setCenterCoordinates(const double& x1, const double& x2, const double& x3) +void GbTriFaceMesh3D::setCenterCoordinates(const double &x1, const double &x2, const double &x3) { - this->translate(x1-getX1Centroid(), x2-getX2Centroid(), x3-getX3Centroid() ); + this->translate(x1 - getX1Centroid(), x2 - getX2Centroid(), x3 - getX3Centroid()); } /*======================================================================*/ -void GbTriFaceMesh3D::scale(const double& sx1, const double& sx2, const double& sx3) +void GbTriFaceMesh3D::scale(const double &sx1, const double &sx2, const double &sx3) { - CoordinateTransformation3D trafoForw(this->getX1Centroid(), this->getX2Centroid(), this->getX3Centroid(), 1.0, 1.0, 1.0, 0.0, 0.0, 0.0); - CoordinateTransformation3D trafoBack(this->getX1Centroid(), this->getX2Centroid(), this->getX3Centroid(), sx1, sx2, sx3, 0, 0, 0); - - vector<Vertex>& vertices = *nodes; - for(size_t i=0; i<vertices.size(); i++) - { - Vertex& v = vertices[i]; - double p1x1 = trafoForw.transformForwardToX1Coordinate(v.x, v.y, v.z); - double p1x2 = trafoForw.transformForwardToX2Coordinate(v.x, v.y, v.z); - double p1x3 = trafoForw.transformForwardToX3Coordinate(v.x, v.y, v.z); - v.x = (float)trafoBack.transformBackwardToX1Coordinate(p1x1, p1x2, p1x3); - v.y = (float)trafoBack.transformBackwardToX2Coordinate(p1x1, p1x2, p1x3); - v.z = (float)trafoBack.transformBackwardToX3Coordinate(p1x1, p1x2, p1x3); - } - this->calculateValues(); + CoordinateTransformation3D trafoForw(this->getX1Centroid(), this->getX2Centroid(), this->getX3Centroid(), 1.0, 1.0, + 1.0, 0.0, 0.0, 0.0); + CoordinateTransformation3D trafoBack(this->getX1Centroid(), this->getX2Centroid(), this->getX3Centroid(), sx1, sx2, + sx3, 0, 0, 0); + + vector<Vertex> &vertices = *nodes; + for (size_t i = 0; i < vertices.size(); i++) { + Vertex &v = vertices[i]; + double p1x1 = trafoForw.transformForwardToX1Coordinate(v.x, v.y, v.z); + double p1x2 = trafoForw.transformForwardToX2Coordinate(v.x, v.y, v.z); + double p1x3 = trafoForw.transformForwardToX3Coordinate(v.x, v.y, v.z); + v.x = (float)trafoBack.transformBackwardToX1Coordinate(p1x1, p1x2, p1x3); + v.y = (float)trafoBack.transformBackwardToX2Coordinate(p1x1, p1x2, p1x3); + v.z = (float)trafoBack.transformBackwardToX3Coordinate(p1x1, p1x2, p1x3); + } + this->calculateValues(); } /*======================================================================*/ -void GbTriFaceMesh3D::rotate(const double& alpha, const double& beta, const double& gamma) +void GbTriFaceMesh3D::rotate(const double &alpha, const double &beta, const double &gamma) { - CoordinateTransformation3D trafoForw(this->getX1Centroid(), this->getX2Centroid(), this->getX3Centroid(), 1.0, 1.0, 1.0, 0.0, 0.0, 0.0); - CoordinateTransformation3D trafoBack(this->getX1Centroid(), this->getX2Centroid(), this->getX3Centroid(), 1.0, 1.0, 1.0, alpha, beta, gamma); - - vector<Vertex>& vertices = *nodes; - for(size_t i=0; i<vertices.size(); i++) - { - Vertex& v = vertices[i]; - double p1x1 = trafoForw.transformForwardToX1Coordinate(v.x, v.y, v.z); - double p1x2 = trafoForw.transformForwardToX2Coordinate(v.x, v.y, v.z); - double p1x3 = trafoForw.transformForwardToX3Coordinate(v.x, v.y, v.z); - v.x = (float)trafoBack.transformBackwardToX1Coordinate(p1x1, p1x2, p1x3); - v.y = (float)trafoBack.transformBackwardToX2Coordinate(p1x1, p1x2, p1x3); - v.z = (float)trafoBack.transformBackwardToX3Coordinate(p1x1, p1x2, p1x3); - } - this->calculateValues(); + CoordinateTransformation3D trafoForw(this->getX1Centroid(), this->getX2Centroid(), this->getX3Centroid(), 1.0, 1.0, + 1.0, 0.0, 0.0, 0.0); + CoordinateTransformation3D trafoBack(this->getX1Centroid(), this->getX2Centroid(), this->getX3Centroid(), 1.0, 1.0, + 1.0, alpha, beta, gamma); + + vector<Vertex> &vertices = *nodes; + for (size_t i = 0; i < vertices.size(); i++) { + Vertex &v = vertices[i]; + double p1x1 = trafoForw.transformForwardToX1Coordinate(v.x, v.y, v.z); + double p1x2 = trafoForw.transformForwardToX2Coordinate(v.x, v.y, v.z); + double p1x3 = trafoForw.transformForwardToX3Coordinate(v.x, v.y, v.z); + v.x = (float)trafoBack.transformBackwardToX1Coordinate(p1x1, p1x2, p1x3); + v.y = (float)trafoBack.transformBackwardToX2Coordinate(p1x1, p1x2, p1x3); + v.z = (float)trafoBack.transformBackwardToX3Coordinate(p1x1, p1x2, p1x3); + } + this->calculateValues(); } /*======================================================================*/ -void GbTriFaceMesh3D::rotateAroundPoint(const double& px1, const double& px2, const double& px3, const double& alpha, const double& beta, const double& gamma) +void GbTriFaceMesh3D::rotateAroundPoint(const double &px1, const double &px2, const double &px3, const double &alpha, + const double &beta, const double &gamma) { - CoordinateTransformation3D trafoForw(px1, px2, px3, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0); - CoordinateTransformation3D trafoBack(px1, px2, px3, 1.0, 1.0, 1.0, alpha, beta, gamma); - - vector<Vertex>& vertices = *nodes; - for(size_t i=0; i<vertices.size(); i++) - { - Vertex& v = vertices[i]; - double p1x1 = trafoForw.transformForwardToX1Coordinate(v.x, v.y, v.z); - double p1x2 = trafoForw.transformForwardToX2Coordinate(v.x, v.y, v.z); - double p1x3 = trafoForw.transformForwardToX3Coordinate(v.x, v.y, v.z); - v.x = (float)trafoBack.transformBackwardToX1Coordinate(p1x1, p1x2, p1x3); - v.y = (float)trafoBack.transformBackwardToX2Coordinate(p1x1, p1x2, p1x3); - v.z = (float)trafoBack.transformBackwardToX3Coordinate(p1x1, p1x2, p1x3); - } - this->calculateValues(); + CoordinateTransformation3D trafoForw(px1, px2, px3, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0); + CoordinateTransformation3D trafoBack(px1, px2, px3, 1.0, 1.0, 1.0, alpha, beta, gamma); + + vector<Vertex> &vertices = *nodes; + for (size_t i = 0; i < vertices.size(); i++) { + Vertex &v = vertices[i]; + double p1x1 = trafoForw.transformForwardToX1Coordinate(v.x, v.y, v.z); + double p1x2 = trafoForw.transformForwardToX2Coordinate(v.x, v.y, v.z); + double p1x3 = trafoForw.transformForwardToX3Coordinate(v.x, v.y, v.z); + v.x = (float)trafoBack.transformBackwardToX1Coordinate(p1x1, p1x2, p1x3); + v.y = (float)trafoBack.transformBackwardToX2Coordinate(p1x1, p1x2, p1x3); + v.z = (float)trafoBack.transformBackwardToX3Coordinate(p1x1, p1x2, p1x3); + } + this->calculateValues(); } - /*======================================================================*/ -void GbTriFaceMesh3D::translate(const double& x1, const double& x2, const double& x3) +void GbTriFaceMesh3D::translate(const double &x1, const double &x2, const double &x3) { - vector<Vertex>& vertices = *nodes; - for(size_t i=0; i<vertices.size(); i++) - { - Vertex& v = vertices[i]; - v.x += static_cast<float>(x1); - v.y += static_cast<float>(x2); - v.z += static_cast<float>(x3); - } - this->calculateValues(); + vector<Vertex> &vertices = *nodes; + for (size_t i = 0; i < vertices.size(); i++) { + Vertex &v = vertices[i]; + v.x += static_cast<float>(x1); + v.y += static_cast<float>(x2); + v.z += static_cast<float>(x3); + } + this->calculateValues(); } /*======================================================================*/ -vector<GbTriangle3D*> GbTriFaceMesh3D::getSurfaceTriangleSet() +vector<GbTriangle3D *> GbTriFaceMesh3D::getSurfaceTriangleSet() { - //SirAnn: eine miese Speicherlochmethode - // hier werden dynmamische Objekte angelegt - // mit sowas rechnet von aussen kein Mensch!!! - vector<GbTriangle3D*> tris( triangles->size() ); - - for(size_t i=0; i<this->triangles->size(); i++) - { - Vertex& v1 = (*nodes)[(*triangles)[i].v1]; - Vertex& v2 = (*nodes)[(*triangles)[i].v2]; - Vertex& v3 = (*nodes)[(*triangles)[i].v3]; - - tris[i] = new GbTriangle3D( new GbPoint3D(v1.x,v1.y,v1.z) - , new GbPoint3D(v2.x,v2.y,v2.z) - , new GbPoint3D(v3.x,v3.y,v3.z) ); - } - return tris; + // SirAnn: eine miese Speicherlochmethode + // hier werden dynmamische Objekte angelegt + // mit sowas rechnet von aussen kein Mensch!!! + vector<GbTriangle3D *> tris(triangles->size()); + + for (size_t i = 0; i < this->triangles->size(); i++) { + Vertex &v1 = (*nodes)[(*triangles)[i].v1]; + Vertex &v2 = (*nodes)[(*triangles)[i].v2]; + Vertex &v3 = (*nodes)[(*triangles)[i].v3]; + + tris[i] = new GbTriangle3D(new GbPoint3D(v1.x, v1.y, v1.z), new GbPoint3D(v2.x, v2.y, v2.z), + new GbPoint3D(v3.x, v3.y, v3.z)); + } + return tris; } /*=======================================================*/ -void GbTriFaceMesh3D::addSurfaceTriangleSet(vector<UbTupleFloat3>& pts, vector<UbTupleInt3>& tris) +void GbTriFaceMesh3D::addSurfaceTriangleSet(vector<UbTupleFloat3> &pts, vector<UbTupleInt3> &tris) { - int nodeNr = int(pts.size()); - for(int i=0; i<(int)this->triangles->size(); i++) - { - Vertex& v1 = (*nodes)[(*triangles)[i].v1]; - Vertex& v2 = (*nodes)[(*triangles)[i].v2]; - Vertex& v3 = (*nodes)[(*triangles)[i].v3]; - pts.push_back( makeUbTuple(v1.x,v1.y,v1.z)); - pts.push_back( makeUbTuple(v2.x,v2.y,v2.z)); - pts.push_back( makeUbTuple(v3.x,v3.y,v3.z)); - - tris.push_back( makeUbTuple( nodeNr, nodeNr+1, nodeNr+2 ) ); - nodeNr+=3; - } + int nodeNr = int(pts.size()); + for (int i = 0; i < (int)this->triangles->size(); i++) { + Vertex &v1 = (*nodes)[(*triangles)[i].v1]; + Vertex &v2 = (*nodes)[(*triangles)[i].v2]; + Vertex &v3 = (*nodes)[(*triangles)[i].v3]; + pts.push_back(makeUbTuple(v1.x, v1.y, v1.z)); + pts.push_back(makeUbTuple(v2.x, v2.y, v2.z)); + pts.push_back(makeUbTuple(v3.x, v3.y, v3.z)); + + tris.push_back(makeUbTuple(nodeNr, nodeNr + 1, nodeNr + 2)); + nodeNr += 3; + } } /*======================================================================*/ -//bool GbTriFaceMesh3D::isPointInGbObject3D(const double& x1, const double& x2, const double& x3, int counter) +// bool GbTriFaceMesh3D::isPointInGbObject3D(const double& x1, const double& x2, const double& x3, int counter) //{ // // @@ -597,7 +615,7 @@ void GbTriFaceMesh3D::addSurfaceTriangleSet(vector<UbTupleFloat3>& pts, vector<U // { // UBLOG(logDEBUG3, "GbTriFaceMesh3D::calculateValues - build KdTree start"); // UbTimer timer; timer.start(); -// if(kdtreeSplitAlg == KDTREE_SAHPLIT ) +// if(kdtreeSplitAlg == KDTREE_SAHPLIT ) // { // UBLOG(logDEBUG3, "GbTriFaceMesh3D::calculateValues - build KdTree with SAHSplit"); // this->kdTree = new Kd::Tree<double>( *this, Kd::SAHSplit<double>() ); @@ -605,7 +623,7 @@ void GbTriFaceMesh3D::addSurfaceTriangleSet(vector<UbTupleFloat3>& pts, vector<U // else if(kdtreeSplitAlg == KDTREE_SPATIALSPLIT) // { // UBLOG(logDEBUG3, "GbTriFaceMesh3D::calculateValues - build KdTree with SpatialMedianSplit"); -// this->kdTree = new Kd::Tree<double>( *this, Kd::SpatialMedianSplit<double>() ); +// this->kdTree = new Kd::Tree<double>( *this, Kd::SpatialMedianSplit<double>() ); // } // else throw UbException(UB_EXARGS, "unknown kdtree split option)" ); // UBLOG(logDEBUG3, "GbTriFaceMesh3D::calculateValues - built kdTree in "<<timer.stop()<<"seconds"); @@ -618,10 +636,11 @@ void GbTriFaceMesh3D::addSurfaceTriangleSet(vector<UbTupleFloat3>& pts, vector<U // // Kd::Ray<double> ray( x1, x2, x3 //, 1, 0 ,0 ); // // , ( x1 < x1center ? UbRandom::rand(-1.0,-0.001, 10) : UbRandom::rand(0.001, 1.0, 10) ) // // , ( x2 < x2center ? UbRandom::rand(-1.0,-0.001, 10) : UbRandom::rand(0.001, 1.0, 10) ) -// // , ( x3 < x3center ? UbRandom::rand(-1.0,-0.001, 10) : UbRandom::rand(0.001, 1.0, 10) ) ); -// // +// // , ( x3 < x3center ? UbRandom::rand(-1.0,-0.001, 10) : UbRandom::rand(0.001, 1.0, 10) ) +// ); +// // // // iSec = kdTree->intersectRay( ray, Kd::CountRayIntersectionHandler<double>() ); -// // +// // // // if( iSec != Kd::Intersection::INTERSECT_EDGE ) //KEINE Kante getroffen // // { // // if(iSec == Kd::Intersection::ON_BOUNDARY ) @@ -634,7 +653,7 @@ void GbTriFaceMesh3D::addSurfaceTriangleSet(vector<UbTupleFloat3>& pts, vector<U // //} // //throw UbException(UB_EXARGS, "ups, nach 100 Strahlen immer noch kein Ergebnis"); // int iSec1,iSec2; -// +// // Kd::Ray<double> ray1( x1, x2, x3, 1.0, 0.0 ,0.0 ); // iSec1 = kdTree->intersectRay( ray1, Kd::CountRayIntersectionHandler<double>() ); // Kd::Ray<double> ray2( x1, x2, x3, -1.0, 0.0 ,0.0 ); @@ -644,20 +663,20 @@ void GbTriFaceMesh3D::addSurfaceTriangleSet(vector<UbTupleFloat3>& pts, vector<U // { // return true; // } -// if( iSec1 == Kd::Intersection::INTERSECT_EDGE && iSec2 == Kd::Intersection::INTERSECT_EDGE) +// if( iSec1 == Kd::Intersection::INTERSECT_EDGE && iSec2 == Kd::Intersection::INTERSECT_EDGE) // { // UBLOG(logINFO, "GbTriFaceMesh3D.isPointInGbObject3D.INTERSECT_EDGE"); // double eps = UbMath::getEqualityEpsilon<float>()*1000.0; // if (counter>100) {return(iSec1&1); UBLOG(logINFO, "NACH 100 Iterationen Eps umsetzen aufgegeben!");} -// return this->isPointInGbObject3D(x1+eps, x2+eps, x3+eps,(counter+1)); +// return this->isPointInGbObject3D(x1+eps, x2+eps, x3+eps,(counter+1)); // } // else if( iSec1 == Kd::Intersection::INTERSECT_EDGE) // { -// return (iSec2&1); +// return (iSec2&1); // } // else if( iSec2 == Kd::Intersection::INTERSECT_EDGE) // { -// return (iSec1&1); +// return (iSec1&1); // } // else // { @@ -675,394 +694,367 @@ void GbTriFaceMesh3D::addSurfaceTriangleSet(vector<UbTupleFloat3>& pts, vector<U // } // return false; //} -bool GbTriFaceMesh3D::isPointInGbObject3D(const double& x1, const double& x2, const double& x3, int counter) +bool GbTriFaceMesh3D::isPointInGbObject3D(const double &x1, const double &x2, const double &x3, int counter) { - if( !nodes->empty() ) - { - //Baum erstellen, wen noch keiner vorhanden - if( !kdTree) - { - UBLOG(logDEBUG3, "GbTriFaceMesh3D::calculateValues - build KdTree start"); - UbTimer timer; timer.start(); - if(kdtreeSplitAlg == KDTREE_SAHPLIT ) - { - UBLOG(logDEBUG3, "GbTriFaceMesh3D::calculateValues - build KdTree with SAHSplit"); - this->kdTree = new Kd::Tree<double>( *this, Kd::SAHSplit<double>() ); - } - else if(kdtreeSplitAlg == KDTREE_SPATIALSPLIT) - { - UBLOG(logDEBUG3, "GbTriFaceMesh3D::calculateValues - build KdTree with SpatialMedianSplit"); - this->kdTree = new Kd::Tree<double>( *this, Kd::SpatialMedianSplit<double>() ); - } - else throw UbException(UB_EXARGS, "unknown kdtree split option)" ); - UBLOG(logDEBUG3, "GbTriFaceMesh3D::calculateValues - built kdTree in "<<timer.stop()<<"seconds"); - } - - //eigentlicher PIO-Test - //int iSec; - //for(int i=0; i<100; i++) - //{ - // Kd::Ray<double> ray( x1, x2, x3 //, 1, 0 ,0 ); - // , ( x1 < x1center ? UbRandom::rand(-1.0,-0.001, 10) : UbRandom::rand(0.001, 1.0, 10) ) - // , ( x2 < x2center ? UbRandom::rand(-1.0,-0.001, 10) : UbRandom::rand(0.001, 1.0, 10) ) - // , ( x3 < x3center ? UbRandom::rand(-1.0,-0.001, 10) : UbRandom::rand(0.001, 1.0, 10) ) ); - // - // iSec = kdTree->intersectRay( ray, Kd::CountRayIntersectionHandler<double>() ); - // - // if( iSec != Kd::Intersection::INTERSECT_EDGE ) //KEINE Kante getroffen - // { - // if(iSec == Kd::Intersection::ON_BOUNDARY ) - // { - // return true; - // } - // return (iSec&1); //ungerade anzahl an schnitten --> drinnen - // } - // UBLOG(logDEBUG3, "GbTriFaceMesh3D.isPointInGbObject3D.if - an edge was hit "); - //} - //throw UbException(UB_EXARGS, "ups, nach 100 Strahlen immer noch kein Ergebnis"); - int iSec1,iSec2; - double eps = 0.05; - Kd::Ray<double> ray1( x1, x2, x3, 1.0+eps*((double)counter), eps*((double)counter) ,eps*((double)counter) ); - iSec1 = kdTree->intersectRay( ray1, Kd::CountRayIntersectionHandler<double>() ); - Kd::Ray<double> ray2( x1, x2, x3, -1.0-eps*((double)counter), -eps*((double)counter) ,-eps*((double)counter) ); - - iSec2 = kdTree->intersectRay( ray2, Kd::CountRayIntersectionHandler<double>() ); - - if(iSec1 == Kd::Intersection::ON_BOUNDARY || iSec2 == Kd::Intersection::ON_BOUNDARY) - { - return true; - } - if( iSec1 == Kd::Intersection::INTERSECT_EDGE && iSec2 == Kd::Intersection::INTERSECT_EDGE) - { - //UBLOG(logINFO, "GbTriFaceMesh3D.isPointInGbObject3D.INTERSECT_EDGE"); - - if (counter>20) {return(iSec1&1); /*UBLOG(logINFO, "NACH 100 Iterationen Eps umsetzen aufgegeben!");*/} - return this->isPointInGbObject3D(x1, x2, x3,(counter+1)); - } - else if( iSec1 == Kd::Intersection::INTERSECT_EDGE) - { - return (iSec2&1); - } - else if( iSec2 == Kd::Intersection::INTERSECT_EDGE) - { - return (iSec1&1); - } - else - { - if((iSec1&1) != (iSec2&1)) - { - //UBLOG(logINFO, "GbTriFaceMesh3D.isPointInGbObject3D.iSec1&1 != iSec2&1"); - - if (counter>20) {return(iSec1&1); /* UBLOG(logINFO, "NACH 100 Iterationen Eps umsetzen aufgegeben!");*/} - return this->isPointInGbObject3D(x1, x2, x3,(counter+1)); - } - return iSec1&1; - } - //throw UbException(UB_EXARGS, "ups, nach 100 Strahlen immer noch kein Ergebnis"); - - } - return false; + if (!nodes->empty()) { + // Baum erstellen, wen noch keiner vorhanden + if (!kdTree) { + UBLOG(logDEBUG3, "GbTriFaceMesh3D::calculateValues - build KdTree start"); + UbTimer timer; + timer.start(); + if (kdtreeSplitAlg == KDTREE_SAHPLIT) { + UBLOG(logDEBUG3, "GbTriFaceMesh3D::calculateValues - build KdTree with SAHSplit"); + this->kdTree = new Kd::Tree<double>(*this, Kd::SAHSplit<double>()); + } else if (kdtreeSplitAlg == KDTREE_SPATIALSPLIT) { + UBLOG(logDEBUG3, "GbTriFaceMesh3D::calculateValues - build KdTree with SpatialMedianSplit"); + this->kdTree = new Kd::Tree<double>(*this, Kd::SpatialMedianSplit<double>()); + } else + throw UbException(UB_EXARGS, "unknown kdtree split option)"); + UBLOG(logDEBUG3, "GbTriFaceMesh3D::calculateValues - built kdTree in " << timer.stop() << "seconds"); + } + + // eigentlicher PIO-Test + // int iSec; + // for(int i=0; i<100; i++) + //{ + // Kd::Ray<double> ray( x1, x2, x3 //, 1, 0 ,0 ); + // , ( x1 < x1center ? UbRandom::rand(-1.0,-0.001, 10) : UbRandom::rand(0.001, 1.0, 10) ) + // , ( x2 < x2center ? UbRandom::rand(-1.0,-0.001, 10) : UbRandom::rand(0.001, 1.0, 10) ) + // , ( x3 < x3center ? UbRandom::rand(-1.0,-0.001, 10) : UbRandom::rand(0.001, 1.0, 10) ) + // ); + // + // iSec = kdTree->intersectRay( ray, Kd::CountRayIntersectionHandler<double>() ); + // + // if( iSec != Kd::Intersection::INTERSECT_EDGE ) //KEINE Kante getroffen + // { + // if(iSec == Kd::Intersection::ON_BOUNDARY ) + // { + // return true; + // } + // return (iSec&1); //ungerade anzahl an schnitten --> drinnen + // } + // UBLOG(logDEBUG3, "GbTriFaceMesh3D.isPointInGbObject3D.if - an edge was hit "); + //} + // throw UbException(UB_EXARGS, "ups, nach 100 Strahlen immer noch kein Ergebnis"); + int iSec1, iSec2; + double eps = 0.05; + Kd::Ray<double> ray1(x1, x2, x3, 1.0 + eps * ((double)counter), eps * ((double)counter), + eps * ((double)counter)); + iSec1 = kdTree->intersectRay(ray1, Kd::CountRayIntersectionHandler<double>()); + Kd::Ray<double> ray2(x1, x2, x3, -1.0 - eps * ((double)counter), -eps * ((double)counter), + -eps * ((double)counter)); + + iSec2 = kdTree->intersectRay(ray2, Kd::CountRayIntersectionHandler<double>()); + + if (iSec1 == Kd::Intersection::ON_BOUNDARY || iSec2 == Kd::Intersection::ON_BOUNDARY) { + return true; + } + if (iSec1 == Kd::Intersection::INTERSECT_EDGE && iSec2 == Kd::Intersection::INTERSECT_EDGE) { + // UBLOG(logINFO, "GbTriFaceMesh3D.isPointInGbObject3D.INTERSECT_EDGE"); + + if (counter > 20) { + return (iSec1 & 1); /*UBLOG(logINFO, "NACH 100 Iterationen Eps umsetzen aufgegeben!");*/ + } + return this->isPointInGbObject3D(x1, x2, x3, (counter + 1)); + } else if (iSec1 == Kd::Intersection::INTERSECT_EDGE) { + return (iSec2 & 1); + } else if (iSec2 == Kd::Intersection::INTERSECT_EDGE) { + return (iSec1 & 1); + } else { + if ((iSec1 & 1) != (iSec2 & 1)) { + // UBLOG(logINFO, "GbTriFaceMesh3D.isPointInGbObject3D.iSec1&1 != iSec2&1"); + + if (counter > 20) { + return (iSec1 & 1); /* UBLOG(logINFO, "NACH 100 Iterationen Eps umsetzen aufgegeben!");*/ + } + return this->isPointInGbObject3D(x1, x2, x3, (counter + 1)); + } + return iSec1 & 1; + } + // throw UbException(UB_EXARGS, "ups, nach 100 Strahlen immer noch kein Ergebnis"); + } + return false; } /*======================================================================*/ -bool GbTriFaceMesh3D::isPointInGbObject3D(const double& x1, const double& x2, const double& x3) +bool GbTriFaceMesh3D::isPointInGbObject3D(const double &x1, const double &x2, const double &x3) { - if( !nodes->empty() ) - { - //Baum erstellen, wen noch keiner vorhanden - if( !kdTree) - { - UBLOG(logDEBUG3, "GbTriFaceMesh3D::calculateValues - build KdTree start"); - UbTimer timer; timer.start(); - if(kdtreeSplitAlg == KDTREE_SAHPLIT ) - { - UBLOG(logDEBUG3, "GbTriFaceMesh3D::calculateValues - build KdTree with SAHSplit"); - cout << "GbTriFaceMesh3D::calculateValues - build KdTree with SAHSplit" << std::endl; - this->kdTree = new Kd::Tree<double>( *this, Kd::SAHSplit<double>() ); - } - else if(kdtreeSplitAlg == KDTREE_SPATIALSPLIT) - { - UBLOG(logDEBUG3, "GbTriFaceMesh3D::calculateValues - build KdTree with SpatialMedianSplit"); - this->kdTree = new Kd::Tree<double>( *this, Kd::SpatialMedianSplit<double>() ); - } - else throw UbException(UB_EXARGS, "unknown kdtree split option)" ); - UBLOG(logDEBUG3, "GbTriFaceMesh3D::calculateValues - built kdTree in "<<timer.stop()<<"seconds"); - cout << "GbTriFaceMesh3D::calculateValues - built kdTree in " << timer.stop() << "seconds" << std::endl; - } - - //eigentlicher PIO-Test - int iSec; - for(int i=0; i<MAX_ITER; i++) - { - Kd::Ray<double> ray( x1, x2, x3 //, 1, 0 ,0 ); - , ( x1 < x1center ? UbRandom::rand(-1.0,-0.001, 10) : UbRandom::rand(0.001, 1.0, 10) ) - , ( x2 < x2center ? UbRandom::rand(-1.0,-0.001, 10) : UbRandom::rand(0.001, 1.0, 10) ) - , ( x3 < x3center ? UbRandom::rand(-1.0,-0.001, 10) : UbRandom::rand(0.001, 1.0, 10) ) ); - - iSec = kdTree->intersectRay( ray, Kd::CountRayIntersectionHandler<double>() ); - - if( iSec != Kd::Intersection::INTERSECT_EDGE ) //KEINE Kante getroffen - { - if(iSec == Kd::Intersection::ON_BOUNDARY ) + if (!nodes->empty()) { + // Baum erstellen, wen noch keiner vorhanden + if (!kdTree) { + UBLOG(logDEBUG3, "GbTriFaceMesh3D::calculateValues - build KdTree start"); + UbTimer timer; + timer.start(); + if (kdtreeSplitAlg == KDTREE_SAHPLIT) { + UBLOG(logDEBUG3, "GbTriFaceMesh3D::calculateValues - build KdTree with SAHSplit"); + cout << "GbTriFaceMesh3D::calculateValues - build KdTree with SAHSplit" << std::endl; + this->kdTree = new Kd::Tree<double>(*this, Kd::SAHSplit<double>()); + } else if (kdtreeSplitAlg == KDTREE_SPATIALSPLIT) { + UBLOG(logDEBUG3, "GbTriFaceMesh3D::calculateValues - build KdTree with SpatialMedianSplit"); + this->kdTree = new Kd::Tree<double>(*this, Kd::SpatialMedianSplit<double>()); + } else + throw UbException(UB_EXARGS, "unknown kdtree split option)"); + UBLOG(logDEBUG3, "GbTriFaceMesh3D::calculateValues - built kdTree in " << timer.stop() << "seconds"); + cout << "GbTriFaceMesh3D::calculateValues - built kdTree in " << timer.stop() << "seconds" << std::endl; + } + + // eigentlicher PIO-Test + int iSec; + for (int i = 0; i < MAX_ITER; i++) { + Kd::Ray<double> ray(x1, x2, x3 //, 1, 0 ,0 ); + , + (x1 < x1center ? UbRandom::rand(-1.0, -0.001, 10) : UbRandom::rand(0.001, 1.0, 10)), + (x2 < x2center ? UbRandom::rand(-1.0, -0.001, 10) : UbRandom::rand(0.001, 1.0, 10)), + (x3 < x3center ? UbRandom::rand(-1.0, -0.001, 10) : UbRandom::rand(0.001, 1.0, 10))); + + iSec = kdTree->intersectRay(ray, Kd::CountRayIntersectionHandler<double>()); + + if (iSec != Kd::Intersection::INTERSECT_EDGE) // KEINE Kante getroffen { - return true; + if (iSec == Kd::Intersection::ON_BOUNDARY) { + return true; + } + return (iSec & 1); // ungerade anzahl an schnitten --> drinnen } - return (iSec&1); //ungerade anzahl an schnitten --> drinnen - } - UBLOG(logDEBUG3, "GbTriFaceMesh3D.isPointInGbObject3D.if - an edge was hit "); - } - throw UbException(UB_EXARGS, "ups, nach 100 Strahlen immer noch kein Ergebnis"); - - // int iSec1,iSec2; - // - // Kd::Ray<double> ray1( x1, x2, x3, 1.0, 0.0 ,0.0 ); - // iSec1 = kdTree->intersectRay( ray1, Kd::CountRayIntersectionHandler<double>() ); - // Kd::Ray<double> ray2( x1, x2, x3, -1.0, 0.0 ,0.0 ); - // iSec2 = kdTree->intersectRay( ray2, Kd::CountRayIntersectionHandler<double>() ); - - // if(iSec1 == Kd::Intersection::ON_BOUNDARY || iSec2 == Kd::Intersection::ON_BOUNDARY) - // { - // return true; - // } - // if( iSec1 == Kd::Intersection::INTERSECT_EDGE && iSec2 == Kd::Intersection::INTERSECT_EDGE) - // { - // //UBLOG(logINFO, "GbTriFaceMesh3D.isPointInGbObject3D.INTERSECT_EDGE"); - // double eps = UbMath::getEqualityEpsilon<double>(); - // if (counter>100) {return(iSec1&1); UBLOG(logINFO, "NACH 100 Iterationen Eps umsetzen aufgegeben!");} - // return this->isPointInGbObject3D(x1+eps, x2+eps, x3+eps,(counter+1)); - // } - // else if( iSec1 == Kd::Intersection::INTERSECT_EDGE) - // { - // return (iSec2&1); - // } - // else if( iSec2 == Kd::Intersection::INTERSECT_EDGE) - // { - // return (iSec1&1); - // } - // else - // { - // if((iSec1&1) != (iSec2&1)) - // { - // UBLOG(logINFO, "GbTriFaceMesh3D.isPointInGbObject3D.iSec1&1 != iSec2&1"); - // double eps = UbMath::getEqualityEpsilon<double>(); - // if (counter>100) {return(iSec1&1); UBLOG(logINFO, "NACH 100 Iterationen Eps umsetzen aufgegeben!");} - // return this->isPointInGbObject3D(x1+eps, x2+eps, x3+eps,(counter+1)); - // } - // return iSec1&1; - // } - // //throw UbException(UB_EXARGS, "ups, nach 100 Strahlen immer noch kein Ergebnis"); - - } - return false; + UBLOG(logDEBUG3, "GbTriFaceMesh3D.isPointInGbObject3D.if - an edge was hit "); + } + throw UbException(UB_EXARGS, "ups, nach 100 Strahlen immer noch kein Ergebnis"); + + // int iSec1,iSec2; + // + // Kd::Ray<double> ray1( x1, x2, x3, 1.0, 0.0 ,0.0 ); + // iSec1 = kdTree->intersectRay( ray1, Kd::CountRayIntersectionHandler<double>() ); + // Kd::Ray<double> ray2( x1, x2, x3, -1.0, 0.0 ,0.0 ); + // iSec2 = kdTree->intersectRay( ray2, Kd::CountRayIntersectionHandler<double>() ); + + // if(iSec1 == Kd::Intersection::ON_BOUNDARY || iSec2 == Kd::Intersection::ON_BOUNDARY) + // { + // return true; + // } + // if( iSec1 == Kd::Intersection::INTERSECT_EDGE && iSec2 == Kd::Intersection::INTERSECT_EDGE) + // { + // //UBLOG(logINFO, "GbTriFaceMesh3D.isPointInGbObject3D.INTERSECT_EDGE"); + // double eps = UbMath::getEqualityEpsilon<double>(); + // if (counter>100) {return(iSec1&1); UBLOG(logINFO, "NACH 100 Iterationen Eps umsetzen aufgegeben!");} + // return this->isPointInGbObject3D(x1+eps, x2+eps, x3+eps,(counter+1)); + // } + // else if( iSec1 == Kd::Intersection::INTERSECT_EDGE) + // { + // return (iSec2&1); + // } + // else if( iSec2 == Kd::Intersection::INTERSECT_EDGE) + // { + // return (iSec1&1); + // } + // else + // { + // if((iSec1&1) != (iSec2&1)) + // { + // UBLOG(logINFO, "GbTriFaceMesh3D.isPointInGbObject3D.iSec1&1 != iSec2&1"); + // double eps = UbMath::getEqualityEpsilon<double>(); + // if (counter>100) {return(iSec1&1); UBLOG(logINFO, "NACH 100 Iterationen Eps umsetzen aufgegeben!");} + // return this->isPointInGbObject3D(x1+eps, x2+eps, x3+eps,(counter+1)); + // } + // return iSec1&1; + // } + // //throw UbException(UB_EXARGS, "ups, nach 100 Strahlen immer noch kein Ergebnis"); + } + return false; } /*======================================================================*/ -bool GbTriFaceMesh3D::isPointInGbObject3D(const double& x1, const double& x2, const double& x3, bool& pointIsOnBoundary) +bool GbTriFaceMesh3D::isPointInGbObject3D(const double &x1, const double &x2, const double &x3, bool &pointIsOnBoundary) { - if( !nodes->empty() ) - { - //Baum erstellen, wen noch keiner vorhanden - if( !kdTree) - { - UBLOG(logDEBUG3, "GbTriFaceMesh3D::calculateValues - build KdTree start"); - UbTimer timer; timer.start(); - if(kdtreeSplitAlg == KDTREE_SAHPLIT ) - { - UBLOG(logDEBUG3, "GbTriFaceMesh3D::calculateValues - build KdTree with SAHSplit"); - this->kdTree = new Kd::Tree<double>( *this, Kd::SAHSplit<double>() ); - } - else if(kdtreeSplitAlg == KDTREE_SPATIALSPLIT) - { - UBLOG(logDEBUG3, "GbTriFaceMesh3D::calculateValues - build KdTree with SpatialMedianSplit"); - this->kdTree = new Kd::Tree<double>( *this, Kd::SpatialMedianSplit<double>() ); - } - else throw UbException(UB_EXARGS, "unknown kdtree split option)" ); - UBLOG(logDEBUG3, "GbTriFaceMesh3D::calculateValues - built kdTree in "<<timer.stop()<<"seconds"); - } - - //eigentlicher PIO-Test - int iSec; - for(int i=0; i<MAX_ITER; i++) - { - Kd::Ray<double> ray( x1, x2, x3 - , float( ( x1 < x1center ? UbRandom::rand(-1.0,-0.001, 10) : UbRandom::rand(0.001, 1.0, 10) ) ) - , float( ( x2 < x2center ? UbRandom::rand(-1.0,-0.001, 10) : UbRandom::rand(0.001, 1.0, 10) ) ) - , float( ( x3 < x3center ? UbRandom::rand(-1.0,-0.001, 10) : UbRandom::rand(0.001, 1.0, 10) ) ) ); - - iSec = kdTree->intersectRay( ray, Kd::CountRayIntersectionHandler<double>() ); - - if( iSec != Kd::Intersection::INTERSECT_EDGE ) //KEINE Kante getroffen - { - if(iSec == Kd::Intersection::ON_BOUNDARY ) + if (!nodes->empty()) { + // Baum erstellen, wen noch keiner vorhanden + if (!kdTree) { + UBLOG(logDEBUG3, "GbTriFaceMesh3D::calculateValues - build KdTree start"); + UbTimer timer; + timer.start(); + if (kdtreeSplitAlg == KDTREE_SAHPLIT) { + UBLOG(logDEBUG3, "GbTriFaceMesh3D::calculateValues - build KdTree with SAHSplit"); + this->kdTree = new Kd::Tree<double>(*this, Kd::SAHSplit<double>()); + } else if (kdtreeSplitAlg == KDTREE_SPATIALSPLIT) { + UBLOG(logDEBUG3, "GbTriFaceMesh3D::calculateValues - build KdTree with SpatialMedianSplit"); + this->kdTree = new Kd::Tree<double>(*this, Kd::SpatialMedianSplit<double>()); + } else + throw UbException(UB_EXARGS, "unknown kdtree split option)"); + UBLOG(logDEBUG3, "GbTriFaceMesh3D::calculateValues - built kdTree in " << timer.stop() << "seconds"); + } + + // eigentlicher PIO-Test + int iSec; + for (int i = 0; i < MAX_ITER; i++) { + Kd::Ray<double> ray( + x1, x2, x3, float((x1 < x1center ? UbRandom::rand(-1.0, -0.001, 10) : UbRandom::rand(0.001, 1.0, 10))), + float((x2 < x2center ? UbRandom::rand(-1.0, -0.001, 10) : UbRandom::rand(0.001, 1.0, 10))), + float((x3 < x3center ? UbRandom::rand(-1.0, -0.001, 10) : UbRandom::rand(0.001, 1.0, 10)))); + + iSec = kdTree->intersectRay(ray, Kd::CountRayIntersectionHandler<double>()); + + if (iSec != Kd::Intersection::INTERSECT_EDGE) // KEINE Kante getroffen { - pointIsOnBoundary = true; - return true; + if (iSec == Kd::Intersection::ON_BOUNDARY) { + pointIsOnBoundary = true; + return true; + } + pointIsOnBoundary = false; + return (iSec & 1); // ungerade anzahl an schnitten --> drinnen } - pointIsOnBoundary = false; - return (iSec&1); //ungerade anzahl an schnitten --> drinnen - } - } - - throw UbException(UB_EXARGS, "ups, nach 100 Strahlen immer noch kein Ergebnis"); - } - - return false; + } + + throw UbException(UB_EXARGS, "ups, nach 100 Strahlen immer noch kein Ergebnis"); + } + + return false; } /*======================================================================*/ -bool GbTriFaceMesh3D::intersectLine(const double& p1_x1, const double& p1_x2, const double& p1_x3, const double& p2_x1, const double& p2_x2, const double& p2_x3) +bool GbTriFaceMesh3D::intersectLine(const double &p1_x1, const double &p1_x2, const double &p1_x3, const double &p2_x1, + const double &p2_x2, const double &p2_x3) { - //Baum erstellen, wen noch keiner vorhanden - if (!kdTree) - { + // Baum erstellen, wen noch keiner vorhanden + if (!kdTree) { UBLOG(logDEBUG3, "GbTriFaceMesh3D::calculateValues - build KdTree start"); - UbTimer timer; timer.start(); - if (kdtreeSplitAlg == KDTREE_SAHPLIT) - { + UbTimer timer; + timer.start(); + if (kdtreeSplitAlg == KDTREE_SAHPLIT) { UBLOG(logDEBUG3, "GbTriFaceMesh3D::calculateValues - build KdTree with SAHSplit"); this->kdTree = new Kd::Tree<double>(*this, Kd::SAHSplit<double>()); - } - else if (kdtreeSplitAlg == KDTREE_SPATIALSPLIT) - { + } else if (kdtreeSplitAlg == KDTREE_SPATIALSPLIT) { UBLOG(logDEBUG3, "GbTriFaceMesh3D::calculateValues - build KdTree with SpatialMedianSplit"); this->kdTree = new Kd::Tree<double>(*this, Kd::SpatialMedianSplit<double>()); - } - else throw UbException(UB_EXARGS, "unknown kdtree split option)"); + } else + throw UbException(UB_EXARGS, "unknown kdtree split option)"); UBLOG(logDEBUG3, "GbTriFaceMesh3D::calculateValues - built kdTree in " << timer.stop() << "seconds"); } - int iSec = kdTree->intersectLine(UbTupleDouble3(p1_x1, p1_x2, p1_x3), UbTupleDouble3(p2_x1, p2_x2, p2_x3), Kd::CountLineIntersectionHandler<double>()); + int iSec = kdTree->intersectLine(UbTupleDouble3(p1_x1, p1_x2, p1_x3), UbTupleDouble3(p2_x1, p2_x2, p2_x3), + Kd::CountLineIntersectionHandler<double>()); return (iSec != Kd::Intersection::NO_INTERSECTION); } /*======================================================================*/ -GbLine3D* GbTriFaceMesh3D::createClippedLine3D (GbPoint3D& /*point1*/, GbPoint3D& /*point2*/) +GbLine3D *GbTriFaceMesh3D::createClippedLine3D(GbPoint3D & /*point1*/, GbPoint3D & /*point2*/) { - throw UbException(UB_EXARGS,"not implemented"); + throw UbException(UB_EXARGS, "not implemented"); } /*======================================================================*/ -UbTuple<string, string> GbTriFaceMesh3D::writeMesh(string filename, WbWriter* writer, bool writeNormals, vector< string >* datanames, std::vector< std::vector < double > >* nodedata ) +UbTuple<string, string> GbTriFaceMesh3D::writeMesh(string filename, WbWriter *writer, bool writeNormals, + vector<string> *datanames, + std::vector<std::vector<double>> *nodedata) { - UBLOG(logINFO, "GbTriFaceMesh3D::writeMesh "); - - vector<UbTupleFloat3 > triNodes(nodes->size()); - vector<UbTupleInt3 > tris(triangles->size()); - - for(size_t i=0; i<nodes->size(); i++) - triNodes[i] = makeUbTuple( (*nodes)[i].x, (*nodes)[i].y, (*nodes)[i].z ); - - for(size_t i=0; i<triangles->size(); i++) - tris[i] = makeUbTuple( (*triangles)[i].v1, (*triangles)[i].v2, (*triangles)[i].v3 ) ; - - UbTuple<string, string> filenames("",""); - - if( !datanames || datanames->empty() || !nodedata ) - { - val<1>(filenames) = writer->writeTriangles(filename,triNodes,tris); - } - else - { - val<1>(filenames) = writer->writeTrianglesWithNodeData(filename,triNodes,tris,*datanames,*nodedata); - } - - if(writeNormals) - { - vector<UbTupleFloat3 > lineNodes(triangles->size()*2); - vector<UbTupleInt2 > lines(triangles->size()); - for(size_t i=0; i<triangles->size(); i++) - { - TriFace& triangle = (*triangles)[i]; - lineNodes[i*2 ] = makeUbTuple( triangle.getX1Centroid(*nodes) - ,triangle.getX2Centroid(*nodes) - ,triangle.getX3Centroid(*nodes)); - - lineNodes[i*2+1] = makeUbTuple( (float)(triangle.getX1Centroid(*nodes)+1.0*triangle.nx) - ,(float)(triangle.getX2Centroid(*nodes)+1.0*triangle.ny) - ,(float)(triangle.getX3Centroid(*nodes)+1.0*triangle.nz)); - - lines[i] = makeUbTuple((int)i*2,(int)i*2+1); - } - val<2>(filenames) = writer->writeLines(filename+"_normals",lineNodes,lines); - } - - return filenames; + UBLOG(logINFO, "GbTriFaceMesh3D::writeMesh "); + + vector<UbTupleFloat3> triNodes(nodes->size()); + vector<UbTupleInt3> tris(triangles->size()); + + for (size_t i = 0; i < nodes->size(); i++) + triNodes[i] = makeUbTuple((*nodes)[i].x, (*nodes)[i].y, (*nodes)[i].z); + + for (size_t i = 0; i < triangles->size(); i++) + tris[i] = makeUbTuple((*triangles)[i].v1, (*triangles)[i].v2, (*triangles)[i].v3); + + UbTuple<string, string> filenames("", ""); + + if (!datanames || datanames->empty() || !nodedata) { + val<1>(filenames) = writer->writeTriangles(filename, triNodes, tris); + } else { + val<1>(filenames) = writer->writeTrianglesWithNodeData(filename, triNodes, tris, *datanames, *nodedata); + } + + if (writeNormals) { + vector<UbTupleFloat3> lineNodes(triangles->size() * 2); + vector<UbTupleInt2> lines(triangles->size()); + for (size_t i = 0; i < triangles->size(); i++) { + TriFace &triangle = (*triangles)[i]; + lineNodes[i * 2] = makeUbTuple(triangle.getX1Centroid(*nodes), triangle.getX2Centroid(*nodes), + triangle.getX3Centroid(*nodes)); + + lineNodes[i * 2 + 1] = makeUbTuple((float)(triangle.getX1Centroid(*nodes) + 1.0 * triangle.nx), + (float)(triangle.getX2Centroid(*nodes) + 1.0 * triangle.ny), + (float)(triangle.getX3Centroid(*nodes) + 1.0 * triangle.nz)); + + lines[i] = makeUbTuple((int)i * 2, (int)i * 2 + 1); + } + val<2>(filenames) = writer->writeLines(filename + "_normals", lineNodes, lines); + } + + return filenames; } /*======================================================================*/ -void GbTriFaceMesh3D::writeMeshPly( const std::string& filename) +void GbTriFaceMesh3D::writeMeshPly(const std::string &filename) { - ofstream out(filename.c_str() ); - if( !out ) - throw UbException(UB_EXARGS, "couldn't open " + filename); - - out << "ply" << endl; - out << "format ascii 1.0" << endl; - out << "element vertex " << (int)nodes->size() << endl; - out << "property float x" << endl; - out << "property float y" << endl; - out << "property float z" << endl; - out << "element face " << (int)triangles->size() << endl; - out << "property list uchar int vertex_indices" << endl; - out << "end_header" << endl; - - for(size_t i=0; i<nodes->size(); i++) - out << (*nodes)[i].x << " " << (*nodes)[i].y << " " << (*nodes)[i].z << endl; - - for(size_t i=0; i<triangles->size(); i++) - out << "3 " << (*triangles)[i].v1 << " " << (*triangles)[i].v2 << " " << (*triangles)[i].v3 << endl; + ofstream out(filename.c_str()); + if (!out) + throw UbException(UB_EXARGS, "couldn't open " + filename); + + out << "ply" << endl; + out << "format ascii 1.0" << endl; + out << "element vertex " << (int)nodes->size() << endl; + out << "property float x" << endl; + out << "property float y" << endl; + out << "property float z" << endl; + out << "element face " << (int)triangles->size() << endl; + out << "property list uchar int vertex_indices" << endl; + out << "end_header" << endl; + + for (size_t i = 0; i < nodes->size(); i++) + out << (*nodes)[i].x << " " << (*nodes)[i].y << " " << (*nodes)[i].z << endl; + + for (size_t i = 0; i < triangles->size(); i++) + out << "3 " << (*triangles)[i].v1 << " " << (*triangles)[i].v2 << " " << (*triangles)[i].v3 << endl; } /*======================================================================*/ void GbTriFaceMesh3D::readMeshFromSTLFile(string filename, bool removeRedundantNodes) { - UBLOG(logDEBUG1,"GbTriFaceMesh3DCreator::readMeshFromSTLFile !!! Dieses Format hat leider redundante Knoten ..."); - - UbFileInputASCII in(filename); - //this->nodes = new vector<GbTriFaceMesh3D::Vertex>; - //this->triangles = new vector<GbTriFaceMesh3D::TriFace>; - string dummy; - - double x, y, z; - int nr=0; - - in.readLine(); - while(dummy!="endsolid") - { - in.readLine(); - in.readLine(); - dummy = in.readString(); - if(dummy!="vertex") throw UbException(UB_EXARGS,"no vertex format"); - x=in.readDouble(); - y=in.readDouble(); - z=in.readDouble(); - nodes->push_back(GbTriFaceMesh3D::Vertex((float)x,(float)y,(float)z)); - in.readLine(); - in.readString(); - x=in.readDouble(); - y=in.readDouble(); - z=in.readDouble(); - nodes->push_back(GbTriFaceMesh3D::Vertex((float)x,(float)y,(float)z)); - in.readLine(); - in.readString(); - x=in.readDouble(); - y=in.readDouble(); - z=in.readDouble(); - nodes->push_back(GbTriFaceMesh3D::Vertex((float)x,(float)y,(float)z)); - triangles->push_back(GbTriFaceMesh3D::TriFace(nr,nr+1,nr+2)); - in.readLine(); - in.readLine(); - in.readLine(); - dummy = in.readString(); - nr+=3; - } - if(removeRedundantNodes) - { - this->deleteRedundantNodes(); //dort wird autoamtisch calculateValues() aufgerufen - } - else - { - this->calculateValues(); - } + UBLOG(logDEBUG1, "GbTriFaceMesh3DCreator::readMeshFromSTLFile !!! Dieses Format hat leider redundante Knoten ..."); + + UbFileInputASCII in(filename); + // this->nodes = new vector<GbTriFaceMesh3D::Vertex>; + // this->triangles = new vector<GbTriFaceMesh3D::TriFace>; + string dummy; + + double x, y, z; + int nr = 0; + + in.readLine(); + while (dummy != "endsolid") { + in.readLine(); + in.readLine(); + dummy = in.readString(); + if (dummy != "vertex") + throw UbException(UB_EXARGS, "no vertex format"); + x = in.readDouble(); + y = in.readDouble(); + z = in.readDouble(); + nodes->push_back(GbTriFaceMesh3D::Vertex((float)x, (float)y, (float)z)); + in.readLine(); + in.readString(); + x = in.readDouble(); + y = in.readDouble(); + z = in.readDouble(); + nodes->push_back(GbTriFaceMesh3D::Vertex((float)x, (float)y, (float)z)); + in.readLine(); + in.readString(); + x = in.readDouble(); + y = in.readDouble(); + z = in.readDouble(); + nodes->push_back(GbTriFaceMesh3D::Vertex((float)x, (float)y, (float)z)); + triangles->push_back(GbTriFaceMesh3D::TriFace(nr, nr + 1, nr + 2)); + in.readLine(); + in.readLine(); + in.readLine(); + dummy = in.readString(); + nr += 3; + } + if (removeRedundantNodes) { + this->deleteRedundantNodes(); // dort wird autoamtisch calculateValues() aufgerufen + } else { + this->calculateValues(); + } } ////////////////////////////////////////////////////////////////////////// -//void GbTriFaceMesh3D::writeMeshToSTLFile(string filename, bool isBinaryFormat) +// void GbTriFaceMesh3D::writeMeshToSTLFile(string filename, bool isBinaryFormat) //{ // vector<GbTriFaceMesh3D::Vertex> *nodes = new vector<GbTriFaceMesh3D::Vertex>; // vector<GbTriFaceMesh3D::TriFace> *triangles = new vector<GbTriFaceMesh3D::TriFace>; diff --git a/src/basics/geometry3d/GbTriFaceMesh3D.h b/src/basics/geometry3d/GbTriFaceMesh3D.h index ec69a7b375b451de3ead1ef99bfbaaffd9226767..5fd77cecac566c143cdc4e692389596c5a86dcac 100644 --- a/src/basics/geometry3d/GbTriFaceMesh3D.h +++ b/src/basics/geometry3d/GbTriFaceMesh3D.h @@ -7,10 +7,10 @@ #ifndef GBTRIFACEMESH3D_H #define GBTRIFACEMESH3D_H -#include <sstream> #include <iostream> -#include <vector> #include <map> +#include <sstream> +#include <vector> #include <basics/utilities/UbException.h> #include <basics/utilities/UbMath.h> @@ -22,12 +22,15 @@ #include <basics_export.h> -namespace Kd -{ - template< typename T> class Tree; - template< typename T > class SplitAlgorithm; - template< typename T > class RayIntersectionHandler; -} +namespace Kd +{ +template <typename T> +class Tree; +template <typename T> +class SplitAlgorithm; +template <typename T> +class RayIntersectionHandler; +} // namespace Kd class WbWriter; @@ -38,289 +41,367 @@ class WbWriter; * This Class provides the triangular meshes. * Note, that up to now no methods for checking consistency are included. * in this context this class describes facettes from an 3D-object !!! -*/ + */ class BASICS_EXPORT GbTriFaceMesh3D : public GbObject3D { public: - // nested class start - class Vertex - { - public: - Vertex() = default; - Vertex(const float& x, const float& y, const float& z) : x(x), y(y),z(z) { } - Vertex(Vertex* vert) - { - this->x = vert->x; - this->y = vert->y; - this->z = vert->z; - } - float operator[] (const int&i) const - { - if (i==0) return x; - else if(i==1) return y; - else if(i==2) return z; - - throw UbException(UB_EXARGS,"i not in [0;2]"); - } - float& operator[] (const int& i) - { - if (i==0) return x; - else if(i==1) return y; - else if(i==2) return z; - - throw UbException(UB_EXARGS,"not in [0;2]"); - } - bool operator== (const Vertex& rhs) - { - return ( fabs(x-rhs.x)<1.E-8 && fabs(y-rhs.y)<1.E-8 && fabs(z-rhs.z)<1.E-8 ); - } - friend inline bool operator<(const Vertex & lhsVert,const Vertex & rhsVert) - { - if( lhsVert.x < rhsVert.x ) return true; - if( lhsVert.x > rhsVert.x ) return false; - if( lhsVert.y < rhsVert.y ) return true; - if( lhsVert.y > rhsVert.y ) return false; - if( lhsVert.z < rhsVert.z ) return true; - - return false; - } - friend std::ostream& operator<<( std::ostream& os, const Vertex& node ) - { - return os<<node.x<<","<<node.y<<","<<node.z; - } - Vertex* clone() - { - return(new Vertex(this)); - } - - public: - float x{0.0}, y{0.0}, z{0.0}; - }; - ////////////////////////////////////////////////////////////////////////// - class TriFace - { - public: - TriFace() - - = default; - TriFace(const int& v1, const int& v2, const int& v3) - : v1(v1), v2(v2), v3(v3) - { - } - - const int& getIndexVertex1() const { return v1; } - const int& getIndexVertex2() const { return v2; } - const int& getIndexVertex3() const { return v3; } - - Vertex& getNode(const int& i, std::vector<Vertex>& nodes) - { - if(i==0) return nodes[v1]; - if(i==1) return nodes[v2]; - if(i==2) return nodes[v3]; - throw UbException(UB_EXARGS,"invalid i - not in range [0;2]"); - } - void setNode(const int& i, const int& index) - { - if (i==0) v1=index; - else if(i==1) v2=index; - else if(i==2) v3=index; - else throw UbException(UB_EXARGS,"invalid i - not in range [0;2]"); - } - - int operator[] (int index) - { - if(index==0) return v1; - if(index==1) return v2; - if(index==2) return v3; - throw UbException(UB_EXARGS,"invalid i - not in range [0;2]"); - } - - float& getV1x(std::vector<Vertex>& nodes) { return nodes[v1].x; } - float& getV1y(std::vector<Vertex>& nodes) { return nodes[v1].y; } - float& getV1z(std::vector<Vertex>& nodes) { return nodes[v1].z; } - - float& getV2x(std::vector<Vertex>& nodes) { return nodes[v2].x; } - float& getV2y(std::vector<Vertex>& nodes) { return nodes[v2].y; } - float& getV2z(std::vector<Vertex>& nodes) { return nodes[v2].z; } - - float& getV3x(std::vector<Vertex>& nodes) { return nodes[v3].x; } - float& getV3y(std::vector<Vertex>& nodes) { return nodes[v3].y; } - float& getV3z(std::vector<Vertex>& nodes) { return nodes[v3].z; } - - float getMinX(std::vector<Vertex>& nodes) { return (float)UbMath::min(nodes[v1].x,nodes[v2].x,nodes[v3].x); } - float getMinY(std::vector<Vertex>& nodes) { return (float)UbMath::min(nodes[v1].y,nodes[v2].y,nodes[v3].y); } - float getMinZ(std::vector<Vertex>& nodes) { return (float)UbMath::min(nodes[v1].z,nodes[v2].z,nodes[v3].z); } - - float getMaxX(std::vector<Vertex>& nodes) { return (float)UbMath::max(nodes[v1].x,nodes[v2].x,nodes[v3].x); } - float getMaxY(std::vector<Vertex>& nodes) { return (float)UbMath::max(nodes[v1].y,nodes[v2].y,nodes[v3].y); } - float getMaxZ(std::vector<Vertex>& nodes) { return (float)UbMath::max(nodes[v1].z,nodes[v2].z,nodes[v3].z); } - - float getX1Centroid(std::vector<Vertex>& nodes) {return (float)UbMath::c1o3 * (getV1x(nodes)+getV2x(nodes)+getV3x(nodes)); } - float getX2Centroid(std::vector<Vertex>& nodes) {return (float)UbMath::c1o3 * (getV1y(nodes)+getV2y(nodes)+getV3y(nodes)); } - float getX3Centroid(std::vector<Vertex>& nodes) {return (float)UbMath::c1o3 * (getV1z(nodes)+getV2z(nodes)+getV3z(nodes)); } - - double calculateDistanceToPoint3D(const double& x1, const double& x2, const double& x3, std::vector<Vertex>& nodes); - - double getArea(std::vector<Vertex>& nodes) - { - //GbVector3D A(nodes[v1].x, nodes[v1].y, nodes[v1].z); - //GbVector3D B(nodes[v2].x, nodes[v2].y, nodes[v2].z); - //GbVector3D C(nodes[v3].x, nodes[v3].y, nodes[v3].z); - //GbVector3D AB = B-A; - //GbVector3D AC = C-A; - //GbVector3D N = AB.Cross(AC); - //return 0.5*N.Length(); - Vector3D A(nodes[v1].x, nodes[v1].y, nodes[v1].z); - Vector3D B(nodes[v2].x, nodes[v2].y, nodes[v2].z); - Vector3D C(nodes[v3].x, nodes[v3].y, nodes[v3].z); - Vector3D AB = B-A; - Vector3D AC = C-A; - Vector3D N = AB.Cross(AC); - return 0.5*N.Length(); - } - void calculateNormal(std::vector<Vertex>& nodes) - { - const float& v1x = nodes[v1].x; const float& v1y = nodes[v1].y; const float& v1z = nodes[v1].z; - const float& v2x = nodes[v2].x; const float& v2y = nodes[v2].y; const float& v2z = nodes[v2].z; - const float& v3x = nodes[v3].x; const float& v3y = nodes[v3].y; const float& v3z = nodes[v3].z; - - nx = ( v3z - v1z) * ( v2y - v1y ) - ( v2z - v1z) * ( v3y - v1y ); - ny = ( v2z - v1z) * ( v3x - v1x ) - ( v2x - v1x) * ( v3z - v1z ); - nz = ( v2x - v1x) * ( v3y - v1y ) - ( v2y - v1y) * ( v3x - v1x ); - - float length = std::sqrt( nx*nx + ny*ny + nz*nz ); - if(length>1.E-10) - { - length = 1.0f/length; - nx *= length; - ny *= length; - nz *= length; - } - else - { - std::cerr<<"GbTriFaceMesh3D::TriFace - calculateNormal: nx=ny=nz=0 -> kann nich sein " - <<"(dreieck hat evtl knoten doppelt oder ist ne Linie)" - <<"->removeRedunantNodes"<<std::endl; - } - } - - public: - int v1{-1}, v2{-1}, v3{-1}; - float nx{0.0}, ny{0.0}, nz{0.0}; - }; + // nested class start + class Vertex + { + public: + Vertex() = default; + Vertex(const float &x, const float &y, const float &z) : x(x), y(y), z(z) {} + Vertex(Vertex *vert) + { + this->x = vert->x; + this->y = vert->y; + this->z = vert->z; + } + float operator[](const int &i) const + { + if (i == 0) + return x; + else if (i == 1) + return y; + else if (i == 2) + return z; + + throw UbException(UB_EXARGS, "i not in [0;2]"); + } + float &operator[](const int &i) + { + if (i == 0) + return x; + else if (i == 1) + return y; + else if (i == 2) + return z; + + throw UbException(UB_EXARGS, "not in [0;2]"); + } + bool operator==(const Vertex &rhs) + { + return (fabs(x - rhs.x) < 1.E-8 && fabs(y - rhs.y) < 1.E-8 && fabs(z - rhs.z) < 1.E-8); + } + friend inline bool operator<(const Vertex &lhsVert, const Vertex &rhsVert) + { + if (lhsVert.x < rhsVert.x) + return true; + if (lhsVert.x > rhsVert.x) + return false; + if (lhsVert.y < rhsVert.y) + return true; + if (lhsVert.y > rhsVert.y) + return false; + if (lhsVert.z < rhsVert.z) + return true; + + return false; + } + friend std::ostream &operator<<(std::ostream &os, const Vertex &node) + { + return os << node.x << "," << node.y << "," << node.z; + } + Vertex *clone() { return (new Vertex(this)); } + + public: + float x{ 0.0 }, y{ 0.0 }, z{ 0.0 }; + }; + ////////////////////////////////////////////////////////////////////////// + class TriFace + { + public: + TriFace() + + = default; + TriFace(const int &v1, const int &v2, const int &v3) : v1(v1), v2(v2), v3(v3) {} + + const int &getIndexVertex1() const { return v1; } + const int &getIndexVertex2() const { return v2; } + const int &getIndexVertex3() const { return v3; } + + Vertex &getNode(const int &i, std::vector<Vertex> &nodes) + { + if (i == 0) + return nodes[v1]; + if (i == 1) + return nodes[v2]; + if (i == 2) + return nodes[v3]; + throw UbException(UB_EXARGS, "invalid i - not in range [0;2]"); + } + void setNode(const int &i, const int &index) + { + if (i == 0) + v1 = index; + else if (i == 1) + v2 = index; + else if (i == 2) + v3 = index; + else + throw UbException(UB_EXARGS, "invalid i - not in range [0;2]"); + } + + int operator[](int index) + { + if (index == 0) + return v1; + if (index == 1) + return v2; + if (index == 2) + return v3; + throw UbException(UB_EXARGS, "invalid i - not in range [0;2]"); + } + + float &getV1x(std::vector<Vertex> &nodes) { return nodes[v1].x; } + float &getV1y(std::vector<Vertex> &nodes) { return nodes[v1].y; } + float &getV1z(std::vector<Vertex> &nodes) { return nodes[v1].z; } + + float &getV2x(std::vector<Vertex> &nodes) { return nodes[v2].x; } + float &getV2y(std::vector<Vertex> &nodes) { return nodes[v2].y; } + float &getV2z(std::vector<Vertex> &nodes) { return nodes[v2].z; } + + float &getV3x(std::vector<Vertex> &nodes) { return nodes[v3].x; } + float &getV3y(std::vector<Vertex> &nodes) { return nodes[v3].y; } + float &getV3z(std::vector<Vertex> &nodes) { return nodes[v3].z; } + + float getMinX(std::vector<Vertex> &nodes) { return (float)UbMath::min(nodes[v1].x, nodes[v2].x, nodes[v3].x); } + float getMinY(std::vector<Vertex> &nodes) { return (float)UbMath::min(nodes[v1].y, nodes[v2].y, nodes[v3].y); } + float getMinZ(std::vector<Vertex> &nodes) { return (float)UbMath::min(nodes[v1].z, nodes[v2].z, nodes[v3].z); } + + float getMaxX(std::vector<Vertex> &nodes) { return (float)UbMath::max(nodes[v1].x, nodes[v2].x, nodes[v3].x); } + float getMaxY(std::vector<Vertex> &nodes) { return (float)UbMath::max(nodes[v1].y, nodes[v2].y, nodes[v3].y); } + float getMaxZ(std::vector<Vertex> &nodes) { return (float)UbMath::max(nodes[v1].z, nodes[v2].z, nodes[v3].z); } + + float getX1Centroid(std::vector<Vertex> &nodes) + { + return (float)UbMath::c1o3 * (getV1x(nodes) + getV2x(nodes) + getV3x(nodes)); + } + float getX2Centroid(std::vector<Vertex> &nodes) + { + return (float)UbMath::c1o3 * (getV1y(nodes) + getV2y(nodes) + getV3y(nodes)); + } + float getX3Centroid(std::vector<Vertex> &nodes) + { + return (float)UbMath::c1o3 * (getV1z(nodes) + getV2z(nodes) + getV3z(nodes)); + } + + double calculateDistanceToPoint3D(const double &x1, const double &x2, const double &x3, + std::vector<Vertex> &nodes); + + double getArea(std::vector<Vertex> &nodes) + { + // GbVector3D A(nodes[v1].x, nodes[v1].y, nodes[v1].z); + // GbVector3D B(nodes[v2].x, nodes[v2].y, nodes[v2].z); + // GbVector3D C(nodes[v3].x, nodes[v3].y, nodes[v3].z); + // GbVector3D AB = B-A; + // GbVector3D AC = C-A; + // GbVector3D N = AB.Cross(AC); + // return 0.5*N.Length(); + Vector3D A(nodes[v1].x, nodes[v1].y, nodes[v1].z); + Vector3D B(nodes[v2].x, nodes[v2].y, nodes[v2].z); + Vector3D C(nodes[v3].x, nodes[v3].y, nodes[v3].z); + Vector3D AB = B - A; + Vector3D AC = C - A; + Vector3D N = AB.Cross(AC); + return 0.5 * N.Length(); + } + void calculateNormal(std::vector<Vertex> &nodes) + { + const float &v1x = nodes[v1].x; + const float &v1y = nodes[v1].y; + const float &v1z = nodes[v1].z; + const float &v2x = nodes[v2].x; + const float &v2y = nodes[v2].y; + const float &v2z = nodes[v2].z; + const float &v3x = nodes[v3].x; + const float &v3y = nodes[v3].y; + const float &v3z = nodes[v3].z; + + nx = (v3z - v1z) * (v2y - v1y) - (v2z - v1z) * (v3y - v1y); + ny = (v2z - v1z) * (v3x - v1x) - (v2x - v1x) * (v3z - v1z); + nz = (v2x - v1x) * (v3y - v1y) - (v2y - v1y) * (v3x - v1x); + + float length = std::sqrt(nx * nx + ny * ny + nz * nz); + if (length > 1.E-10) { + length = 1.0f / length; + nx *= length; + ny *= length; + nz *= length; + } else { + std::cerr << "GbTriFaceMesh3D::TriFace - calculateNormal: nx=ny=nz=0 -> kann nich sein " + << "(dreieck hat evtl knoten doppelt oder ist ne Linie)" + << "->removeRedunantNodes" << std::endl; + } + } + + public: + int v1{ -1 }, v2{ -1 }, v3{ -1 }; + float nx{ 0.0 }, ny{ 0.0 }, nz{ 0.0 }; + }; public: - enum KDTREE_SPLITAGORITHM { KDTREE_SAHPLIT, KDTREE_SPATIALSPLIT }; + enum KDTREE_SPLITAGORITHM { KDTREE_SAHPLIT, KDTREE_SPATIALSPLIT }; public: - GbTriFaceMesh3D(); - GbTriFaceMesh3D(std::string name, std::vector<Vertex>* nodes, std::vector<TriFace>* triangles, KDTREE_SPLITAGORITHM splitAlg = KDTREE_SAHPLIT, bool removeRedundantNodes=true); - ~GbTriFaceMesh3D() override; - - GbTriFaceMesh3D* clone() override;// { throw UbException(UB_EXARGS,"not implemented"); } - void finalize() override {} - - //void setRegardPointInPolyhedronTest(bool value) { this->regardPiO=value; } - - std::string toString() override; - - //std::string getName(); - std::vector<Vertex>* getNodes(); - std::vector<TriFace>* getTriangles(); - - void setTransferViaFilename(bool transferViaFilename, std::string filename, double transX1, double transX2, double transX3) - { - this->filename = filename; - this->transferViaFilename = transferViaFilename; - this->transX1 = transX1; - this->transX2 = transX2; - this->transX3 = transX3; - } - void readMeshFromSTLFile(std::string filename, bool removeRedundantNodes); - - double getX1Minimum() override { if(!this->consistent) this->calculateValues(); return this->x1min; } - double getX1Maximum() override { if(!this->consistent) this->calculateValues(); return this->x1max; } - double getX1Centroid() override { if(!this->consistent) this->calculateValues(); return this->x1center; } - - double getX2Minimum() override { if(!this->consistent) this->calculateValues(); return this->x2min; } - double getX2Maximum() override { if(!this->consistent) this->calculateValues(); return this->x2max; } - double getX2Centroid() override { if(!this->consistent) this->calculateValues(); return this->x2center; } - - double getX3Minimum() override { if(!this->consistent) this->calculateValues(); return this->x3min; } - double getX3Centroid() override { if(!this->consistent) this->calculateValues(); return this->x3center; } - double getX3Maximum() override { if(!this->consistent) this->calculateValues(); return this->x3max; } - - void calculateValues(); - - double getVolume(); - void deleteRedundantNodes(); - - UbTupleDouble6 calculateMomentOfInertia(double rhoP); - UbTupleDouble3 calculateCenterOfGravity(); - - void setCenterCoordinates(const double& x1, const double& x2, const double& x3) override; - - - void scale(const double& sx1, const double& sx2, const double& sx3) override; - void rotate(const double& alpha, const double& beta, const double& gamma) override; - void rotateAroundPoint(const double& px1, const double& px2, const double& px3, const double& alpha, const double& beta, const double& gamma); - void translate(const double& x1, const double& x2, const double& x3) override; - void reflectAcrossXYLine(const double& alpha); - - bool isPointInGbObject3D(const double& x1, const double& x2, const double& x3) override; - bool isPointInGbObject3D(const double& x1, const double& x2, const double& x3, int counter); - bool isPointInGbObject3D(const double& x1, const double& x2, const double& x3, bool& pointIsOnBoundary) override; - - GbLine3D* createClippedLine3D (GbPoint3D &point1,GbPoint3D &point2) override; - - std::vector<GbTriangle3D*> getSurfaceTriangleSet() override; - void addSurfaceTriangleSet(std::vector<UbTupleFloat3>& nodes, std::vector<UbTupleInt3>& triangles) override; - - std::vector<GbTriFaceMesh3D::TriFace*> getTrianglesForVertex(Vertex* vertex); - - void setKdTreeSplitAlgorithm(KDTREE_SPLITAGORITHM mode); - KDTREE_SPLITAGORITHM getKdTreeSplitAlgorithm() { return this->kdtreeSplitAlg; } - Kd::Tree<double>* getKdTree() { return this->kdTree; } - - virtual UbTuple<std::string, std::string> writeMesh(std::string filename, WbWriter* writer, bool writeNormals=false, std::vector< std::string >* datanames=NULL, std::vector< std::vector < double > >* nodedata=NULL ); - void writeMeshPly( const std::string& filename); - - /*======================================================================*/ - using GbObject3D::isPointInGbObject3D; //Grund: dadurch muss man hier isPointInGbObject3D(GbPoint3D*) nicht ausprogrammieren, welche sonst hier "ueberdeckt" waere - - bool intersectLine(const double& p1_x1, const double& p1_x2, const double& p1_x3, const double& p2_x1, const double& p2_x2, const double& p2_x3); - + GbTriFaceMesh3D(); + GbTriFaceMesh3D(std::string name, std::vector<Vertex> *nodes, std::vector<TriFace> *triangles, + KDTREE_SPLITAGORITHM splitAlg = KDTREE_SAHPLIT, bool removeRedundantNodes = true); + ~GbTriFaceMesh3D() override; + + GbTriFaceMesh3D *clone() override; // { throw UbException(UB_EXARGS,"not implemented"); } + void finalize() override {} + + // void setRegardPointInPolyhedronTest(bool value) { this->regardPiO=value; } + + std::string toString() override; + + // std::string getName(); + std::vector<Vertex> *getNodes(); + std::vector<TriFace> *getTriangles(); + + void setTransferViaFilename(bool transferViaFilename, std::string filename, double transX1, double transX2, + double transX3) + { + this->filename = filename; + this->transferViaFilename = transferViaFilename; + this->transX1 = transX1; + this->transX2 = transX2; + this->transX3 = transX3; + } + void readMeshFromSTLFile(std::string filename, bool removeRedundantNodes); + + double getX1Minimum() override + { + if (!this->consistent) + this->calculateValues(); + return this->x1min; + } + double getX1Maximum() override + { + if (!this->consistent) + this->calculateValues(); + return this->x1max; + } + double getX1Centroid() override + { + if (!this->consistent) + this->calculateValues(); + return this->x1center; + } + + double getX2Minimum() override + { + if (!this->consistent) + this->calculateValues(); + return this->x2min; + } + double getX2Maximum() override + { + if (!this->consistent) + this->calculateValues(); + return this->x2max; + } + double getX2Centroid() override + { + if (!this->consistent) + this->calculateValues(); + return this->x2center; + } + + double getX3Minimum() override + { + if (!this->consistent) + this->calculateValues(); + return this->x3min; + } + double getX3Centroid() override + { + if (!this->consistent) + this->calculateValues(); + return this->x3center; + } + double getX3Maximum() override + { + if (!this->consistent) + this->calculateValues(); + return this->x3max; + } + + void calculateValues(); + + double getVolume(); + void deleteRedundantNodes(); + + UbTupleDouble6 calculateMomentOfInertia(double rhoP); + UbTupleDouble3 calculateCenterOfGravity(); + + void setCenterCoordinates(const double &x1, const double &x2, const double &x3) override; + + void scale(const double &sx1, const double &sx2, const double &sx3) override; + void rotate(const double &alpha, const double &beta, const double &gamma) override; + void rotateAroundPoint(const double &px1, const double &px2, const double &px3, const double &alpha, + const double &beta, const double &gamma); + void translate(const double &x1, const double &x2, const double &x3) override; + void reflectAcrossXYLine(const double &alpha); + + bool isPointInGbObject3D(const double &x1, const double &x2, const double &x3) override; + bool isPointInGbObject3D(const double &x1, const double &x2, const double &x3, int counter); + bool isPointInGbObject3D(const double &x1, const double &x2, const double &x3, bool &pointIsOnBoundary) override; + + GbLine3D *createClippedLine3D(GbPoint3D &point1, GbPoint3D &point2) override; + + std::vector<GbTriangle3D *> getSurfaceTriangleSet() override; + void addSurfaceTriangleSet(std::vector<UbTupleFloat3> &nodes, std::vector<UbTupleInt3> &triangles) override; + + std::vector<GbTriFaceMesh3D::TriFace *> getTrianglesForVertex(Vertex *vertex); + + void setKdTreeSplitAlgorithm(KDTREE_SPLITAGORITHM mode); + KDTREE_SPLITAGORITHM getKdTreeSplitAlgorithm() { return this->kdtreeSplitAlg; } + Kd::Tree<double> *getKdTree() { return this->kdTree; } + + virtual UbTuple<std::string, std::string> writeMesh(std::string filename, WbWriter *writer, + bool writeNormals = false, + std::vector<std::string> *datanames = NULL, + std::vector<std::vector<double>> *nodedata = NULL); + void writeMeshPly(const std::string &filename); + + /*======================================================================*/ + using GbObject3D::isPointInGbObject3D; // Grund: dadurch muss man hier isPointInGbObject3D(GbPoint3D*) nicht + // ausprogrammieren, welche sonst hier "ueberdeckt" waere + + bool intersectLine(const double &p1_x1, const double &p1_x2, const double &p1_x3, const double &p2_x1, + const double &p2_x2, const double &p2_x3); protected: - KDTREE_SPLITAGORITHM kdtreeSplitAlg; - void init(); - - std::vector<Vertex>* nodes; - std::vector<TriFace>* triangles; - //for transfer - std::string filename; - bool transferViaFilename{false}; - double transX1{0.0}; - double transX2{0.0}; - double transX3{0.0}; - - double x1min; - double x1max; - double x2min; - double x2max; - double x3min; - double x3max; - double x1center; - double x2center; - double x3center; - - bool consistent {false}; - - bool buildVertTriRelationMap{false}; - std::multimap<Vertex*,TriFace*> relationVertTris; - - Kd::Tree< double >* kdTree = nullptr; + KDTREE_SPLITAGORITHM kdtreeSplitAlg; + void init(); + + std::vector<Vertex> *nodes; + std::vector<TriFace> *triangles; + // for transfer + std::string filename; + bool transferViaFilename{ false }; + double transX1{ 0.0 }; + double transX2{ 0.0 }; + double transX3{ 0.0 }; + + double x1min; + double x1max; + double x2min; + double x2max; + double x3min; + double x3max; + double x1center; + double x2center; + double x3center; + + bool consistent{ false }; + + bool buildVertTriRelationMap{ false }; + std::multimap<Vertex *, TriFace *> relationVertTris; + + Kd::Tree<double> *kdTree = nullptr; }; - -#endif //GBTRIFACEMESH3D_H +#endif // GBTRIFACEMESH3D_H diff --git a/src/basics/geometry3d/GbTriangle3D.cpp b/src/basics/geometry3d/GbTriangle3D.cpp index 51edfa5eafcd6160790480abea450de372bfc5b9..3b5a96af747d9ee6157b9a246de7b4482f3b4b8b 100644 --- a/src/basics/geometry3d/GbTriangle3D.cpp +++ b/src/basics/geometry3d/GbTriangle3D.cpp @@ -1,28 +1,28 @@ //======================================================================================= -// ____ ____ __ ______ __________ __ __ __ __ -// \ \ | | | | | _ \ |___ ___| | | | | / \ | | -// \ \ | | | | | |_) | | | | | | | / \ | | -// \ \ | | | | | _ / | | | | | | / /\ \ | | -// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ -// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| -// \ \ | | ________________________________________________________________ -// \ \ | | | ______________________________________________________________| -// \ \| | | | __ __ __ __ ______ _______ -// \ | | |_____ | | | | | | | | | _ \ / _____) -// \ | | _____| | | | | | | | | | | \ \ \_______ +// ____ ____ __ ______ __________ __ __ __ __ +// \ \ | | | | | _ \ |___ ___| | | | | / \ | | +// \ \ | | | | | |_) | | | | | | | / \ | | +// \ \ | | | | | _ / | | | | | | / /\ \ | | +// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ +// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| +// \ \ | | ________________________________________________________________ +// \ \ | | | ______________________________________________________________| +// \ \| | | | __ __ __ __ ______ _______ +// \ | | |_____ | | | | | | | | | _ \ / _____) +// \ | | _____| | | | | | | | | | | \ \ \_______ // \ | | | | |_____ | \_/ | | | | |_/ / _____ | -// \ _____| |__| |________| \_______/ |__| |______/ (_______/ +// \ _____| |__| |________| \_______/ |__| |______/ (_______/ // -// This file is part of VirtualFluids. VirtualFluids is free software: you can +// This file is part of VirtualFluids. VirtualFluids is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of +// License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. -// -// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// +// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License along // with VirtualFluids (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>. // @@ -30,489 +30,531 @@ //! \ingroup geometry3d //! \author Soeren Freudiger, Sebastian Geller //======================================================================================= -#include <GbTriangle3D.h> -#include <GbSystem3D.h> -#include <GbLine3D.h> #include <GbCuboid3D.h> +#include <GbLine3D.h> +#include <GbSystem3D.h> +#include <GbTriangle3D.h> #include <basics/utilities/UbMath.h> -using namespace std; +using namespace std; GbTriangle3D::GbTriangle3D() { - this->init(); - this->consistent = false; + this->init(); + this->consistent = false; } /*======================================================================*/ /* -* Creates an empty 2D triangle with the specified points. -* @param point1 the 1st point -* @param point2 the 2nd point -* @param point3 the 3nd point -*/ -GbTriangle3D::GbTriangle3D(GbPoint3D* point1, GbPoint3D* point2, GbPoint3D* point3) + * Creates an empty 2D triangle with the specified points. + * @param point1 the 1st point + * @param point2 the 2nd point + * @param point3 the 3nd point + */ +GbTriangle3D::GbTriangle3D(GbPoint3D *point1, GbPoint3D *point2, GbPoint3D *point3) { - this->init(); - this->points[0] = point1; - this->points[1] = point2; - this->points[2] = point3; - - this->calculateNormal(); - this->consistent = false; - - this->points[0]->addObserver(this); - this->points[1]->addObserver(this); - this->points[2]->addObserver(this); - - //this.po = new PointObserver(this); - //this.points[0].addObserver(this.po); - //this.points[1].addObserver(this.po); - //this.points[2].addObserver(this.po); + this->init(); + this->points[0] = point1; + this->points[1] = point2; + this->points[2] = point3; + + this->calculateNormal(); + this->consistent = false; + + this->points[0]->addObserver(this); + this->points[1]->addObserver(this); + this->points[2]->addObserver(this); + + // this.po = new PointObserver(this); + // this.points[0].addObserver(this.po); + // this.points[1].addObserver(this.po); + // this.points[2].addObserver(this.po); } /*======================================================================*/ /* -* Creates a 3D triangle as clone of the specified 2D triangle. -* @param triangle the 3D triangle to be cloned -*/ -GbTriangle3D::GbTriangle3D(GbTriangle3D* triangle) + * Creates a 3D triangle as clone of the specified 2D triangle. + * @param triangle the 3D triangle to be cloned + */ +GbTriangle3D::GbTriangle3D(GbTriangle3D *triangle) { - this->init(); - this->points[0] = triangle->points[0]->clone(); - this->points[1] = triangle->points[1]->clone(); - this->points[2] = triangle->points[2]->clone(); - - this->consistent = false; - this->calculateNormal(); - this->calculateValues(); + this->init(); + this->points[0] = triangle->points[0]->clone(); + this->points[1] = triangle->points[1]->clone(); + this->points[2] = triangle->points[2]->clone(); + + this->consistent = false; + this->calculateNormal(); + this->calculateValues(); } /*======================================================================*/ GbTriangle3D::~GbTriangle3D() { - if(this->points[0]) this->points[0]->removeObserver(this); - if(this->points[1]) this->points[1]->removeObserver(this); - if(this->points[2]) this->points[2]->removeObserver(this); + if (this->points[0]) + this->points[0]->removeObserver(this); + if (this->points[1]) + this->points[1]->removeObserver(this); + if (this->points[2]) + this->points[2]->removeObserver(this); } /*======================================================================*/ void GbTriangle3D::deletePoints() -{ - if(points[0]) { delete points[0]; points[0]=NULL;} - if(points[1]) { delete points[1]; points[1]=NULL;} - if(points[2]) { delete points[2]; points[2]=NULL;} +{ + if (points[0]) { + delete points[0]; + points[0] = NULL; + } + if (points[1]) { + delete points[1]; + points[1] = NULL; + } + if (points[2]) { + delete points[2]; + points[2] = NULL; + } } /*======================================================================*/ /* Methoden */ /* */ /* -* Creates a 3D triangle as clone of this 3D triangle. -*/ -GbTriangle3D* GbTriangle3D::clone() -{ - return(new GbTriangle3D(this)); -} + * Creates a 3D triangle as clone of this 3D triangle. + */ +GbTriangle3D *GbTriangle3D::clone() { return (new GbTriangle3D(this)); } /*======================================================================*/ /* -* Returns the number of times this 2D triangle contains the specified point. -* @param point the point -* @return the number of times this 2D triangle contains the specified point -*/ -int GbTriangle3D::contains(GbPoint3D* point) + * Returns the number of times this 2D triangle contains the specified point. + * @param point the point + * @return the number of times this 2D triangle contains the specified point + */ +int GbTriangle3D::contains(GbPoint3D *point) { - int n = 0; - for(int i=0; i<3; i++) if(this->points[i]->equals(point)) n++; - return(n); + int n = 0; + for (int i = 0; i < 3; i++) + if (this->points[i]->equals(point)) + n++; + return (n); } /*======================================================================*/ /* -* Returns the number of times this 2D triangle contains a point equal to the specified point. -* @param point the point -* @return the number of times this 2D triangle contains a point equal to the specified point -*/ -int GbTriangle3D::containsEqual(GbPoint3D* point) + * Returns the number of times this 2D triangle contains a point equal to the specified point. + * @param point the point + * @return the number of times this 2D triangle contains a point equal to the specified point + */ +int GbTriangle3D::containsEqual(GbPoint3D *point) { - int n = 0; - for(int i=0; i<3; i++) if(this->points[i]->equals(point)) n++; - return(n); + int n = 0; + for (int i = 0; i < 3; i++) + if (this->points[i]->equals(point)) + n++; + return (n); } /*======================================================================*/ /* -* Returns the specified point. -* @param index the index (must be 0, 1, or 2) -* @return the specified point -* @exception ArrayIndexOutOfBoundsException if the specified index is not valid -*/ -GbPoint3D* GbTriangle3D::getPoint(const int& index) + * Returns the specified point. + * @param index the index (must be 0, 1, or 2) + * @return the specified point + * @exception ArrayIndexOutOfBoundsException if the specified index is not valid + */ +GbPoint3D *GbTriangle3D::getPoint(const int &index) { - if(index < 0 || index > 2) throw UbException(UB_EXARGS,"invalid index specified: "); - return((this->points[index])); + if (index < 0 || index > 2) + throw UbException(UB_EXARGS, "invalid index specified: "); + return ((this->points[index])); } /*======================================================================*/ -vector<GbPoint3D> GbTriangle3D::getPoints() +vector<GbPoint3D> GbTriangle3D::getPoints() { - vector<GbPoint3D> p(3); - p[0] = *(points[0]); - p[1] = *(points[1]); - p[2] = *(points[2]); - return p; - // - //vector<GbPoint3D> p(3);// = new vector<GbPoint3D*>; - //p.resize(3);//, NULL); - //p[0] = this->points[0]; - //p[1] = this->points[1]; - //p[2] = this->points[2]; - //return(p); + vector<GbPoint3D> p(3); + p[0] = *(points[0]); + p[1] = *(points[1]); + p[2] = *(points[2]); + return p; + // + // vector<GbPoint3D> p(3);// = new vector<GbPoint3D*>; + // p.resize(3);//, NULL); + // p[0] = this->points[0]; + // p[1] = this->points[1]; + // p[2] = this->points[2]; + // return(p); } /*======================================================================*/ /* -* Returns the area of this triangle. -* The area is positive for positive ordered points, otherwise negative. -* @return the area of this triangle -*/ + * Returns the area of this triangle. + * The area is positive for positive ordered points, otherwise negative. + * @return the area of this triangle + */ double GbTriangle3D::getArea() { - if(!this->consistent) this->calculateValues(); - // throw UbException(UB_EXARGS,"not correct calculated ..."); - return(this->area); + if (!this->consistent) + this->calculateValues(); + // throw UbException(UB_EXARGS,"not correct calculated ..."); + return (this->area); } /* -* Returns the centroid x1 coordinate of this triangle. -* @return the centroid x1 coordinate of this triangle -*/ + * Returns the centroid x1 coordinate of this triangle. + * @return the centroid x1 coordinate of this triangle + */ double GbTriangle3D::getX1Centroid() { - if(!this->consistent) this->calculateValues(); - return(this->x1s); + if (!this->consistent) + this->calculateValues(); + return (this->x1s); } /* -* Returns the minimum x1 coordinate of this triangle. -* @return the minimum x1 coordinate of this triangle -*/ + * Returns the minimum x1 coordinate of this triangle. + * @return the minimum x1 coordinate of this triangle + */ double GbTriangle3D::getX1Minimum() { - if(!this->consistent) this->calculateValues(); - return(this->x1min); + if (!this->consistent) + this->calculateValues(); + return (this->x1min); } /* -* Returns the maximum x1 coordinate of this triangle. -* @return the maximum x1 coordinate of this triangle -*/ + * Returns the maximum x1 coordinate of this triangle. + * @return the maximum x1 coordinate of this triangle + */ double GbTriangle3D::getX1Maximum() { - if(!this->consistent) this->calculateValues(); - return(this->x1max); + if (!this->consistent) + this->calculateValues(); + return (this->x1max); } /* -* Returns the centroid x2 coordinate of this triangle. -* @return the centroid x2 coordinate of this triangle -*/ + * Returns the centroid x2 coordinate of this triangle. + * @return the centroid x2 coordinate of this triangle + */ double GbTriangle3D::getX2Centroid() { - if(!this->consistent) this->calculateValues(); - return(this->x2s); + if (!this->consistent) + this->calculateValues(); + return (this->x2s); } -/* -* Returns the minimum x2 coordinate of this triangle. -* @return the minimum x2 coordinate of this triangle -*/ +/* + * Returns the minimum x2 coordinate of this triangle. + * @return the minimum x2 coordinate of this triangle + */ double GbTriangle3D::getX2Minimum() { - if(!this->consistent) this->calculateValues(); - return(this->x2min); + if (!this->consistent) + this->calculateValues(); + return (this->x2min); } /* -* Returns the maximum x2 coordinate of this triangle. -* @return the maximum x2 coordinate of this triangle -*/ + * Returns the maximum x2 coordinate of this triangle. + * @return the maximum x2 coordinate of this triangle + */ double GbTriangle3D::getX2Maximum() { - if(!this->consistent) this->calculateValues(); - return(this->x2max); + if (!this->consistent) + this->calculateValues(); + return (this->x2max); } double GbTriangle3D::getX3Centroid() { - if(!this->consistent) this->calculateValues(); - return(this->x3s); + if (!this->consistent) + this->calculateValues(); + return (this->x3s); } double GbTriangle3D::getX3Minimum() { - if(!this->consistent) this->calculateValues(); - return(this->x3min); + if (!this->consistent) + this->calculateValues(); + return (this->x3min); } double GbTriangle3D::getX3Maximum() { - if(!this->consistent) this->calculateValues(); - return(this->x3max); + if (!this->consistent) + this->calculateValues(); + return (this->x3max); } /* -* Sets the specified point. -* @param point the point -* @param index the index (must be 0, 1, or 2) -* @exception ArrayIndexOutOfBoundsException if the specified index is not valid -*/ -void GbTriangle3D::setPoint(GbPoint3D* point, int index) + * Sets the specified point. + * @param point the point + * @param index the index (must be 0, 1, or 2) + * @exception ArrayIndexOutOfBoundsException if the specified index is not valid + */ +void GbTriangle3D::setPoint(GbPoint3D *point, int index) { - if(index < 0 || index > 2) throw UbException(UB_EXARGS,"invalid index specified: "); - this->points[index] = point; - this->consistent = false; - this->calculateNormal(); + if (index < 0 || index > 2) + throw UbException(UB_EXARGS, "invalid index specified: "); + this->points[index] = point; + this->consistent = false; + this->calculateNormal(); } /* -* Returns the surface triangle set with new nodes !!! -* @returns the surface triangle set with new nodes !!! -*/ -vector<GbTriangle3D*> GbTriangle3D::getSurfaceTriangleSet() + * Returns the surface triangle set with new nodes !!! + * @returns the surface triangle set with new nodes !!! + */ +vector<GbTriangle3D *> GbTriangle3D::getSurfaceTriangleSet() { - vector<GbTriangle3D*> triangles; - - triangles.push_back(new GbTriangle3D(new GbPoint3D(getPoint1()),new GbPoint3D(getPoint2()),new GbPoint3D(getPoint3()))); + vector<GbTriangle3D *> triangles; - return triangles; -} + triangles.push_back( + new GbTriangle3D(new GbPoint3D(getPoint1()), new GbPoint3D(getPoint2()), new GbPoint3D(getPoint3()))); + return triangles; +} /* -* Returns the string representation of the triangle -* @returns the string representation of the triangle -*/ + * Returns the string representation of the triangle + * @returns the string representation of the triangle + */ string GbTriangle3D::toString() { - stringstream ss; - ss<<"GbTriangle3D[area="; - ss<<this->getArea(); - - ss<<", x1s="<<this->x1s; - ss<<", x2s="<<this->x2s; - ss<<", x3s="<<this->x3s; - ss<<", x1min="<<this->x1min; - ss<<", x1max="<<this->x1max; - ss<<", x2min="<<this->x2min; - ss<<", x2max="<<this->x2max; - ss<<", x3min="<<this->x3min; - ss<<", x3max="<<this->x3max; - ss<<", points1="<<this->points[0]->toString(); - ss<<", points2="<<this->points[1]->toString(); - ss<<", points3="<<this->points[2]->toString(); - ss<<"]"; - return((ss.str()).c_str()); + stringstream ss; + ss << "GbTriangle3D[area="; + ss << this->getArea(); + + ss << ", x1s=" << this->x1s; + ss << ", x2s=" << this->x2s; + ss << ", x3s=" << this->x3s; + ss << ", x1min=" << this->x1min; + ss << ", x1max=" << this->x1max; + ss << ", x2min=" << this->x2min; + ss << ", x2max=" << this->x2max; + ss << ", x3min=" << this->x3min; + ss << ", x3max=" << this->x3max; + ss << ", points1=" << this->points[0]->toString(); + ss << ", points2=" << this->points[1]->toString(); + ss << ", points3=" << this->points[2]->toString(); + ss << "]"; + return ((ss.str()).c_str()); } /*======================================================================*/ -double GbTriangle3D::getIntersectionRaytraceFactor(const double& x1, const double& x2, const double& x3, const double& rx1, const double& rx2, const double& rx3) +double GbTriangle3D::getIntersectionRaytraceFactor(const double &x1, const double &x2, const double &x3, + const double &rx1, const double &rx2, const double &rx3) { - //e1 = v1 - v0 - double e1x1 = this->points[1]->x1-this->points[0]->x1; - double e1x2 = this->points[1]->x2-this->points[0]->x2; - double e1x3 = this->points[1]->x3-this->points[0]->x3; - - //e2 = v2 - v0 - double e2x1 = this->points[2]->x1-this->points[0]->x1; - double e2x2 = this->points[2]->x2-this->points[0]->x2; - double e2x3 = this->points[2]->x3-this->points[0]->x3; - - //p = d x e2 - double px1 = rx2*e2x3 - rx3*e2x2; - double px2 = rx3*e2x1 - rx1*e2x3; - double px3 = rx1*e2x2 - rx2*e2x1; - - //a = e1 dot p - double a = e1x1*px1 + e1x2*px2 + e1x3*px3; - if(fabs(a)<1.E-10) return -1.0; - double f = 1.0/a; - - //s = o - v0 - double sx1 = x1 - this->points[0]->x1; - double sx2 = x2 - this->points[0]->x2; - double sx3 = x3 - this->points[0]->x3; - - //u = f * ( s dot p) - double u = f * ( sx1*px1 + sx2*px2 + sx3*px3 ); - if(u<-1.E-10 || u>1.0+1.E-10) return -1.0; - - //q = s x e1 - double qx1 = sx2*e1x3 - sx3*e1x2; - double qx2 = sx3*e1x1 - sx1*e1x3; - double qx3 = sx1*e1x2 - sx2*e1x1; - - //v = f*(e2 dot q) - double v = f * (rx1*qx1 + rx2*qx2 + rx3*qx3); - if(v<-1.E-10 || (u+v)>1.0+1.E-10) return -1.0; - - //t = f * (e2 dot q) - return f * (e2x1*qx1 + e2x2*qx2 + e2x3*qx3); + // e1 = v1 - v0 + double e1x1 = this->points[1]->x1 - this->points[0]->x1; + double e1x2 = this->points[1]->x2 - this->points[0]->x2; + double e1x3 = this->points[1]->x3 - this->points[0]->x3; + + // e2 = v2 - v0 + double e2x1 = this->points[2]->x1 - this->points[0]->x1; + double e2x2 = this->points[2]->x2 - this->points[0]->x2; + double e2x3 = this->points[2]->x3 - this->points[0]->x3; + + // p = d x e2 + double px1 = rx2 * e2x3 - rx3 * e2x2; + double px2 = rx3 * e2x1 - rx1 * e2x3; + double px3 = rx1 * e2x2 - rx2 * e2x1; + + // a = e1 dot p + double a = e1x1 * px1 + e1x2 * px2 + e1x3 * px3; + if (fabs(a) < 1.E-10) + return -1.0; + double f = 1.0 / a; + + // s = o - v0 + double sx1 = x1 - this->points[0]->x1; + double sx2 = x2 - this->points[0]->x2; + double sx3 = x3 - this->points[0]->x3; + + // u = f * ( s dot p) + double u = f * (sx1 * px1 + sx2 * px2 + sx3 * px3); + if (u < -1.E-10 || u > 1.0 + 1.E-10) + return -1.0; + + // q = s x e1 + double qx1 = sx2 * e1x3 - sx3 * e1x2; + double qx2 = sx3 * e1x1 - sx1 * e1x3; + double qx3 = sx1 * e1x2 - sx2 * e1x1; + + // v = f*(e2 dot q) + double v = f * (rx1 * qx1 + rx2 * qx2 + rx3 * qx3); + if (v < -1.E-10 || (u + v) > 1.0 + 1.E-10) + return -1.0; + + // t = f * (e2 dot q) + return f * (e2x1 * qx1 + e2x2 * qx2 + e2x3 * qx3); } /*===========================================================*/ -GbLine3D* GbTriangle3D::createClippedLine3D(GbPoint3D& point1, GbPoint3D& point2) +GbLine3D *GbTriangle3D::createClippedLine3D(GbPoint3D &point1, GbPoint3D &point2) { - GbPoint3D *result = this->calculateIntersectionPoints3D(&point1, &point2); - if(!result) return NULL; + GbPoint3D *result = this->calculateIntersectionPoints3D(&point1, &point2); + if (!result) + return NULL; - return new GbLine3D(result, new GbPoint3D(point2)); + return new GbLine3D(result, new GbPoint3D(point2)); - //return GbSystem::createClipLine3D(point1, point2, - //p1->getX1Coordinate(),p1->getX2Coordinate(),p1->getX3Coordinate(), - //p2->getX1Coordinate(),p2->getX2Coordinate(),p2->getX3Coordinate() ); + // return GbSystem::createClipLine3D(point1, point2, + // p1->getX1Coordinate(),p1->getX2Coordinate(),p1->getX3Coordinate(), + // p2->getX1Coordinate(),p2->getX2Coordinate(),p2->getX3Coordinate() ); } -//von Navodit ... +// von Navodit ... /*===========================================================*/ -GbPoint3D* GbTriangle3D::calculateIntersectionPoints3D(GbLine3D* line) +GbPoint3D *GbTriangle3D::calculateIntersectionPoints3D(GbLine3D *line) { - return this->calculateIntersectionPoints3D(line->getPoint1(), line->getPoint2()); + return this->calculateIntersectionPoints3D(line->getPoint1(), line->getPoint2()); } /*===========================================================*/ -GbPoint3D* GbTriangle3D::calculateIntersectionPoints3D(GbPoint3D* linePoint1, GbPoint3D* linePoint2) +GbPoint3D *GbTriangle3D::calculateIntersectionPoints3D(GbPoint3D *linePoint1, GbPoint3D *linePoint2) { - GbVector3D Point1(linePoint1->x1, linePoint1->x2, linePoint1->x3); - GbVector3D Point2(linePoint2->x1, linePoint2->x2, linePoint2->x3); - GbVector3D direction = Point2-Point1; - GbVector3D GbPoint3D1(this->getPoint1()->x1,this->getPoint1()->x2,this->getPoint1()->x3); - GbVector3D GbPoint3D2(this->getPoint2()->x1,this->getPoint2()->x2,this->getPoint2()->x3); - GbVector3D GbPoint3D3(this->getPoint3()->x1,this->getPoint3()->x2,this->getPoint3()->x3); - GbVector3D V2V1 = GbPoint3D2-GbPoint3D1; - GbVector3D V3V1 = GbPoint3D3-GbPoint3D1; - GbVector3D V2V1V3V1 = V2V1.Cross(V3V1); - V2V1V3V1.Normalize(); - GbVector3D Normal = V2V1V3V1; - - double d = -Normal.Dot(GbPoint3D1); - double denom = Normal.Dot(direction); - - if (UbMath::zero(denom)) return NULL; //line does not intersect the plane of the triangle ! - else - { - double mu = -1.*(d + Point1.Dot(Normal))/denom; //mu = -(d+ Normal.Point1)/denom - - // GbVector3D p1 = Point2-Point1; - // GbVector3D p2 = p1*mu; - // GbVector3D p3 = Point1+p2; - GbVector3D point = Point1 + mu*(Point2 -Point1); - - if (mu<0.0 || mu>1.0) return NULL; // Point of intersection of line and plane does not lie on the triangle - else - { - //Test whether Point lies inside the triangle or not - bool test=true; - GbVector3D a = GbPoint3D1-point; - GbVector3D b = GbPoint3D2-point; - GbVector3D c = GbPoint3D3-point; - GbVector3D ab = a.Cross(b); - GbVector3D bc = b.Cross(c); - GbVector3D ca = c.Cross(a); - GbVector3D Q1 = ab*0.5; - GbVector3D Q2 = bc*0.5; - GbVector3D Q3 = ca*0.5; - GbVector3D Q1Q2 = Q1+Q2; - GbVector3D Q = Q1Q2+Q3; - - if (UbMath::less(Q.Dot(Q1), 0.0)) test = false; - if (UbMath::less(Q.Dot(Q2), 0.0)) test = false; - if (UbMath::less(Q.Dot(Q3), 0.0)) test = false; - - if (test == true) return (new GbPoint3D(point.X1(), point.X2(), point.X3())); - else return NULL; - } - } + GbVector3D Point1(linePoint1->x1, linePoint1->x2, linePoint1->x3); + GbVector3D Point2(linePoint2->x1, linePoint2->x2, linePoint2->x3); + GbVector3D direction = Point2 - Point1; + GbVector3D GbPoint3D1(this->getPoint1()->x1, this->getPoint1()->x2, this->getPoint1()->x3); + GbVector3D GbPoint3D2(this->getPoint2()->x1, this->getPoint2()->x2, this->getPoint2()->x3); + GbVector3D GbPoint3D3(this->getPoint3()->x1, this->getPoint3()->x2, this->getPoint3()->x3); + GbVector3D V2V1 = GbPoint3D2 - GbPoint3D1; + GbVector3D V3V1 = GbPoint3D3 - GbPoint3D1; + GbVector3D V2V1V3V1 = V2V1.Cross(V3V1); + V2V1V3V1.Normalize(); + GbVector3D Normal = V2V1V3V1; + + double d = -Normal.Dot(GbPoint3D1); + double denom = Normal.Dot(direction); + + if (UbMath::zero(denom)) + return NULL; // line does not intersect the plane of the triangle ! + else { + double mu = -1. * (d + Point1.Dot(Normal)) / denom; // mu = -(d+ Normal.Point1)/denom + + // GbVector3D p1 = Point2-Point1; + // GbVector3D p2 = p1*mu; + // GbVector3D p3 = Point1+p2; + GbVector3D point = Point1 + mu * (Point2 - Point1); + + if (mu < 0.0 || mu > 1.0) + return NULL; // Point of intersection of line and plane does not lie on the triangle + else { + // Test whether Point lies inside the triangle or not + bool test = true; + GbVector3D a = GbPoint3D1 - point; + GbVector3D b = GbPoint3D2 - point; + GbVector3D c = GbPoint3D3 - point; + GbVector3D ab = a.Cross(b); + GbVector3D bc = b.Cross(c); + GbVector3D ca = c.Cross(a); + GbVector3D Q1 = ab * 0.5; + GbVector3D Q2 = bc * 0.5; + GbVector3D Q3 = ca * 0.5; + GbVector3D Q1Q2 = Q1 + Q2; + GbVector3D Q = Q1Q2 + Q3; + + if (UbMath::less(Q.Dot(Q1), 0.0)) + test = false; + if (UbMath::less(Q.Dot(Q2), 0.0)) + test = false; + if (UbMath::less(Q.Dot(Q3), 0.0)) + test = false; + + if (test == true) + return (new GbPoint3D(point.X1(), point.X2(), point.X3())); + else + return NULL; + } + } } /** -* Returns the distance between the 3D triangle and the specified 3D Point -* @param point the 3D point from whom the distance is to be calculated -* @return the distance of the specified point from the triangle -*/ -double GbTriangle3D::calculateDistanceToPoint3D(GbPoint3D *point) + * Returns the distance between the 3D triangle and the specified 3D Point + * @param point the 3D point from whom the distance is to be calculated + * @return the distance of the specified point from the triangle + */ +double GbTriangle3D::calculateDistanceToPoint3D(GbPoint3D *point) { - return this->calculateDistanceToPoint3D(point->x1, point->x2, point->x3); + return this->calculateDistanceToPoint3D(point->x1, point->x2, point->x3); } /*=======================================================================*/ -double GbTriangle3D::calculateDistanceToPoint3D(const double& x1, const double& x2, const double& x3) +double GbTriangle3D::calculateDistanceToPoint3D(const double &x1, const double &x2, const double &x3) { - // - //throw UbException(UB_EXARGS,"Ich glaub GbTriangle3D::calculateDistanceToPoint3D(...) kann man so nicht nehmen,jedenfalls nicht fuer die q's"); - cout<<"??? ch glaub GbTriangle3D::calculateDistanceToPoint3D(...) kann man so nicht nehmen,jedenfalls nicht fuer die q's"<<endl; - GbVector3D P0(x1, x2, x3); - GbVector3D P1(this->points[0]->x1, this->points[0]->x2, this->points[0]->x3); - GbVector3D P2(this->points[1]->x1, this->points[1]->x2, this->points[1]->x3); - GbVector3D P3(this->points[2]->x1, this->points[2]->x2, this->points[2]->x3); - - //Determine normal to triangle - GbVector3D Normal = (P1-P2).Cross(P1-P3); - double alpha = UbMath::ACos((P1-P0).Dot(Normal)/((P1-P0).Length()*Normal.Length())); - - double P0P0dash = (P0-P1).Length()*cos(alpha); - Normal.Normalize(); - GbVector3D Projection = Normal*(-P0P0dash); - - GbVector3D P0dash = P0+Projection; - - //Check if point P0dash lies within the triangle P1P2P3. - bool test = false; - if ( ((P1-P0).Cross(P2-P0)).Dot(Normal) > 0 ) test = true; - if ( ((P2-P0).Cross(P3-P0)).Dot(Normal) > 0 ) test = true; - if ( ((P3-P0).Cross(P1-P0)).Dot(Normal) > 0 ) test = true; - - if (test == true) return (P0-P0dash).Length(); - else - // Determine the distance of point P0 from all edges and vertices and return the minimum distance - { - double dP0P1 = (P0-P1).Length(); //Distance of Point P0 from Point P1 - double dP0P2 = (P0-P2).Length(); //Distance of Point P0 from Point P2 - double dP0P3 = (P0-P3).Length(); //Distance of Point P0 from Point P3 - - GbVector3D MP1P2 = P2-P1; //Direction vector for line P1P2 - GbVector3D MP2P3 = P3-P2; //Direction vector for line P2P3 - GbVector3D MP3P1 = P1-P3; //Direction vector for line P3P1 - - double tP1P2 = MP1P2.Dot(P0-P1) / MP1P2.Dot(MP1P2); - double tP2P3 = MP2P3.Dot(P0-P2) / MP2P3.Dot(MP2P3); - double tP3P1 = MP3P1.Dot(P0-P3) / MP3P1.Dot(MP3P1); - - double dP1P2 = (P0-(P1+(MP1P2*tP1P2))).Length(); //Distance of Point P0 from line P1P2 - double dP2P3 = (P0-(P2+(MP2P3*tP2P3))).Length(); //Distance of Point P0 from line P2P3 - double dP3P1 = (P0-(P3+(MP3P1*tP3P1))).Length(); //Distance of Point P0 from line P3P1 - - double distanceP0[6]; //Array to store all the distances from Point P0 - distanceP0[0] = dP0P1; - distanceP0[1] = dP0P2; - distanceP0[2] = dP0P3; - distanceP0[3] = dP1P2; - distanceP0[4] = dP2P3; - distanceP0[5] = dP3P1; - - double d = 0.0; - //Find the minimum distance from Point P0 - for (int i=0; i<6; i++) - { - if(distanceP0[i]<d) d = distanceP0[i]; - } - return d; - } + // + // throw UbException(UB_EXARGS,"Ich glaub GbTriangle3D::calculateDistanceToPoint3D(...) kann man so nicht + // nehmen,jedenfalls nicht fuer die q's"); + cout << "??? ch glaub GbTriangle3D::calculateDistanceToPoint3D(...) kann man so nicht nehmen,jedenfalls nicht fuer " + "die q's" + << endl; + GbVector3D P0(x1, x2, x3); + GbVector3D P1(this->points[0]->x1, this->points[0]->x2, this->points[0]->x3); + GbVector3D P2(this->points[1]->x1, this->points[1]->x2, this->points[1]->x3); + GbVector3D P3(this->points[2]->x1, this->points[2]->x2, this->points[2]->x3); + + // Determine normal to triangle + GbVector3D Normal = (P1 - P2).Cross(P1 - P3); + double alpha = UbMath::ACos((P1 - P0).Dot(Normal) / ((P1 - P0).Length() * Normal.Length())); + + double P0P0dash = (P0 - P1).Length() * cos(alpha); + Normal.Normalize(); + GbVector3D Projection = Normal * (-P0P0dash); + + GbVector3D P0dash = P0 + Projection; + + // Check if point P0dash lies within the triangle P1P2P3. + bool test = false; + if (((P1 - P0).Cross(P2 - P0)).Dot(Normal) > 0) + test = true; + if (((P2 - P0).Cross(P3 - P0)).Dot(Normal) > 0) + test = true; + if (((P3 - P0).Cross(P1 - P0)).Dot(Normal) > 0) + test = true; + + if (test == true) + return (P0 - P0dash).Length(); + else + // Determine the distance of point P0 from all edges and vertices and return the minimum distance + { + double dP0P1 = (P0 - P1).Length(); // Distance of Point P0 from Point P1 + double dP0P2 = (P0 - P2).Length(); // Distance of Point P0 from Point P2 + double dP0P3 = (P0 - P3).Length(); // Distance of Point P0 from Point P3 + + GbVector3D MP1P2 = P2 - P1; // Direction vector for line P1P2 + GbVector3D MP2P3 = P3 - P2; // Direction vector for line P2P3 + GbVector3D MP3P1 = P1 - P3; // Direction vector for line P3P1 + + double tP1P2 = MP1P2.Dot(P0 - P1) / MP1P2.Dot(MP1P2); + double tP2P3 = MP2P3.Dot(P0 - P2) / MP2P3.Dot(MP2P3); + double tP3P1 = MP3P1.Dot(P0 - P3) / MP3P1.Dot(MP3P1); + + double dP1P2 = (P0 - (P1 + (MP1P2 * tP1P2))).Length(); // Distance of Point P0 from line P1P2 + double dP2P3 = (P0 - (P2 + (MP2P3 * tP2P3))).Length(); // Distance of Point P0 from line P2P3 + double dP3P1 = (P0 - (P3 + (MP3P1 * tP3P1))).Length(); // Distance of Point P0 from line P3P1 + + double distanceP0[6]; // Array to store all the distances from Point P0 + distanceP0[0] = dP0P1; + distanceP0[1] = dP0P2; + distanceP0[2] = dP0P3; + distanceP0[3] = dP1P2; + distanceP0[4] = dP2P3; + distanceP0[5] = dP3P1; + + double d = 0.0; + // Find the minimum distance from Point P0 + for (int i = 0; i < 6; i++) { + if (distanceP0[i] < d) + d = distanceP0[i]; + } + return d; + } } /** -* Returns the normalized distance between the 3D triangle and the specified 3D Point -* copied from Benjamin A. -* @param point the 3D point from whom the distance is to be calculated -* @return the distance of the specified point from the triangle -*/ -double GbTriangle3D::calculateNormalizedDistanceToPoint3D(const double& x1, const double& y1, const double& z1, - const double& x2, const double& y2, const double& z2) + * Returns the normalized distance between the 3D triangle and the specified 3D Point + * copied from Benjamin A. + * @param point the 3D point from whom the distance is to be calculated + * @return the distance of the specified point from the triangle + */ +double GbTriangle3D::calculateNormalizedDistanceToPoint3D(const double &x1, const double &y1, const double &z1, + const double &x2, const double &y2, const double &z2) { - //face* pf + // face* pf double xa, xb, xc, ya, yb, yc, za, zb, zc; - //double xp, yp, zp; - double tt=0, xi=0, eta=0; + // double xp, yp, zp; + double tt = 0, xi = 0, eta = 0; double zaehler, nenner; double wurzel3 = sqrt(3.); - //Weltkoordinaten der Dreiecke + // Weltkoordinaten der Dreiecke xa = this->points[0]->x1; xb = this->points[1]->x1; xc = this->points[2]->x1; - + ya = this->points[0]->x2; yb = this->points[1]->x2; yc = this->points[2]->x2; @@ -521,164 +563,185 @@ double GbTriangle3D::calculateNormalizedDistanceToPoint3D(const double& x1, cons zb = this->points[1]->x3; zc = this->points[2]->x3; - //Shape-Funktionen zum Berechnen der Schnittpunkte - zaehler = - static_cast<double>(((-1.0*zc+zb)*ya+(yc-1.0*yb)*za+zc*yb-1.0*zb*yc)*x1 - +((-1.0*zb+zc)*xa+(xb-1.0*xc)*za-1.0*xb*zc+xc*zb)*y1+((-1.0*yc+yb)*xa - +(-1.0*xb+xc)*ya-1.0*xc*yb+xb*yc)*z1+((-1.0*zc+zb)*ya+(yc-1.0*yb)*za - +zc*yb-1.0*zb*yc)*x2+((-1.0*zb+zc)*xa+(xb-1.0*xc)*za-1.0*xb*zc+xc*zb)*y2 - +((-1.0*yc+yb)*xa+(-1.0*xb+xc)*ya-1.0*xc*yb+xb*yc)*z2+(2.0*zb*yc-2.0*zc*yb)*xa - +(2.0*xb*zc-2.0*xc*zb)*ya+(-2.0*xb*yc+2.0*xc*yb)*za); - nenner = - static_cast<double>((((-1.0*zc+zb)*ya+(yc-1.0*yb)*za+zc*yb-1.0*zb*yc)*x1 - +((-1.0*zb+zc)*xa+(xb-1.0*xc)*za-1.0*xb*zc+xc*zb)*y1+((-1.0*yc+yb)*xa - +(-1.0*xb+xc)*ya-1.0*xc*yb+xb*yc)*z1+((-1.0*zb+zc)*ya+(-1.0*yc+yb)*za-1.0*zc*yb+zb*yc) - *x2+((-1.0*zc+zb)*xa+(-1.0*xb+xc)*za+xb*zc-1.0*xc*zb)*y2+((yc-1.0*yb)*xa+(xb - -1.0*xc)*ya+xc*yb-1.0*xb*yc)*z2)); - if( UbMath::greater(nenner, 0.0) ) tt = zaehler/nenner; - else tt=-999.; - - zaehler = - static_cast<double>(((-2.0*zc+za+zb)*y2+(-1.0*yb-1.0*ya+2.0*yc)*z2+zc*ya - -1.0*zb*yc+zc*yb-1.0*za*yc)*x1+((-1.0*za+2.0*zc-1.0*zb)*x2+(xa-2.0*xc+xb)*z2 - -1.0*xa*zc-1.0*xb*zc+xc*za+xc*zb)*y1+((-2.0*yc+ya+yb)*x2+(-1.0*xa-1.0*xb+2.0*xc) - *y2-1.0*xc*yb+xa*yc+xb*yc-1.0*xc*ya)*z1+(zb*yc-1.0*zc*ya-1.0*zc*yb+za*yc) - *x2+(-1.0*xc*za+xb*zc+xa*zc-1.0*xc*zb)*y2+(xc*yb-1.0*xa*yc-1.0*xb*yc+xc*ya)*z2); - nenner = - static_cast<double>((((zc-1.0*zb)*ya+(yb-1.0*yc)*za+zb*yc-1.0*zc*yb)*x1 - +((zb-1.0*zc)*xa+(xc-1.0*xb)*za-1.0*xc*zb+xb*zc)*y1+((-1.0*yb+yc)*xa+(xb-1.0*xc) - *ya-1.0*xb*yc+xc*yb)*z1+((zb-1.0*zc)*ya+(-1.0*yb+yc)*za+zc*yb-1.0*zb*yc)*x2 - +((zc-1.0*zb)*xa+(xb-1.0*xc)*za-1.0*xb*zc+xc*zb)*y2+((yb-1.0*yc)*xa - +(xc-1.0*xb)*ya+xb*yc-1.0*xc*yb)*z2)); - if( UbMath::greater(nenner, 0.0) ) xi = zaehler/nenner; - else xi=-999.; - - zaehler = - static_cast<double>(((za-1.0*zb)*y2+(-1.0*ya+yb)*z2-1.0*za*yb+zb*ya)*x1+ - ((-1.0*za+zb)*x2+(xa-1.0*xb)*z2-1.0*xa*zb+xb*za)*y1+((ya-1.0*yb)*x2+(xb-1.0*xa) - *y2+xa*yb-1.0*xb*ya)*z1+(-1.0*zb*ya+za*yb)*x2+(-1.0*xb*za+xa*zb)*y2 - +(-1.0*xa*yb+xb*ya)*z2); - nenner = - static_cast<double>((((zc-1.0*zb)*ya+(yb-1.0*yc)*za+zb*yc-1.0*zc*yb)*x1 - +((zb-1.0*zc)*xa+(xc-1.0*xb)*za-1.0*xc*zb+xb*zc)*y1+((-1.0*yb+yc)*xa+(xb-1.0*xc) - *ya-1.0*xb*yc+xc*yb)*z1+((zb-1.0*zc)*ya+(-1.0*yb+yc)*za+zc*yb-1.0*zb*yc)*x2 - +((zc-1.0*zb)*xa+(xb-1.0*xc)*za-1.0*xb*zc+xc*zb)*y2+((yb-1.0*yc)*xa+(xc-1.0*xb) - *ya+xb*yc-1.0*xc*yb)*z2)); - if ( UbMath::greater(nenner, 0.0) ) eta = static_cast<double>((zaehler/nenner)*wurzel3*-1.); - else eta=-999.; - - if (tt >= -1.0-UbMath::Epsilon<double>::val() && tt <= 1.0){ - if(xi >= -1.0+eta/wurzel3-UbMath::Epsilon<double>::val() && xi <= - 1.0-eta/wurzel3+UbMath::Epsilon<double>::val()){ - if (eta >= 0-UbMath::Epsilon<double>::val() && eta <= wurzel3+UbMath::Epsilon<double>::val()){ + // Shape-Funktionen zum Berechnen der Schnittpunkte + zaehler = static_cast<double>(((-1.0 * zc + zb) * ya + (yc - 1.0 * yb) * za + zc * yb - 1.0 * zb * yc) * x1 + + ((-1.0 * zb + zc) * xa + (xb - 1.0 * xc) * za - 1.0 * xb * zc + xc * zb) * y1 + + ((-1.0 * yc + yb) * xa + (-1.0 * xb + xc) * ya - 1.0 * xc * yb + xb * yc) * z1 + + ((-1.0 * zc + zb) * ya + (yc - 1.0 * yb) * za + zc * yb - 1.0 * zb * yc) * x2 + + ((-1.0 * zb + zc) * xa + (xb - 1.0 * xc) * za - 1.0 * xb * zc + xc * zb) * y2 + + ((-1.0 * yc + yb) * xa + (-1.0 * xb + xc) * ya - 1.0 * xc * yb + xb * yc) * z2 + + (2.0 * zb * yc - 2.0 * zc * yb) * xa + (2.0 * xb * zc - 2.0 * xc * zb) * ya + + (-2.0 * xb * yc + 2.0 * xc * yb) * za); + nenner = static_cast<double>((((-1.0 * zc + zb) * ya + (yc - 1.0 * yb) * za + zc * yb - 1.0 * zb * yc) * x1 + + ((-1.0 * zb + zc) * xa + (xb - 1.0 * xc) * za - 1.0 * xb * zc + xc * zb) * y1 + + ((-1.0 * yc + yb) * xa + (-1.0 * xb + xc) * ya - 1.0 * xc * yb + xb * yc) * z1 + + ((-1.0 * zb + zc) * ya + (-1.0 * yc + yb) * za - 1.0 * zc * yb + zb * yc) * x2 + + ((-1.0 * zc + zb) * xa + (-1.0 * xb + xc) * za + xb * zc - 1.0 * xc * zb) * y2 + + ((yc - 1.0 * yb) * xa + (xb - 1.0 * xc) * ya + xc * yb - 1.0 * xb * yc) * z2)); + if (UbMath::greater(nenner, 0.0)) + tt = zaehler / nenner; + else + tt = -999.; + + zaehler = static_cast<double>(((-2.0 * zc + za + zb) * y2 + (-1.0 * yb - 1.0 * ya + 2.0 * yc) * z2 + zc * ya - + 1.0 * zb * yc + zc * yb - 1.0 * za * yc) * + x1 + + ((-1.0 * za + 2.0 * zc - 1.0 * zb) * x2 + (xa - 2.0 * xc + xb) * z2 - 1.0 * xa * zc - + 1.0 * xb * zc + xc * za + xc * zb) * + y1 + + ((-2.0 * yc + ya + yb) * x2 + (-1.0 * xa - 1.0 * xb + 2.0 * xc) * y2 - 1.0 * xc * yb + + xa * yc + xb * yc - 1.0 * xc * ya) * + z1 + + (zb * yc - 1.0 * zc * ya - 1.0 * zc * yb + za * yc) * x2 + + (-1.0 * xc * za + xb * zc + xa * zc - 1.0 * xc * zb) * y2 + + (xc * yb - 1.0 * xa * yc - 1.0 * xb * yc + xc * ya) * z2); + nenner = static_cast<double>((((zc - 1.0 * zb) * ya + (yb - 1.0 * yc) * za + zb * yc - 1.0 * zc * yb) * x1 + + ((zb - 1.0 * zc) * xa + (xc - 1.0 * xb) * za - 1.0 * xc * zb + xb * zc) * y1 + + ((-1.0 * yb + yc) * xa + (xb - 1.0 * xc) * ya - 1.0 * xb * yc + xc * yb) * z1 + + ((zb - 1.0 * zc) * ya + (-1.0 * yb + yc) * za + zc * yb - 1.0 * zb * yc) * x2 + + ((zc - 1.0 * zb) * xa + (xb - 1.0 * xc) * za - 1.0 * xb * zc + xc * zb) * y2 + + ((yb - 1.0 * yc) * xa + (xc - 1.0 * xb) * ya + xb * yc - 1.0 * xc * yb) * z2)); + if (UbMath::greater(nenner, 0.0)) + xi = zaehler / nenner; + else + xi = -999.; + + zaehler = static_cast<double>(((za - 1.0 * zb) * y2 + (-1.0 * ya + yb) * z2 - 1.0 * za * yb + zb * ya) * x1 + + ((-1.0 * za + zb) * x2 + (xa - 1.0 * xb) * z2 - 1.0 * xa * zb + xb * za) * y1 + + ((ya - 1.0 * yb) * x2 + (xb - 1.0 * xa) * y2 + xa * yb - 1.0 * xb * ya) * z1 + + (-1.0 * zb * ya + za * yb) * x2 + (-1.0 * xb * za + xa * zb) * y2 + + (-1.0 * xa * yb + xb * ya) * z2); + nenner = static_cast<double>((((zc - 1.0 * zb) * ya + (yb - 1.0 * yc) * za + zb * yc - 1.0 * zc * yb) * x1 + + ((zb - 1.0 * zc) * xa + (xc - 1.0 * xb) * za - 1.0 * xc * zb + xb * zc) * y1 + + ((-1.0 * yb + yc) * xa + (xb - 1.0 * xc) * ya - 1.0 * xb * yc + xc * yb) * z1 + + ((zb - 1.0 * zc) * ya + (-1.0 * yb + yc) * za + zc * yb - 1.0 * zb * yc) * x2 + + ((zc - 1.0 * zb) * xa + (xb - 1.0 * xc) * za - 1.0 * xb * zc + xc * zb) * y2 + + ((yb - 1.0 * yc) * xa + (xc - 1.0 * xb) * ya + xb * yc - 1.0 * xc * yb) * z2)); + if (UbMath::greater(nenner, 0.0)) + eta = static_cast<double>((zaehler / nenner) * wurzel3 * -1.); + else + eta = -999.; + + if (tt >= -1.0 - UbMath::Epsilon<double>::val() && tt <= 1.0) { + if (xi >= -1.0 + eta / wurzel3 - UbMath::Epsilon<double>::val() && + xi <= 1.0 - eta / wurzel3 + UbMath::Epsilon<double>::val()) { + if (eta >= 0 - UbMath::Epsilon<double>::val() && eta <= wurzel3 + UbMath::Epsilon<double>::val()) { /*xp = x1*(0.5-tt/2)+x2*(0.5+tt/2); yp = y1*(0.5-tt/2)+y2*(0.5+tt/2); zp = z1*(0.5-tt/2)+z2*(0.5+tt/2);*/ - return - static_cast<double>((sqrt(pow((x1*(0.5-tt/2)+x2*(0.5+tt/2))-x1,2) - +pow((y1*(0.5-tt/2)+y2*(0.5+tt/2))-y1,2)+pow((z1*(0.5-tt/2)+z2*(0.5+tt/2))-z1,2)))); - } - } + return static_cast<double>((sqrt(pow((x1 * (0.5 - tt / 2) + x2 * (0.5 + tt / 2)) - x1, 2) + + pow((y1 * (0.5 - tt / 2) + y2 * (0.5 + tt / 2)) - y1, 2) + + pow((z1 * (0.5 - tt / 2) + z2 * (0.5 + tt / 2)) - z1, 2)))); + } + } } return (-999.); } /* -* Returns true if the specified 2D point lies within (or on the border of) this 2D triangle. -* @param point the 2D point to check -* @return true if the specified 2D point lies within (or on the border of) this 2D triangle -*/ - bool GbTriangle3D::enclosesPoint2D(double x1, double x2) - { - int i=0; - //Punkt(x1,x2) liegt auf einem der Eckpunkte - if(x1==this->getPoint(0)->getX1Coordinate() && x2 == this->getPoint(0)->getX2Coordinate()) return true; - if(x1==this->getPoint(1)->getX1Coordinate() && x2 == this->getPoint(1)->getX2Coordinate()) return true; - if(x1==this->getPoint(2)->getX1Coordinate() && x2 == this->getPoint(2)->getX2Coordinate()) return true; - - //Erste Grade aus dem zu pruefenden Punkt(x,y) und einem zweiten Punkt(x+0.333,y+2.333) - GbPoint3D p1; p1.setX1(x1); p1.setX2(x2); p1.setX3(0.0); - GbPoint3D p2; p2.setX1(x1+0.333); p2.setX2(x2+3.333); p2.setX3(0.0); - //Punkte des Dreiecks auf 2D reduziert - GbPoint3D dp1; dp1.setX1(this->getPoint(0)->getX1Coordinate()); dp1.setX2(this->getPoint(0)->getX2Coordinate()); dp1.setX3(0.0); - GbPoint3D dp2; dp2.setX1(this->getPoint(1)->getX1Coordinate()); dp2.setX2(this->getPoint(1)->getX2Coordinate()); dp2.setX3(0.0); - GbPoint3D dp3; dp3.setX1(this->getPoint(2)->getX1Coordinate()); dp3.setX2(this->getPoint(2)->getX2Coordinate()); dp3.setX3(0.0); - //ueberpruefen, ob der Punkt(x,y) innerhalt der Boundingbox des Dreiecks liegt - if( x1<this->getX1Maximum() && x1>getX1Minimum() - && x2<this->getX2Maximum() && x2>getX2Minimum()) - { - GbPoint3D* dummy = NULL; - //ueberpruefen, ob der Punkt innerhalb des Dreiecks liegt - dummy = GbSystem3D::calculateIntersectionPoint3D(p1,p2,dp1,dp2); - if(dummy!=NULL) - { - if(dummy->getX1Coordinate()==p1.getX1Coordinate() && dummy->getX2Coordinate()==p1.getX2Coordinate()) - { - delete dummy; - return true; - } - else if(dummy->getX1Coordinate()>p1.getX1Coordinate()) - { - i++; - } - else - { - i--; - } - } - if(dummy) delete dummy; - - dummy = GbSystem3D::calculateIntersectionPoint3D(p1,p2,dp2,dp3); - if(dummy!=NULL) - { - if(dummy->getX1Coordinate()==p1.getX1Coordinate() && dummy->getX2Coordinate()==p1.getX2Coordinate()) - { - if(dummy) delete dummy; - return true; - } - else if(dummy->getX1Coordinate()>p1.getX1Coordinate()) - { - i++; - } - else - { - i--; - } - } - if(dummy) delete dummy; - - dummy = GbSystem3D::calculateIntersectionPoint3D(p1,p2,dp3,dp1); - if(dummy!=NULL) - { - if(dummy->getX1Coordinate()==p1.getX1Coordinate() && dummy->getX2Coordinate()==p1.getX2Coordinate()) - { - if(dummy) delete dummy; - return true; - } - else if(dummy->getX1Coordinate()>p1.getX1Coordinate()) - { - i++; - } - else - { - i--; - } - } - if(dummy) delete dummy; - } - if(i==-1) return true; - if(i==1 ) return true; - + * Returns true if the specified 2D point lies within (or on the border of) this 2D triangle. + * @param point the 2D point to check + * @return true if the specified 2D point lies within (or on the border of) this 2D triangle + */ +bool GbTriangle3D::enclosesPoint2D(double x1, double x2) +{ + int i = 0; + // Punkt(x1,x2) liegt auf einem der Eckpunkte + if (x1 == this->getPoint(0)->getX1Coordinate() && x2 == this->getPoint(0)->getX2Coordinate()) + return true; + if (x1 == this->getPoint(1)->getX1Coordinate() && x2 == this->getPoint(1)->getX2Coordinate()) + return true; + if (x1 == this->getPoint(2)->getX1Coordinate() && x2 == this->getPoint(2)->getX2Coordinate()) + return true; + + // Erste Grade aus dem zu pruefenden Punkt(x,y) und einem zweiten Punkt(x+0.333,y+2.333) + GbPoint3D p1; + p1.setX1(x1); + p1.setX2(x2); + p1.setX3(0.0); + GbPoint3D p2; + p2.setX1(x1 + 0.333); + p2.setX2(x2 + 3.333); + p2.setX3(0.0); + // Punkte des Dreiecks auf 2D reduziert + GbPoint3D dp1; + dp1.setX1(this->getPoint(0)->getX1Coordinate()); + dp1.setX2(this->getPoint(0)->getX2Coordinate()); + dp1.setX3(0.0); + GbPoint3D dp2; + dp2.setX1(this->getPoint(1)->getX1Coordinate()); + dp2.setX2(this->getPoint(1)->getX2Coordinate()); + dp2.setX3(0.0); + GbPoint3D dp3; + dp3.setX1(this->getPoint(2)->getX1Coordinate()); + dp3.setX2(this->getPoint(2)->getX2Coordinate()); + dp3.setX3(0.0); + // ueberpruefen, ob der Punkt(x,y) innerhalt der Boundingbox des Dreiecks liegt + if (x1 < this->getX1Maximum() && x1 > getX1Minimum() && x2 < this->getX2Maximum() && x2 > getX2Minimum()) { + GbPoint3D *dummy = NULL; + // ueberpruefen, ob der Punkt innerhalb des Dreiecks liegt + dummy = GbSystem3D::calculateIntersectionPoint3D(p1, p2, dp1, dp2); + if (dummy != NULL) { + if (dummy->getX1Coordinate() == p1.getX1Coordinate() && dummy->getX2Coordinate() == p1.getX2Coordinate()) { + delete dummy; + return true; + } else if (dummy->getX1Coordinate() > p1.getX1Coordinate()) { + i++; + } else { + i--; + } + } + if (dummy) + delete dummy; + + dummy = GbSystem3D::calculateIntersectionPoint3D(p1, p2, dp2, dp3); + if (dummy != NULL) { + if (dummy->getX1Coordinate() == p1.getX1Coordinate() && dummy->getX2Coordinate() == p1.getX2Coordinate()) { + if (dummy) + delete dummy; + return true; + } else if (dummy->getX1Coordinate() > p1.getX1Coordinate()) { + i++; + } else { + i--; + } + } + if (dummy) + delete dummy; + + dummy = GbSystem3D::calculateIntersectionPoint3D(p1, p2, dp3, dp1); + if (dummy != NULL) { + if (dummy->getX1Coordinate() == p1.getX1Coordinate() && dummy->getX2Coordinate() == p1.getX2Coordinate()) { + if (dummy) + delete dummy; + return true; + } else if (dummy->getX1Coordinate() > p1.getX1Coordinate()) { + i++; + } else { + i--; + } + } + if (dummy) + delete dummy; + } + if (i == -1) + return true; + if (i == 1) + return true; + return false; - } +} ///* //* Returns a new 2D polygon clipped by the specified 2D rectangle (result may be null!). //* @param rectangle the 2D rectangle //* @return a new 2D polygon clipped by the specified 2D rectangle //*/ -GbPolygon3D* GbTriangle3D::createClippedPolygon3D(GbCuboid3D* cube) +GbPolygon3D *GbTriangle3D::createClippedPolygon3D(GbCuboid3D *cube) { - return(GbSystem3D::clipPolygon3D(this->getPoints(), cube->getPoint1()->getX1Coordinate(), cube->getPoint1()->getX2Coordinate(), cube->getPoint1()->getX3Coordinate(), cube->getPoint2()->getX1Coordinate(), cube->getPoint2()->getX2Coordinate(), cube->getPoint2()->getX3Coordinate())); + return (GbSystem3D::clipPolygon3D(this->getPoints(), cube->getPoint1()->getX1Coordinate(), + cube->getPoint1()->getX2Coordinate(), cube->getPoint1()->getX3Coordinate(), + cube->getPoint2()->getX1Coordinate(), cube->getPoint2()->getX2Coordinate(), + cube->getPoint2()->getX3Coordinate())); } ///* //* Returns a new 2D polygon clipped by the specified 2D rectangle (result may be null!). @@ -686,445 +749,400 @@ GbPolygon3D* GbTriangle3D::createClippedPolygon3D(GbCuboid3D* cube) //* @param p2 the 2nd point of the rectangle //* @return a new 2D polygon clipped by the specified 2D rectangle //*/ -//public GbPolygon2D createClippedPolygon2D(GbPoint2D p1, GbPoint2D p2) +// public GbPolygon2D createClippedPolygon2D(GbPoint2D p1, GbPoint2D p2) //{ // return(GbSystem.clipPolygon2D(this.points, p1.x1, p1.x2, p2.x1, p2.x2)); //} /* -* Returns a new 2D polygon clipped by the specified 2D rectangle (result may be null!). -* @param p1x1 the 1st x1 coordinate of the rectangle -* @param p1x2 the 1st x2 coordinate of the rectangle -* @param p2x1 the 2nd x1 coordinate of the rectangle -* @param p2x2 the 2nd x2 coordinate of the rectangle -* @return a new 2D polygon clipped by the specified 2D rectangle -*/ -GbPolygon3D* GbTriangle3D::createClippedPolygon3D(const double& p1x1, const double& p1x2, const double& p1x3, const double& p2x1, const double& p2x2, const double& p2x3) + * Returns a new 2D polygon clipped by the specified 2D rectangle (result may be null!). + * @param p1x1 the 1st x1 coordinate of the rectangle + * @param p1x2 the 1st x2 coordinate of the rectangle + * @param p2x1 the 2nd x1 coordinate of the rectangle + * @param p2x2 the 2nd x2 coordinate of the rectangle + * @return a new 2D polygon clipped by the specified 2D rectangle + */ +GbPolygon3D *GbTriangle3D::createClippedPolygon3D(const double &p1x1, const double &p1x2, const double &p1x3, + const double &p2x1, const double &p2x2, const double &p2x3) { - return(GbSystem3D::clipPolygon3D(this->getPoints(), p1x1, p1x2, p1x3, p2x1, p2x2, p2x3)); + return (GbSystem3D::clipPolygon3D(this->getPoints(), p1x1, p1x2, p1x3, p2x1, p2x2, p2x3)); } /* -* Returns true if the specified 2D rectangle lies completely within this 2D triangle. -* @param rectangle the 2D rectangle to check -* @return true if the specified 2D rectangle lies completely within this 2D triangle -*/ -//bool enclosesRectangle2D(GbRectangle2D *rectangle) + * Returns true if the specified 2D rectangle lies completely within this 2D triangle. + * @param rectangle the 2D rectangle to check + * @return true if the specified 2D rectangle lies completely within this 2D triangle + */ +// bool enclosesRectangle2D(GbRectangle2D *rectangle) //{ -// GbPolygon2D p = GbSystem.clipPolygon2D(this.points, rectangle.p1.x1, rectangle.p1.x2, rectangle.p2.x1, rectangle.p2.x2); -// return(p!=null && GbSystem.equal(Math.abs(p.getArea()), rectangle.getArea())); +// GbPolygon2D p = GbSystem.clipPolygon2D(this.points, rectangle.p1.x1, rectangle.p1.x2, rectangle.p2.x1, +// rectangle.p2.x2); return(p!=null && GbSystem.equal(Math.abs(p.getArea()), rectangle.getArea())); //} /* -* Returns true if the specified 2D rectangle lies completely within this 2D triangle. -* @param p1 the 1st point of the rectangle to check -* @param p2 the 2nd point of the rectangle to check triangle -* @return true if the specified 2D rectangle lies completely within this 2D -*/ -//public boolean enclosesRectangle2D(GbPoint2D p1, GbPoint2D p2) + * Returns true if the specified 2D rectangle lies completely within this 2D triangle. + * @param p1 the 1st point of the rectangle to check + * @param p2 the 2nd point of the rectangle to check triangle + * @return true if the specified 2D rectangle lies completely within this 2D + */ +// public boolean enclosesRectangle2D(GbPoint2D p1, GbPoint2D p2) //{ // GbPolygon2D p = GbSystem.clipPolygon2D(this.points, p1.x1, p1.x2, p2.x1, p2.x2); // return(p!=null && GbSystem.equal(Math.abs(p.getArea()), Math.abs((p1.x1-p2.x1)*(p1.x2-p2.x2)))); //} /* -* Returns true if the specified 2D rectangle lies completely within this 2D triangle. -* @param p1x1 the 1st x1 coordinate of the rectangle to check -* @param p1x2 the 1st x2 coordinate of the rectangle to check -* @param p2x1 the 2nd x1 coordinate of the rectangle to check -* @param p2x2 the 2nd x2 coordinate of the rectangle to check -* @return true if the specified 2D rectangle lies completely within this 2D triangle -*/ -//public boolean enclosesRectangle2D(double p1x1, double p1x2, double p2x1, double p2x2) + * Returns true if the specified 2D rectangle lies completely within this 2D triangle. + * @param p1x1 the 1st x1 coordinate of the rectangle to check + * @param p1x2 the 1st x2 coordinate of the rectangle to check + * @param p2x1 the 2nd x1 coordinate of the rectangle to check + * @param p2x2 the 2nd x2 coordinate of the rectangle to check + * @return true if the specified 2D rectangle lies completely within this 2D triangle + */ +// public boolean enclosesRectangle2D(double p1x1, double p1x2, double p2x1, double p2x2) //{ // GbPolygon2D p = GbSystem.clipPolygon2D(this.points, p1x1, p1x2, p2x1, p2x2); // return(p!=null && GbSystem.equal(Math.abs(p.getArea()), Math.abs((p1x1-p2x1)*(p1x2-p2x2)))); //} /* -* Returns true if the specified 2D rectangle is crossed by this 2D triangle. -* @param rectangle the 2D rectangle to check -* @return true if the specified 2D rectangle is crossed by this 2D triangle -*/ -//public boolean crossesRectangle2D(GbRectangle2D rectangle) + * Returns true if the specified 2D rectangle is crossed by this 2D triangle. + * @param rectangle the 2D rectangle to check + * @return true if the specified 2D rectangle is crossed by this 2D triangle + */ +// public boolean crossesRectangle2D(GbRectangle2D rectangle) //{ -// GbPolygon2D p = GbSystem.clipPolygon2D(this.points, rectangle.p1.x1, rectangle.p1.x2, rectangle.p2.x1, rectangle.p2.x2); -// return(p!=null && GbSystem.inOpenInterval(Math.abs(p.getArea()), 0.0, rectangle.getArea())); +// GbPolygon2D p = GbSystem.clipPolygon2D(this.points, rectangle.p1.x1, rectangle.p1.x2, rectangle.p2.x1, +// rectangle.p2.x2); return(p!=null && GbSystem.inOpenInterval(Math.abs(p.getArea()), 0.0, rectangle.getArea())); //} /* -* Returns true if the specified 2D rectangle is crossed by this 2D triangle. -* @param p1 the 1st point of the rectangle to check -* @param p2 the 2nd point of the rectangle to check -* @return true if the specified 2D rectangle is crossed by this 2D triangle -*/ -//public boolean crossesRectangle2D(GbPoint2D p1, GbPoint2D p2) + * Returns true if the specified 2D rectangle is crossed by this 2D triangle. + * @param p1 the 1st point of the rectangle to check + * @param p2 the 2nd point of the rectangle to check + * @return true if the specified 2D rectangle is crossed by this 2D triangle + */ +// public boolean crossesRectangle2D(GbPoint2D p1, GbPoint2D p2) //{ // GbPolygon2D p = GbSystem.clipPolygon2D(this.points, p1.x1, p1.x2, p2.x1, p2.x2); // return(p!=null && GbSystem.inOpenInterval(Math.abs(p.getArea()), 0.0, Math.abs((p1.x1-p2.x1)*(p1.x2-p2.x2)))); //} /* -* Returns true if the specified 2D rectangle is crossed by this 2D triangle. -* @param p1x1 the 1st x1 coordinate of the rectangle to check -* @param p1x2 the 1st x2 coordinate of the rectangle to check -* @param p2x1 the 2nd x1 coordinate of the rectangle to check -* @param p2x2 the 2nd x2 coordinate of the rectangle to check -* @return true if the specified 2D rectangle is crossed by this 2D triangle -*/ -//public boolean crossesRectangle2D(double p1x1, double p1x2, double p2x1, double p2x2) + * Returns true if the specified 2D rectangle is crossed by this 2D triangle. + * @param p1x1 the 1st x1 coordinate of the rectangle to check + * @param p1x2 the 1st x2 coordinate of the rectangle to check + * @param p2x1 the 2nd x1 coordinate of the rectangle to check + * @param p2x2 the 2nd x2 coordinate of the rectangle to check + * @return true if the specified 2D rectangle is crossed by this 2D triangle + */ +// public boolean crossesRectangle2D(double p1x1, double p1x2, double p2x1, double p2x2) //{ // GbPolygon2D p = GbSystem.clipPolygon2D(this.points, p1x1, p1x2, p2x1, p2x2); // return(p!=null && GbSystem.inOpenInterval(Math.abs(p.getArea()), 0.0, Math.abs((p1x1-p2x1)*(p1x2-p2x2)))); //} /* -* Returns true if the specified 2D rectangle lies (at least partly) within this 2D triangle. -* @param rectangle the 2D rectangle to check -* @return true if the specified 2D rectangle lies (at least partly) within this 2D triangle -*/ -//public boolean enclosesOrCrossesRectangle2D(GbRectangle2D rectangle) + * Returns true if the specified 2D rectangle lies (at least partly) within this 2D triangle. + * @param rectangle the 2D rectangle to check + * @return true if the specified 2D rectangle lies (at least partly) within this 2D triangle + */ +// public boolean enclosesOrCrossesRectangle2D(GbRectangle2D rectangle) //{ -// GbPolygon2D p = GbSystem.clipPolygon2D(this.points, rectangle.p1.x1, rectangle.p1.x2, rectangle.p2.x1, rectangle.p2.x2); -// return(p!=null && GbSystem.greater(Math.abs(p.getArea()), 0.0)); +// GbPolygon2D p = GbSystem.clipPolygon2D(this.points, rectangle.p1.x1, rectangle.p1.x2, rectangle.p2.x1, +// rectangle.p2.x2); return(p!=null && GbSystem.greater(Math.abs(p.getArea()), 0.0)); //} /* -* Returns true if the specified 2D rectangle lies (at least partly) within this 2D triangle. -* @param p1 the 1st point of the rectangle to check -* @param p2 the 2nd point of the rectangle to check -* @return true if the specified 2D rectangle lies (at least partly) within this 2D triangle -*/ -//public boolean enclosesOrCrossesRectangle2D(GbPoint2D p1, GbPoint2D p2) + * Returns true if the specified 2D rectangle lies (at least partly) within this 2D triangle. + * @param p1 the 1st point of the rectangle to check + * @param p2 the 2nd point of the rectangle to check + * @return true if the specified 2D rectangle lies (at least partly) within this 2D triangle + */ +// public boolean enclosesOrCrossesRectangle2D(GbPoint2D p1, GbPoint2D p2) //{ // GbPolygon2D p = GbSystem.clipPolygon2D(this.points, p1.x1, p1.x2, p2.x1, p2.x2); // return(p!=null && GbSystem.greater(Math.abs(p.getArea()), 0.0)); //} /* -* Returns true if the specified 2D rectangle lies (at least partly) within this 2D triangle. -* @param p1x1 the 1st x1 coordinate of the rectangle to check -* @param p1x2 the 1st x2 coordinate of the rectangle to check -* @param p2x1 the 2nd x1 coordinate of the rectangle to check -* @param p2x2 the 2nd x2 coordinate of the rectangle to check -* @return true if the specified 2D rectangle lies (at least partly) within this 2D triangle -*/ -//public boolean enclosesOrCrossesRectangle2D(double p1x1, double p1x2, double p2x1, double p2x2) + * Returns true if the specified 2D rectangle lies (at least partly) within this 2D triangle. + * @param p1x1 the 1st x1 coordinate of the rectangle to check + * @param p1x2 the 1st x2 coordinate of the rectangle to check + * @param p2x1 the 2nd x1 coordinate of the rectangle to check + * @param p2x2 the 2nd x2 coordinate of the rectangle to check + * @return true if the specified 2D rectangle lies (at least partly) within this 2D triangle + */ +// public boolean enclosesOrCrossesRectangle2D(double p1x1, double p1x2, double p2x1, double p2x2) //{ // GbPolygon2D p = GbSystem.clipPolygon2D(this.points, p1x1, p1x2, p2x1, p2x2); // return(p!=null && GbSystem.greater(Math.abs(p.getArea()), 0.0)); //} /*======================================================================*/ - /*======================================================================*/ /* Private Methoden */ /* */ void GbTriangle3D::calculateValues() { - this->x1min = this->points[0]->x1; - this->x1max = this->points[0]->x1; - this->x2min = this->points[0]->x2; - this->x2max = this->points[0]->x2; - this->x3min = this->points[0]->x3; - this->x3max = this->points[0]->x3; - - if(this->points[1]->x1 < this->x1min) this->x1min = this->points[1]->x1; - if(this->points[1]->x1 > this->x1max) this->x1max = this->points[1]->x1; - if(this->points[1]->x2 < this->x2min) this->x2min = this->points[1]->x2; - if(this->points[1]->x2 > this->x2max) this->x2max = this->points[1]->x2; - if(this->points[1]->x3 < this->x3min) this->x3min = this->points[1]->x3; - if(this->points[1]->x3 > this->x3max) this->x3max = this->points[1]->x3; - - if(this->points[2]->x1 < this->x1min) this->x1min = this->points[2]->x1; - if(this->points[2]->x1 > this->x1max) this->x1max = this->points[2]->x1; - if(this->points[2]->x2 < this->x2min) this->x2min = this->points[2]->x2; - if(this->points[2]->x2 > this->x2max) this->x2max = this->points[2]->x2; - if(this->points[2]->x3 < this->x3min) this->x3min = this->points[2]->x3; - if(this->points[2]->x3 > this->x3max) this->x3max = this->points[2]->x3; - - this->x1s = (this->points[0]->x1+this->points[1]->x1+this->points[2]->x1)/3.0; - this->x2s = (this->points[0]->x2+this->points[1]->x2+this->points[2]->x2)/3.0; - this->x3s = (this->points[0]->x3+this->points[1]->x3+this->points[2]->x3)/3.0; - - GbVector3D A(points[0]->x1,points[0]->x2,points[0]->x3); - GbVector3D B(points[1]->x1,points[1]->x2,points[1]->x3); - GbVector3D C(points[2]->x1,points[2]->x2,points[2]->x3); - GbVector3D AB = B-A; - GbVector3D AC = C-A; - GbVector3D N = AB.Cross(AC); - this->area = 0.5*N.Length(); - this->consistent = true; + this->x1min = this->points[0]->x1; + this->x1max = this->points[0]->x1; + this->x2min = this->points[0]->x2; + this->x2max = this->points[0]->x2; + this->x3min = this->points[0]->x3; + this->x3max = this->points[0]->x3; + + if (this->points[1]->x1 < this->x1min) + this->x1min = this->points[1]->x1; + if (this->points[1]->x1 > this->x1max) + this->x1max = this->points[1]->x1; + if (this->points[1]->x2 < this->x2min) + this->x2min = this->points[1]->x2; + if (this->points[1]->x2 > this->x2max) + this->x2max = this->points[1]->x2; + if (this->points[1]->x3 < this->x3min) + this->x3min = this->points[1]->x3; + if (this->points[1]->x3 > this->x3max) + this->x3max = this->points[1]->x3; + + if (this->points[2]->x1 < this->x1min) + this->x1min = this->points[2]->x1; + if (this->points[2]->x1 > this->x1max) + this->x1max = this->points[2]->x1; + if (this->points[2]->x2 < this->x2min) + this->x2min = this->points[2]->x2; + if (this->points[2]->x2 > this->x2max) + this->x2max = this->points[2]->x2; + if (this->points[2]->x3 < this->x3min) + this->x3min = this->points[2]->x3; + if (this->points[2]->x3 > this->x3max) + this->x3max = this->points[2]->x3; + + this->x1s = (this->points[0]->x1 + this->points[1]->x1 + this->points[2]->x1) / 3.0; + this->x2s = (this->points[0]->x2 + this->points[1]->x2 + this->points[2]->x2) / 3.0; + this->x3s = (this->points[0]->x3 + this->points[1]->x3 + this->points[2]->x3) / 3.0; + + GbVector3D A(points[0]->x1, points[0]->x2, points[0]->x3); + GbVector3D B(points[1]->x1, points[1]->x2, points[1]->x3); + GbVector3D C(points[2]->x1, points[2]->x2, points[2]->x3); + GbVector3D AB = B - A; + GbVector3D AC = C - A; + GbVector3D N = AB.Cross(AC); + this->area = 0.5 * N.Length(); + this->consistent = true; } /*======================================================================*/ - /*======================================================================*/ GbVector3D GbTriangle3D::getNormal() { - this->calculateNormal(); - return normal; + this->calculateNormal(); + return normal; } /*======================================================================*/ void GbTriangle3D::init() { - x1s = 0.0; - x2s = 0.0; - x3s = 0.0; - x1min = 0.0; - x1max = 0.0; - x2min = 0.0; - x2max = 0.0; - area = 0.0; - consistent = false; - points.resize(3,NULL); + x1s = 0.0; + x2s = 0.0; + x3s = 0.0; + x1min = 0.0; + x1max = 0.0; + x2min = 0.0; + x2max = 0.0; + area = 0.0; + consistent = false; + points.resize(3, NULL); } /*=======================================================*/ void GbTriangle3D::calculateNormal() { - GbPoint3D*& a = points[0]; - GbPoint3D*& b = points[1]; - GbPoint3D*& c = points[2]; - normal[0] = ( c->getX3Coordinate() - a->getX3Coordinate()) * ( b->getX2Coordinate() - a->getX2Coordinate() ) - - ( b->getX3Coordinate() - a->getX3Coordinate()) * ( c->getX2Coordinate() - a->getX2Coordinate() ); - normal[1] = ( b->getX3Coordinate() - a->getX3Coordinate()) * ( c->getX1Coordinate() - a->getX1Coordinate() ) - - ( b->getX1Coordinate() - a->getX1Coordinate()) * ( c->getX3Coordinate() - a->getX3Coordinate() ); - normal[2] = ( b->getX1Coordinate() - a->getX1Coordinate()) * ( c->getX2Coordinate() - a->getX2Coordinate() ) - - ( b->getX2Coordinate() - a->getX2Coordinate()) * ( c->getX1Coordinate() - a->getX1Coordinate() ); - normal.Normalize(); + GbPoint3D *&a = points[0]; + GbPoint3D *&b = points[1]; + GbPoint3D *&c = points[2]; + normal[0] = (c->getX3Coordinate() - a->getX3Coordinate()) * (b->getX2Coordinate() - a->getX2Coordinate()) - + (b->getX3Coordinate() - a->getX3Coordinate()) * (c->getX2Coordinate() - a->getX2Coordinate()); + normal[1] = (b->getX3Coordinate() - a->getX3Coordinate()) * (c->getX1Coordinate() - a->getX1Coordinate()) - + (b->getX1Coordinate() - a->getX1Coordinate()) * (c->getX3Coordinate() - a->getX3Coordinate()); + normal[2] = (b->getX1Coordinate() - a->getX1Coordinate()) * (c->getX2Coordinate() - a->getX2Coordinate()) - + (b->getX2Coordinate() - a->getX2Coordinate()) * (c->getX1Coordinate() - a->getX1Coordinate()); + normal.Normalize(); } /*=======================================================*/ -//toDo: +// toDo: double GbTriangle3D::getDistanceFromPoint(GbVector3D punct) { - GbVector3D Point1(this->getPoint1()->getX1Coordinate(), this->getPoint1()->getX2Coordinate(), this->getPoint1()->getX3Coordinate()); - GbVector3D Point2(this->getPoint2()->getX1Coordinate(), this->getPoint2()->getX2Coordinate(), this->getPoint2()->getX3Coordinate()); - GbVector3D Point3(this->getPoint3()->getX1Coordinate(), this->getPoint3()->getX2Coordinate(), this->getPoint3()->getX3Coordinate()); - - GbVector3D kDiff = Point1 - punct; - GbVector3D kEdge0 = Point2 - Point1; - GbVector3D kEdge1 = Point3 - Point1; - double fA00 = kEdge0.SquaredLength(); - double fA01 = kEdge0.Dot(kEdge1); - double fA11 = kEdge1.SquaredLength(); - double fB0 = kDiff.Dot(kEdge0); - double fB1 = kDiff.Dot(kEdge1); - double fC = kDiff.SquaredLength(); - double fDet = fabs(fA00*fA11-fA01*fA01); - double fS = fA01*fB1-fA11*fB0; - double fT = fA01*fB0-fA00*fB1; - double fSqrDistance; - - if (fS + fT <= fDet) - { - if (fS < (double)0.0) - { - if (fT < (double)0.0) // region 4 - { - if (fB0 < (double)0.0) - { - fT = (double)0.0; - if (-fB0 >= fA00) - { - fS = (double)1.0; - fSqrDistance = fA00+((double)2.0)*fB0+fC; - } - else - { - fS = -fB0/fA00; - fSqrDistance = fB0*fS+fC; - } - } - else - { - fS = (double)0.0; - if (fB1 >= (double)0.0) - { - fT = (double)0.0; - fSqrDistance = fC; - } - else if (-fB1 >= fA11) - { - fT = (double)1.0; - fSqrDistance = fA11+((double)2.0)*fB1+fC; - } - else - { - fT = -fB1/fA11; - fSqrDistance = fB1*fT+fC; - } - } - } - else // region 3 - { - fS = (double)0.0; - if (fB1 >= (double)0.0) - { - fT = (double)0.0; - fSqrDistance = fC; - } - else if (-fB1 >= fA11) - { - fT = (double)1.0; - fSqrDistance = fA11+((double)2.0)*fB1+fC; - } - else - { - fT = -fB1/fA11; - fSqrDistance = fB1*fT+fC; - } - } - } - else if (fT < (double)0.0) // region 5 - { - fT = (double)0.0; - if (fB0 >= (double)0.0) - { - fS = (double)0.0; - fSqrDistance = fC; - } - else if (-fB0 >= fA00) - { - fS = (double)1.0; - fSqrDistance = fA00+((double)2.0)*fB0+fC; - } - else - { - fS = -fB0/fA00; - fSqrDistance = fB0*fS+fC; - } - } - else // region 0 - { - // minimum at interior point - double fInvDet = ((double)1.0)/fDet; - fS *= fInvDet; - fT *= fInvDet; - fSqrDistance = fS*(fA00*fS+fA01*fT+((double)2.0)*fB0) + - fT*(fA01*fS+fA11*fT+((double)2.0)*fB1)+fC; - } - } - else - { - double fTmp0, fTmp1, fNumer, fDenom; - - if (fS < (double)0.0) // region 2 - { - fTmp0 = fA01 + fB0; - fTmp1 = fA11 + fB1; - if (fTmp1 > fTmp0) - { - fNumer = fTmp1 - fTmp0; - fDenom = fA00-2.0f*fA01+fA11; - if (fNumer >= fDenom) - { - fS = (double)1.0; - fT = (double)0.0; - fSqrDistance = fA00+((double)2.0)*fB0+fC; - } - else - { - fS = fNumer/fDenom; - fT = (double)1.0 - fS; - fSqrDistance = fS*(fA00*fS+fA01*fT+2.0f*fB0) + - fT*(fA01*fS+fA11*fT+((double)2.0)*fB1)+fC; - } - } - else - { - fS = (double)0.0; - if (fTmp1 <= (double)0.0) - { - fT = (double)1.0; - fSqrDistance = fA11+((double)2.0)*fB1+fC; - } - else if (fB1 >= (double)0.0) - { - fT = (double)0.0; - fSqrDistance = fC; - } - else - { - fT = -fB1/fA11; - fSqrDistance = fB1*fT+fC; - } - } - } - else if (fT < (double)0.0) // region 6 - { - fTmp0 = fA01 + fB1; - fTmp1 = fA00 + fB0; - if (fTmp1 > fTmp0) - { - fNumer = fTmp1 - fTmp0; - fDenom = fA00-((double)2.0)*fA01+fA11; - if (fNumer >= fDenom) - { - fT = (double)1.0; - fS = (double)0.0; - fSqrDistance = fA11+((double)2.0)*fB1+fC; - } - else - { - fT = fNumer/fDenom; - fS = (double)1.0 - fT; - fSqrDistance = fS*(fA00*fS+fA01*fT+((double)2.0)*fB0) + - fT*(fA01*fS+fA11*fT+((double)2.0)*fB1)+fC; - } - } - else - { - fT = (double)0.0; - if (fTmp1 <= (double)0.0) - { - fS = (double)1.0; - fSqrDistance = fA00+((double)2.0)*fB0+fC; - } - else if (fB0 >= (double)0.0) - { - fS = (double)0.0; - fSqrDistance = fC; - } - else - { - fS = -fB0/fA00; - fSqrDistance = fB0*fS+fC; - } - } - } - else // region 1 - { - fNumer = fA11 + fB1 - fA01 - fB0; - if (fNumer <= (double)0.0) - { - fS = (double)0.0; - fT = (double)1.0; - fSqrDistance = fA11+((double)2.0)*fB1+fC; - } - else - { - fDenom = fA00-2.0f*fA01+fA11; - if (fNumer >= fDenom) - { - fS = (double)1.0; - fT = (double)0.0; - fSqrDistance = fA00+((double)2.0)*fB0+fC; - } - else - { - fS = fNumer/fDenom; - fT = (double)1.0 - fS; - fSqrDistance = fS*(fA00*fS+fA01*fT+((double)2.0)*fB0) + - fT*(fA01*fS+fA11*fT+((double)2.0)*fB1)+fC; - } - } - } - } - - // account for numerical round-off error - if (fSqrDistance < (double)0.0) - { - fSqrDistance = (double)0.0; - } -/* - m_kClosestPoint0 = punct; - m_kClosestPoint1 = m_rkTriangle.V[0] + fS*kEdge0 + fT*kEdge1; - m_afTriangleBary[1] = fS; - m_afTriangleBary[2] = fT; - m_afTriangleBary[0] = (double)1.0 - fS - fT; -*/ - return sqrt(fSqrDistance); + GbVector3D Point1(this->getPoint1()->getX1Coordinate(), this->getPoint1()->getX2Coordinate(), + this->getPoint1()->getX3Coordinate()); + GbVector3D Point2(this->getPoint2()->getX1Coordinate(), this->getPoint2()->getX2Coordinate(), + this->getPoint2()->getX3Coordinate()); + GbVector3D Point3(this->getPoint3()->getX1Coordinate(), this->getPoint3()->getX2Coordinate(), + this->getPoint3()->getX3Coordinate()); + + GbVector3D kDiff = Point1 - punct; + GbVector3D kEdge0 = Point2 - Point1; + GbVector3D kEdge1 = Point3 - Point1; + double fA00 = kEdge0.SquaredLength(); + double fA01 = kEdge0.Dot(kEdge1); + double fA11 = kEdge1.SquaredLength(); + double fB0 = kDiff.Dot(kEdge0); + double fB1 = kDiff.Dot(kEdge1); + double fC = kDiff.SquaredLength(); + double fDet = fabs(fA00 * fA11 - fA01 * fA01); + double fS = fA01 * fB1 - fA11 * fB0; + double fT = fA01 * fB0 - fA00 * fB1; + double fSqrDistance; + + if (fS + fT <= fDet) { + if (fS < (double)0.0) { + if (fT < (double)0.0) // region 4 + { + if (fB0 < (double)0.0) { + fT = (double)0.0; + if (-fB0 >= fA00) { + fS = (double)1.0; + fSqrDistance = fA00 + ((double)2.0) * fB0 + fC; + } else { + fS = -fB0 / fA00; + fSqrDistance = fB0 * fS + fC; + } + } else { + fS = (double)0.0; + if (fB1 >= (double)0.0) { + fT = (double)0.0; + fSqrDistance = fC; + } else if (-fB1 >= fA11) { + fT = (double)1.0; + fSqrDistance = fA11 + ((double)2.0) * fB1 + fC; + } else { + fT = -fB1 / fA11; + fSqrDistance = fB1 * fT + fC; + } + } + } else // region 3 + { + fS = (double)0.0; + if (fB1 >= (double)0.0) { + fT = (double)0.0; + fSqrDistance = fC; + } else if (-fB1 >= fA11) { + fT = (double)1.0; + fSqrDistance = fA11 + ((double)2.0) * fB1 + fC; + } else { + fT = -fB1 / fA11; + fSqrDistance = fB1 * fT + fC; + } + } + } else if (fT < (double)0.0) // region 5 + { + fT = (double)0.0; + if (fB0 >= (double)0.0) { + fS = (double)0.0; + fSqrDistance = fC; + } else if (-fB0 >= fA00) { + fS = (double)1.0; + fSqrDistance = fA00 + ((double)2.0) * fB0 + fC; + } else { + fS = -fB0 / fA00; + fSqrDistance = fB0 * fS + fC; + } + } else // region 0 + { + // minimum at interior point + double fInvDet = ((double)1.0) / fDet; + fS *= fInvDet; + fT *= fInvDet; + fSqrDistance = fS * (fA00 * fS + fA01 * fT + ((double)2.0) * fB0) + + fT * (fA01 * fS + fA11 * fT + ((double)2.0) * fB1) + fC; + } + } else { + double fTmp0, fTmp1, fNumer, fDenom; + + if (fS < (double)0.0) // region 2 + { + fTmp0 = fA01 + fB0; + fTmp1 = fA11 + fB1; + if (fTmp1 > fTmp0) { + fNumer = fTmp1 - fTmp0; + fDenom = fA00 - 2.0f * fA01 + fA11; + if (fNumer >= fDenom) { + fS = (double)1.0; + fT = (double)0.0; + fSqrDistance = fA00 + ((double)2.0) * fB0 + fC; + } else { + fS = fNumer / fDenom; + fT = (double)1.0 - fS; + fSqrDistance = fS * (fA00 * fS + fA01 * fT + 2.0f * fB0) + + fT * (fA01 * fS + fA11 * fT + ((double)2.0) * fB1) + fC; + } + } else { + fS = (double)0.0; + if (fTmp1 <= (double)0.0) { + fT = (double)1.0; + fSqrDistance = fA11 + ((double)2.0) * fB1 + fC; + } else if (fB1 >= (double)0.0) { + fT = (double)0.0; + fSqrDistance = fC; + } else { + fT = -fB1 / fA11; + fSqrDistance = fB1 * fT + fC; + } + } + } else if (fT < (double)0.0) // region 6 + { + fTmp0 = fA01 + fB1; + fTmp1 = fA00 + fB0; + if (fTmp1 > fTmp0) { + fNumer = fTmp1 - fTmp0; + fDenom = fA00 - ((double)2.0) * fA01 + fA11; + if (fNumer >= fDenom) { + fT = (double)1.0; + fS = (double)0.0; + fSqrDistance = fA11 + ((double)2.0) * fB1 + fC; + } else { + fT = fNumer / fDenom; + fS = (double)1.0 - fT; + fSqrDistance = fS * (fA00 * fS + fA01 * fT + ((double)2.0) * fB0) + + fT * (fA01 * fS + fA11 * fT + ((double)2.0) * fB1) + fC; + } + } else { + fT = (double)0.0; + if (fTmp1 <= (double)0.0) { + fS = (double)1.0; + fSqrDistance = fA00 + ((double)2.0) * fB0 + fC; + } else if (fB0 >= (double)0.0) { + fS = (double)0.0; + fSqrDistance = fC; + } else { + fS = -fB0 / fA00; + fSqrDistance = fB0 * fS + fC; + } + } + } else // region 1 + { + fNumer = fA11 + fB1 - fA01 - fB0; + if (fNumer <= (double)0.0) { + fS = (double)0.0; + fT = (double)1.0; + fSqrDistance = fA11 + ((double)2.0) * fB1 + fC; + } else { + fDenom = fA00 - 2.0f * fA01 + fA11; + if (fNumer >= fDenom) { + fS = (double)1.0; + fT = (double)0.0; + fSqrDistance = fA00 + ((double)2.0) * fB0 + fC; + } else { + fS = fNumer / fDenom; + fT = (double)1.0 - fS; + fSqrDistance = fS * (fA00 * fS + fA01 * fT + ((double)2.0) * fB0) + + fT * (fA01 * fS + fA11 * fT + ((double)2.0) * fB1) + fC; + } + } + } + } + + // account for numerical round-off error + if (fSqrDistance < (double)0.0) { + fSqrDistance = (double)0.0; + } + /* + m_kClosestPoint0 = punct; + m_kClosestPoint1 = m_rkTriangle.V[0] + fS*kEdge0 + fT*kEdge1; + m_afTriangleBary[1] = fS; + m_afTriangleBary[2] = fT; + m_afTriangleBary[0] = (double)1.0 - fS - fT; + */ + return sqrt(fSqrDistance); } diff --git a/src/basics/geometry3d/GbTriangle3D.h b/src/basics/geometry3d/GbTriangle3D.h index ae20245f03bb09dcd5982efcb37d4874003533df..a48b0828d0f53f96068abec528747f5b7a4365fe 100644 --- a/src/basics/geometry3d/GbTriangle3D.h +++ b/src/basics/geometry3d/GbTriangle3D.h @@ -1,28 +1,28 @@ //======================================================================================= -// ____ ____ __ ______ __________ __ __ __ __ -// \ \ | | | | | _ \ |___ ___| | | | | / \ | | -// \ \ | | | | | |_) | | | | | | | / \ | | -// \ \ | | | | | _ / | | | | | | / /\ \ | | -// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ -// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| -// \ \ | | ________________________________________________________________ -// \ \ | | | ______________________________________________________________| -// \ \| | | | __ __ __ __ ______ _______ -// \ | | |_____ | | | | | | | | | _ \ / _____) -// \ | | _____| | | | | | | | | | | \ \ \_______ +// ____ ____ __ ______ __________ __ __ __ __ +// \ \ | | | | | _ \ |___ ___| | | | | / \ | | +// \ \ | | | | | |_) | | | | | | | / \ | | +// \ \ | | | | | _ / | | | | | | / /\ \ | | +// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ +// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| +// \ \ | | ________________________________________________________________ +// \ \ | | | ______________________________________________________________| +// \ \| | | | __ __ __ __ ______ _______ +// \ | | |_____ | | | | | | | | | _ \ / _____) +// \ | | _____| | | | | | | | | | | \ \ \_______ // \ | | | | |_____ | \_/ | | | | |_/ / _____ | -// \ _____| |__| |________| \_______/ |__| |______/ (_______/ +// \ _____| |__| |________| \_______/ |__| |______/ (_______/ // -// This file is part of VirtualFluids. VirtualFluids is free software: you can +// This file is part of VirtualFluids. VirtualFluids is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of +// License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. -// -// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// +// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License along // with VirtualFluids (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>. // @@ -36,8 +36,8 @@ #include <sstream> #include <GbObject3D.h> -#include <GbVector3D.h> #include <GbPoint3D.h> +#include <GbVector3D.h> #include <PointerDefinitions.h> @@ -46,170 +46,177 @@ class GbPolygon3D; class GbObject3DCreator; ////////////////////////////////////////////////////////////////////////// -//! +//! //! \class GbTriangle3D -//! +//! //! \brief This Class provides basic 3D triangle objects. //! \details The describing points are observed by 2D triangle objects. -//! -////////////////////////////////////////////////////////////////////////// +//! +////////////////////////////////////////////////////////////////////////// -class GbTriangle3D : public GbObject3D , public UbObserver +class GbTriangle3D : public GbObject3D, public UbObserver { public: - /*======================================================================*/ - /* Konstruktoren */ - /* */ - GbTriangle3D(); - GbTriangle3D(GbPoint3D* point1, GbPoint3D* point2, GbPoint3D* point3); - GbTriangle3D(GbTriangle3D* triangle); - ~GbTriangle3D() override; - /*======================================================================*/ - /* Methoden */ - /* */ - GbTriangle3D* clone() override; - void finalize() override - { - this->deletePoints(); - } - - GbPoint3D* getPoint1() { return this->points[0]; } - GbPoint3D* getPoint2() { return this->points[1]; } - GbPoint3D* getPoint3() { return this->points[2]; } - - GbVector3D getNormal(); - void calculateNormal(); - - void deletePoints(); - - int contains(GbPoint3D* point); - int containsEqual(GbPoint3D* point); - GbPoint3D* getPoint(const int& index); - std::vector<GbPoint3D> getPoints(); - double getArea(); - double getX1Centroid() override; - double getX1Minimum() override; - double getX1Maximum() override; - double getX2Centroid() override; - double getX2Minimum() override; - double getX2Maximum() override; - double getX3Centroid() override; - double getX3Minimum() override; - double getX3Maximum() override; - - void setInconsistent() { this->consistent = false;} - - void setPoint(GbPoint3D *point, int index); - - //bool equals(GbObject3D *object) - std::vector<GbTriangle3D*> getSurfaceTriangleSet() override; - bool isPointInGbObject3D(const double& /*x1*/, const double& /*x2*/, const double& /*x3*/) override - { - //der einfachheit halber ... - return false; - //throw UbException(__FILE__, __LINE__, "GbTriangle3D::isPointInObject3D- not implemented"); - } - bool isPointInGbObject3D(const double& /*x1*/, const double& /*x2*/, const double& /*x3*/, bool& pointIsOnBoundary) override - { - //der einfachheit halber ... - pointIsOnBoundary = false; - return false; - //throw UbException(__FILE__, __LINE__, "GbTriangle3D::isPointInObject3D- not implemented"); - } - bool isCellInsideGbObject3D(const double& /*x11*/,const double& /*x21*/,const double& /*x31*/,const double& /*x12*/,const double& /*x22*/,const double& /*x23*/) override { return false; } - - - // get distance from a point to the triangle - //todo CHANGE... - double getDistanceFromPoint(GbVector3D punct); - - std::string toString() override; - - /*======================================================================*/ - /* Calculation */ - /* */ -// std::vector<GbPoint3D> calculateIntersectionPoints3D(GbLine3D *line); - bool hasRaytracing() override { return true; } - /*|r| must be 1! einheitsvector!!*/ - double getIntersectionRaytraceFactor(const double& x1, const double& x2, const double& x3, const double& rx1, const double& rx2, const double& rx3) override; -// bool isPointOnEdge(GbVector3D& q); - - GbPoint3D* calculateIntersectionPoints3D(GbLine3D* line); - GbPoint3D* calculateIntersectionPoints3D(GbPoint3D* linePoint1, GbPoint3D* linePoint2); - double calculateDistanceToPoint3D(GbPoint3D *point); - double calculateDistanceToPoint3D(const double& x1, const double& x2, const double& x3); - double calculateNormalizedDistanceToPoint3D(const double& x1, const double& y1, const double& z1, const double& x2, const double& y2, const double& z2); - - bool enclosesPoint2D(double x1, double x2); - GbPolygon3D* createClippedPolygon3D(GbCuboid3D* cube); - GbLine3D* createClippedLine3D (GbPoint3D& point1, GbPoint3D& point2) override; - //public GbPolygon2D createClippedPolygon2D(GbPoint2D p1, GbPoint2D p2); - GbPolygon3D* createClippedPolygon3D(const double& p1x1, const double& p1x2, const double& p1x3, const double& p2x1, const double& p2x2, const double& p2x3); - //bool enclosesRectangle2D(GbRectangle2D *rectangle); - //public boolean enclosesRectangle2D(GbPoint2D p1, GbPoint2D p2); - //public boolean enclosesRectangle2D(double p1x1, double p1x2, double p2x1, double p2x2); - //public boolean crossesRectangle2D(GbRectangle2D rectangle); - //public boolean crossesRectangle2D(GbPoint2D p1, GbPoint2D p2); - //public boolean crossesRectangle2D(double p1x1, double p1x2, double p2x1, double p2x2); - //public boolean enclosesOrCrossesRectangle2D(GbRectangle2D rectangle); - //public boolean enclosesOrCrossesRectangle2D(GbPoint2D p1, GbPoint2D p2); - //public boolean enclosesOrCrossesRectangle2D(double p1x1, double p1x2, double p2x1, double p2x2); - /*======================================================================*/ - /*======================================================================*/ - /* Private Methoden */ - /* */ - virtual void calculateValues(); - - - //virtuelle Methoden von UbObserver - //!! quick and dirty von sirann !! - void objectChanged(UbObservable* changedObject) override - { - GbPoint3D* point = dynamic_cast<GbPoint3D*>(changedObject); - if(!point || ( this->points[0]!=point && this->points[1]!=point && this->points[2]!=point) ) - return; - - this->consistent = false; - } - void objectWillBeDeleted(UbObservable* objectForDeletion) override - { - if(this->points[0]) - { - UbObservable* observedObj = dynamic_cast<UbObservable*>(this->points[0]); - if(objectForDeletion == observedObj) { this->points[0] = NULL; } - } - if(this->points[1]) - { - UbObservable* observedObj = dynamic_cast<UbObservable*>(this->points[1]); - if(objectForDeletion == observedObj) { this->points[1] = NULL; } - } - if(this->points[2]) - { - UbObservable* observedObj = dynamic_cast<UbObservable*>(this->points[2]); - if(objectForDeletion == observedObj) { this->points[2] = NULL; } - } - //ACHTUNG: eigentlich muessten in allen methoden von GbLine if abfragen fuer NULL pointer hin... toDo - } - using GbObject3D::isPointInGbObject3D; //Grund: dadurch muss man hier isPointInGbObject3D(GbPoint3D*) nicht ausprogrammieren, welche sonst hier "ueberdeckt" waere + /*======================================================================*/ + /* Konstruktoren */ + /* */ + GbTriangle3D(); + GbTriangle3D(GbPoint3D *point1, GbPoint3D *point2, GbPoint3D *point3); + GbTriangle3D(GbTriangle3D *triangle); + ~GbTriangle3D() override; + /*======================================================================*/ + /* Methoden */ + /* */ + GbTriangle3D *clone() override; + void finalize() override { this->deletePoints(); } + + GbPoint3D *getPoint1() { return this->points[0]; } + GbPoint3D *getPoint2() { return this->points[1]; } + GbPoint3D *getPoint3() { return this->points[2]; } + + GbVector3D getNormal(); + void calculateNormal(); + + void deletePoints(); + + int contains(GbPoint3D *point); + int containsEqual(GbPoint3D *point); + GbPoint3D *getPoint(const int &index); + std::vector<GbPoint3D> getPoints(); + double getArea(); + double getX1Centroid() override; + double getX1Minimum() override; + double getX1Maximum() override; + double getX2Centroid() override; + double getX2Minimum() override; + double getX2Maximum() override; + double getX3Centroid() override; + double getX3Minimum() override; + double getX3Maximum() override; + + void setInconsistent() { this->consistent = false; } + + void setPoint(GbPoint3D *point, int index); + + // bool equals(GbObject3D *object) + std::vector<GbTriangle3D *> getSurfaceTriangleSet() override; + bool isPointInGbObject3D(const double & /*x1*/, const double & /*x2*/, const double & /*x3*/) override + { + // der einfachheit halber ... + return false; + // throw UbException(__FILE__, __LINE__, "GbTriangle3D::isPointInObject3D- not implemented"); + } + bool isPointInGbObject3D(const double & /*x1*/, const double & /*x2*/, const double & /*x3*/, + bool &pointIsOnBoundary) override + { + // der einfachheit halber ... + pointIsOnBoundary = false; + return false; + // throw UbException(__FILE__, __LINE__, "GbTriangle3D::isPointInObject3D- not implemented"); + } + bool isCellInsideGbObject3D(const double & /*x11*/, const double & /*x21*/, const double & /*x31*/, + const double & /*x12*/, const double & /*x22*/, const double & /*x23*/) override + { + return false; + } + + // get distance from a point to the triangle + // todo CHANGE... + double getDistanceFromPoint(GbVector3D punct); + + std::string toString() override; + + /*======================================================================*/ + /* Calculation */ + /* */ + // std::vector<GbPoint3D> calculateIntersectionPoints3D(GbLine3D *line); + bool hasRaytracing() override { return true; } + /*|r| must be 1! einheitsvector!!*/ + double getIntersectionRaytraceFactor(const double &x1, const double &x2, const double &x3, const double &rx1, + const double &rx2, const double &rx3) override; + // bool isPointOnEdge(GbVector3D& q); + + GbPoint3D *calculateIntersectionPoints3D(GbLine3D *line); + GbPoint3D *calculateIntersectionPoints3D(GbPoint3D *linePoint1, GbPoint3D *linePoint2); + double calculateDistanceToPoint3D(GbPoint3D *point); + double calculateDistanceToPoint3D(const double &x1, const double &x2, const double &x3); + double calculateNormalizedDistanceToPoint3D(const double &x1, const double &y1, const double &z1, const double &x2, + const double &y2, const double &z2); + + bool enclosesPoint2D(double x1, double x2); + GbPolygon3D *createClippedPolygon3D(GbCuboid3D *cube); + GbLine3D *createClippedLine3D(GbPoint3D &point1, GbPoint3D &point2) override; + // public GbPolygon2D createClippedPolygon2D(GbPoint2D p1, GbPoint2D p2); + GbPolygon3D *createClippedPolygon3D(const double &p1x1, const double &p1x2, const double &p1x3, const double &p2x1, + const double &p2x2, const double &p2x3); + // bool enclosesRectangle2D(GbRectangle2D *rectangle); + // public boolean enclosesRectangle2D(GbPoint2D p1, GbPoint2D p2); + // public boolean enclosesRectangle2D(double p1x1, double p1x2, double p2x1, double p2x2); + // public boolean crossesRectangle2D(GbRectangle2D rectangle); + // public boolean crossesRectangle2D(GbPoint2D p1, GbPoint2D p2); + // public boolean crossesRectangle2D(double p1x1, double p1x2, double p2x1, double p2x2); + // public boolean enclosesOrCrossesRectangle2D(GbRectangle2D rectangle); + // public boolean enclosesOrCrossesRectangle2D(GbPoint2D p1, GbPoint2D p2); + // public boolean enclosesOrCrossesRectangle2D(double p1x1, double p1x2, double p2x1, double p2x2); + /*======================================================================*/ + /*======================================================================*/ + /* Private Methoden */ + /* */ + virtual void calculateValues(); + + // virtuelle Methoden von UbObserver + //!! quick and dirty von sirann !! + void objectChanged(UbObservable *changedObject) override + { + GbPoint3D *point = dynamic_cast<GbPoint3D *>(changedObject); + if (!point || (this->points[0] != point && this->points[1] != point && this->points[2] != point)) + return; + + this->consistent = false; + } + void objectWillBeDeleted(UbObservable *objectForDeletion) override + { + if (this->points[0]) { + UbObservable *observedObj = dynamic_cast<UbObservable *>(this->points[0]); + if (objectForDeletion == observedObj) { + this->points[0] = NULL; + } + } + if (this->points[1]) { + UbObservable *observedObj = dynamic_cast<UbObservable *>(this->points[1]); + if (objectForDeletion == observedObj) { + this->points[1] = NULL; + } + } + if (this->points[2]) { + UbObservable *observedObj = dynamic_cast<UbObservable *>(this->points[2]); + if (objectForDeletion == observedObj) { + this->points[2] = NULL; + } + } + // ACHTUNG: eigentlich muessten in allen methoden von GbLine if abfragen fuer NULL pointer hin... toDo + } + using GbObject3D::isPointInGbObject3D; // Grund: dadurch muss man hier isPointInGbObject3D(GbPoint3D*) nicht + // ausprogrammieren, welche sonst hier "ueberdeckt" waere protected: - bool consistent; - double x1s; - double x2s; - double x3s; - double x1min; - double x1max; - double x2min; - double x2max; - double x3min; - double x3max; - double area; - - GbVector3D normal; - std::vector<GbPoint3D*> points; - + bool consistent; + double x1s; + double x2s; + double x3s; + double x1min; + double x1max; + double x2min; + double x2max; + double x3min; + double x3max; + double area; + + GbVector3D normal; + std::vector<GbPoint3D *> points; + private: - void init(); + void init(); }; /*=========================================================================*/ diff --git a/src/basics/geometry3d/GbTriangularMesh3D.cpp b/src/basics/geometry3d/GbTriangularMesh3D.cpp index de781b33886f41a8244aaec495ad0a2b76dc676b..94138be759437d57271e172f71be923e493c2c23 100644 --- a/src/basics/geometry3d/GbTriangularMesh3D.cpp +++ b/src/basics/geometry3d/GbTriangularMesh3D.cpp @@ -4,292 +4,306 @@ #include <basics/utilities/UbMath.h> -#include <geometry3d/GbHalfSpace3D.h> -#include <geometry3d/GbCuboid3D.h> #include <geometry3d/CoordinateTransformation3D.h> - +#include <geometry3d/GbCuboid3D.h> +#include <geometry3d/GbHalfSpace3D.h> + using namespace std; GbTriangularMesh3D::GbTriangularMesh3D() : GbObject3D() { - this->setName("new GbMesh"); - this->nodes = new vector<GbPoint3D*>; - this->triangles = new vector<GbTriangle3D*>; - this->edges = new vector<GbLine3D*>; - - this->pointinobjecttest = RAYCROSSING; - - this->consistent = false; - x1min = x1max = x2min = x2max = x3min = x3max = 0.0; + this->setName("new GbMesh"); + this->nodes = new vector<GbPoint3D *>; + this->triangles = new vector<GbTriangle3D *>; + this->edges = new vector<GbLine3D *>; + + this->pointinobjecttest = RAYCROSSING; + + this->consistent = false; + x1min = x1max = x2min = x2max = x3min = x3max = 0.0; } /*=============================================================================================*/ -GbTriangularMesh3D::GbTriangularMesh3D(string name, vector<GbPoint3D*> *nodes, vector<GbTriangle3D*> *triangles) : GbObject3D() +GbTriangularMesh3D::GbTriangularMesh3D(string name, vector<GbPoint3D *> *nodes, vector<GbTriangle3D *> *triangles) + : GbObject3D() { - if(name.size()==0 ) throw UbException(UB_EXARGS,"no name specified"); - if(!nodes ) throw UbException(UB_EXARGS,"no nodes specified"); - if(!triangles ) throw UbException(UB_EXARGS,"no triangles specified"); - - this->setName(name); - this->nodes = nodes; - this->triangles = triangles; - this->edges = new vector<GbLine3D*>; - this->pointinobjecttest = RAYCROSSING; - - this->consistent = false; - x1min = x1max = x2min = x2max = x3min = x3max = 0.0; + if (name.size() == 0) + throw UbException(UB_EXARGS, "no name specified"); + if (!nodes) + throw UbException(UB_EXARGS, "no nodes specified"); + if (!triangles) + throw UbException(UB_EXARGS, "no triangles specified"); + + this->setName(name); + this->nodes = nodes; + this->triangles = triangles; + this->edges = new vector<GbLine3D *>; + this->pointinobjecttest = RAYCROSSING; + + this->consistent = false; + x1min = x1max = x2min = x2max = x3min = x3max = 0.0; } /*=============================================================================================*/ -GbTriangularMesh3D::GbTriangularMesh3D(string name, vector<GbTriangle3D*> *tris) : GbObject3D() +GbTriangularMesh3D::GbTriangularMesh3D(string name, vector<GbTriangle3D *> *tris) : GbObject3D() { - cout<<"Das Teil erzeugt seinen KnotenVector aus den Dreiecken ...\n Es sollte deleteRedundantNodes() aufgerufen werden \n"; - if(name.size()==0 ) throw UbException(UB_EXARGS,"no name specified"); - if(!tris ) throw UbException(UB_EXARGS,"no triangles specified"); - - vector<GbPoint3D*> *points = new vector<GbPoint3D*>; - this->triangles = new vector<GbTriangle3D*>; - GbPoint3D* p1 = NULL; - GbPoint3D* p2 = NULL; - GbPoint3D* p3 = NULL; - for(int u=0;u<(int)tris->size();u++) - { - if(UbMath::zero((*tris)[u]->getArea())) - { - (*tris)[u]->finalize(); - delete (*tris)[u]; - (*tris)[u] = NULL; - continue; - } - this->triangles->push_back((*tris)[u]); - p1 = (*tris)[u]->getPoint1(); - p2 = (*tris)[u]->getPoint2(); - p3 = (*tris)[u]->getPoint3(); - points->push_back(p1); - points->push_back(p2); - points->push_back(p3); - } - - this->setName(name); - this->nodes = points; - //this->triangles = triangles; - this->edges = new vector<GbLine3D*>; - this->edges->resize(0, NULL); - this->pointinobjecttest = RAYCROSSING; - - this->consistent = false; - x1min = x1max = x2min = x2max = x3min = x3max = 0.0; + cout << "Das Teil erzeugt seinen KnotenVector aus den Dreiecken ...\n Es sollte deleteRedundantNodes() aufgerufen " + "werden \n"; + if (name.size() == 0) + throw UbException(UB_EXARGS, "no name specified"); + if (!tris) + throw UbException(UB_EXARGS, "no triangles specified"); + + vector<GbPoint3D *> *points = new vector<GbPoint3D *>; + this->triangles = new vector<GbTriangle3D *>; + GbPoint3D *p1 = NULL; + GbPoint3D *p2 = NULL; + GbPoint3D *p3 = NULL; + for (int u = 0; u < (int)tris->size(); u++) { + if (UbMath::zero((*tris)[u]->getArea())) { + (*tris)[u]->finalize(); + delete (*tris)[u]; + (*tris)[u] = NULL; + continue; + } + this->triangles->push_back((*tris)[u]); + p1 = (*tris)[u]->getPoint1(); + p2 = (*tris)[u]->getPoint2(); + p3 = (*tris)[u]->getPoint3(); + points->push_back(p1); + points->push_back(p2); + points->push_back(p3); + } + + this->setName(name); + this->nodes = points; + // this->triangles = triangles; + this->edges = new vector<GbLine3D *>; + this->edges->resize(0, NULL); + this->pointinobjecttest = RAYCROSSING; + + this->consistent = false; + x1min = x1max = x2min = x2max = x3min = x3max = 0.0; } /*=============================================================================================*/ -GbTriangularMesh3D::GbTriangularMesh3D(string name, vector<GbPoint3D*> *nodes, vector<GbLine3D*> *edges, vector<GbTriangle3D*> *triangles) : GbObject3D() +GbTriangularMesh3D::GbTriangularMesh3D(string name, vector<GbPoint3D *> *nodes, vector<GbLine3D *> *edges, + vector<GbTriangle3D *> *triangles) + : GbObject3D() { - if(name.size()==0) throw UbException(UB_EXARGS,"no name specified"); - if(!nodes ) throw UbException(UB_EXARGS,"no nodes specified"); - if(!triangles ) throw UbException(UB_EXARGS,"no triangles specified"); - if(!edges ) throw UbException(UB_EXARGS,"no edges specified"); - - this->setName(name); - this->nodes = nodes; - this->edges = edges; - this->triangles = triangles; - this->pointinobjecttest = RAYCROSSING; - - this->consistent = false; - x1min = x1max = x2min = x2max = x3min = x3max = 0.0; + if (name.size() == 0) + throw UbException(UB_EXARGS, "no name specified"); + if (!nodes) + throw UbException(UB_EXARGS, "no nodes specified"); + if (!triangles) + throw UbException(UB_EXARGS, "no triangles specified"); + if (!edges) + throw UbException(UB_EXARGS, "no edges specified"); + + this->setName(name); + this->nodes = nodes; + this->edges = edges; + this->triangles = triangles; + this->pointinobjecttest = RAYCROSSING; + + this->consistent = false; + x1min = x1max = x2min = x2max = x3min = x3max = 0.0; } /*=============================================================================================*/ GbTriangularMesh3D::~GbTriangularMesh3D() { - if( this->nodes ) - { - for(unsigned u=0; u<nodes->size(); u++) delete (*nodes)[u]; - delete nodes; - } - if(triangles) - { - for(unsigned u=0; u<triangles->size(); u++) delete (*triangles)[u]; - delete triangles; - } + if (this->nodes) { + for (unsigned u = 0; u < nodes->size(); u++) + delete (*nodes)[u]; + delete nodes; + } + if (triangles) { + for (unsigned u = 0; u < triangles->size(); u++) + delete (*triangles)[u]; + delete triangles; + } } /*======================================================================*/ void GbTriangularMesh3D::deleteRedundantNodes() { - std::map<GbPoint3D*,GbTriangle3D*> pointTriMap; - GbPoint3D* p1 = NULL; - GbPoint3D* p2 = NULL; - GbPoint3D* p3 = NULL; - GbTriangle3D* tri = NULL; - - for(int u=0;u<(int)this->triangles->size();u++) - { - tri = (*this->triangles)[u]; - p1 = tri->getPoint1(); - p2 = tri->getPoint2(); - p3 = tri->getPoint3(); - pointTriMap.insert(pair<GbPoint3D*,GbTriangle3D*>(p1,tri)); - pointTriMap.insert(pair<GbPoint3D*,GbTriangle3D*>(p2,tri)); - pointTriMap.insert(pair<GbPoint3D*,GbTriangle3D*>(p3,tri)); - } - - cout<<"Nodes before deleting redundant:"<<this->nodes->size()<<endl; - GbPoint3D* pA = NULL; - GbPoint3D* pB = NULL; - std::map<GbPoint3D*,GbTriangle3D*>::iterator mapIterator; - for(int u=0;u<(int)this->nodes->size();u++) - { - //cout<<u<<" von "<<this->nodes->size()<<endl; - pA = (*this->nodes)[u]; - if(pA==NULL) continue; - for(int w=u+1;w<(int)this->nodes->size();w++) - { - // cout<<w<<" Wvon "<<this->nodes->size()<<endl; - pB = (*this->nodes)[w]; - if(pB==NULL) continue; - if(pA->equals(pB)) - { - //doppelter Knoten ... - mapIterator = pointTriMap.find(pB); - tri = dynamic_cast<GbTriangle3D*>(mapIterator->second); - if(!tri) throw UbException(UB_EXARGS,"triangle not found"); - p1 = tri->getPoint1(); - p2 = tri->getPoint2(); - p3 = tri->getPoint3(); - if(pB==p1) tri->setPoint(pA, 0); - else if(pB==p2) tri->setPoint(pA, 1); - else if(pB==p3) tri->setPoint(pA, 2); - else throw UbException(UB_EXARGS,"node should be there"); - delete pB; - (*this->nodes)[w] = NULL; - } - } - } - vector<GbPoint3D*> *points = new vector<GbPoint3D*>; - for(int u=0;u<(int)this->nodes->size();u++) - { - pA = (*this->nodes)[u]; - if(pA!=NULL) points->push_back(pA); - } - delete this->nodes; - this->nodes = points; - cout<<"Nodes after deleting redundant:"<<this->nodes->size()<<endl; - - -//nochmal kontrolle ... - pointTriMap.clear(); - for(int u=0;u<(int)this->triangles->size();u++) - { - tri = (*this->triangles)[u]; - p1 = tri->getPoint1(); - p2 = tri->getPoint2(); - p3 = tri->getPoint3(); - pointTriMap.insert(pair<GbPoint3D*,GbTriangle3D*>(p1,tri)); - pointTriMap.insert(pair<GbPoint3D*,GbTriangle3D*>(p2,tri)); - pointTriMap.insert(pair<GbPoint3D*,GbTriangle3D*>(p3,tri)); - } - for(int u=0;u<(int)this->nodes->size();u++) - { - pA = (*this->nodes)[u]; - if(pA==NULL) throw UbException(UB_EXARGS,"sollte kein NULL pointer sein ..."); - mapIterator = pointTriMap.find(pA); - tri = dynamic_cast<GbTriangle3D*>(mapIterator->second); - if(!tri) throw UbException(UB_EXARGS,"triangle not found"); - } + std::map<GbPoint3D *, GbTriangle3D *> pointTriMap; + GbPoint3D *p1 = NULL; + GbPoint3D *p2 = NULL; + GbPoint3D *p3 = NULL; + GbTriangle3D *tri = NULL; + + for (int u = 0; u < (int)this->triangles->size(); u++) { + tri = (*this->triangles)[u]; + p1 = tri->getPoint1(); + p2 = tri->getPoint2(); + p3 = tri->getPoint3(); + pointTriMap.insert(pair<GbPoint3D *, GbTriangle3D *>(p1, tri)); + pointTriMap.insert(pair<GbPoint3D *, GbTriangle3D *>(p2, tri)); + pointTriMap.insert(pair<GbPoint3D *, GbTriangle3D *>(p3, tri)); + } + + cout << "Nodes before deleting redundant:" << this->nodes->size() << endl; + GbPoint3D *pA = NULL; + GbPoint3D *pB = NULL; + std::map<GbPoint3D *, GbTriangle3D *>::iterator mapIterator; + for (int u = 0; u < (int)this->nodes->size(); u++) { + // cout<<u<<" von "<<this->nodes->size()<<endl; + pA = (*this->nodes)[u]; + if (pA == NULL) + continue; + for (int w = u + 1; w < (int)this->nodes->size(); w++) { + // cout<<w<<" Wvon "<<this->nodes->size()<<endl; + pB = (*this->nodes)[w]; + if (pB == NULL) + continue; + if (pA->equals(pB)) { + // doppelter Knoten ... + mapIterator = pointTriMap.find(pB); + tri = dynamic_cast<GbTriangle3D *>(mapIterator->second); + if (!tri) + throw UbException(UB_EXARGS, "triangle not found"); + p1 = tri->getPoint1(); + p2 = tri->getPoint2(); + p3 = tri->getPoint3(); + if (pB == p1) + tri->setPoint(pA, 0); + else if (pB == p2) + tri->setPoint(pA, 1); + else if (pB == p3) + tri->setPoint(pA, 2); + else + throw UbException(UB_EXARGS, "node should be there"); + delete pB; + (*this->nodes)[w] = NULL; + } + } + } + vector<GbPoint3D *> *points = new vector<GbPoint3D *>; + for (int u = 0; u < (int)this->nodes->size(); u++) { + pA = (*this->nodes)[u]; + if (pA != NULL) + points->push_back(pA); + } + delete this->nodes; + this->nodes = points; + cout << "Nodes after deleting redundant:" << this->nodes->size() << endl; + + // nochmal kontrolle ... + pointTriMap.clear(); + for (int u = 0; u < (int)this->triangles->size(); u++) { + tri = (*this->triangles)[u]; + p1 = tri->getPoint1(); + p2 = tri->getPoint2(); + p3 = tri->getPoint3(); + pointTriMap.insert(pair<GbPoint3D *, GbTriangle3D *>(p1, tri)); + pointTriMap.insert(pair<GbPoint3D *, GbTriangle3D *>(p2, tri)); + pointTriMap.insert(pair<GbPoint3D *, GbTriangle3D *>(p3, tri)); + } + for (int u = 0; u < (int)this->nodes->size(); u++) { + pA = (*this->nodes)[u]; + if (pA == NULL) + throw UbException(UB_EXARGS, "sollte kein NULL pointer sein ..."); + mapIterator = pointTriMap.find(pA); + tri = dynamic_cast<GbTriangle3D *>(mapIterator->second); + if (!tri) + throw UbException(UB_EXARGS, "triangle not found"); + } } /*======================================================================*/ -void GbTriangularMesh3D::translate(const double& x1, const double& x2, const double& x3) +void GbTriangularMesh3D::translate(const double &x1, const double &x2, const double &x3) { - GbPoint3D* pt; - for(int u=0;u<(int)this->nodes->size();u++) - { - pt = (*nodes)[u]; - pt->setX1(pt->getX1Coordinate()+x1); - pt->setX2(pt->getX2Coordinate()+x2); - pt->setX3(pt->getX3Coordinate()+x3); - } - this->consistent = false; + GbPoint3D *pt; + for (int u = 0; u < (int)this->nodes->size(); u++) { + pt = (*nodes)[u]; + pt->setX1(pt->getX1Coordinate() + x1); + pt->setX2(pt->getX2Coordinate() + x2); + pt->setX3(pt->getX3Coordinate() + x3); + } + this->consistent = false; } /*======================================================================*/ -void GbTriangularMesh3D::rotate(const double& alpha, const double& beta, const double& gamma) +void GbTriangularMesh3D::rotate(const double &alpha, const double &beta, const double &gamma) { - if(!this->consistent) this->calculateValues(); - double a1 = this->getX1Centroid(); - double a2 = this->getX2Centroid(); - double a3 = this->getX3Centroid(); - CoordinateTransformation3D trafoFor(a1, a2, a3, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0); - CoordinateTransformation3D trafoBack(a1, a2, a3, 1.0, 1.0, 1.0, alpha, beta, gamma); - - vector<GbPoint3D*> points; - GbPoint3D* p1 = NULL; - GbPoint3D* p2 = NULL; - GbPoint3D* p3 = NULL; - for(int u=0;u<(int)this->triangles->size();u++) - { - p1 = (*triangles)[u]->getPoint1(); - p2 = (*triangles)[u]->getPoint2(); - p3 = (*triangles)[u]->getPoint3(); - double p1x1 = trafoFor.transformForwardToX1Coordinate(p1->x1, p1->x2, p1->x3); - double p1x2 = trafoFor.transformForwardToX2Coordinate(p1->x1, p1->x2, p1->x3); - double p1x3 = trafoFor.transformForwardToX3Coordinate(p1->x1, p1->x2, p1->x3); - double p2x1 = trafoFor.transformForwardToX1Coordinate(p2->x1, p2->x2, p2->x3); - double p2x2 = trafoFor.transformForwardToX2Coordinate(p2->x1, p2->x2, p2->x3); - double p2x3 = trafoFor.transformForwardToX3Coordinate(p2->x1, p2->x2, p2->x3); - double p3x1 = trafoFor.transformForwardToX1Coordinate(p3->x1, p3->x2, p3->x3); - double p3x2 = trafoFor.transformForwardToX2Coordinate(p3->x1, p3->x2, p3->x3); - double p3x3 = trafoFor.transformForwardToX3Coordinate(p3->x1, p3->x2, p3->x3); - p1->x1 = trafoBack.transformBackwardToX1Coordinate(p1x1, p1x2, p1x3); - p1->x2 = trafoBack.transformBackwardToX2Coordinate(p1x1, p1x2, p1x3); - p1->x3 = trafoBack.transformBackwardToX3Coordinate(p1x1, p1x2, p1x3); - p2->x1 = trafoBack.transformBackwardToX1Coordinate(p2x1, p2x2, p2x3); - p2->x2 = trafoBack.transformBackwardToX2Coordinate(p2x1, p2x2, p2x3); - p2->x3 = trafoBack.transformBackwardToX3Coordinate(p2x1, p2x2, p2x3); - p3->x1 = trafoBack.transformBackwardToX1Coordinate(p3x1, p3x2, p3x3); - p3->x2 = trafoBack.transformBackwardToX2Coordinate(p3x1, p3x2, p3x3); - p3->x3 = trafoBack.transformBackwardToX3Coordinate(p3x1, p3x2, p3x3); - } - this->calculateValues(); + if (!this->consistent) + this->calculateValues(); + double a1 = this->getX1Centroid(); + double a2 = this->getX2Centroid(); + double a3 = this->getX3Centroid(); + CoordinateTransformation3D trafoFor(a1, a2, a3, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0); + CoordinateTransformation3D trafoBack(a1, a2, a3, 1.0, 1.0, 1.0, alpha, beta, gamma); + + vector<GbPoint3D *> points; + GbPoint3D *p1 = NULL; + GbPoint3D *p2 = NULL; + GbPoint3D *p3 = NULL; + for (int u = 0; u < (int)this->triangles->size(); u++) { + p1 = (*triangles)[u]->getPoint1(); + p2 = (*triangles)[u]->getPoint2(); + p3 = (*triangles)[u]->getPoint3(); + double p1x1 = trafoFor.transformForwardToX1Coordinate(p1->x1, p1->x2, p1->x3); + double p1x2 = trafoFor.transformForwardToX2Coordinate(p1->x1, p1->x2, p1->x3); + double p1x3 = trafoFor.transformForwardToX3Coordinate(p1->x1, p1->x2, p1->x3); + double p2x1 = trafoFor.transformForwardToX1Coordinate(p2->x1, p2->x2, p2->x3); + double p2x2 = trafoFor.transformForwardToX2Coordinate(p2->x1, p2->x2, p2->x3); + double p2x3 = trafoFor.transformForwardToX3Coordinate(p2->x1, p2->x2, p2->x3); + double p3x1 = trafoFor.transformForwardToX1Coordinate(p3->x1, p3->x2, p3->x3); + double p3x2 = trafoFor.transformForwardToX2Coordinate(p3->x1, p3->x2, p3->x3); + double p3x3 = trafoFor.transformForwardToX3Coordinate(p3->x1, p3->x2, p3->x3); + p1->x1 = trafoBack.transformBackwardToX1Coordinate(p1x1, p1x2, p1x3); + p1->x2 = trafoBack.transformBackwardToX2Coordinate(p1x1, p1x2, p1x3); + p1->x3 = trafoBack.transformBackwardToX3Coordinate(p1x1, p1x2, p1x3); + p2->x1 = trafoBack.transformBackwardToX1Coordinate(p2x1, p2x2, p2x3); + p2->x2 = trafoBack.transformBackwardToX2Coordinate(p2x1, p2x2, p2x3); + p2->x3 = trafoBack.transformBackwardToX3Coordinate(p2x1, p2x2, p2x3); + p3->x1 = trafoBack.transformBackwardToX1Coordinate(p3x1, p3x2, p3x3); + p3->x2 = trafoBack.transformBackwardToX2Coordinate(p3x1, p3x2, p3x3); + p3->x3 = trafoBack.transformBackwardToX3Coordinate(p3x1, p3x2, p3x3); + } + this->calculateValues(); } /*======================================================================*/ - /** - * Returns a string representation of this triangular mesh. - * @return a string representation of this triangular mesh - */ +/** + * Returns a string representation of this triangular mesh. + * @return a string representation of this triangular mesh + */ string GbTriangularMesh3D::toString() { - stringstream ss; - ss<<"GbTriangularMesh3D["; - ss<<(int)this->triangles->size()<<"-Triangles, "<<(int)this->nodes->size()<<"-Nodes, "<<(int)this->edges->size()<<"-Edges"<<endl; - //ss<<"\""<<this->name<<", Area=sollt mal berechnet werden ;-)"<<"\""; - //ss<<", x1min="<<this->x1min; - //ss<<", x1max="<<this->x1max; - //ss<<", x2min="<<this->x2min; - //ss<<", x2max="<<this->x2max; - //ss<<", x3min="<<this->x3min; - //ss<<", x3max="<<this->x3max; - ss<<"]"; - return(ss.str()); + stringstream ss; + ss << "GbTriangularMesh3D["; + ss << (int)this->triangles->size() << "-Triangles, " << (int)this->nodes->size() << "-Nodes, " + << (int)this->edges->size() << "-Edges" << endl; + // ss<<"\""<<this->name<<", Area=sollt mal berechnet werden ;-)"<<"\""; + // ss<<", x1min="<<this->x1min; + // ss<<", x1max="<<this->x1max; + // ss<<", x2min="<<this->x2min; + // ss<<", x2max="<<this->x2max; + // ss<<", x3min="<<this->x3min; + // ss<<", x3max="<<this->x3max; + ss << "]"; + return (ss.str()); } /** * Returns the name of this triangular mesh. * @return the name of this triangular mesh */ -//string GbTriangularMesh3D::getName(){ return(this->name); } +// string GbTriangularMesh3D::getName(){ return(this->name); } /** * Returns the nodes of this triangular mesh. * @return the nodes of this triangular mesh */ -vector<GbPoint3D*>* GbTriangularMesh3D::getNodes() { return(this->nodes); } +vector<GbPoint3D *> *GbTriangularMesh3D::getNodes() { return (this->nodes); } /** * Returns the triangles of this triangular mesh. * @return the triangles of this triangular mesh */ -vector<GbTriangle3D*>* GbTriangularMesh3D::getTriangles() { return(this->triangles); } +vector<GbTriangle3D *> *GbTriangularMesh3D::getTriangles() { return (this->triangles); } /** * Returns the center x1 coordinate of this triangular mesh. * @return the center x1 coordinate of this triangular mesh */ double GbTriangularMesh3D::getX1Centroid() { - if(!this->consistent) this->calculateValues(); - return(0.5*(this->x1min+this->x1max)); + if (!this->consistent) + this->calculateValues(); + return (0.5 * (this->x1min + this->x1max)); } /** * Returns the center x2 coordinate of this triangular mesh. @@ -297,17 +311,19 @@ double GbTriangularMesh3D::getX1Centroid() */ double GbTriangularMesh3D::getX2Centroid() { - if(!this->consistent) this->calculateValues(); - return(0.5*(this->x2min+this->x2max)); + if (!this->consistent) + this->calculateValues(); + return (0.5 * (this->x2min + this->x2max)); } /** -* Returns the center x3 coordinate of this triangular mesh. - * @return the center x3 coordinate of this triangular mesh - */ + * Returns the center x3 coordinate of this triangular mesh. + * @return the center x3 coordinate of this triangular mesh + */ double GbTriangularMesh3D::getX3Centroid() { - if(!this->consistent) this->calculateValues(); - return(0.5*(this->x3min+this->x3max)); + if (!this->consistent) + this->calculateValues(); + return (0.5 * (this->x3min + this->x3max)); } /** @@ -316,8 +332,9 @@ double GbTriangularMesh3D::getX3Centroid() */ double GbTriangularMesh3D::getX1Minimum() { - if(!this->consistent) this->calculateValues(); - return(this->x1min); + if (!this->consistent) + this->calculateValues(); + return (this->x1min); } /** * Returns the maximum x1 coordinate of this triangular mesh. @@ -325,8 +342,9 @@ double GbTriangularMesh3D::getX1Minimum() */ double GbTriangularMesh3D::getX1Maximum() { - if(!this->consistent) this->calculateValues(); - return(this->x1max); + if (!this->consistent) + this->calculateValues(); + return (this->x1max); } /** * Returns the minimum x2 coordinate of this triangular mesh. @@ -334,8 +352,9 @@ double GbTriangularMesh3D::getX1Maximum() */ double GbTriangularMesh3D::getX2Minimum() { - if(!this->consistent) this->calculateValues(); - return(this->x2min); + if (!this->consistent) + this->calculateValues(); + return (this->x2min); } /** * Returns the maximum x2 coordinate of this triangular mesh. @@ -343,8 +362,9 @@ double GbTriangularMesh3D::getX2Minimum() */ double GbTriangularMesh3D::getX2Maximum() { - if(!this->consistent) this->calculateValues(); - return(this->x2max); + if (!this->consistent) + this->calculateValues(); + return (this->x2max); } /** * Returns the minimum x3 coordinate of this triangular mesh. @@ -352,8 +372,9 @@ double GbTriangularMesh3D::getX2Maximum() */ double GbTriangularMesh3D::getX3Minimum() { - if(!this->consistent) this->calculateValues(); - return(this->x3min); + if (!this->consistent) + this->calculateValues(); + return (this->x3min); } /** * Returns the maximum x3 coordinate of this triangular mesh. @@ -361,34 +382,40 @@ double GbTriangularMesh3D::getX3Minimum() */ double GbTriangularMesh3D::getX3Maximum() { - if(!this->consistent) this->calculateValues(); - return(this->x3max); + if (!this->consistent) + this->calculateValues(); + return (this->x3max); } void GbTriangularMesh3D::calculateValues() { - double x1, x2, x3; - - this->x1min = (*this->nodes)[0]->getX1Coordinate(); - this->x1max = (*this->nodes)[0]->getX1Coordinate(); - this->x2min = (*this->nodes)[0]->getX2Coordinate(); - this->x2max = (*this->nodes)[0]->getX2Coordinate(); - this->x3min = (*this->nodes)[0]->getX3Coordinate(); - this->x3max = (*this->nodes)[0]->getX3Coordinate(); - - for(int i=1; i<(int)this->nodes->size(); i++) - { - x1 = (*this->nodes)[i]->getX1Coordinate(); - x2 = (*this->nodes)[i]->getX2Coordinate(); - x3 = (*this->nodes)[i]->getX3Coordinate(); - if(x1 < this->x1min) this->x1min = x1; - if(x1 > this->x1max) this->x1max = x1; - if(x2 < this->x2min) this->x2min = x2; - if(x2 > this->x2max) this->x2max = x2; - if(x3 < this->x3min) this->x3min = x3; - if(x3 > this->x3max) this->x3max = x3; - } - this->consistent = true; + double x1, x2, x3; + + this->x1min = (*this->nodes)[0]->getX1Coordinate(); + this->x1max = (*this->nodes)[0]->getX1Coordinate(); + this->x2min = (*this->nodes)[0]->getX2Coordinate(); + this->x2max = (*this->nodes)[0]->getX2Coordinate(); + this->x3min = (*this->nodes)[0]->getX3Coordinate(); + this->x3max = (*this->nodes)[0]->getX3Coordinate(); + + for (int i = 1; i < (int)this->nodes->size(); i++) { + x1 = (*this->nodes)[i]->getX1Coordinate(); + x2 = (*this->nodes)[i]->getX2Coordinate(); + x3 = (*this->nodes)[i]->getX3Coordinate(); + if (x1 < this->x1min) + this->x1min = x1; + if (x1 > this->x1max) + this->x1max = x1; + if (x2 < this->x2min) + this->x2min = x2; + if (x2 > this->x2max) + this->x2max = x2; + if (x3 < this->x3min) + this->x3min = x3; + if (x3 > this->x3max) + this->x3max = x3; + } + this->consistent = true; } /** @@ -397,219 +424,243 @@ void GbTriangularMesh3D::calculateValues() */ double GbTriangularMesh3D::getArea() { - double area = 0.0; - for(int i=0; i<(int)this->triangles->size(); i++) area += (*this->triangles)[i]->getArea(); - return(area); + double area = 0.0; + for (int i = 0; i < (int)this->triangles->size(); i++) + area += (*this->triangles)[i]->getArea(); + return (area); } /** * Returns the total volume of this triangular mesh. * @return the total volume of this triangular mesh - */ + */ double GbTriangularMesh3D::getVolume() { - GbTriangle3D* triangle; - GbPoint3D* p1; - GbPoint3D* p2; - GbPoint3D* p3; - - double x1,x2,x3,y1,y2,y3,z1,z2,z3; - double G3i; - double volume = 0.0; - int size = (int)this->triangles->size(); - for(int u=0; u<size;u++) - { - triangle = (*this->triangles)[u]; - p1 = triangle->getPoint1(); - p2 = triangle->getPoint2(); - p3 = triangle->getPoint3(); - x1 = p1->getX1Coordinate(); y1 = p1->getX2Coordinate(); z1 = p1->getX3Coordinate(); - x2 = p2->getX1Coordinate(); y2 = p2->getX2Coordinate(); z2 = p2->getX3Coordinate(); - x3 = p3->getX1Coordinate(); y3 = p3->getX2Coordinate(); z3 = p3->getX3Coordinate(); - G3i = x1*(y2*z3-z2*y3)+y1*(z2*x3-x2*z3)+z1*(x2*y3-y2*x3); - volume = volume+G3i/6.0; - } - return volume; + GbTriangle3D *triangle; + GbPoint3D *p1; + GbPoint3D *p2; + GbPoint3D *p3; + + double x1, x2, x3, y1, y2, y3, z1, z2, z3; + double G3i; + double volume = 0.0; + int size = (int)this->triangles->size(); + for (int u = 0; u < size; u++) { + triangle = (*this->triangles)[u]; + p1 = triangle->getPoint1(); + p2 = triangle->getPoint2(); + p3 = triangle->getPoint3(); + x1 = p1->getX1Coordinate(); + y1 = p1->getX2Coordinate(); + z1 = p1->getX3Coordinate(); + x2 = p2->getX1Coordinate(); + y2 = p2->getX2Coordinate(); + z2 = p2->getX3Coordinate(); + x3 = p3->getX1Coordinate(); + y3 = p3->getX2Coordinate(); + z3 = p3->getX3Coordinate(); + G3i = x1 * (y2 * z3 - z2 * y3) + y1 * (z2 * x3 - x2 * z3) + z1 * (x2 * y3 - y2 * x3); + volume = volume + G3i / 6.0; + } + return volume; } /*===============================================*/ UbTupleDouble3 GbTriangularMesh3D::calculateCenterOfGravity() { - GbTriangle3D* triangle; - GbPoint3D* p1; - GbPoint3D* p2; - GbPoint3D* p3; - - double x1,x2,x3,y1,y2,y3,z1,z2,z3; - double G3i; - double rSP1 = 0.0;double rSP2 = 0.0;double rSP3 = 0.0; - double volume = 0.0; - int size = (int)this->triangles->size(); - for(int u=0; u<size;u++) - { - triangle = (*this->triangles)[u]; - p1 = triangle->getPoint1(); - p2 = triangle->getPoint2(); - p3 = triangle->getPoint3(); - x1 = p1->getX1Coordinate(); y1 = p1->getX2Coordinate(); z1 = p1->getX3Coordinate(); - x2 = p2->getX1Coordinate(); y2 = p2->getX2Coordinate(); z2 = p2->getX3Coordinate(); - x3 = p3->getX1Coordinate(); y3 = p3->getX2Coordinate(); z3 = p3->getX3Coordinate(); - G3i = x1*(y2*z3-z2*y3)+y1*(z2*x3-x2*z3)+z1*(x2*y3-y2*x3); - volume = volume+G3i/6.0; - rSP1 = rSP1+G3i*(x1+x2+x3); - rSP2 = rSP2+G3i*(y1+y2+y3); - rSP3 = rSP3+G3i*(z1+z2+z3); - } - rSP1 = rSP1/(24.0*volume); - rSP2 = rSP2/(24.0*volume); - rSP3 = rSP3/(24.0*volume); - - return {rSP1, rSP2, rSP3}; + GbTriangle3D *triangle; + GbPoint3D *p1; + GbPoint3D *p2; + GbPoint3D *p3; + + double x1, x2, x3, y1, y2, y3, z1, z2, z3; + double G3i; + double rSP1 = 0.0; + double rSP2 = 0.0; + double rSP3 = 0.0; + double volume = 0.0; + int size = (int)this->triangles->size(); + for (int u = 0; u < size; u++) { + triangle = (*this->triangles)[u]; + p1 = triangle->getPoint1(); + p2 = triangle->getPoint2(); + p3 = triangle->getPoint3(); + x1 = p1->getX1Coordinate(); + y1 = p1->getX2Coordinate(); + z1 = p1->getX3Coordinate(); + x2 = p2->getX1Coordinate(); + y2 = p2->getX2Coordinate(); + z2 = p2->getX3Coordinate(); + x3 = p3->getX1Coordinate(); + y3 = p3->getX2Coordinate(); + z3 = p3->getX3Coordinate(); + G3i = x1 * (y2 * z3 - z2 * y3) + y1 * (z2 * x3 - x2 * z3) + z1 * (x2 * y3 - y2 * x3); + volume = volume + G3i / 6.0; + rSP1 = rSP1 + G3i * (x1 + x2 + x3); + rSP2 = rSP2 + G3i * (y1 + y2 + y3); + rSP3 = rSP3 + G3i * (z1 + z2 + z3); + } + rSP1 = rSP1 / (24.0 * volume); + rSP2 = rSP2 / (24.0 * volume); + rSP3 = rSP3 / (24.0 * volume); + + return { rSP1, rSP2, rSP3 }; } /*===============================================*/ UbTupleDouble6 GbTriangularMesh3D::calculateMomentOfInertia(double rhoP) { - GbTriangle3D* triangle; - GbPoint3D* p1; - GbPoint3D* p2; - GbPoint3D* p3; - - double x1,x2,x3,y1,y2,y3,z1,z2,z3; - double G3i; - double xx,yy,zz,xy,yz,zx; - double rSP1 = 0.0;double rSP2 = 0.0;double rSP3 = 0.0; - double volume = 0.0; - double top11 = 0.0;double top22 = 0.0;double top33 = 0.0; - double top12 = 0.0;double top23 = 0.0;double top13 = 0.0; - int size = (int)this->triangles->size(); - for(int u=0; u<size;u++) - { - triangle = (*this->triangles)[u]; - p1 = triangle->getPoint1(); - p2 = triangle->getPoint2(); - p3 = triangle->getPoint3(); - x1 = p1->getX1Coordinate(); y1 = p1->getX2Coordinate(); z1 = p1->getX3Coordinate(); - x2 = p2->getX1Coordinate(); y2 = p2->getX2Coordinate(); z2 = p2->getX3Coordinate(); - x3 = p3->getX1Coordinate(); y3 = p3->getX2Coordinate(); z3 = p3->getX3Coordinate(); - G3i = x1*(y2*z3-z2*y3)+y1*(z2*x3-x2*z3)+z1*(x2*y3-y2*x3); - volume = volume+G3i/6.0; - rSP1 = rSP1+G3i*(x1+x2+x3); - rSP2 = rSP2+G3i*(y1+y2+y3); - rSP3 = rSP3+G3i*(z1+z2+z3); - } - rSP1 = rSP1/(24.0*volume); - rSP2 = rSP2/(24.0*volume); - rSP3 = rSP3/(24.0*volume); - - double x1s = 0.0;//rSP1;//0.0;// - double x2s = 0.0;//rSP2;//0.0;// - double x3s = 0.0;//rSP3;//0.0;// - - for(int u=0; u<size;u++) - { - triangle = (*this->triangles)[u]; - p1 = triangle->getPoint1(); - p2 = triangle->getPoint2(); - p3 = triangle->getPoint3(); - x1 = p1->getX1Coordinate()-x1s; - y1 = p1->getX2Coordinate()-x2s; - z1 = p1->getX3Coordinate()-x3s; - x2 = p2->getX1Coordinate()-x1s; - y2 = p2->getX2Coordinate()-x2s; - z2 = p2->getX3Coordinate()-x3s; - x3 = p3->getX1Coordinate()-x1s; - y3 = p3->getX2Coordinate()-x2s; - z3 = p3->getX3Coordinate()-x3s; - G3i = x1*(y2*z3-z2*y3)+y1*(z2*x3-x2*z3)+z1*(x2*y3-y2*x3); - //rSP1 = rSP1+G3i*(x1+x2+x3)/(24.0*volume); - //rSP2 = rSP2+G3i*(y1+y2+y3)/(24.0*volume); - //rSP3 = rSP3+G3i*(z1+z2+z3)/(24.0*volume); - xx = x1*x1+x2*x2+x3*x3+x1*x2+x2*x3+x3*x1; - yy = y1*y1+y2*y2+y3*y3+y1*y2+y2*y3+y3*y1; - zz = z1*z1+z2*z2+z3*z3+z1*z2+z2*z3+z3*z1; - top11 = top11+(yy+zz)*rhoP*G3i/60.; - top22 = top22+(xx+zz)*rhoP*G3i/60.; - top33 = top33+(yy+xx)*rhoP*G3i/60.; - xy = 2.0*(x1*y1+x2*y2+x3*y3)+x2*y3+x3*y1+x1*y2+x3*y2+x1*y3+x2*y1; - yz = 2.0*(y1*z1+y2*z2+y3*z3)+y2*z3+y3*z1+y1*z2+y3*z2+y1*z3+y2*z1; - zx = 2.0*(z1*x1+z2*x2+z3*x3)+z2*x3+z3*x1+z1*x2+z3*x2+z1*x3+z2*x1; - top12 = top12-xy*rhoP*G3i/120.; - top23 = top23-yz*rhoP*G3i/120.; - top13 = top13-zx*rhoP*G3i/120.; - } - //Satz von Steiner ... - top11 = top11-rhoP*volume*(rSP2*rSP2+rSP3+rSP3); - top22 = top22-rhoP*volume*(rSP3*rSP3+rSP1*rSP1); - top33 = top33-rhoP*volume*(rSP1*rSP1+rSP2*rSP2); - top12 = top12+rhoP*volume*rSP1*rSP2; - top23 = top23+rhoP*volume*rSP2*rSP3; - top13 = top13+rhoP*volume*rSP3*rSP1; - - cout<<"Volume:"<<volume<<"\n Traegheitsmomente:\n"; - cout<<" top11:"<<top11<<" top22:"<<top22<<" top33:"<<top33<<endl; - cout<<" top12:"<<top12<<" top23:"<<top23<<" top13:"<<top13<<endl; - - return {top11,top22,top33,top12,top23,top13}; + GbTriangle3D *triangle; + GbPoint3D *p1; + GbPoint3D *p2; + GbPoint3D *p3; + + double x1, x2, x3, y1, y2, y3, z1, z2, z3; + double G3i; + double xx, yy, zz, xy, yz, zx; + double rSP1 = 0.0; + double rSP2 = 0.0; + double rSP3 = 0.0; + double volume = 0.0; + double top11 = 0.0; + double top22 = 0.0; + double top33 = 0.0; + double top12 = 0.0; + double top23 = 0.0; + double top13 = 0.0; + int size = (int)this->triangles->size(); + for (int u = 0; u < size; u++) { + triangle = (*this->triangles)[u]; + p1 = triangle->getPoint1(); + p2 = triangle->getPoint2(); + p3 = triangle->getPoint3(); + x1 = p1->getX1Coordinate(); + y1 = p1->getX2Coordinate(); + z1 = p1->getX3Coordinate(); + x2 = p2->getX1Coordinate(); + y2 = p2->getX2Coordinate(); + z2 = p2->getX3Coordinate(); + x3 = p3->getX1Coordinate(); + y3 = p3->getX2Coordinate(); + z3 = p3->getX3Coordinate(); + G3i = x1 * (y2 * z3 - z2 * y3) + y1 * (z2 * x3 - x2 * z3) + z1 * (x2 * y3 - y2 * x3); + volume = volume + G3i / 6.0; + rSP1 = rSP1 + G3i * (x1 + x2 + x3); + rSP2 = rSP2 + G3i * (y1 + y2 + y3); + rSP3 = rSP3 + G3i * (z1 + z2 + z3); + } + rSP1 = rSP1 / (24.0 * volume); + rSP2 = rSP2 / (24.0 * volume); + rSP3 = rSP3 / (24.0 * volume); + + double x1s = 0.0; // rSP1;//0.0;// + double x2s = 0.0; // rSP2;//0.0;// + double x3s = 0.0; // rSP3;//0.0;// + + for (int u = 0; u < size; u++) { + triangle = (*this->triangles)[u]; + p1 = triangle->getPoint1(); + p2 = triangle->getPoint2(); + p3 = triangle->getPoint3(); + x1 = p1->getX1Coordinate() - x1s; + y1 = p1->getX2Coordinate() - x2s; + z1 = p1->getX3Coordinate() - x3s; + x2 = p2->getX1Coordinate() - x1s; + y2 = p2->getX2Coordinate() - x2s; + z2 = p2->getX3Coordinate() - x3s; + x3 = p3->getX1Coordinate() - x1s; + y3 = p3->getX2Coordinate() - x2s; + z3 = p3->getX3Coordinate() - x3s; + G3i = x1 * (y2 * z3 - z2 * y3) + y1 * (z2 * x3 - x2 * z3) + z1 * (x2 * y3 - y2 * x3); + // rSP1 = rSP1+G3i*(x1+x2+x3)/(24.0*volume); + // rSP2 = rSP2+G3i*(y1+y2+y3)/(24.0*volume); + // rSP3 = rSP3+G3i*(z1+z2+z3)/(24.0*volume); + xx = x1 * x1 + x2 * x2 + x3 * x3 + x1 * x2 + x2 * x3 + x3 * x1; + yy = y1 * y1 + y2 * y2 + y3 * y3 + y1 * y2 + y2 * y3 + y3 * y1; + zz = z1 * z1 + z2 * z2 + z3 * z3 + z1 * z2 + z2 * z3 + z3 * z1; + top11 = top11 + (yy + zz) * rhoP * G3i / 60.; + top22 = top22 + (xx + zz) * rhoP * G3i / 60.; + top33 = top33 + (yy + xx) * rhoP * G3i / 60.; + xy = 2.0 * (x1 * y1 + x2 * y2 + x3 * y3) + x2 * y3 + x3 * y1 + x1 * y2 + x3 * y2 + x1 * y3 + x2 * y1; + yz = 2.0 * (y1 * z1 + y2 * z2 + y3 * z3) + y2 * z3 + y3 * z1 + y1 * z2 + y3 * z2 + y1 * z3 + y2 * z1; + zx = 2.0 * (z1 * x1 + z2 * x2 + z3 * x3) + z2 * x3 + z3 * x1 + z1 * x2 + z3 * x2 + z1 * x3 + z2 * x1; + top12 = top12 - xy * rhoP * G3i / 120.; + top23 = top23 - yz * rhoP * G3i / 120.; + top13 = top13 - zx * rhoP * G3i / 120.; + } + // Satz von Steiner ... + top11 = top11 - rhoP * volume * (rSP2 * rSP2 + rSP3 + rSP3); + top22 = top22 - rhoP * volume * (rSP3 * rSP3 + rSP1 * rSP1); + top33 = top33 - rhoP * volume * (rSP1 * rSP1 + rSP2 * rSP2); + top12 = top12 + rhoP * volume * rSP1 * rSP2; + top23 = top23 + rhoP * volume * rSP2 * rSP3; + top13 = top13 + rhoP * volume * rSP3 * rSP1; + + cout << "Volume:" << volume << "\n Traegheitsmomente:\n"; + cout << " top11:" << top11 << " top22:" << top22 << " top33:" << top33 << endl; + cout << " top12:" << top12 << " top23:" << top23 << " top13:" << top13 << endl; + + return { top11, top22, top33, top12, top23, top13 }; } - /** - * Returns the volume of this triangular mesh within the specified rectangle. - * @param p1x1 the 1st x1 coordinate of the rectangle - * @param p1x2 the 1st x2 coordinate of the rectangle - * @param p2x1 the 2nd x1 coordinate of the rectangle - * @param p2x2 the 2nd x2 coordinate of the rectangle - * @return the volume of this triangular mesh within the specified rectangle - * @exception NullPointerException if no triangles are found within the specified rectangle - */ -double GbTriangularMesh3D::getVolumeForRectangle(const double& /*p1x1*/, const double& /*p1x2*/, const double& /*p2x1*/, const double& /*p2x2*/) +/** + * Returns the volume of this triangular mesh within the specified rectangle. + * @param p1x1 the 1st x1 coordinate of the rectangle + * @param p1x2 the 1st x2 coordinate of the rectangle + * @param p2x1 the 2nd x1 coordinate of the rectangle + * @param p2x2 the 2nd x2 coordinate of the rectangle + * @return the volume of this triangular mesh within the specified rectangle + * @exception NullPointerException if no triangles are found within the specified rectangle + */ +double GbTriangularMesh3D::getVolumeForRectangle(const double & /*p1x1*/, const double & /*p1x2*/, + const double & /*p2x1*/, const double & /*p2x2*/) { - throw UbException(UB_EXARGS,"not yet implemented"); - // GbPolygon2D polygon; - // double volume = 0.0; - // double area1 = Math.abs((p1x1-p2x1)*(p1x2-p2x2)); - // double area2 = 0.0; - // double t1min, t1max, t2min, t2max; - // double x1, x2; - // boolean f = false; - - // for(int i=0; i<this.triangles.length; i++) - // { - // t1min = this.triangles[i].getX1Minimum(); - // t1max = this.triangles[i].getX1Maximum(); - // if(GbSystem.less2(t1min, t1max, p1x1, p2x1)) continue; - // if(GbSystem.greater2(t1min, t1max, p1x1, p2x1)) continue; - - // t2min = this.triangles[i].getX2Minimum(); - // t2max = this.triangles[i].getX2Maximum(); - // if(GbSystem.less2(t2min, t2max, p1x2, p2x2)) continue; - // if(GbSystem.greater2(t2min, t2max, p1x2, p2x2)) continue; - - // if(GbSystem.inOpenInterval(t1min, p1x1, p2x1) && GbSystem.inOpenInterval(t1max, p1x1, p2x1) && - // GbSystem.inOpenInterval(t2min, p1x2, p2x2) && GbSystem.inOpenInterval(t2max, p1x2, p2x2)) - // { - // volume += this.triangles[i].getVolume(); - // area2 += this.triangles[i].getArea(); - // f = true; - // } - // else - // { - // polygon = this.triangles[i].createClippedPolygon3D(p1x1, p1x2, p2x1, p2x2); - - // if(polygon != null && polygon.size() > 2) - // { - // try - // { - // x1 = polygon.getX1Centroid(); - // x2 = polygon.getX2Centroid(); - // volume += this.triangles[i].getX3Coordinate(x1, x2) * Math.abs(polygon.getArea()); - // area2 += Math.abs(polygon.getArea()); - // f = true; - // } - // catch(Exception e){} - // } - // } - // if(GbSystem.greaterEqual(area2, area1)) break; - //} - // if(f) return(volume); - // else throw new NullPointerException(); + throw UbException(UB_EXARGS, "not yet implemented"); + // GbPolygon2D polygon; + // double volume = 0.0; + // double area1 = Math.abs((p1x1-p2x1)*(p1x2-p2x2)); + // double area2 = 0.0; + // double t1min, t1max, t2min, t2max; + // double x1, x2; + // boolean f = false; + + // for(int i=0; i<this.triangles.length; i++) + // { + // t1min = this.triangles[i].getX1Minimum(); + // t1max = this.triangles[i].getX1Maximum(); + // if(GbSystem.less2(t1min, t1max, p1x1, p2x1)) continue; + // if(GbSystem.greater2(t1min, t1max, p1x1, p2x1)) continue; + + // t2min = this.triangles[i].getX2Minimum(); + // t2max = this.triangles[i].getX2Maximum(); + // if(GbSystem.less2(t2min, t2max, p1x2, p2x2)) continue; + // if(GbSystem.greater2(t2min, t2max, p1x2, p2x2)) continue; + + // if(GbSystem.inOpenInterval(t1min, p1x1, p2x1) && GbSystem.inOpenInterval(t1max, p1x1, p2x1) && + // GbSystem.inOpenInterval(t2min, p1x2, p2x2) && GbSystem.inOpenInterval(t2max, p1x2, p2x2)) + // { + // volume += this.triangles[i].getVolume(); + // area2 += this.triangles[i].getArea(); + // f = true; + // } + // else + // { + // polygon = this.triangles[i].createClippedPolygon3D(p1x1, p1x2, p2x1, p2x2); + + // if(polygon != null && polygon.size() > 2) + // { + // try + // { + // x1 = polygon.getX1Centroid(); + // x2 = polygon.getX2Centroid(); + // volume += this.triangles[i].getX3Coordinate(x1, x2) * Math.abs(polygon.getArea()); + // area2 += Math.abs(polygon.getArea()); + // f = true; + // } + // catch(Exception e){} + // } + // } + // if(GbSystem.greaterEqual(area2, area1)) break; + //} + // if(f) return(volume); + // else throw new NullPointerException(); } /** @@ -620,45 +671,46 @@ double GbTriangularMesh3D::getVolumeForRectangle(const double& /*p1x1*/, const * @param p2x2 the 2nd x2 coordinate of the rectangle * @return the triangles of this triangular mesh located within the specified rectangle */ -vector<GbTriangle3D*>* GbTriangularMesh3D::getTrianglesForRectangle(const double& /*p1x1*/, const double& /*p1x2*/, const double& /*p2x1*/, const double& /*p2x2*/) +vector<GbTriangle3D *> *GbTriangularMesh3D::getTrianglesForRectangle(const double & /*p1x1*/, const double & /*p1x2*/, + const double & /*p2x1*/, const double & /*p2x2*/) { - throw UbException(UB_EXARGS,"not yet implemented"); - // QbList triangleList = new QbList(GbTriangle3D.class); - // GbPolygon2D polygon; - // double t1min, t1max, t2min, t2max; - // double area1 = Math.abs((p1x1-p2x1)*(p1x2-p2x2)); - // double area2 = 0.0; - - // for(int i=0; i<this.triangles.length; i++) - // { - // t1min = this.triangles[i].getX1Minimum(); - // t1max = this.triangles[i].getX1Maximum(); - // if(GbSystem.less2(t1min, t1max, p1x1, p2x1)) continue; - // if(GbSystem.greater2(t1min, t1max, p1x1, p2x1)) continue; - - // t2min = this.triangles[i].getX2Minimum(); - // t2max = this.triangles[i].getX2Maximum(); - // if(GbSystem.less2(t2min, t2max, p1x2, p2x2)) continue; - // if(GbSystem.greater2(t2min, t2max, p1x2, p2x2)) continue; - - // if(GbSystem.inOpenInterval(t1min, p1x1, p2x1) && GbSystem.inOpenInterval(t1max, p1x1, p2x1) && - // GbSystem.inOpenInterval(t2min, p1x2, p2x2) && GbSystem.inOpenInterval(t2max, p1x2, p2x2)) - // { - // try { triangleList.append(this.triangles[i]); } catch(Exception e){} - // area2 += this.triangles[i].getArea(); - // } - // else - // { - // polygon = this.triangles[i].createClippedPolygon3D(p1x1, p1x2, p2x1, p2x2); - // if(polygon != null && polygon.size() > 2) - // { - // try { triangleList.append(this.triangles[i]); } catch(Exception e){} - // area2 += Math.abs(polygon.getArea()); - // } - // } - // if(GbSystem.greaterEqual(area2, area1)) break; - //} - // return((GbTriangle3D[])triangleList.getObjectArray()); + throw UbException(UB_EXARGS, "not yet implemented"); + // QbList triangleList = new QbList(GbTriangle3D.class); + // GbPolygon2D polygon; + // double t1min, t1max, t2min, t2max; + // double area1 = Math.abs((p1x1-p2x1)*(p1x2-p2x2)); + // double area2 = 0.0; + + // for(int i=0; i<this.triangles.length; i++) + // { + // t1min = this.triangles[i].getX1Minimum(); + // t1max = this.triangles[i].getX1Maximum(); + // if(GbSystem.less2(t1min, t1max, p1x1, p2x1)) continue; + // if(GbSystem.greater2(t1min, t1max, p1x1, p2x1)) continue; + + // t2min = this.triangles[i].getX2Minimum(); + // t2max = this.triangles[i].getX2Maximum(); + // if(GbSystem.less2(t2min, t2max, p1x2, p2x2)) continue; + // if(GbSystem.greater2(t2min, t2max, p1x2, p2x2)) continue; + + // if(GbSystem.inOpenInterval(t1min, p1x1, p2x1) && GbSystem.inOpenInterval(t1max, p1x1, p2x1) && + // GbSystem.inOpenInterval(t2min, p1x2, p2x2) && GbSystem.inOpenInterval(t2max, p1x2, p2x2)) + // { + // try { triangleList.append(this.triangles[i]); } catch(Exception e){} + // area2 += this.triangles[i].getArea(); + // } + // else + // { + // polygon = this.triangles[i].createClippedPolygon3D(p1x1, p1x2, p2x1, p2x2); + // if(polygon != null && polygon.size() > 2) + // { + // try { triangleList.append(this.triangles[i]); } catch(Exception e){} + // area2 += Math.abs(polygon.getArea()); + // } + // } + // if(GbSystem.greaterEqual(area2, area1)) break; + //} + // return((GbTriangle3D[])triangleList.getObjectArray()); } /** * Returns the nodes of this triangular mesh located within the specified rectangle (may be an empty array). @@ -668,19 +720,21 @@ vector<GbTriangle3D*>* GbTriangularMesh3D::getTrianglesForRectangle(const double * @param p2x2 the 2nd x2 coordinate of the rectangle * @return the nodes of this triangular mesh located within the specified rectangle */ -vector<GbPoint3D*>* GbTriangularMesh3D::getNodesForRectangle(const double& /*p1x1*/, const double& /*p1x2*/, const double& /*p2x1*/, const double& /*p2x2*/) +vector<GbPoint3D *> *GbTriangularMesh3D::getNodesForRectangle(const double & /*p1x1*/, const double & /*p1x2*/, + const double & /*p2x1*/, const double & /*p2x2*/) { - throw UbException(UB_EXARGS,"not implemented"); -// QbList nodeList = new QbList(GbPoint3D.class); - - // for(int i=0; i<this.edges.length; i++) - // { - //if(GbSystem.inClosedInterval(this.nodes[i].getX1Coordinate(), p1x1, p2x1) && GbSystem.inClosedInterval(this.nodes[i].getX2Coordinate(), p1x2, p2x2)) - //{ - // try { nodeList.append(this.nodes[i]); } catch(Exception e){} - //} - // } - // return((GbPoint3D[])nodeList.getObjectArray()); + throw UbException(UB_EXARGS, "not implemented"); + // QbList nodeList = new QbList(GbPoint3D.class); + + // for(int i=0; i<this.edges.length; i++) + // { + // if(GbSystem.inClosedInterval(this.nodes[i].getX1Coordinate(), p1x1, p2x1) && + // GbSystem.inClosedInterval(this.nodes[i].getX2Coordinate(), p1x2, p2x2)) + //{ + // try { nodeList.append(this.nodes[i]); } catch(Exception e){} + //} + // } + // return((GbPoint3D[])nodeList.getObjectArray()); } /** @@ -693,69 +747,70 @@ vector<GbPoint3D*>* GbTriangularMesh3D::getNodesForRectangle(const double& /*p1 * @return the difference of maximum and minimum x3 coordinates of this triangular mesh within the specified rectangle * @exception NullPointerException if no triangles are found within the specified rectangle */ -double GbTriangularMesh3D::getX3RangeForRectangle(const double& /*p1x1*/, const double& /*p1x2*/, const double& /*p2x1*/, const double& /*p2x2*/) +double GbTriangularMesh3D::getX3RangeForRectangle(const double & /*p1x1*/, const double & /*p1x2*/, + const double & /*p2x1*/, const double & /*p2x2*/) { - throw UbException(UB_EXARGS,"not implemented"); - // GbPolygon3D polygon; - // boolean f = false; - // double x3min = 0.0; - // double x3max = 0.0; - // double t1min, t1max, t2min, t2max; - // double area1 = Math.abs((p1x1-p2x1)*(p1x2-p2x2)); - // double area2 = 0.0; - - // for(int i=0; i<this.triangles.length; i++) - // { - // t1min = this.triangles[i].getX1Minimum(); - // t1max = this.triangles[i].getX1Maximum(); - // if(GbSystem.less2(t1min, t1max, p1x1, p2x1)) continue; - // if(GbSystem.greater2(t1min, t1max, p1x1, p2x1)) continue; - - // t2min = this.triangles[i].getX2Minimum(); - // t2max = this.triangles[i].getX2Maximum(); - // if(GbSystem.less2(t2min, t2max, p1x2, p2x2)) continue; - // if(GbSystem.greater2(t2min, t2max, p1x2, p2x2)) continue; - - // if(GbSystem.inOpenInterval(t1min, p1x1, p2x1) && GbSystem.inOpenInterval(t1max, p1x1, p2x1) && - // GbSystem.inOpenInterval(t2min, p1x2, p2x2) && GbSystem.inOpenInterval(t2max, p1x2, p2x2)) - // { - // if(f) - // { - // if(this.triangles[i].getX3Minimum() < x3min) x3min = this.triangles[i].getX3Minimum(); - // if(this.triangles[i].getX3Maximum() > x3max) x3max = this.triangles[i].getX3Maximum(); - // } - // else - // { - // x3min = this.triangles[i].getX3Minimum(); - // x3max = this.triangles[i].getX3Maximum(); - // f = true; - // } - // area2 += this.triangles[i].getArea(); - //} - // else - // { - // polygon = this.triangles[i].createClippedPolygon3D(p1x1, p1x2, p2x1, p2x2); - - // if(polygon != null && polygon.size() > 2) - // { - // if(f) - // { - // if(polygon.getX3Minimum() < x3min) x3min = polygon.getX3Minimum(); - // if(polygon.getX3Maximum() > x3max) x3max = polygon.getX3Maximum(); - // } - // else - // { - // x3min = polygon.getX3Minimum(); - // x3max = polygon.getX3Maximum(); - // f = true; - // } - // area2 += Math.abs(polygon.getArea()); - // } - // } - // if(GbSystem.greaterEqual(area2, area1)) break; - // } - // if(f) return(x3max-x3min); - // else throw new NullPointerException(); + throw UbException(UB_EXARGS, "not implemented"); + // GbPolygon3D polygon; + // boolean f = false; + // double x3min = 0.0; + // double x3max = 0.0; + // double t1min, t1max, t2min, t2max; + // double area1 = Math.abs((p1x1-p2x1)*(p1x2-p2x2)); + // double area2 = 0.0; + + // for(int i=0; i<this.triangles.length; i++) + // { + // t1min = this.triangles[i].getX1Minimum(); + // t1max = this.triangles[i].getX1Maximum(); + // if(GbSystem.less2(t1min, t1max, p1x1, p2x1)) continue; + // if(GbSystem.greater2(t1min, t1max, p1x1, p2x1)) continue; + + // t2min = this.triangles[i].getX2Minimum(); + // t2max = this.triangles[i].getX2Maximum(); + // if(GbSystem.less2(t2min, t2max, p1x2, p2x2)) continue; + // if(GbSystem.greater2(t2min, t2max, p1x2, p2x2)) continue; + + // if(GbSystem.inOpenInterval(t1min, p1x1, p2x1) && GbSystem.inOpenInterval(t1max, p1x1, p2x1) && + // GbSystem.inOpenInterval(t2min, p1x2, p2x2) && GbSystem.inOpenInterval(t2max, p1x2, p2x2)) + // { + // if(f) + // { + // if(this.triangles[i].getX3Minimum() < x3min) x3min = this.triangles[i].getX3Minimum(); + // if(this.triangles[i].getX3Maximum() > x3max) x3max = this.triangles[i].getX3Maximum(); + // } + // else + // { + // x3min = this.triangles[i].getX3Minimum(); + // x3max = this.triangles[i].getX3Maximum(); + // f = true; + // } + // area2 += this.triangles[i].getArea(); + //} + // else + // { + // polygon = this.triangles[i].createClippedPolygon3D(p1x1, p1x2, p2x1, p2x2); + + // if(polygon != null && polygon.size() > 2) + // { + // if(f) + // { + // if(polygon.getX3Minimum() < x3min) x3min = polygon.getX3Minimum(); + // if(polygon.getX3Maximum() > x3max) x3max = polygon.getX3Maximum(); + // } + // else + // { + // x3min = polygon.getX3Minimum(); + // x3max = polygon.getX3Maximum(); + // f = true; + // } + // area2 += Math.abs(polygon.getArea()); + // } + // } + // if(GbSystem.greaterEqual(area2, area1)) break; + // } + // if(f) return(x3max-x3min); + // else throw new NullPointerException(); } /** * Returns the minimum x3 coordinates of this triangular mesh within the specified rectangle. @@ -766,64 +821,65 @@ double GbTriangularMesh3D::getX3RangeForRectangle(const double& /*p1x1*/, const * @return the minimum x3 coordinates of this triangular mesh within the specified rectangle * @exception NullPointerException if no triangles are found within the specified rectangle */ -double GbTriangularMesh3D::getX3MinimumForRectangle(const double& /*p1x1*/, const double& /*p1x2*/, const double& /*p2x1*/, const double& /*p2x2*/) +double GbTriangularMesh3D::getX3MinimumForRectangle(const double & /*p1x1*/, const double & /*p1x2*/, + const double & /*p2x1*/, const double & /*p2x2*/) { - throw UbException(UB_EXARGS,"not implemented"); - // GbPolygon3D polygon; - // boolean f = false; - // double x3min = 0.0; - // double t1min, t1max, t2min, t2max; - // double area1 = Math.abs((p1x1-p2x1)*(p1x2-p2x2)); - // double area2 = 0.0; - - // for(int i=0; i<this.triangles.length; i++) - // { - //t1min = this.triangles[i].getX1Minimum(); - //t1max = this.triangles[i].getX1Maximum(); - //if(GbSystem.less2(t1min, t1max, p1x1, p2x1)) continue; - //if(GbSystem.greater2(t1min, t1max, p1x1, p2x1)) continue; - - //t2min = this.triangles[i].getX2Minimum(); - //t2max = this.triangles[i].getX2Maximum(); - //if(GbSystem.less2(t2min, t2max, p1x2, p2x2)) continue; - //if(GbSystem.greater2(t2min, t2max, p1x2, p2x2)) continue; - - //if(GbSystem.inOpenInterval(t1min, p1x1, p2x1) && GbSystem.inOpenInterval(t1max, p1x1, p2x1) && - // GbSystem.inOpenInterval(t2min, p1x2, p2x2) && GbSystem.inOpenInterval(t2max, p1x2, p2x2)) - //{ - // if(f) - // { - // if(this.triangles[i].getX3Minimum() < x3min) x3min = this.triangles[i].getX3Minimum(); - // } - // else - // { - // x3min = this.triangles[i].getX3Minimum(); - // f = true; - // } - // area2 += this.triangles[i].getArea(); - //} - //else - //{ - // polygon = this.triangles[i].createClippedPolygon3D(p1x1, p1x2, p2x1, p2x2); - - // if(polygon != null && polygon.size() > 2) - // { - // if(f) - // { - // if(polygon.getX3Minimum() < x3min) x3min = polygon.getX3Minimum(); - // } - // else - // { - // x3min = polygon.getX3Minimum(); - // f = true; - // } - // area2 += Math.abs(polygon.getArea()); - // } - //} - //if(GbSystem.greaterEqual(area2, area1)) break; - // } - // if(f) return(x3min); - // else throw new NullPointerException(); + throw UbException(UB_EXARGS, "not implemented"); + // GbPolygon3D polygon; + // boolean f = false; + // double x3min = 0.0; + // double t1min, t1max, t2min, t2max; + // double area1 = Math.abs((p1x1-p2x1)*(p1x2-p2x2)); + // double area2 = 0.0; + + // for(int i=0; i<this.triangles.length; i++) + // { + // t1min = this.triangles[i].getX1Minimum(); + // t1max = this.triangles[i].getX1Maximum(); + // if(GbSystem.less2(t1min, t1max, p1x1, p2x1)) continue; + // if(GbSystem.greater2(t1min, t1max, p1x1, p2x1)) continue; + + // t2min = this.triangles[i].getX2Minimum(); + // t2max = this.triangles[i].getX2Maximum(); + // if(GbSystem.less2(t2min, t2max, p1x2, p2x2)) continue; + // if(GbSystem.greater2(t2min, t2max, p1x2, p2x2)) continue; + + // if(GbSystem.inOpenInterval(t1min, p1x1, p2x1) && GbSystem.inOpenInterval(t1max, p1x1, p2x1) && + // GbSystem.inOpenInterval(t2min, p1x2, p2x2) && GbSystem.inOpenInterval(t2max, p1x2, p2x2)) + //{ + // if(f) + // { + // if(this.triangles[i].getX3Minimum() < x3min) x3min = this.triangles[i].getX3Minimum(); + // } + // else + // { + // x3min = this.triangles[i].getX3Minimum(); + // f = true; + // } + // area2 += this.triangles[i].getArea(); + //} + // else + //{ + // polygon = this.triangles[i].createClippedPolygon3D(p1x1, p1x2, p2x1, p2x2); + + // if(polygon != null && polygon.size() > 2) + // { + // if(f) + // { + // if(polygon.getX3Minimum() < x3min) x3min = polygon.getX3Minimum(); + // } + // else + // { + // x3min = polygon.getX3Minimum(); + // f = true; + // } + // area2 += Math.abs(polygon.getArea()); + // } + //} + // if(GbSystem.greaterEqual(area2, area1)) break; + // } + // if(f) return(x3min); + // else throw new NullPointerException(); } /** * Returns the maximum x3 coordinates of this triangular mesh within the specified rectangle. @@ -834,199 +890,206 @@ double GbTriangularMesh3D::getX3MinimumForRectangle(const double& /*p1x1*/, con * @return the maximum x3 coordinates of this triangular mesh within the specified rectangle * @exception NullPointerException if no triangles are found within the specified rectangle */ -double GbTriangularMesh3D::getX3MaximumForRectangle(const double& /*p1x1*/, const double& /*p1x2*/, const double& /*p2x1*/, const double& /*p2x2*/) +double GbTriangularMesh3D::getX3MaximumForRectangle(const double & /*p1x1*/, const double & /*p1x2*/, + const double & /*p2x1*/, const double & /*p2x2*/) { - throw UbException(UB_EXARGS,"not implemented"); - // GbPolygon3D polygon; - // boolean f = false; - // double x3max = 0.0; - // double t1min, t1max, t2min, t2max; - // double area1 = Math.abs((p1x1-p2x1)*(p1x2-p2x2)); - // double area2 = 0.0; - - // for(int i=0; i<this.triangles.length; i++) - // { - //t1min = this.triangles[i].getX1Minimum(); - //t1max = this.triangles[i].getX1Maximum(); - //if(GbSystem.less2(t1min, t1max, p1x1, p2x1)) continue; - //if(GbSystem.greater2(t1min, t1max, p1x1, p2x1)) continue; - - //t2min = this.triangles[i].getX2Minimum(); - //t2max = this.triangles[i].getX2Maximum(); - //if(GbSystem.less2(t2min, t2max, p1x2, p2x2)) continue; - //if(GbSystem.greater2(t2min, t2max, p1x2, p2x2)) continue; - - //if(GbSystem.inOpenInterval(t1min, p1x1, p2x1) && GbSystem.inOpenInterval(t1max, p1x1, p2x1) && - // GbSystem.inOpenInterval(t2min, p1x2, p2x2) && GbSystem.inOpenInterval(t2max, p1x2, p2x2)) - //{ - // if(f) - // { - // if(this.triangles[i].getX3Maximum() < x3max) x3max = this.triangles[i].getX3Maximum(); - // } - // else - // { - // x3max = this.triangles[i].getX3Maximum(); - // f = true; - // } - // area2 += this.triangles[i].getArea(); - //} - //else - //{ - // polygon = this.triangles[i].createClippedPolygon3D(p1x1, p1x2, p2x1, p2x2); - - // if(polygon != null && polygon.size() > 2) - // { - // if(f) - // { - // if(polygon.getX3Maximum() < x3max) x3max = polygon.getX3Maximum(); - // } - // else - // { - // x3max = polygon.getX3Maximum(); - // f = true; - // } - // area2 += Math.abs(polygon.getArea()); - // } - //} - //if(GbSystem.greaterEqual(area2, area1)) break; - // } - // if(f) return(x3max); - // else throw new NullPointerException(); + throw UbException(UB_EXARGS, "not implemented"); + // GbPolygon3D polygon; + // boolean f = false; + // double x3max = 0.0; + // double t1min, t1max, t2min, t2max; + // double area1 = Math.abs((p1x1-p2x1)*(p1x2-p2x2)); + // double area2 = 0.0; + + // for(int i=0; i<this.triangles.length; i++) + // { + // t1min = this.triangles[i].getX1Minimum(); + // t1max = this.triangles[i].getX1Maximum(); + // if(GbSystem.less2(t1min, t1max, p1x1, p2x1)) continue; + // if(GbSystem.greater2(t1min, t1max, p1x1, p2x1)) continue; + + // t2min = this.triangles[i].getX2Minimum(); + // t2max = this.triangles[i].getX2Maximum(); + // if(GbSystem.less2(t2min, t2max, p1x2, p2x2)) continue; + // if(GbSystem.greater2(t2min, t2max, p1x2, p2x2)) continue; + + // if(GbSystem.inOpenInterval(t1min, p1x1, p2x1) && GbSystem.inOpenInterval(t1max, p1x1, p2x1) && + // GbSystem.inOpenInterval(t2min, p1x2, p2x2) && GbSystem.inOpenInterval(t2max, p1x2, p2x2)) + //{ + // if(f) + // { + // if(this.triangles[i].getX3Maximum() < x3max) x3max = this.triangles[i].getX3Maximum(); + // } + // else + // { + // x3max = this.triangles[i].getX3Maximum(); + // f = true; + // } + // area2 += this.triangles[i].getArea(); + //} + // else + //{ + // polygon = this.triangles[i].createClippedPolygon3D(p1x1, p1x2, p2x1, p2x2); + + // if(polygon != null && polygon.size() > 2) + // { + // if(f) + // { + // if(polygon.getX3Maximum() < x3max) x3max = polygon.getX3Maximum(); + // } + // else + // { + // x3max = polygon.getX3Maximum(); + // f = true; + // } + // area2 += Math.abs(polygon.getArea()); + // } + //} + // if(GbSystem.greaterEqual(area2, area1)) break; + // } + // if(f) return(x3max); + // else throw new NullPointerException(); } /*======================================================================*/ -vector<GbTriangle3D*> GbTriangularMesh3D::getSurfaceTriangleSet() +vector<GbTriangle3D *> GbTriangularMesh3D::getSurfaceTriangleSet() { - vector<GbTriangle3D*> tris; - GbTriangle3D* triangle; - GbPoint3D* p1; - GbPoint3D* p2; - GbPoint3D* p3; - int size = (int)this->triangles->size(); - for(int u=0; u<size;u++) - { - triangle = (*this->triangles)[u]; - p1 = new GbPoint3D(triangle->getPoint1()); - p2 = new GbPoint3D(triangle->getPoint2()); - p3 = new GbPoint3D(triangle->getPoint3()); - tris.push_back(new GbTriangle3D(p1, p2, p3)); - } - return tris; + vector<GbTriangle3D *> tris; + GbTriangle3D *triangle; + GbPoint3D *p1; + GbPoint3D *p2; + GbPoint3D *p3; + int size = (int)this->triangles->size(); + for (int u = 0; u < size; u++) { + triangle = (*this->triangles)[u]; + p1 = new GbPoint3D(triangle->getPoint1()); + p2 = new GbPoint3D(triangle->getPoint2()); + p3 = new GbPoint3D(triangle->getPoint3()); + tris.push_back(new GbTriangle3D(p1, p2, p3)); + } + return tris; } /*======================================================================*/ /* -* Function to determine if the point is inside the polyhedron defined as a 3D object -* using the Halfspace algorithm -* @param xp the x-coordinate of the point -* @param yp the y-coordinate of the point -* @param zp the z-coordinate of the point -* @return true if point is inside else return false -*/ -bool GbTriangularMesh3D::isPointInObject3DHalfSpace(const double& xp, const double& yp, const double& zp) -{ - vector<GbTriangle3D*> *Triangles = this->triangles; - int Trianglesize = (int)Triangles->size(); - //GbPoint3D Point(xp,yp,zp); - for (int i=0; i<Trianglesize; i++) - { - //GbPoint3D* point1 = (*Triangles)[i]->getPoint1(); - //GbPoint3D* point2 = (*Triangles)[i]->getPoint2(); - //GbPoint3D* point3 = (*Triangles)[i]->getPoint3(); - - //GbHalfSpace3D halfspace(point1, point2, point3); - GbHalfSpace3D halfspace((*Triangles)[i]); - if (halfspace.ptInside(xp,yp,zp)) return false; - } - return true; + * Function to determine if the point is inside the polyhedron defined as a 3D object + * using the Halfspace algorithm + * @param xp the x-coordinate of the point + * @param yp the y-coordinate of the point + * @param zp the z-coordinate of the point + * @return true if point is inside else return false + */ +bool GbTriangularMesh3D::isPointInObject3DHalfSpace(const double &xp, const double &yp, const double &zp) +{ + vector<GbTriangle3D *> *Triangles = this->triangles; + int Trianglesize = (int)Triangles->size(); + // GbPoint3D Point(xp,yp,zp); + for (int i = 0; i < Trianglesize; i++) { + // GbPoint3D* point1 = (*Triangles)[i]->getPoint1(); + // GbPoint3D* point2 = (*Triangles)[i]->getPoint2(); + // GbPoint3D* point3 = (*Triangles)[i]->getPoint3(); + + // GbHalfSpace3D halfspace(point1, point2, point3); + GbHalfSpace3D halfspace((*Triangles)[i]); + if (halfspace.ptInside(xp, yp, zp)) + return false; + } + return true; } /*======================================================================*/ -bool GbTriangularMesh3D::isPointInObject3DRayCrossing(const double& xp, const double& yp, const double& zp, int radius, int /*numVertices*/, int numTriangles) +bool GbTriangularMesh3D::isPointInObject3DRayCrossing(const double &xp, const double &yp, const double &zp, int radius, + int /*numVertices*/, int numTriangles) { - GbVector3D point(xp,yp,zp); + GbVector3D point(xp, yp, zp); - if ( this->InPolyhedron(numTriangles, point, radius) ) return true; - else return false; - + if (this->InPolyhedron(numTriangles, point, radius)) + return true; + else + return false; } /*======================================================================*/ -bool GbTriangularMesh3D::isPointInGbObject3D(const double& x1, const double& x2, const double& x3) +bool GbTriangularMesh3D::isPointInGbObject3D(const double &x1, const double &x2, const double &x3) { - double xmin=this->getX1Minimum(); double xmax=this->getX1Maximum(); - double ymin=this->getX2Minimum(); double ymax=this->getX2Maximum(); - double zmin=this->getX3Minimum(); double zmax=this->getX3Maximum(); - double dX = (xmax-xmin)/100.; - double dY = (ymax-ymin)/100.; - double dZ = (zmax-zmin)/100.; - GbCuboid3D boundingCube(xmin-dX, ymin-dY, zmin-dZ, xmax+dX, ymax+dY, zmax+dZ); - if(!boundingCube.isPointInGbObject3D(x1, x2, x3)) { boundingCube.finalize(); return false; } - - // Halfspace algorithm, Area of spherical polygons algorithm or Ray crossing algorithm - GbVector3D bMin(boundingCube.getPoint1()); - GbVector3D bMax(boundingCube.getPoint2()); - - boundingCube.finalize(); - - bMin = bMax.Subtract(bMin); - int radius = (int)(bMin.Length()+1)+1; - - if(this->pointinobjecttest == HALFSPACE) return this->isPointInObject3DHalfSpace(x1,x2,x3); - else if(this->pointinobjecttest == RAYCROSSING) return this->isPointInObject3DRayCrossing(x1,x2,x3,radius,(int)this->nodes->size(),(int)this->triangles->size()); - else throw UbException(UB_EXARGS,"no ptInObjTest"); + double xmin = this->getX1Minimum(); + double xmax = this->getX1Maximum(); + double ymin = this->getX2Minimum(); + double ymax = this->getX2Maximum(); + double zmin = this->getX3Minimum(); + double zmax = this->getX3Maximum(); + double dX = (xmax - xmin) / 100.; + double dY = (ymax - ymin) / 100.; + double dZ = (zmax - zmin) / 100.; + GbCuboid3D boundingCube(xmin - dX, ymin - dY, zmin - dZ, xmax + dX, ymax + dY, zmax + dZ); + if (!boundingCube.isPointInGbObject3D(x1, x2, x3)) { + boundingCube.finalize(); + return false; + } + + // Halfspace algorithm, Area of spherical polygons algorithm or Ray crossing algorithm + GbVector3D bMin(boundingCube.getPoint1()); + GbVector3D bMax(boundingCube.getPoint2()); + + boundingCube.finalize(); + + bMin = bMax.Subtract(bMin); + int radius = (int)(bMin.Length() + 1) + 1; + + if (this->pointinobjecttest == HALFSPACE) + return this->isPointInObject3DHalfSpace(x1, x2, x3); + else if (this->pointinobjecttest == RAYCROSSING) + return this->isPointInObject3DRayCrossing(x1, x2, x3, radius, (int)this->nodes->size(), + (int)this->triangles->size()); + else + throw UbException(UB_EXARGS, "no ptInObjTest"); } /*======================================================================*/ -bool GbTriangularMesh3D::isPointInGbObject3D(const double& /*x1*/, const double& /*x2*/, const double& /*x3*/, bool& /*pointIsOnBoundary*/) +bool GbTriangularMesh3D::isPointInGbObject3D(const double & /*x1*/, const double & /*x2*/, const double & /*x3*/, + bool & /*pointIsOnBoundary*/) { - throw UbException(UB_EXARGS,"not implemented"); + throw UbException(UB_EXARGS, "not implemented"); } /*======================================================================*/ -GbLine3D* GbTriangularMesh3D::createClippedLine3D(GbPoint3D& /*point1*/, GbPoint3D& /*point2*/) +GbLine3D *GbTriangularMesh3D::createClippedLine3D(GbPoint3D & /*point1*/, GbPoint3D & /*point2*/) { - throw UbException(UB_EXARGS,"not implemented"); + throw UbException(UB_EXARGS, "not implemented"); } /*======================================================================*/ -void GbTriangularMesh3D::writeMesh(string filename, WbWriter* writer, bool writeNormals) +void GbTriangularMesh3D::writeMesh(string filename, WbWriter *writer, bool writeNormals) { - vector<UbTupleFloat3 > nodes(triangles->size()*3); - vector<UbTupleInt3 > tris(triangles->size()); - - for(size_t i=0; i<triangles->size(); i++) - { - GbTriangle3D& tri = *((*triangles)[i]); - GbPoint3D& node1 = *tri.getPoint(0); - GbPoint3D& node2 = *tri.getPoint(1); - GbPoint3D& node3 = *tri.getPoint(2); - - nodes[i*3 ] = makeUbTuple( (float)node1.getX1Coordinate() - ,(float)node1.getX2Coordinate() - ,(float)node1.getX3Coordinate()); - nodes[i*3+1] = makeUbTuple( (float)node2.getX1Coordinate() - ,(float)node2.getX2Coordinate() - ,(float)node2.getX3Coordinate()); - nodes[i*3+2] = makeUbTuple( (float)node3.getX1Coordinate() - ,(float)node3.getX2Coordinate() - ,(float)node3.getX3Coordinate()); - - tris[i] = makeUbTuple((int)i*3,(int)i*3+1,(int)i*3+2); - } - writer->writeTriangles(filename,nodes,tris); - - if(writeNormals) - { - vector<UbTupleFloat3 > lineNodes(triangles->size()*2); - vector<UbTupleInt2 > lines(triangles->size()); - for(size_t i=0; i<triangles->size(); i++) - { - GbVector3D vec = (*triangles)[i]->getNormal(); - lineNodes[i*2 ] = makeUbTuple( (float)(*triangles)[i]->getX1Centroid() - ,(float)(*triangles)[i]->getX2Centroid() - ,(float)(*triangles)[i]->getX3Centroid()); - lineNodes[i*2+1] = makeUbTuple( (float)((*triangles)[i]->getX1Centroid()+vec.X1()) - ,(float)((*triangles)[i]->getX2Centroid()+vec.X2()) - ,(float)((*triangles)[i]->getX3Centroid()+vec.X3())); - - lines[i] = makeUbTuple((int)i*2,(int)i*2+1); - } - writer->writeLines(filename+"_normals",lineNodes,lines); - } + vector<UbTupleFloat3> nodes(triangles->size() * 3); + vector<UbTupleInt3> tris(triangles->size()); + + for (size_t i = 0; i < triangles->size(); i++) { + GbTriangle3D &tri = *((*triangles)[i]); + GbPoint3D &node1 = *tri.getPoint(0); + GbPoint3D &node2 = *tri.getPoint(1); + GbPoint3D &node3 = *tri.getPoint(2); + + nodes[i * 3] = + makeUbTuple((float)node1.getX1Coordinate(), (float)node1.getX2Coordinate(), (float)node1.getX3Coordinate()); + nodes[i * 3 + 1] = + makeUbTuple((float)node2.getX1Coordinate(), (float)node2.getX2Coordinate(), (float)node2.getX3Coordinate()); + nodes[i * 3 + 2] = + makeUbTuple((float)node3.getX1Coordinate(), (float)node3.getX2Coordinate(), (float)node3.getX3Coordinate()); + + tris[i] = makeUbTuple((int)i * 3, (int)i * 3 + 1, (int)i * 3 + 2); + } + writer->writeTriangles(filename, nodes, tris); + + if (writeNormals) { + vector<UbTupleFloat3> lineNodes(triangles->size() * 2); + vector<UbTupleInt2> lines(triangles->size()); + for (size_t i = 0; i < triangles->size(); i++) { + GbVector3D vec = (*triangles)[i]->getNormal(); + lineNodes[i * 2] = + makeUbTuple((float)(*triangles)[i]->getX1Centroid(), (float)(*triangles)[i]->getX2Centroid(), + (float)(*triangles)[i]->getX3Centroid()); + lineNodes[i * 2 + 1] = makeUbTuple((float)((*triangles)[i]->getX1Centroid() + vec.X1()), + (float)((*triangles)[i]->getX2Centroid() + vec.X2()), + (float)((*triangles)[i]->getX3Centroid() + vec.X3())); + + lines[i] = makeUbTuple((int)i * 2, (int)i * 2 + 1); + } + writer->writeLines(filename + "_normals", lineNodes, lines); + } } /*======================================================================*/ @@ -1038,68 +1101,76 @@ This function returns a char: 'i': the query point a is strictly interior to polyhedron P. 'o': the query point a is strictly exterior to( or outside of) polyhedron P. */ -bool GbTriangularMesh3D::InPolyhedron( int F, GbVector3D& q, int radius ) +bool GbTriangularMesh3D::InPolyhedron(int F, GbVector3D &q, int radius) { - GbVector3D r; /* Ray endpoint. */ - GbVector3D p; /* Intersection point; not used. */ - int f, k = 0, crossings = 0; - char code = '?'; - - while( k++ < F ) - { - crossings = 0; - - RandomRay( r, radius ); - r = q.Add(r); - // printf("Ray endpoint: (%d,%d,%d)\n", r[0],r[1],r[2] ); - - for ( f = 0; f < F; f++ ) /* Begin check each face */ - { - if( BoxTest( (*this->triangles)[f], q, r ) == false ) code = '0'; // printf("BoxTest = 0!\n"); - else code = SegTriInt( (*this->triangles)[f], q, r, p );// printf( "Face = %d: BoxTest/SegTriInt returns %c\n\n", f, code ); - - /* If ray is degenerate, then goto outer while to generate another. */ - if( code=='p' || code=='v' || code=='e' ) break; //goto LOOP; //printf("Degenerate ray\n"); - /* If ray hits face at interior point, increment crossings. */ - else if ( code=='f' ) crossings++; // printf( "crossings = %d\n", crossings ); - /* If query endpoint q sits on a V/E/F, return that code. */ - else if ( code=='V' || code=='E' || code=='F' ) return true; - /* If ray misses triangle, do nothing. */ - else if ( code=='0' ) { /*nothing to do*/ } - else throw UbException(UB_EXARGS,"Error" ); - } /* End check each face */ - - /* No degeneracies encountered: ray is generic, so finished. */ - if(f>=F) break; - } /* End while loop */ - - // printf( "Crossings = %d\n", crossings ); - /* q strictly interior to polyhedron iff an odd number of crossings. */ - if( (crossings%2) == 1 ) return true; - - return false; + GbVector3D r; /* Ray endpoint. */ + GbVector3D p; /* Intersection point; not used. */ + int f, k = 0, crossings = 0; + char code = '?'; + + while (k++ < F) { + crossings = 0; + + RandomRay(r, radius); + r = q.Add(r); + // printf("Ray endpoint: (%d,%d,%d)\n", r[0],r[1],r[2] ); + + for (f = 0; f < F; f++) /* Begin check each face */ + { + if (BoxTest((*this->triangles)[f], q, r) == false) + code = '0'; // printf("BoxTest = 0!\n"); + else + code = SegTriInt((*this->triangles)[f], q, r, + p); // printf( "Face = %d: BoxTest/SegTriInt returns %c\n\n", f, code ); + + /* If ray is degenerate, then goto outer while to generate another. */ + if (code == 'p' || code == 'v' || code == 'e') + break; // goto LOOP; //printf("Degenerate ray\n"); + /* If ray hits face at interior point, increment crossings. */ + else if (code == 'f') + crossings++; // printf( "crossings = %d\n", crossings ); + /* If query endpoint q sits on a V/E/F, return that code. */ + else if (code == 'V' || code == 'E' || code == 'F') + return true; + /* If ray misses triangle, do nothing. */ + else if (code == '0') { /*nothing to do*/ + } else + throw UbException(UB_EXARGS, "Error"); + } /* End check each face */ + + /* No degeneracies encountered: ray is generic, so finished. */ + if (f >= F) + break; + } /* End while loop */ + + // printf( "Crossings = %d\n", crossings ); + /* q strictly interior to polyhedron iff an odd number of crossings. */ + if ((crossings % 2) == 1) + return true; + + return false; } /* Return a random ray endpoint */ -void GbTriangularMesh3D::RandomRay( GbVector3D& ray, int radius ) +void GbTriangularMesh3D::RandomRay(GbVector3D &ray, int radius) { - double x, y, z, w, t; - - double MAX_INT = 2147483647; - /* Generate a random point on a sphere of radius 1. */ - /* the sphere is sliced at z, and a random point at angle t - generated on the circle of intersection. */ - z = 2.0 * (double) rand() / MAX_INT - 1.0; - t = 2.0 * UbMath::PI * (double) rand() / MAX_INT; - w = sqrt( 1 - z*z ); - x = w * cos( t ); - y = w * sin( t ); - - ray[0] = radius * x; - ray[1] = radius * y; - ray[2] = radius * z; - - /*printf( "RandomRay returns %6d %6d %6d\n", ray[X], ray[Y], ray[Z] );*/ + double x, y, z, w, t; + + double MAX_INT = 2147483647; + /* Generate a random point on a sphere of radius 1. */ + /* the sphere is sliced at z, and a random point at angle t + generated on the circle of intersection. */ + z = 2.0 * (double)rand() / MAX_INT - 1.0; + t = 2.0 * UbMath::PI * (double)rand() / MAX_INT; + w = sqrt(1 - z * z); + x = w * cos(t); + y = w * sin(t); + + ray[0] = radius * x; + ray[1] = radius * y; + ray[2] = radius * z; + + /*printf( "RandomRay returns %6d %6d %6d\n", ray[X], ray[Y], ray[Z] );*/ } /*--------------------------------------------------------------------- @@ -1109,80 +1180,78 @@ void GbTriangularMesh3D::RandomRay( GbVector3D& ray, int radius ) '0': The segment lies strictly to one side or the other of the plane. '1': The segement intersects the plane, and 'p' does not hold. ---------------------------------------------------------------------*/ -char GbTriangularMesh3D::SegPlaneInt( GbTriangle3D* T, GbVector3D& q, GbVector3D& r, GbVector3D& p, int *m) +char GbTriangularMesh3D::SegPlaneInt(GbTriangle3D *T, GbVector3D &q, GbVector3D &r, GbVector3D &p, int *m) { - // cout<<"SegPlaneInt..\n"; - GbVector3D N; double D; - GbVector3D rq; - double num, denom, t; - int i; - - *m = PlaneCoeff( T, N, &D ); - /*printf("m=%d; plane=(%lf,%lf,%lf,%lf)\n", m, N[X],N[Y],N[Z],D);*/ - num = D - q.Dot( N ); - rq = r.Subtract( q ); - denom = rq.Dot( N ); - /*printf("SegPlaneInt: num=%lf, denom=%lf\n", num, denom );*/ - - if ( denom == 0.0 ) { /* Segment is parallel to plane. */ - if ( num == 0.0 ) /* q is on plane. */ - //if (UbMath::zero(denom)) { /* Segment is parallel to plane. */ - // if ( UbMath::zero(num)) /* q is on plane. */ - return 'p'; - else - return '0'; - } - else - t = num / denom; - /*printf("SegPlaneInt: t=%lf \n", t );*/ - - for( i = 0; i < 3; i++ ) - p[i] = q[i] + t * ( r[i] - q[i] ); - - if ( (0.0 < t) && (t < 1.0) ) - return '1'; - else if ( num == 0.0 ) /* t == 0 */ - return 'q'; - else if ( num == denom ) /* t == 1 */ - return 'r'; - else return '0'; - - //if ( (0.0 < t) && (t < 1.0) ) - // return '1'; - //else if ( UbMath::zero(num)) /* t == 0 */ - // return 'q'; - //else if ( UbMath::equal(num , denom) ) /* t == 1 */ - // return 'r'; - //else return '0'; - + // cout<<"SegPlaneInt..\n"; + GbVector3D N; + double D; + GbVector3D rq; + double num, denom, t; + int i; + + *m = PlaneCoeff(T, N, &D); + /*printf("m=%d; plane=(%lf,%lf,%lf,%lf)\n", m, N[X],N[Y],N[Z],D);*/ + num = D - q.Dot(N); + rq = r.Subtract(q); + denom = rq.Dot(N); + /*printf("SegPlaneInt: num=%lf, denom=%lf\n", num, denom );*/ + + if (denom == 0.0) { /* Segment is parallel to plane. */ + if (num == 0.0) /* q is on plane. */ + // if (UbMath::zero(denom)) { /* Segment is parallel to plane. */ + // if ( UbMath::zero(num)) /* q is on plane. */ + return 'p'; + else + return '0'; + } else + t = num / denom; + /*printf("SegPlaneInt: t=%lf \n", t );*/ + + for (i = 0; i < 3; i++) + p[i] = q[i] + t * (r[i] - q[i]); + + if ((0.0 < t) && (t < 1.0)) + return '1'; + else if (num == 0.0) /* t == 0 */ + return 'q'; + else if (num == denom) /* t == 1 */ + return 'r'; + else + return '0'; + + // if ( (0.0 < t) && (t < 1.0) ) + // return '1'; + // else if ( UbMath::zero(num)) /* t == 0 */ + // return 'q'; + // else if ( UbMath::equal(num , denom) ) /* t == 1 */ + // return 'r'; + // else return '0'; } /*--------------------------------------------------------------------- Computes N & D and returns index m of largest component. ---------------------------------------------------------------------*/ -int GbTriangularMesh3D::PlaneCoeff( GbTriangle3D* T, GbVector3D& N, double *D ) +int GbTriangularMesh3D::PlaneCoeff(GbTriangle3D *T, GbVector3D &N, double *D) { - int i; - double t; /* Temp storage */ - double biggest = 0.0; /* Largest component of normal vector. */ - int m = 0; /* Index of largest component. */ - - N = T->getNormal(); - /*printf("PlaneCoeff: N=(%lf,%lf,%lf)\n", N[X],N[Y],N[Z]);*/ - GbVector3D a(T->getPoint1()); - - *D = a.Dot( N ); - - /* Find the largest component of N. */ - for ( i = 0; i < 3; i++ ) - { - t = std::fabs( N[i] ); - if ( t > biggest ) - { - biggest = t; - m = i; - } - } - return m; + int i; + double t; /* Temp storage */ + double biggest = 0.0; /* Largest component of normal vector. */ + int m = 0; /* Index of largest component. */ + + N = T->getNormal(); + /*printf("PlaneCoeff: N=(%lf,%lf,%lf)\n", N[X],N[Y],N[Z]);*/ + GbVector3D a(T->getPoint1()); + + *D = a.Dot(N); + + /* Find the largest component of N. */ + for (i = 0; i < 3; i++) { + t = std::fabs(N[i]); + if (t > biggest) { + biggest = t; + m = i; + } + } + return m; } /* Assumption: p lies in the plane containing T. @@ -1193,128 +1262,126 @@ Returns a char: '0': the query point p does not intersect (misses) triangle T. */ -char GbTriangularMesh3D::InTri3D( GbTriangle3D* T, int m, GbVector3D& /*p*/ ) +char GbTriangularMesh3D::InTri3D(GbTriangle3D *T, int m, GbVector3D & /*p*/) { -// int i; /* Index for X,Y,Z */ - int j; /* Index for X,Y */ -// int k; /* Index for triangle vertex */ - GbVector3D pp; /* projected p */ - GbVector3D Tp[3]; /* projected T: three new vertices */ - - /* Project out coordinate m in both p and the triangular face */ - //j = 0; - //for ( i = 0; i < 3; i++ ) { - // if ( i != m ) { /* skip largest coordinate */ - // pp[j] = p[i]; - // //for ( k = 0; k < 3; k++ ) - // std::cout<<"aachtung###############################################"; - // // Tp[k][j] = Vertices[T[k]][i]; - // j++; - // } - //} - j=0; - if(m!=0) - { - Tp[0][j] = T->getPoint1()->getX1Coordinate(); - Tp[1][j] = T->getPoint2()->getX1Coordinate(); - Tp[2][j] = T->getPoint3()->getX1Coordinate(); - j++; - } - if(m!=1) - { - Tp[0][j] = T->getPoint1()->getX2Coordinate(); - Tp[1][j] = T->getPoint2()->getX2Coordinate(); - Tp[2][j] = T->getPoint3()->getX2Coordinate(); - j++; - } - if(m!=2) - { - Tp[0][j] = T->getPoint1()->getX3Coordinate(); - Tp[1][j] = T->getPoint2()->getX3Coordinate(); - Tp[2][j] = T->getPoint3()->getX3Coordinate(); - j++; - } - - return( InTri2D( Tp, pp ) ); + // int i; /* Index for X,Y,Z */ + int j; /* Index for X,Y */ + // int k; /* Index for triangle vertex */ + GbVector3D pp; /* projected p */ + GbVector3D Tp[3]; /* projected T: three new vertices */ + + /* Project out coordinate m in both p and the triangular face */ + // j = 0; + // for ( i = 0; i < 3; i++ ) { + // if ( i != m ) { /* skip largest coordinate */ + // pp[j] = p[i]; + // //for ( k = 0; k < 3; k++ ) + // std::cout<<"aachtung###############################################"; + // // Tp[k][j] = Vertices[T[k]][i]; + // j++; + // } + //} + j = 0; + if (m != 0) { + Tp[0][j] = T->getPoint1()->getX1Coordinate(); + Tp[1][j] = T->getPoint2()->getX1Coordinate(); + Tp[2][j] = T->getPoint3()->getX1Coordinate(); + j++; + } + if (m != 1) { + Tp[0][j] = T->getPoint1()->getX2Coordinate(); + Tp[1][j] = T->getPoint2()->getX2Coordinate(); + Tp[2][j] = T->getPoint3()->getX2Coordinate(); + j++; + } + if (m != 2) { + Tp[0][j] = T->getPoint1()->getX3Coordinate(); + Tp[1][j] = T->getPoint2()->getX3Coordinate(); + Tp[2][j] = T->getPoint3()->getX3Coordinate(); + j++; + } + + return (InTri2D(Tp, pp)); } -char GbTriangularMesh3D::InTri2D( GbVector3D Tp[3], GbVector3D& pp ) +char GbTriangularMesh3D::InTri2D(GbVector3D Tp[3], GbVector3D &pp) { - double area0, area1, area2; - - /* compute three AreaSign() values for pp w.r.t. each edge of the face in 2D */ - area0 = AreaSign( pp, Tp[0], Tp[1] ); - area1 = AreaSign( pp, Tp[1], Tp[2] ); - area2 = AreaSign( pp, Tp[2], Tp[0] ); - // printf("area0=%f area1=%f area2=%f\n",area0,area1,area2); - - if ( (( area0 == 0. ) && ( area1 > 0. ) && ( area2 > 0. )) || - (( area1 == 0. ) && ( area0 > 0. ) && ( area2 > 0. )) || - (( area2 == 0. ) && ( area0 > 0. ) && ( area1 > 0. )) ) - return 'E'; - - if ( (( area0 == 0. ) && ( area1 < 0. ) && ( area2 < 0. )) || - (( area1 == 0. ) && ( area0 < 0. ) && ( area2 < 0. )) || - (( area2 == 0. ) && ( area0 < 0. ) && ( area1 < 0. )) ) - return 'E'; - - if ( (( area0 > 0. ) && ( area1 > 0. ) && ( area2 > 0. )) || - (( area0 < 0. ) && ( area1 < 0. ) && ( area2 < 0. )) ) - return 'F'; - - if ( ( area0 == 0.0 ) && ( area1 == 0.0 ) && ( area2 == 0.0 ) ) - fprintf( stderr, "Error in InTriD\n" ), exit(EXIT_FAILURE); - - if ( (( area0 == 0. ) && ( area1 == 0. )) || - (( area0 == 0. ) && ( area2 == 0. )) || - (( area1 == 0. ) && ( area2 == 0. )) ) - return 'V'; - - else - return '0'; + double area0, area1, area2; + + /* compute three AreaSign() values for pp w.r.t. each edge of the face in 2D */ + area0 = AreaSign(pp, Tp[0], Tp[1]); + area1 = AreaSign(pp, Tp[1], Tp[2]); + area2 = AreaSign(pp, Tp[2], Tp[0]); + // printf("area0=%f area1=%f area2=%f\n",area0,area1,area2); + + if (((area0 == 0.) && (area1 > 0.) && (area2 > 0.)) || ((area1 == 0.) && (area0 > 0.) && (area2 > 0.)) || + ((area2 == 0.) && (area0 > 0.) && (area1 > 0.))) + return 'E'; + + if (((area0 == 0.) && (area1 < 0.) && (area2 < 0.)) || ((area1 == 0.) && (area0 < 0.) && (area2 < 0.)) || + ((area2 == 0.) && (area0 < 0.) && (area1 < 0.))) + return 'E'; + + if (((area0 > 0.) && (area1 > 0.) && (area2 > 0.)) || ((area0 < 0.) && (area1 < 0.) && (area2 < 0.))) + return 'F'; + + if ((area0 == 0.0) && (area1 == 0.0) && (area2 == 0.0)) + fprintf(stderr, "Error in InTriD\n"), exit(EXIT_FAILURE); + + if (((area0 == 0.) && (area1 == 0.)) || ((area0 == 0.) && (area2 == 0.)) || ((area1 == 0.) && (area2 == 0.))) + return 'V'; + + else + return '0'; } -double GbTriangularMesh3D::AreaSign( GbVector3D& a, GbVector3D& b, GbVector3D& c ) +double GbTriangularMesh3D::AreaSign(GbVector3D &a, GbVector3D &b, GbVector3D &c) { - double area2; + double area2; - area2 = ( b[0] - a[0] ) * ( c[1] - a[1] ) - - ( c[0] - a[0] ) * ( b[1] - a[1] ); + area2 = (b[0] - a[0]) * (c[1] - a[1]) - (c[0] - a[0]) * (b[1] - a[1]); - return area2; - /* The area should be an integer. */ - // FIXME: unrechable code - //if ( area2 > 0.5 ) return 1; - //else if ( area2 < -0.5 ) return -1; - //else return 0; -} + return area2; + /* The area should be an integer. */ + // FIXME: unrechable code + // if ( area2 > 0.5 ) return 1; + // else if ( area2 < -0.5 ) return -1; + // else return 0; +} -char GbTriangularMesh3D::SegTriInt( GbTriangle3D* T, GbVector3D& q, GbVector3D& r, GbVector3D& p ) +char GbTriangularMesh3D::SegTriInt(GbTriangle3D *T, GbVector3D &q, GbVector3D &r, GbVector3D &p) { - int code = '?'; - int m = -1; - - code = (unsigned char)SegPlaneInt( T, q, r, p, &m ); - // printf("SegPlaneInt code=%c, m=%d; p=(%lf,%lf,%lf)\n", code,m,p[0],p[1],p[2]); - - if ( code == '0') return '0'; - else if ( code == 'q') return InTri3D( T, m, q ); - else if ( code == 'r') return InTri3D( T, m, r ); - else if ( code == 'p' ) return InPlane( T, m, q, r, p ); - else if ( code == '1' ) return SegTriCross( T, q, r ); - else /* Error */ return code; + int code = '?'; + int m = -1; + + code = (unsigned char)SegPlaneInt(T, q, r, p, &m); + // printf("SegPlaneInt code=%c, m=%d; p=(%lf,%lf,%lf)\n", code,m,p[0],p[1],p[2]); + + if (code == '0') + return '0'; + else if (code == 'q') + return InTri3D(T, m, q); + else if (code == 'r') + return InTri3D(T, m, r); + else if (code == 'p') + return InPlane(T, m, q, r, p); + else if (code == '1') + return SegTriCross(T, q, r); + else /* Error */ + return code; } -char GbTriangularMesh3D::InPlane( GbTriangle3D* /*T*/, int /*m*/, GbVector3D& /*q*/, GbVector3D& /*r*/, GbVector3D& /*p*/) +char GbTriangularMesh3D::InPlane(GbTriangle3D * /*T*/, int /*m*/, GbVector3D & /*q*/, GbVector3D & /*r*/, + GbVector3D & /*p*/) { - // cout<<"inplane\n"; - /* NOT IMPLEMENTED */ - return 'p'; + // cout<<"inplane\n"; + /* NOT IMPLEMENTED */ + return 'p'; } /*--------------------------------------------------------------------- The signed volumes of three tetrahedra are computed, determined -by the segment qr, and each edge of the triangle. +by the segment qr, and each edge of the triangle. Returns a char: 'v': the open segment includes a vertex of T. 'e': the open segment includes a point in the relative interior of an edge @@ -1324,108 +1391,109 @@ of T. '0': the open segment does not intersect triangle T. ---------------------------------------------------------------------*/ -char GbTriangularMesh3D::SegTriCross( GbTriangle3D* T, GbVector3D& q, GbVector3D& r ) +char GbTriangularMesh3D::SegTriCross(GbTriangle3D *T, GbVector3D &q, GbVector3D &r) { - // cout<<"SegTriCross\n"; - double vol0, vol1, vol2; - GbVector3D vert0(T->getPoint1()); - GbVector3D vert1(T->getPoint2()); - GbVector3D vert2(T->getPoint3()); - - vol0 = VolumeSign( q, vert0, vert1, r ); - vol1 = VolumeSign( q, vert1, vert2, r ); - vol2 = VolumeSign( q, vert2, vert0, r ); - - // printf( "SegTriCross: vol0 = %d; vol1 = %d; vol2 = %d\n", vol0, vol1, vol2 ); - - /* Same sign: segment intersects interior of triangle. */ - if ( ( ( vol0 > 0. ) && ( vol1 > 0. ) && ( vol2 > 0. ) ) || - ( ( vol0 < 0. ) && ( vol1 < 0. ) && ( vol2 < 0. ) ) ) - //if ( ( UbMath::greater(vol0, 0. ) && UbMath::greater(vol1 , 0. ) && UbMath::greater(vol2 , 0. ) ) || - // ( UbMath::less(vol0, 0. ) && UbMath::less(vol1, 0. ) && UbMath::less(vol2, 0. ) ) ) - { - return 'f'; - } - - /* Opposite sign: no intersection between segment and triangle */ - if ( ( ( vol0 > 0. ) || ( vol1 > 0. ) || ( vol2 > 0. ) ) && - ( ( vol0 < 0. ) || ( vol1 < 0. ) || ( vol2 < 0. ) ) ) - { - return '0'; - } - else if ( ( vol0 == 0.0 ) && ( vol1 == 0.0 ) && ( vol2 == 0.0 ) ) - { - std::cout<<vol0<<" "<<vol1<<" "<<vol2<<std::endl; - fprintf( stderr, "Error 1 in SegTriCross\n" ), exit(EXIT_FAILURE); - } - - /* Two zeros: segment intersects vertex. */ - else if ( ( ( vol0 == 0. ) && ( vol1 == 0. ) ) || - ( ( vol0 == 0. ) && ( vol2 == 0. ) ) || - ( ( vol1 == 0. ) && ( vol2 == 0. ) ) ) - { - return 'v'; - } - - /* One zero: segment intersects edge. */ - else if ( ( vol0 == 0. ) || ( vol1 == 0. ) || ( vol2 == 0. ) ) - { - return 'e'; - } - - throw UbException(UB_EXARGS,"fprintf( stderr, Error 2 in SegTriCross\n ), exit(EXIT_FAILURE);"); + // cout<<"SegTriCross\n"; + double vol0, vol1, vol2; + GbVector3D vert0(T->getPoint1()); + GbVector3D vert1(T->getPoint2()); + GbVector3D vert2(T->getPoint3()); + + vol0 = VolumeSign(q, vert0, vert1, r); + vol1 = VolumeSign(q, vert1, vert2, r); + vol2 = VolumeSign(q, vert2, vert0, r); + + // printf( "SegTriCross: vol0 = %d; vol1 = %d; vol2 = %d\n", vol0, vol1, vol2 ); + + /* Same sign: segment intersects interior of triangle. */ + if (((vol0 > 0.) && (vol1 > 0.) && (vol2 > 0.)) || ((vol0 < 0.) && (vol1 < 0.) && (vol2 < 0.))) + // if ( ( UbMath::greater(vol0, 0. ) && UbMath::greater(vol1 , 0. ) && UbMath::greater(vol2 , 0. ) ) || + // ( UbMath::less(vol0, 0. ) && UbMath::less(vol1, 0. ) && UbMath::less(vol2, 0. ) ) ) + { + return 'f'; + } + + /* Opposite sign: no intersection between segment and triangle */ + if (((vol0 > 0.) || (vol1 > 0.) || (vol2 > 0.)) && ((vol0 < 0.) || (vol1 < 0.) || (vol2 < 0.))) { + return '0'; + } else if ((vol0 == 0.0) && (vol1 == 0.0) && (vol2 == 0.0)) { + std::cout << vol0 << " " << vol1 << " " << vol2 << std::endl; + fprintf(stderr, "Error 1 in SegTriCross\n"), exit(EXIT_FAILURE); + } + + /* Two zeros: segment intersects vertex. */ + else if (((vol0 == 0.) && (vol1 == 0.)) || ((vol0 == 0.) && (vol2 == 0.)) || ((vol1 == 0.) && (vol2 == 0.))) { + return 'v'; + } + + /* One zero: segment intersects edge. */ + else if ((vol0 == 0.) || (vol1 == 0.) || (vol2 == 0.)) { + return 'e'; + } + + throw UbException(UB_EXARGS, "fprintf( stderr, Error 2 in SegTriCross\n ), exit(EXIT_FAILURE);"); } - -double GbTriangularMesh3D::VolumeSign( GbVector3D& a, GbVector3D& b, GbVector3D& c, GbVector3D& d ) -{ - double vol; - double ax, ay, az, bx, by, bz, cx, cy, cz, dx, dy, dz; - double bxdx, bydy, bzdz, cxdx, cydy, czdz; - - ax = a[0]; ay = a[1]; az = a[2]; - bx = b[0]; by = b[1]; bz = b[2]; - cx = c[0]; cy = c[1]; cz = c[2]; - dx = d[0]; dy = d[1]; dz = d[2]; - - bxdx=bx-dx; - bydy=by-dy; - bzdz=bz-dz; - cxdx=cx-dx; - cydy=cy-dy; - czdz=cz-dz; - vol = (az-dz) * (bxdx*cydy - bydy*cxdx) - + (ay-dy) * (bzdz*cxdx - bxdx*czdz) - + (ax-dx) * (bydy*czdz - bzdz*cydy); - - //std::cout<< vol<<std::endl; - return vol; - - - /* The volume should be an integer. */ - // FIXME: unreachable code - //if ( vol > 0.5 ) return 1; - //else if ( vol < -0.5 ) return -1; - //else return 0; +double GbTriangularMesh3D::VolumeSign(GbVector3D &a, GbVector3D &b, GbVector3D &c, GbVector3D &d) +{ + double vol; + double ax, ay, az, bx, by, bz, cx, cy, cz, dx, dy, dz; + double bxdx, bydy, bzdz, cxdx, cydy, czdz; + + ax = a[0]; + ay = a[1]; + az = a[2]; + bx = b[0]; + by = b[1]; + bz = b[2]; + cx = c[0]; + cy = c[1]; + cz = c[2]; + dx = d[0]; + dy = d[1]; + dz = d[2]; + + bxdx = bx - dx; + bydy = by - dy; + bzdz = bz - dz; + cxdx = cx - dx; + cydy = cy - dy; + czdz = cz - dz; + vol = (az - dz) * (bxdx * cydy - bydy * cxdx) + (ay - dy) * (bzdz * cxdx - bxdx * czdz) + + (ax - dx) * (bydy * czdz - bzdz * cydy); + + // std::cout<< vol<<std::endl; + return vol; + + /* The volume should be an integer. */ + // FIXME: unreachable code + // if ( vol > 0.5 ) return 1; + // else if ( vol < -0.5 ) return -1; + // else return 0; } -bool GbTriangularMesh3D::BoxTest(GbTriangle3D* triangle, GbVector3D& PointQ, GbVector3D& PointR) +bool GbTriangularMesh3D::BoxTest(GbTriangle3D *triangle, GbVector3D &PointQ, GbVector3D &PointR) { - double minX1 = triangle->getX1Minimum(); - double minX2 = triangle->getX2Minimum(); - double minX3 = triangle->getX3Minimum(); - - double maxX1 = triangle->getX1Maximum(); - double maxX2 = triangle->getX2Maximum(); - double maxX3 = triangle->getX3Maximum(); - - if((PointQ.X1() < minX1) && (PointR.X1() < minX1)) return false; - if((PointQ.X2() < minX2) && (PointR.X2() < minX2)) return false; - if((PointQ.X3() < minX3) && (PointR.X3() < minX3)) return false; - if((PointQ.X1() > maxX1) && (PointR.X1() > maxX1)) return false; - if((PointQ.X2() > maxX2) && (PointR.X2() > maxX2)) return false; - if((PointQ.X3() > maxX3) && (PointR.X3() > maxX3)) return false; - - return true; + double minX1 = triangle->getX1Minimum(); + double minX2 = triangle->getX2Minimum(); + double minX3 = triangle->getX3Minimum(); + + double maxX1 = triangle->getX1Maximum(); + double maxX2 = triangle->getX2Maximum(); + double maxX3 = triangle->getX3Maximum(); + + if ((PointQ.X1() < minX1) && (PointR.X1() < minX1)) + return false; + if ((PointQ.X2() < minX2) && (PointR.X2() < minX2)) + return false; + if ((PointQ.X3() < minX3) && (PointR.X3() < minX3)) + return false; + if ((PointQ.X1() > maxX1) && (PointR.X1() > maxX1)) + return false; + if ((PointQ.X2() > maxX2) && (PointR.X2() > maxX2)) + return false; + if ((PointQ.X3() > maxX3) && (PointR.X3() > maxX3)) + return false; + + return true; } - diff --git a/src/basics/geometry3d/GbTriangularMesh3D.h b/src/basics/geometry3d/GbTriangularMesh3D.h index 2691a95c1b3a404ca9c27e005964a5fe1273d1d3..46be833a2ccd4b6f89b4aa20b7a87a7ca028e118 100644 --- a/src/basics/geometry3d/GbTriangularMesh3D.h +++ b/src/basics/geometry3d/GbTriangularMesh3D.h @@ -7,9 +7,8 @@ #ifndef GBTRIANGULARMESH_H #define GBTRIANGULARMESH_H -#include <sstream> #include <iostream> - +#include <sstream> #include <geometry3d/GbLine3D.h> #include <geometry3d/GbPoint3D.h> @@ -19,8 +18,8 @@ #include <basics/writer/WbWriter.h> #ifdef CAB_RCF - #include <3rdParty/rcf/RcfSerializationIncludes.h> -#endif //CAB_RCF +#include <3rdParty/rcf/RcfSerializationIncludes.h> +#endif // CAB_RCF #include <PointerDefinitions.h> @@ -31,143 +30,144 @@ * This Class provides the triangular meshes. * Note, that up to now no methods for checking consistency are included. * in this context this class describes facettes from an 3D-object !!! -*/ -class GbTriangularMesh3D : public GbObject3D -{ + */ +class GbTriangularMesh3D : public GbObject3D +{ public: - enum POINTINOBJECTTEST { RAYCROSSING, HALFSPACE}; - - GbTriangularMesh3D(); - GbTriangularMesh3D(std::string name, std::vector<GbPoint3D*> *nodes, std::vector<GbTriangle3D*> *triangles); - GbTriangularMesh3D(std::string name, std::vector<GbTriangle3D*> *triangles); - GbTriangularMesh3D(std::string name, std::vector<GbPoint3D*> *nodes, std::vector<GbLine3D*> *edges, std::vector<GbTriangle3D*> *triangles); - ~GbTriangularMesh3D() override; - GbTriangularMesh3D* clone() override { throw UbException(UB_EXARGS,"not implemented"); } - void finalize() override - { - throw UbException("GbTriangularMesh3D::finalize() - toDo"); - } - void setPointInObjectTest(POINTINOBJECTTEST mode) { this->pointinobjecttest = mode; } - - std::string getClassName() {return "GbTriangularMesh3D"; } - - std::string toString() override; - //std::string getName(); - std::vector<GbPoint3D*>* getNodes(); - std::vector<GbTriangle3D*>* getTriangles(); - double getX1Centroid() override; - double getX2Centroid() override; - double getX3Centroid() override; - double getX1Minimum() override; - double getX1Maximum() override; - double getX2Minimum() override; - double getX2Maximum() override; - double getX3Minimum() override; - double getX3Maximum() override; - - void rotate(const double& alpha, const double& beta, const double& gamma) override; - void translate(const double& x1, const double& x2, const double& x3) override; - - void calculateValues(); - void deleteRedundantNodes(); - - UbTupleDouble6 calculateMomentOfInertia(double rhoP); - UbTupleDouble3 calculateCenterOfGravity(); - - double getArea(); - double getVolume(); - double getVolumeForRectangle(const double& p1x1, const double& p1x2, const double& p2x1, const double& p2x2); - std::vector<GbTriangle3D*>* getTrianglesForRectangle(const double& p1x1, const double& p1x2, const double& p2x1, const double& p2x2); - std::vector<GbPoint3D*>* getNodesForRectangle(const double& p1x1, const double& p1x2, const double& p2x1, const double& p2x2); - double getX3RangeForRectangle(const double& p1x1, const double& p1x2, const double& p2x1, const double& p2x2); - double getX3MinimumForRectangle(const double& p1x1, const double& p1x2, const double& p2x1, const double& p2x2); - double getX3MaximumForRectangle(const double& p1x1, const double& p1x2, const double& p2x1, const double& p2x2); - - bool isPointInGbObject3D(const double& x1, const double& x2, const double& x3) override; - - bool isPointInGbObject3D(const double& x1, const double& x2, const double& x3, bool& pointIsOnBoundary) override; - - bool isPointInObject3DHalfSpace(const double& xp, const double& yp, const double& zp); //based on Halfspace algorithm - bool isPointInObject3DSpherical(const double& xp, const double& yp, const double& zp, int numTriangles); //based on Spherical polygon area method - - //should be checked !!! - bool isPointInObject3DRayCrossing(const double& xp, const double& yp, const double& zp, int radius, int numVertices, int numTriangles); //based on Ray tracing algorithm - - bool InPolyhedron( int F, GbVector3D& q, int radius ); - void RandomRay( GbVector3D& ray, int radius ); - char SegPlaneInt( GbTriangle3D* Tri, GbVector3D& q, GbVector3D& r, GbVector3D& p, int *m); - int PlaneCoeff( GbTriangle3D* Tri, GbVector3D& Normal, double *D ); - char InTri3D( GbTriangle3D* T, int m, GbVector3D& p ); - char InTri2D( GbVector3D Tp[3], GbVector3D& pp ); - double AreaSign( GbVector3D& a, GbVector3D& b, GbVector3D& c ); - char SegTriInt(GbTriangle3D* Tri, GbVector3D& q, GbVector3D& r, GbVector3D& p ); - char InPlane( GbTriangle3D* T, int m, GbVector3D& q, GbVector3D& r, GbVector3D& p); - char SegTriCross( GbTriangle3D* T, GbVector3D& q, GbVector3D& r ); - double VolumeSign( GbVector3D& a, GbVector3D& b, GbVector3D& c, GbVector3D& d ); - bool BoxTest ( GbTriangle3D* triangle, GbVector3D& PointQ, GbVector3D& PointR); - //till here !!! - - - GbLine3D* createClippedLine3D (GbPoint3D &point1,GbPoint3D &point2) override; - std::vector<GbTriangle3D*> getSurfaceTriangleSet() override; - - void writeMesh(std::string filename, WbWriter* writer, bool writeNormals=false); - /*======================================================================*/ - using GbObject3D::isPointInGbObject3D; //Grund: dadurch muss man hier isPointInGbObject3D(GbPoint3D*) nicht ausprogrammieren, welche sonst hier "ueberdeckt" waere + enum POINTINOBJECTTEST { RAYCROSSING, HALFSPACE }; + + GbTriangularMesh3D(); + GbTriangularMesh3D(std::string name, std::vector<GbPoint3D *> *nodes, std::vector<GbTriangle3D *> *triangles); + GbTriangularMesh3D(std::string name, std::vector<GbTriangle3D *> *triangles); + GbTriangularMesh3D(std::string name, std::vector<GbPoint3D *> *nodes, std::vector<GbLine3D *> *edges, + std::vector<GbTriangle3D *> *triangles); + ~GbTriangularMesh3D() override; + GbTriangularMesh3D *clone() override { throw UbException(UB_EXARGS, "not implemented"); } + void finalize() override { throw UbException("GbTriangularMesh3D::finalize() - toDo"); } + void setPointInObjectTest(POINTINOBJECTTEST mode) { this->pointinobjecttest = mode; } + + std::string getClassName() { return "GbTriangularMesh3D"; } + + std::string toString() override; + // std::string getName(); + std::vector<GbPoint3D *> *getNodes(); + std::vector<GbTriangle3D *> *getTriangles(); + double getX1Centroid() override; + double getX2Centroid() override; + double getX3Centroid() override; + double getX1Minimum() override; + double getX1Maximum() override; + double getX2Minimum() override; + double getX2Maximum() override; + double getX3Minimum() override; + double getX3Maximum() override; + + void rotate(const double &alpha, const double &beta, const double &gamma) override; + void translate(const double &x1, const double &x2, const double &x3) override; + + void calculateValues(); + void deleteRedundantNodes(); + + UbTupleDouble6 calculateMomentOfInertia(double rhoP); + UbTupleDouble3 calculateCenterOfGravity(); + + double getArea(); + double getVolume(); + double getVolumeForRectangle(const double &p1x1, const double &p1x2, const double &p2x1, const double &p2x2); + std::vector<GbTriangle3D *> *getTrianglesForRectangle(const double &p1x1, const double &p1x2, const double &p2x1, + const double &p2x2); + std::vector<GbPoint3D *> *getNodesForRectangle(const double &p1x1, const double &p1x2, const double &p2x1, + const double &p2x2); + double getX3RangeForRectangle(const double &p1x1, const double &p1x2, const double &p2x1, const double &p2x2); + double getX3MinimumForRectangle(const double &p1x1, const double &p1x2, const double &p2x1, const double &p2x2); + double getX3MaximumForRectangle(const double &p1x1, const double &p1x2, const double &p2x1, const double &p2x2); + + bool isPointInGbObject3D(const double &x1, const double &x2, const double &x3) override; + + bool isPointInGbObject3D(const double &x1, const double &x2, const double &x3, bool &pointIsOnBoundary) override; + + bool isPointInObject3DHalfSpace(const double &xp, const double &yp, + const double &zp); // based on Halfspace algorithm + bool isPointInObject3DSpherical(const double &xp, const double &yp, const double &zp, + int numTriangles); // based on Spherical polygon area method + + // should be checked !!! + bool isPointInObject3DRayCrossing(const double &xp, const double &yp, const double &zp, int radius, int numVertices, + int numTriangles); // based on Ray tracing algorithm + + bool InPolyhedron(int F, GbVector3D &q, int radius); + void RandomRay(GbVector3D &ray, int radius); + char SegPlaneInt(GbTriangle3D *Tri, GbVector3D &q, GbVector3D &r, GbVector3D &p, int *m); + int PlaneCoeff(GbTriangle3D *Tri, GbVector3D &Normal, double *D); + char InTri3D(GbTriangle3D *T, int m, GbVector3D &p); + char InTri2D(GbVector3D Tp[3], GbVector3D &pp); + double AreaSign(GbVector3D &a, GbVector3D &b, GbVector3D &c); + char SegTriInt(GbTriangle3D *Tri, GbVector3D &q, GbVector3D &r, GbVector3D &p); + char InPlane(GbTriangle3D *T, int m, GbVector3D &q, GbVector3D &r, GbVector3D &p); + char SegTriCross(GbTriangle3D *T, GbVector3D &q, GbVector3D &r); + double VolumeSign(GbVector3D &a, GbVector3D &b, GbVector3D &c, GbVector3D &d); + bool BoxTest(GbTriangle3D *triangle, GbVector3D &PointQ, GbVector3D &PointR); + // till here !!! + + GbLine3D *createClippedLine3D(GbPoint3D &point1, GbPoint3D &point2) override; + std::vector<GbTriangle3D *> getSurfaceTriangleSet() override; + + void writeMesh(std::string filename, WbWriter *writer, bool writeNormals = false); + /*======================================================================*/ + using GbObject3D::isPointInGbObject3D; // Grund: dadurch muss man hier isPointInGbObject3D(GbPoint3D*) nicht + // ausprogrammieren, welche sonst hier "ueberdeckt" waere #ifdef CAB_RCF - template<class Archive> - void SF_SERIALIZE(Archive & ar) - { - SF_SERIALIZE_PARENT<GbObject3D>(ar, *this); - ar & triangles; - if(ArchiveTools::isWriting(ar)) - { - for(std::size_t t=0; t<triangles->size(); t++) - { - nodes->push_back((*triangles)[t]->getPoint(0)); - nodes->push_back((*triangles)[t]->getPoint(1)); - nodes->push_back((*triangles)[t]->getPoint(2)); - } - } - //ar & nodes; //<- problem redundanz - //ar & edges; - ar & pointinobjecttest; - ar & x1min; - ar & x1max; - ar & x2min; - ar & x2max; - ar & x3min; - ar & x3max; - ar & consistent; - } -#endif //CAB_RCF + template <class Archive> + void SF_SERIALIZE(Archive &ar) + { + SF_SERIALIZE_PARENT<GbObject3D>(ar, *this); + ar &triangles; + if (ArchiveTools::isWriting(ar)) { + for (std::size_t t = 0; t < triangles->size(); t++) { + nodes->push_back((*triangles)[t]->getPoint(0)); + nodes->push_back((*triangles)[t]->getPoint(1)); + nodes->push_back((*triangles)[t]->getPoint(2)); + } + } + // ar & nodes; //<- problem redundanz + // ar & edges; + ar &pointinobjecttest; + ar &x1min; + ar &x1max; + ar &x2min; + ar &x2max; + ar &x3min; + ar &x3max; + ar &consistent; + } +#endif // CAB_RCF protected: - std::vector<GbPoint3D*>* nodes; - std::vector<GbLine3D*>* edges; - std::vector<GbTriangle3D*>* triangles; + std::vector<GbPoint3D *> *nodes; + std::vector<GbLine3D *> *edges; + std::vector<GbTriangle3D *> *triangles; private: - POINTINOBJECTTEST pointinobjecttest; - void init(); - /*======================================================================*/ - double x1min; - double x1max; - double x2min; - double x2max; - double x3min; - double x3max; - bool consistent; + POINTINOBJECTTEST pointinobjecttest; + void init(); + /*======================================================================*/ + double x1min; + double x1max; + double x2min; + double x2max; + double x3min; + double x3max; + bool consistent; }; /*=========================================================================*/ #if defined(RCF_USE_SF_SERIALIZATION) && !defined(SWIG) - #if CAB_RCF <= 903 - SF_SERIALIZE_ENUM(GbTriangularMesh3D::POINTINOBJECTTEST) //bei klassen ausserhalb der klasse;-) - #endif - UB_AUTO_RUN_NAMED( SF::registerType<GbTriangularMesh3D >("GbTriangularMesh3D ") , SF_GbTriangularMesh3D ); - UB_AUTO_RUN_NAMED( ( SF::registerBaseAndDerived< GbObject3D, GbTriangularMesh3D >() ), SF_GbTriangularMesh3D_BD1 ); -#endif //RCF_USE_SF_SERIALIZATION +#if CAB_RCF <= 903 +SF_SERIALIZE_ENUM(GbTriangularMesh3D::POINTINOBJECTTEST) // bei klassen ausserhalb der klasse;-) +#endif +UB_AUTO_RUN_NAMED(SF::registerType<GbTriangularMesh3D>("GbTriangularMesh3D "), SF_GbTriangularMesh3D); +UB_AUTO_RUN_NAMED((SF::registerBaseAndDerived<GbObject3D, GbTriangularMesh3D>()), SF_GbTriangularMesh3D_BD1); +#endif // RCF_USE_SF_SERIALIZATION #endif diff --git a/src/basics/geometry3d/GbVector3D.cpp b/src/basics/geometry3d/GbVector3D.cpp index e763e425a6677ceeed5b9e23355b311e2a71e8a3..0c666a87586e64be83408eb5769c8f3a46a3ce98 100644 --- a/src/basics/geometry3d/GbVector3D.cpp +++ b/src/basics/geometry3d/GbVector3D.cpp @@ -1,28 +1,28 @@ //======================================================================================= -// ____ ____ __ ______ __________ __ __ __ __ -// \ \ | | | | | _ \ |___ ___| | | | | / \ | | -// \ \ | | | | | |_) | | | | | | | / \ | | -// \ \ | | | | | _ / | | | | | | / /\ \ | | -// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ -// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| -// \ \ | | ________________________________________________________________ -// \ \ | | | ______________________________________________________________| -// \ \| | | | __ __ __ __ ______ _______ -// \ | | |_____ | | | | | | | | | _ \ / _____) -// \ | | _____| | | | | | | | | | | \ \ \_______ +// ____ ____ __ ______ __________ __ __ __ __ +// \ \ | | | | | _ \ |___ ___| | | | | / \ | | +// \ \ | | | | | |_) | | | | | | | / \ | | +// \ \ | | | | | _ / | | | | | | / /\ \ | | +// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ +// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| +// \ \ | | ________________________________________________________________ +// \ \ | | | ______________________________________________________________| +// \ \| | | | __ __ __ __ ______ _______ +// \ | | |_____ | | | | | | | | | _ \ / _____) +// \ | | _____| | | | | | | | | | | \ \ \_______ // \ | | | | |_____ | \_/ | | | | |_/ / _____ | -// \ _____| |__| |________| \_______/ |__| |______/ (_______/ +// \ _____| |__| |________| \_______/ |__| |______/ (_______/ // -// This file is part of VirtualFluids. VirtualFluids is free software: you can +// This file is part of VirtualFluids. VirtualFluids is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of +// License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. -// -// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// +// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License along // with VirtualFluids (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>. // @@ -30,649 +30,513 @@ //! \ingroup geometry3d //! \author Soeren Freudiger, Sebastian Geller //======================================================================================= -#include <GbVector3D.h> #include <GbPoint3D.h> +#include <GbVector3D.h> -#include <basics/utilities/UbMath.h> #include <basics/utilities/UbInfinity.h> +#include <basics/utilities/UbMath.h> using namespace std; - -const GbVector3D GbVector3D::ZERO(0.0,0.0,0.0); -const GbVector3D GbVector3D::UNIT_X1(1.0,0.0,0.0); -const GbVector3D GbVector3D::UNIT_X2(0.0,1.0,0.0); -const GbVector3D GbVector3D::UNIT_X3(0.0,0.0,1.0); +const GbVector3D GbVector3D::ZERO(0.0, 0.0, 0.0); +const GbVector3D GbVector3D::UNIT_X1(1.0, 0.0, 0.0); +const GbVector3D GbVector3D::UNIT_X2(0.0, 1.0, 0.0); +const GbVector3D GbVector3D::UNIT_X3(0.0, 0.0, 1.0); //---------------------------------------------------------------------------- -GbVector3D::GbVector3D () -{ - m_afTuple[0] = 0.0; - m_afTuple[1] = 0.0; - m_afTuple[2] = 0.0; +GbVector3D::GbVector3D() +{ + m_afTuple[0] = 0.0; + m_afTuple[1] = 0.0; + m_afTuple[2] = 0.0; } //---------------------------------------------------------------------------- -GbVector3D::GbVector3D (const double& fX, const double& fY, const double& fZ) +GbVector3D::GbVector3D(const double &fX, const double &fY, const double &fZ) { - m_afTuple[0] = fX; - m_afTuple[1] = fY; - m_afTuple[2] = fZ; + m_afTuple[0] = fX; + m_afTuple[1] = fY; + m_afTuple[2] = fZ; } //---------------------------------------------------------------------------- -GbVector3D::GbVector3D (const GbVector3D& rkV) +GbVector3D::GbVector3D(const GbVector3D &rkV) { - m_afTuple[0] = rkV.m_afTuple[0]; - m_afTuple[1] = rkV.m_afTuple[1]; - m_afTuple[2] = rkV.m_afTuple[2]; + m_afTuple[0] = rkV.m_afTuple[0]; + m_afTuple[1] = rkV.m_afTuple[1]; + m_afTuple[2] = rkV.m_afTuple[2]; } //---------------------------------------------------------------------------- -GbVector3D::GbVector3D (const GbPoint3D& point) +GbVector3D::GbVector3D(const GbPoint3D &point) { - m_afTuple[0] = point.x1; - m_afTuple[1] = point.x2; - m_afTuple[2] = point.x3; + m_afTuple[0] = point.x1; + m_afTuple[1] = point.x2; + m_afTuple[2] = point.x3; } //---------------------------------------------------------------------------- string GbVector3D::toString() { - std::stringstream ss; - ss<< "GbVector3D["<<m_afTuple[0]<<","<<m_afTuple[1]<<","<<m_afTuple[2]<<"]"; - ss<<endl; - return((ss.str()).c_str()); + std::stringstream ss; + ss << "GbVector3D[" << m_afTuple[0] << "," << m_afTuple[1] << "," << m_afTuple[2] << "]"; + ss << endl; + return ((ss.str()).c_str()); } //---------------------------------------------------------------------------- -GbVector3D::operator const double* () const -{ - return m_afTuple; -} +GbVector3D::operator const double *() const { return m_afTuple; } //---------------------------------------------------------------------------- -GbVector3D::operator double* () -{ - return m_afTuple; -} +GbVector3D::operator double *() { return m_afTuple; } //---------------------------------------------------------------------------- -double GbVector3D::operator[] (int i) const +double GbVector3D::operator[](int i) const { - assert( 0 <= i && i <= 2 ); - if ( i < 0 ) - i = 0; - else if ( i > 2 ) - i = 2; + assert(0 <= i && i <= 2); + if (i < 0) + i = 0; + else if (i > 2) + i = 2; - return m_afTuple[i]; + return m_afTuple[i]; } //---------------------------------------------------------------------------- -double& GbVector3D::operator[] (int i) +double &GbVector3D::operator[](int i) { - assert( 0 <= i && i <= 2 ); - if ( i < 0 ) - i = 0; - else if ( i > 2 ) - i = 2; + assert(0 <= i && i <= 2); + if (i < 0) + i = 0; + else if (i > 2) + i = 2; - return m_afTuple[i]; + return m_afTuple[i]; } //---------------------------------------------------------------------------- -double GbVector3D::X1 () const -{ - return m_afTuple[0]; -} +double GbVector3D::X1() const { return m_afTuple[0]; } //---------------------------------------------------------------------------- -double& GbVector3D::X1 () -{ - return m_afTuple[0]; -} +double &GbVector3D::X1() { return m_afTuple[0]; } //---------------------------------------------------------------------------- -double GbVector3D::X2 () const -{ - return m_afTuple[1]; -} +double GbVector3D::X2() const { return m_afTuple[1]; } //---------------------------------------------------------------------------- -double& GbVector3D::X2 () -{ - return m_afTuple[1]; -} +double &GbVector3D::X2() { return m_afTuple[1]; } //---------------------------------------------------------------------------- -double GbVector3D::X3 () const -{ - return m_afTuple[2]; -} +double GbVector3D::X3() const { return m_afTuple[2]; } //---------------------------------------------------------------------------- -double& GbVector3D::X3 () -{ - return m_afTuple[2]; -} +double &GbVector3D::X3() { return m_afTuple[2]; } //---------------------------------------------------------------------------- -GbVector3D& GbVector3D::operator= (const GbVector3D& rkV) +GbVector3D &GbVector3D::operator=(const GbVector3D &rkV) { - if(this == &rkV) + if (this == &rkV) return *this; m_afTuple[0] = rkV.m_afTuple[0]; - m_afTuple[1] = rkV.m_afTuple[1]; - m_afTuple[2] = rkV.m_afTuple[2]; - return *this; + m_afTuple[1] = rkV.m_afTuple[1]; + m_afTuple[2] = rkV.m_afTuple[2]; + return *this; } //---------------------------------------------------------------------------- -int GbVector3D::CompareArrays (const GbVector3D& rkV) const +int GbVector3D::CompareArrays(const GbVector3D &rkV) const { - return memcmp(m_afTuple,rkV.m_afTuple,3*sizeof(double)); + return memcmp(m_afTuple, rkV.m_afTuple, 3 * sizeof(double)); } //---------------------------------------------------------------------------- -bool GbVector3D::operator== (const GbVector3D& rkV) const -{ - return CompareArrays(rkV) == 0; -} +bool GbVector3D::operator==(const GbVector3D &rkV) const { return CompareArrays(rkV) == 0; } //---------------------------------------------------------------------------- -bool GbVector3D::operator!= (const GbVector3D& rkV) const -{ - return CompareArrays(rkV) != 0; -} +bool GbVector3D::operator!=(const GbVector3D &rkV) const { return CompareArrays(rkV) != 0; } //---------------------------------------------------------------------------- -bool GbVector3D::operator< (const GbVector3D& rkV) const -{ - return CompareArrays(rkV) < 0; -} +bool GbVector3D::operator<(const GbVector3D &rkV) const { return CompareArrays(rkV) < 0; } //---------------------------------------------------------------------------- -bool GbVector3D::operator<= (const GbVector3D& rkV) const -{ - return CompareArrays(rkV) <= 0; -} +bool GbVector3D::operator<=(const GbVector3D &rkV) const { return CompareArrays(rkV) <= 0; } //---------------------------------------------------------------------------- -bool GbVector3D::operator> (const GbVector3D& rkV) const -{ - return CompareArrays(rkV) > 0; -} +bool GbVector3D::operator>(const GbVector3D &rkV) const { return CompareArrays(rkV) > 0; } //---------------------------------------------------------------------------- -bool GbVector3D::operator>= (const GbVector3D& rkV) const -{ - return CompareArrays(rkV) >= 0; -} +bool GbVector3D::operator>=(const GbVector3D &rkV) const { return CompareArrays(rkV) >= 0; } //---------------------------------------------------------------------------- -GbVector3D GbVector3D::operator+ (const GbVector3D& rkV) const +GbVector3D GbVector3D::operator+(const GbVector3D &rkV) const { - return GbVector3D( - m_afTuple[0]+rkV.m_afTuple[0], - m_afTuple[1]+rkV.m_afTuple[1], - m_afTuple[2]+rkV.m_afTuple[2]); + return GbVector3D(m_afTuple[0] + rkV.m_afTuple[0], m_afTuple[1] + rkV.m_afTuple[1], + m_afTuple[2] + rkV.m_afTuple[2]); } //---------------------------------------------------------------------------- -GbVector3D GbVector3D::Add(GbVector3D& vector) +GbVector3D GbVector3D::Add(GbVector3D &vector) { - return GbVector3D( - m_afTuple[0]+vector.m_afTuple[0], - m_afTuple[1]+vector.m_afTuple[1], - m_afTuple[2]+vector.m_afTuple[2]); + return GbVector3D(m_afTuple[0] + vector.m_afTuple[0], m_afTuple[1] + vector.m_afTuple[1], + m_afTuple[2] + vector.m_afTuple[2]); } //---------------------------------------------------------------------------- -GbVector3D GbVector3D::operator- (const GbVector3D& rkV) const +GbVector3D GbVector3D::operator-(const GbVector3D &rkV) const { - return GbVector3D( - m_afTuple[0]-rkV.m_afTuple[0], - m_afTuple[1]-rkV.m_afTuple[1], - m_afTuple[2]-rkV.m_afTuple[2]); + return GbVector3D(m_afTuple[0] - rkV.m_afTuple[0], m_afTuple[1] - rkV.m_afTuple[1], + m_afTuple[2] - rkV.m_afTuple[2]); } //---------------------------------------------------------------------------- -GbVector3D GbVector3D::Subtract(GbVector3D& vector) +GbVector3D GbVector3D::Subtract(GbVector3D &vector) { - return GbVector3D( - m_afTuple[0]-vector.m_afTuple[0], - m_afTuple[1]-vector.m_afTuple[1], - m_afTuple[2]-vector.m_afTuple[2]); + return GbVector3D(m_afTuple[0] - vector.m_afTuple[0], m_afTuple[1] - vector.m_afTuple[1], + m_afTuple[2] - vector.m_afTuple[2]); } //---------------------------------------------------------------------------- -GbVector3D GbVector3D::operator* (const double& fScalar) const +GbVector3D GbVector3D::operator*(const double &fScalar) const { - return GbVector3D( fScalar*m_afTuple[0], - fScalar*m_afTuple[1], - fScalar*m_afTuple[2]); + return GbVector3D(fScalar * m_afTuple[0], fScalar * m_afTuple[1], fScalar * m_afTuple[2]); } //---------------------------------------------------------------------------- -GbVector3D GbVector3D::operator/ (const double& fScalar) const +GbVector3D GbVector3D::operator/(const double &fScalar) const { - GbVector3D kQuot; + GbVector3D kQuot; - if ( fScalar != 0.0 ) - { - double fInvScalar = 1.0/fScalar; - kQuot.m_afTuple[0] = fInvScalar*m_afTuple[0]; - kQuot.m_afTuple[1] = fInvScalar*m_afTuple[1]; - kQuot.m_afTuple[2] = fInvScalar*m_afTuple[2]; - } - else - { - kQuot.m_afTuple[0] = Ub::inf; - kQuot.m_afTuple[1] = Ub::inf; - kQuot.m_afTuple[2] = Ub::inf; - } + if (fScalar != 0.0) { + double fInvScalar = 1.0 / fScalar; + kQuot.m_afTuple[0] = fInvScalar * m_afTuple[0]; + kQuot.m_afTuple[1] = fInvScalar * m_afTuple[1]; + kQuot.m_afTuple[2] = fInvScalar * m_afTuple[2]; + } else { + kQuot.m_afTuple[0] = Ub::inf; + kQuot.m_afTuple[1] = Ub::inf; + kQuot.m_afTuple[2] = Ub::inf; + } - return kQuot; + return kQuot; } //---------------------------------------------------------------------------- -GbVector3D GbVector3D::operator- () const -{ - return GbVector3D( - -m_afTuple[0], - -m_afTuple[1], - -m_afTuple[2]); -} +GbVector3D GbVector3D::operator-() const { return GbVector3D(-m_afTuple[0], -m_afTuple[1], -m_afTuple[2]); } //---------------------------------------------------------------------------- -GbVector3D operator* (const double& fScalar, const GbVector3D& rkV) +GbVector3D operator*(const double &fScalar, const GbVector3D &rkV) { - return GbVector3D( - fScalar*rkV[0], - fScalar*rkV[1], - fScalar*rkV[2]); + return GbVector3D(fScalar * rkV[0], fScalar * rkV[1], fScalar * rkV[2]); } //---------------------------------------------------------------------------- -GbVector3D& GbVector3D::operator+= (const GbVector3D& rkV) +GbVector3D &GbVector3D::operator+=(const GbVector3D &rkV) { - m_afTuple[0] += rkV.m_afTuple[0]; - m_afTuple[1] += rkV.m_afTuple[1]; - m_afTuple[2] += rkV.m_afTuple[2]; - return *this; + m_afTuple[0] += rkV.m_afTuple[0]; + m_afTuple[1] += rkV.m_afTuple[1]; + m_afTuple[2] += rkV.m_afTuple[2]; + return *this; } //---------------------------------------------------------------------------- -GbVector3D& GbVector3D::operator-= (const GbVector3D& rkV) +GbVector3D &GbVector3D::operator-=(const GbVector3D &rkV) { - m_afTuple[0] -= rkV.m_afTuple[0]; - m_afTuple[1] -= rkV.m_afTuple[1]; - m_afTuple[2] -= rkV.m_afTuple[2]; - return *this; + m_afTuple[0] -= rkV.m_afTuple[0]; + m_afTuple[1] -= rkV.m_afTuple[1]; + m_afTuple[2] -= rkV.m_afTuple[2]; + return *this; } //---------------------------------------------------------------------------- -GbVector3D& GbVector3D::operator*= (const double& fScalar) +GbVector3D &GbVector3D::operator*=(const double &fScalar) { - m_afTuple[0] *= fScalar; - m_afTuple[1] *= fScalar; - m_afTuple[2] *= fScalar; - return *this; + m_afTuple[0] *= fScalar; + m_afTuple[1] *= fScalar; + m_afTuple[2] *= fScalar; + return *this; } //---------------------------------------------------------------------------- -GbVector3D& GbVector3D::operator/= (const double& fScalar) +GbVector3D &GbVector3D::operator/=(const double &fScalar) { - if ( fScalar != (double)0.0 ) - { - double fInvScalar = ((double)1.0)/fScalar; - m_afTuple[0] *= fInvScalar; - m_afTuple[1] *= fInvScalar; - m_afTuple[2] *= fInvScalar; - } - else - { - m_afTuple[0] = Ub::inf; - m_afTuple[1] = Ub::inf; - m_afTuple[2] = Ub::inf; - } + if (fScalar != (double)0.0) { + double fInvScalar = ((double)1.0) / fScalar; + m_afTuple[0] *= fInvScalar; + m_afTuple[1] *= fInvScalar; + m_afTuple[2] *= fInvScalar; + } else { + m_afTuple[0] = Ub::inf; + m_afTuple[1] = Ub::inf; + m_afTuple[2] = Ub::inf; + } - return *this; + return *this; } //---------------------------------------------------------------------------- -GbVector3D GbVector3D::Scale(const double& x) +GbVector3D GbVector3D::Scale(const double &x) { - GbVector3D PointA(0.0,0.0,0.0); - PointA.m_afTuple[0] = x * m_afTuple[0]; - PointA.m_afTuple[1] = x * m_afTuple[1]; - PointA.m_afTuple[2] = x * m_afTuple[2]; - return PointA; + GbVector3D PointA(0.0, 0.0, 0.0); + PointA.m_afTuple[0] = x * m_afTuple[0]; + PointA.m_afTuple[1] = x * m_afTuple[1]; + PointA.m_afTuple[2] = x * m_afTuple[2]; + return PointA; } //---------------------------------------------------------------------------- -double GbVector3D::Length () const +double GbVector3D::Length() const { - return std::sqrt( - m_afTuple[0]*m_afTuple[0] + - m_afTuple[1]*m_afTuple[1] + - m_afTuple[2]*m_afTuple[2]); + return std::sqrt(m_afTuple[0] * m_afTuple[0] + m_afTuple[1] * m_afTuple[1] + m_afTuple[2] * m_afTuple[2]); } //---------------------------------------------------------------------------- -double GbVector3D::SquaredLength () const +double GbVector3D::SquaredLength() const { - return - m_afTuple[0]*m_afTuple[0] + - m_afTuple[1]*m_afTuple[1] + - m_afTuple[2]*m_afTuple[2]; + return m_afTuple[0] * m_afTuple[0] + m_afTuple[1] * m_afTuple[1] + m_afTuple[2] * m_afTuple[2]; } //---------------------------------------------------------------------------- -double GbVector3D::Dot (const GbVector3D& rkV) const +double GbVector3D::Dot(const GbVector3D &rkV) const { - return - m_afTuple[0]*rkV.m_afTuple[0] + - m_afTuple[1]*rkV.m_afTuple[1] + - m_afTuple[2]*rkV.m_afTuple[2]; + return m_afTuple[0] * rkV.m_afTuple[0] + m_afTuple[1] * rkV.m_afTuple[1] + m_afTuple[2] * rkV.m_afTuple[2]; } //---------------------------------------------------------------------------- -double GbVector3D::Normalize () +double GbVector3D::Normalize() { - double fLength = Length(); + double fLength = Length(); - if ( fLength > UbMath::Epsilon<double>::val() ) - { - double fInvLength = ((double)1.0)/fLength; - m_afTuple[0] *= fInvLength; - m_afTuple[1] *= fInvLength; - m_afTuple[2] *= fInvLength; - } - else - { - fLength = 0.0; - m_afTuple[0] = 0.0; - m_afTuple[1] = 0.0; - m_afTuple[2] = 0.0; - } + if (fLength > UbMath::Epsilon<double>::val()) { + double fInvLength = ((double)1.0) / fLength; + m_afTuple[0] *= fInvLength; + m_afTuple[1] *= fInvLength; + m_afTuple[2] *= fInvLength; + } else { + fLength = 0.0; + m_afTuple[0] = 0.0; + m_afTuple[1] = 0.0; + m_afTuple[2] = 0.0; + } - return fLength; + return fLength; } //---------------------------------------------------------------------------- -GbVector3D GbVector3D::Cross (const GbVector3D& rkV) const +GbVector3D GbVector3D::Cross(const GbVector3D &rkV) const { - return GbVector3D( - m_afTuple[1]*rkV.m_afTuple[2] - m_afTuple[2]*rkV.m_afTuple[1], - m_afTuple[2]*rkV.m_afTuple[0] - m_afTuple[0]*rkV.m_afTuple[2], - m_afTuple[0]*rkV.m_afTuple[1] - m_afTuple[1]*rkV.m_afTuple[0]); + return GbVector3D(m_afTuple[1] * rkV.m_afTuple[2] - m_afTuple[2] * rkV.m_afTuple[1], + m_afTuple[2] * rkV.m_afTuple[0] - m_afTuple[0] * rkV.m_afTuple[2], + m_afTuple[0] * rkV.m_afTuple[1] - m_afTuple[1] * rkV.m_afTuple[0]); } //---------------------------------------------------------------------------- -GbVector3D GbVector3D::UnitCross (const GbVector3D& rkV) const +GbVector3D GbVector3D::UnitCross(const GbVector3D &rkV) const { - GbVector3D kCross( - m_afTuple[1]*rkV.m_afTuple[2] - m_afTuple[2]*rkV.m_afTuple[1], - m_afTuple[2]*rkV.m_afTuple[0] - m_afTuple[0]*rkV.m_afTuple[2], - m_afTuple[0]*rkV.m_afTuple[1] - m_afTuple[1]*rkV.m_afTuple[0]); - kCross.Normalize(); - return kCross; + GbVector3D kCross(m_afTuple[1] * rkV.m_afTuple[2] - m_afTuple[2] * rkV.m_afTuple[1], + m_afTuple[2] * rkV.m_afTuple[0] - m_afTuple[0] * rkV.m_afTuple[2], + m_afTuple[0] * rkV.m_afTuple[1] - m_afTuple[1] * rkV.m_afTuple[0]); + kCross.Normalize(); + return kCross; } //---------------------------------------------------------------------------- -void GbVector3D::GetBarycentrics (const GbVector3D& rkV0, - const GbVector3D& rkV1, const GbVector3D& rkV2, - const GbVector3D& rkV3, double afBary[4]) const +void GbVector3D::GetBarycentrics(const GbVector3D &rkV0, const GbVector3D &rkV1, const GbVector3D &rkV2, + const GbVector3D &rkV3, double afBary[4]) const { - // compute the vectors relative to V3 of the tetrahedron - GbVector3D akDiff[4] = - { - rkV0 - rkV3, - rkV1 - rkV3, - rkV2 - rkV3, - *this - rkV3 - }; - - // If the vertices have large magnitude, the linear system of - // equations for computing barycentric coordinates can be - // ill-conditioned. To avoid this, uniformly scale the tetrahedron - // edges to be of order 1. The scaling of all differences does not - // change the barycentric coordinates. - double fMax = (double)0.0; - int i; - for (i = 0; i < 3; i++) - { - for (int j = 0; j < 3; j++) - { - double fValue = std::fabs(akDiff[i][j]); - if ( fValue > fMax ) - fMax = fValue; - } - } + // compute the vectors relative to V3 of the tetrahedron + GbVector3D akDiff[4] = { rkV0 - rkV3, rkV1 - rkV3, rkV2 - rkV3, *this - rkV3 }; - // scale down only large data - if ( fMax > (double)1.0 ) - { - double fInvMax = ((double)1.0)/fMax; - for (i = 0; i < 4; i++) - akDiff[i] *= fInvMax; - } + // If the vertices have large magnitude, the linear system of + // equations for computing barycentric coordinates can be + // ill-conditioned. To avoid this, uniformly scale the tetrahedron + // edges to be of order 1. The scaling of all differences does not + // change the barycentric coordinates. + double fMax = (double)0.0; + int i; + for (i = 0; i < 3; i++) { + for (int j = 0; j < 3; j++) { + double fValue = std::fabs(akDiff[i][j]); + if (fValue > fMax) + fMax = fValue; + } + } - double fDet = akDiff[0].Dot(akDiff[1].Cross(akDiff[2])); - GbVector3D kE1cE2 = akDiff[1].Cross(akDiff[2]); - GbVector3D kE2cE0 = akDiff[2].Cross(akDiff[0]); - GbVector3D kE0cE1 = akDiff[0].Cross(akDiff[1]); - if ( std::fabs(fDet) > UbMath::Epsilon<double>::val() ) - { - double fInvDet = ((double)1.0)/fDet; - afBary[0] = akDiff[3].Dot(kE1cE2)*fInvDet; - afBary[1] = akDiff[3].Dot(kE2cE0)*fInvDet; - afBary[2] = akDiff[3].Dot(kE0cE1)*fInvDet; - afBary[3] = (double)1.0 - afBary[0] - afBary[1] - afBary[2]; - } - else - { - // The tetrahedron is potentially flat. Determine the face of - // maximum area and compute barycentric coordinates with respect - // to that face. - GbVector3D kE02 = rkV0 - rkV2; - GbVector3D kE12 = rkV1 - rkV2; - GbVector3D kE02cE12 = kE02.Cross(kE12); - double fMaxSqrArea = kE02cE12.SquaredLength(); - int iMaxIndex = 3; - double fSqrArea = kE0cE1.SquaredLength(); - if ( fSqrArea > fMaxSqrArea ) - { - iMaxIndex = 0; - fMaxSqrArea = fSqrArea; - } - fSqrArea = kE1cE2.SquaredLength(); - if ( fSqrArea > fMaxSqrArea ) - { - iMaxIndex = 1; - fMaxSqrArea = fSqrArea; - } - fSqrArea = kE2cE0.SquaredLength(); - if ( fSqrArea > fMaxSqrArea ) - { - iMaxIndex = 2; - fMaxSqrArea = fSqrArea; - } + // scale down only large data + if (fMax > (double)1.0) { + double fInvMax = ((double)1.0) / fMax; + for (i = 0; i < 4; i++) + akDiff[i] *= fInvMax; + } - if ( fMaxSqrArea > UbMath::Epsilon<double>::val() ) - { - double fInvSqrArea = ((double)1.0)/fMaxSqrArea; - GbVector3D kTmp; - if ( iMaxIndex == 0 ) - { - kTmp = akDiff[3].Cross(akDiff[1]); - afBary[0] = kE0cE1.Dot(kTmp)*fInvSqrArea; - kTmp = akDiff[0].Cross(akDiff[3]); - afBary[1] = kE0cE1.Dot(kTmp)*fInvSqrArea; - afBary[2] = (double)0.0; - afBary[3] = (double)1.0 - afBary[0] - afBary[1]; - } - else if ( iMaxIndex == 1 ) - { - afBary[0] = (double)0.0; - kTmp = akDiff[3].Cross(akDiff[2]); - afBary[1] = kE1cE2.Dot(kTmp)*fInvSqrArea; - kTmp = akDiff[1].Cross(akDiff[3]); - afBary[2] = kE1cE2.Dot(kTmp)*fInvSqrArea; - afBary[3] = (double)1.0 - afBary[1] - afBary[2]; - } - else if ( iMaxIndex == 2 ) - { - kTmp = akDiff[2].Cross(akDiff[3]); - afBary[0] = kE2cE0.Dot(kTmp)*fInvSqrArea; - afBary[1] = (double)0.0; - kTmp = akDiff[3].Cross(akDiff[0]); - afBary[2] = kE2cE0.Dot(kTmp)*fInvSqrArea; - afBary[3] = (double)1.0 - afBary[0] - afBary[2]; - } - else - { - akDiff[3] = *this - rkV2; - kTmp = akDiff[3].Cross(kE12); - afBary[0] = kE02cE12.Dot(kTmp)*fInvSqrArea; - kTmp = kE02.Cross(akDiff[3]); - afBary[1] = kE02cE12.Dot(kTmp)*fInvSqrArea; - afBary[2] = (double)1.0 - afBary[0] - afBary[1]; - afBary[3] = (double)0.0; - } - } - else - { - // The tetrahedron is potentially a sliver. Determine the edge of - // maximum length and compute barycentric coordinates with respect - // to that edge. - double fMaxSqrLength = akDiff[0].SquaredLength(); - iMaxIndex = 0; // <V0,V3> - double fSqrLength = akDiff[1].SquaredLength(); - if ( fSqrLength > fMaxSqrLength ) - { - iMaxIndex = 1; // <V1,V3> - fMaxSqrLength = fSqrLength; - } - fSqrLength = akDiff[2].SquaredLength(); - if ( fSqrLength > fMaxSqrLength ) - { - iMaxIndex = 2; // <V2,V3> - fMaxSqrLength = fSqrLength; - } - fSqrLength = kE02.SquaredLength(); - if ( fSqrLength > fMaxSqrLength ) - { - iMaxIndex = 3; // <V0,V2> - fMaxSqrLength = fSqrLength; - } - fSqrLength = kE12.SquaredLength(); - if ( fSqrLength > fMaxSqrLength ) - { - iMaxIndex = 4; // <V1,V2> - fMaxSqrLength = fSqrLength; - } - GbVector3D kE01 = rkV0 - rkV1; - fSqrLength = kE01.SquaredLength(); - if ( fSqrLength > fMaxSqrLength ) - { - iMaxIndex = 5; // <V0,V1> - fMaxSqrLength = fSqrLength; - } + double fDet = akDiff[0].Dot(akDiff[1].Cross(akDiff[2])); + GbVector3D kE1cE2 = akDiff[1].Cross(akDiff[2]); + GbVector3D kE2cE0 = akDiff[2].Cross(akDiff[0]); + GbVector3D kE0cE1 = akDiff[0].Cross(akDiff[1]); + if (std::fabs(fDet) > UbMath::Epsilon<double>::val()) { + double fInvDet = ((double)1.0) / fDet; + afBary[0] = akDiff[3].Dot(kE1cE2) * fInvDet; + afBary[1] = akDiff[3].Dot(kE2cE0) * fInvDet; + afBary[2] = akDiff[3].Dot(kE0cE1) * fInvDet; + afBary[3] = (double)1.0 - afBary[0] - afBary[1] - afBary[2]; + } else { + // The tetrahedron is potentially flat. Determine the face of + // maximum area and compute barycentric coordinates with respect + // to that face. + GbVector3D kE02 = rkV0 - rkV2; + GbVector3D kE12 = rkV1 - rkV2; + GbVector3D kE02cE12 = kE02.Cross(kE12); + double fMaxSqrArea = kE02cE12.SquaredLength(); + int iMaxIndex = 3; + double fSqrArea = kE0cE1.SquaredLength(); + if (fSqrArea > fMaxSqrArea) { + iMaxIndex = 0; + fMaxSqrArea = fSqrArea; + } + fSqrArea = kE1cE2.SquaredLength(); + if (fSqrArea > fMaxSqrArea) { + iMaxIndex = 1; + fMaxSqrArea = fSqrArea; + } + fSqrArea = kE2cE0.SquaredLength(); + if (fSqrArea > fMaxSqrArea) { + iMaxIndex = 2; + fMaxSqrArea = fSqrArea; + } - if ( fMaxSqrLength > UbMath::Epsilon<double>::val() ) - { - double fInvSqrLength = ((double)1.0)/fMaxSqrLength; - if ( iMaxIndex == 0 ) - { - // P-V3 = t*(V0-V3) - afBary[0] = akDiff[3].Dot(akDiff[0])*fInvSqrLength; - afBary[1] = (double)0.0; - afBary[2] = (double)0.0; - afBary[3] = (double)1.0 - afBary[0]; + if (fMaxSqrArea > UbMath::Epsilon<double>::val()) { + double fInvSqrArea = ((double)1.0) / fMaxSqrArea; + GbVector3D kTmp; + if (iMaxIndex == 0) { + kTmp = akDiff[3].Cross(akDiff[1]); + afBary[0] = kE0cE1.Dot(kTmp) * fInvSqrArea; + kTmp = akDiff[0].Cross(akDiff[3]); + afBary[1] = kE0cE1.Dot(kTmp) * fInvSqrArea; + afBary[2] = (double)0.0; + afBary[3] = (double)1.0 - afBary[0] - afBary[1]; + } else if (iMaxIndex == 1) { + afBary[0] = (double)0.0; + kTmp = akDiff[3].Cross(akDiff[2]); + afBary[1] = kE1cE2.Dot(kTmp) * fInvSqrArea; + kTmp = akDiff[1].Cross(akDiff[3]); + afBary[2] = kE1cE2.Dot(kTmp) * fInvSqrArea; + afBary[3] = (double)1.0 - afBary[1] - afBary[2]; + } else if (iMaxIndex == 2) { + kTmp = akDiff[2].Cross(akDiff[3]); + afBary[0] = kE2cE0.Dot(kTmp) * fInvSqrArea; + afBary[1] = (double)0.0; + kTmp = akDiff[3].Cross(akDiff[0]); + afBary[2] = kE2cE0.Dot(kTmp) * fInvSqrArea; + afBary[3] = (double)1.0 - afBary[0] - afBary[2]; + } else { + akDiff[3] = *this - rkV2; + kTmp = akDiff[3].Cross(kE12); + afBary[0] = kE02cE12.Dot(kTmp) * fInvSqrArea; + kTmp = kE02.Cross(akDiff[3]); + afBary[1] = kE02cE12.Dot(kTmp) * fInvSqrArea; + afBary[2] = (double)1.0 - afBary[0] - afBary[1]; + afBary[3] = (double)0.0; } - else if ( iMaxIndex == 1 ) - { - // P-V3 = t*(V1-V3) - afBary[0] = (double)0.0; - afBary[1] = akDiff[3].Dot(akDiff[1])*fInvSqrLength; - afBary[2] = (double)0.0; - afBary[3] = (double)1.0 - afBary[1]; + } else { + // The tetrahedron is potentially a sliver. Determine the edge of + // maximum length and compute barycentric coordinates with respect + // to that edge. + double fMaxSqrLength = akDiff[0].SquaredLength(); + iMaxIndex = 0; // <V0,V3> + double fSqrLength = akDiff[1].SquaredLength(); + if (fSqrLength > fMaxSqrLength) { + iMaxIndex = 1; // <V1,V3> + fMaxSqrLength = fSqrLength; } - else if ( iMaxIndex == 2 ) - { - // P-V3 = t*(V2-V3) - afBary[0] = (double)0.0; - afBary[1] = (double)0.0; - afBary[2] = akDiff[3].Dot(akDiff[2])*fInvSqrLength; - afBary[3] = (double)1.0 - afBary[2]; + fSqrLength = akDiff[2].SquaredLength(); + if (fSqrLength > fMaxSqrLength) { + iMaxIndex = 2; // <V2,V3> + fMaxSqrLength = fSqrLength; } - else if ( iMaxIndex == 3 ) - { - // P-V2 = t*(V0-V2) - akDiff[3] = *this - rkV2; - afBary[0] = akDiff[3].Dot(kE02)*fInvSqrLength; - afBary[1] = (double)0.0; - afBary[2] = (double)1.0 - afBary[0]; - afBary[3] = (double)0.0; + fSqrLength = kE02.SquaredLength(); + if (fSqrLength > fMaxSqrLength) { + iMaxIndex = 3; // <V0,V2> + fMaxSqrLength = fSqrLength; } - else if ( iMaxIndex == 4 ) - { - // P-V2 = t*(V1-V2) - akDiff[3] = *this - rkV2; - afBary[0] = (double)0.0; - afBary[1] = akDiff[3].Dot(kE12)*fInvSqrLength; - afBary[2] = (double)1.0 - afBary[1]; - afBary[3] = (double)0.0; + fSqrLength = kE12.SquaredLength(); + if (fSqrLength > fMaxSqrLength) { + iMaxIndex = 4; // <V1,V2> + fMaxSqrLength = fSqrLength; } - else - { - // P-V1 = t*(V0-V1) - akDiff[3] = *this - rkV1; - afBary[0] = akDiff[3].Dot(kE01)*fInvSqrLength; - afBary[1] = (double)1.0 - afBary[0]; - afBary[2] = (double)0.0; - afBary[3] = (double)0.0; + GbVector3D kE01 = rkV0 - rkV1; + fSqrLength = kE01.SquaredLength(); + if (fSqrLength > fMaxSqrLength) { + iMaxIndex = 5; // <V0,V1> + fMaxSqrLength = fSqrLength; } - } - else - { - // tetrahedron is a nearly a point, just return equal weights - afBary[0] = (double)0.25; - afBary[1] = afBary[0]; - afBary[2] = afBary[0]; - afBary[3] = afBary[0]; - } - } - } + + if (fMaxSqrLength > UbMath::Epsilon<double>::val()) { + double fInvSqrLength = ((double)1.0) / fMaxSqrLength; + if (iMaxIndex == 0) { + // P-V3 = t*(V0-V3) + afBary[0] = akDiff[3].Dot(akDiff[0]) * fInvSqrLength; + afBary[1] = (double)0.0; + afBary[2] = (double)0.0; + afBary[3] = (double)1.0 - afBary[0]; + } else if (iMaxIndex == 1) { + // P-V3 = t*(V1-V3) + afBary[0] = (double)0.0; + afBary[1] = akDiff[3].Dot(akDiff[1]) * fInvSqrLength; + afBary[2] = (double)0.0; + afBary[3] = (double)1.0 - afBary[1]; + } else if (iMaxIndex == 2) { + // P-V3 = t*(V2-V3) + afBary[0] = (double)0.0; + afBary[1] = (double)0.0; + afBary[2] = akDiff[3].Dot(akDiff[2]) * fInvSqrLength; + afBary[3] = (double)1.0 - afBary[2]; + } else if (iMaxIndex == 3) { + // P-V2 = t*(V0-V2) + akDiff[3] = *this - rkV2; + afBary[0] = akDiff[3].Dot(kE02) * fInvSqrLength; + afBary[1] = (double)0.0; + afBary[2] = (double)1.0 - afBary[0]; + afBary[3] = (double)0.0; + } else if (iMaxIndex == 4) { + // P-V2 = t*(V1-V2) + akDiff[3] = *this - rkV2; + afBary[0] = (double)0.0; + afBary[1] = akDiff[3].Dot(kE12) * fInvSqrLength; + afBary[2] = (double)1.0 - afBary[1]; + afBary[3] = (double)0.0; + } else { + // P-V1 = t*(V0-V1) + akDiff[3] = *this - rkV1; + afBary[0] = akDiff[3].Dot(kE01) * fInvSqrLength; + afBary[1] = (double)1.0 - afBary[0]; + afBary[2] = (double)0.0; + afBary[3] = (double)0.0; + } + } else { + // tetrahedron is a nearly a point, just return equal weights + afBary[0] = (double)0.25; + afBary[1] = afBary[0]; + afBary[2] = afBary[0]; + afBary[3] = afBary[0]; + } + } + } } //---------------------------------------------------------------------------- -void GbVector3D::Orthonormalize (GbVector3D& rkU, GbVector3D& rkV, GbVector3D& rkW) +void GbVector3D::Orthonormalize(GbVector3D &rkU, GbVector3D &rkV, GbVector3D &rkW) { - // If the input vectors are v0, v1, and v2, then the Gram-Schmidt - // orthonormalization produces vectors u0, u1, and u2 as follows, - // - // u0 = v0/|v0| - // u1 = (v1-(u0*v1)u0)/|v1-(u0*v1)u0| - // u2 = (v2-(u0*v2)u0-(u1*v2)u1)/|v2-(u0*v2)u0-(u1*v2)u1| - // - // where |A| indicates length of vector A and A*B indicates dot - // product of vectors A and B. + // If the input vectors are v0, v1, and v2, then the Gram-Schmidt + // orthonormalization produces vectors u0, u1, and u2 as follows, + // + // u0 = v0/|v0| + // u1 = (v1-(u0*v1)u0)/|v1-(u0*v1)u0| + // u2 = (v2-(u0*v2)u0-(u1*v2)u1)/|v2-(u0*v2)u0-(u1*v2)u1| + // + // where |A| indicates length of vector A and A*B indicates dot + // product of vectors A and B. - // compute u0 - rkU.Normalize(); + // compute u0 + rkU.Normalize(); - // compute u1 - double fDot0 = rkU.Dot(rkV); - rkV -= fDot0*rkU; - rkV.Normalize(); + // compute u1 + double fDot0 = rkU.Dot(rkV); + rkV -= fDot0 * rkU; + rkV.Normalize(); - // compute u2 - double fDot1 = rkV.Dot(rkW); - fDot0 = rkU.Dot(rkW); - rkW -= fDot0*rkU + fDot1*rkV; - rkW.Normalize(); + // compute u2 + double fDot1 = rkV.Dot(rkW); + fDot0 = rkU.Dot(rkW); + rkW -= fDot0 * rkU + fDot1 * rkV; + rkW.Normalize(); } //---------------------------------------------------------------------------- -void GbVector3D::Orthonormalize (GbVector3D* akV) -{ - Orthonormalize(akV[0],akV[1],akV[2]); -} +void GbVector3D::Orthonormalize(GbVector3D *akV) { Orthonormalize(akV[0], akV[1], akV[2]); } //---------------------------------------------------------------------------- -void GbVector3D::GenerateOrthonormalBasis (GbVector3D& rkU, GbVector3D& rkV, - GbVector3D& rkW, bool bUnitLengthW) +void GbVector3D::GenerateOrthonormalBasis(GbVector3D &rkU, GbVector3D &rkV, GbVector3D &rkW, bool bUnitLengthW) { - if ( !bUnitLengthW ) - rkW.Normalize(); + if (!bUnitLengthW) + rkW.Normalize(); - double fInvLength; + double fInvLength; - if ( std::fabs(rkW.m_afTuple[0]) >= - std::fabs(rkW.m_afTuple[1]) ) - { - // W.x or W.z is the largest magnitude component, swap them - fInvLength = UbMath::invSqrt(rkW.m_afTuple[0]*rkW.m_afTuple[0] + rkW.m_afTuple[2]*rkW.m_afTuple[2]); - rkU.m_afTuple[0] = -rkW.m_afTuple[2]*fInvLength; - rkU.m_afTuple[1] = (double)0.0; - rkU.m_afTuple[2] = +rkW.m_afTuple[0]*fInvLength; - } - else - { - // W.y or W.z is the largest magnitude component, swap them - fInvLength = UbMath::invSqrt(rkW.m_afTuple[1]*rkW.m_afTuple[1] + rkW.m_afTuple[2]*rkW.m_afTuple[2]); - rkU.m_afTuple[0] = (double)0.0; - rkU.m_afTuple[1] = +rkW.m_afTuple[2]*fInvLength; - rkU.m_afTuple[2] = -rkW.m_afTuple[1]*fInvLength; - } + if (std::fabs(rkW.m_afTuple[0]) >= std::fabs(rkW.m_afTuple[1])) { + // W.x or W.z is the largest magnitude component, swap them + fInvLength = UbMath::invSqrt(rkW.m_afTuple[0] * rkW.m_afTuple[0] + rkW.m_afTuple[2] * rkW.m_afTuple[2]); + rkU.m_afTuple[0] = -rkW.m_afTuple[2] * fInvLength; + rkU.m_afTuple[1] = (double)0.0; + rkU.m_afTuple[2] = +rkW.m_afTuple[0] * fInvLength; + } else { + // W.y or W.z is the largest magnitude component, swap them + fInvLength = UbMath::invSqrt(rkW.m_afTuple[1] * rkW.m_afTuple[1] + rkW.m_afTuple[2] * rkW.m_afTuple[2]); + rkU.m_afTuple[0] = (double)0.0; + rkU.m_afTuple[1] = +rkW.m_afTuple[2] * fInvLength; + rkU.m_afTuple[2] = -rkW.m_afTuple[1] * fInvLength; + } - rkV = rkW.Cross(rkU); + rkV = rkW.Cross(rkU); } //---------------------------------------------------------------------------- - diff --git a/src/basics/geometry3d/GbVector3D.h b/src/basics/geometry3d/GbVector3D.h index 9bf699fa2141043245bfa29396351f823ccc3c11..f92ae5ae21effc4adaafbf343426e231cd4d7452 100644 --- a/src/basics/geometry3d/GbVector3D.h +++ b/src/basics/geometry3d/GbVector3D.h @@ -1,28 +1,28 @@ //======================================================================================= -// ____ ____ __ ______ __________ __ __ __ __ -// \ \ | | | | | _ \ |___ ___| | | | | / \ | | -// \ \ | | | | | |_) | | | | | | | / \ | | -// \ \ | | | | | _ / | | | | | | / /\ \ | | -// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ -// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| -// \ \ | | ________________________________________________________________ -// \ \ | | | ______________________________________________________________| -// \ \| | | | __ __ __ __ ______ _______ -// \ | | |_____ | | | | | | | | | _ \ / _____) -// \ | | _____| | | | | | | | | | | \ \ \_______ +// ____ ____ __ ______ __________ __ __ __ __ +// \ \ | | | | | _ \ |___ ___| | | | | / \ | | +// \ \ | | | | | |_) | | | | | | | / \ | | +// \ \ | | | | | _ / | | | | | | / /\ \ | | +// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ +// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| +// \ \ | | ________________________________________________________________ +// \ \ | | | ______________________________________________________________| +// \ \| | | | __ __ __ __ ______ _______ +// \ | | |_____ | | | | | | | | | _ \ / _____) +// \ | | _____| | | | | | | | | | | \ \ \_______ // \ | | | | |_____ | \_/ | | | | |_/ / _____ | -// \ _____| |__| |________| \_______/ |__| |______/ (_______/ +// \ _____| |__| |________| \_______/ |__| |______/ (_______/ // -// This file is part of VirtualFluids. VirtualFluids is free software: you can +// This file is part of VirtualFluids. VirtualFluids is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of +// License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. -// -// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// +// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License along // with VirtualFluids (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>. // @@ -32,9 +32,9 @@ //======================================================================================= #ifndef GBVECTOR3D_H #define GBVECTOR3D_H - -#include <cfloat> -#include <cassert> + +#include <cassert> +#include <cfloat> #include <string> #include <PointerDefinitions.h> @@ -42,89 +42,87 @@ class GbPoint3D; //! \brief This Class provides basic 3D vector objects. -class GbVector3D +class GbVector3D { public: - // construction - GbVector3D (); - GbVector3D (const double& fX1, const double& fX2, const double& fX3); - GbVector3D (const GbVector3D& rkV); - GbVector3D (const GbPoint3D& rkV); + // construction + GbVector3D(); + GbVector3D(const double &fX1, const double &fX2, const double &fX3); + GbVector3D(const GbVector3D &rkV); + GbVector3D(const GbPoint3D &rkV); std::string toString(); // coordinate access - operator const double* () const; - operator double* (); - double operator[] (int i) const; - double& operator[] (int i); - double X1 () const; - double& X1 (); - double X2 () const; - double& X2 (); - double X3 () const; - double& X3 (); + operator const double *() const; + operator double *(); + double operator[](int i) const; + double &operator[](int i); + double X1() const; + double &X1(); + double X2() const; + double &X2(); + double X3() const; + double &X3(); // assignment - GbVector3D& operator= (const GbVector3D& rkV); + GbVector3D &operator=(const GbVector3D &rkV); // comparison - bool operator== (const GbVector3D& rkV) const; - bool operator!= (const GbVector3D& rkV) const; - bool operator< (const GbVector3D& rkV) const; - bool operator<= (const GbVector3D& rkV) const; - bool operator> (const GbVector3D& rkV) const; - bool operator>= (const GbVector3D& rkV) const; + bool operator==(const GbVector3D &rkV) const; + bool operator!=(const GbVector3D &rkV) const; + bool operator<(const GbVector3D &rkV) const; + bool operator<=(const GbVector3D &rkV) const; + bool operator>(const GbVector3D &rkV) const; + bool operator>=(const GbVector3D &rkV) const; // arithmetic operations - GbVector3D operator+ (const GbVector3D& rkV) const; - GbVector3D operator- (const GbVector3D& rkV) const; - GbVector3D operator* (const double& fScalar) const; - GbVector3D operator/ (const double& fScalar) const; - GbVector3D operator- () const; + GbVector3D operator+(const GbVector3D &rkV) const; + GbVector3D operator-(const GbVector3D &rkV) const; + GbVector3D operator*(const double &fScalar) const; + GbVector3D operator/(const double &fScalar) const; + GbVector3D operator-() const; // arithmetic updates - GbVector3D& operator+= (const GbVector3D& rkV); - GbVector3D& operator-= (const GbVector3D& rkV); - GbVector3D& operator*= (const double& fScalar); - GbVector3D& operator/= (const double& fScalar); + GbVector3D &operator+=(const GbVector3D &rkV); + GbVector3D &operator-=(const GbVector3D &rkV); + GbVector3D &operator*=(const double &fScalar); + GbVector3D &operator/=(const double &fScalar); - GbVector3D Add(GbVector3D& vector); - GbVector3D Subtract(GbVector3D& vector); - GbVector3D Scale(const double& x); + GbVector3D Add(GbVector3D &vector); + GbVector3D Subtract(GbVector3D &vector); + GbVector3D Scale(const double &x); // vector operations - double Length () const; - double SquaredLength () const; - double Dot (const GbVector3D& rkV) const; - double Normalize (); + double Length() const; + double SquaredLength() const; + double Dot(const GbVector3D &rkV) const; + double Normalize(); // The cross products are computed using the right-handed rule. Be aware // that some graphics APIs use a left-handed rule. If you have to compute // a cross product with these functions and send the result to the API // that expects left-handed, you will need to change sign on the vector // (replace each component value c by -c). - GbVector3D Cross (const GbVector3D& rkV) const; - GbVector3D UnitCross (const GbVector3D& rkV) const; + GbVector3D Cross(const GbVector3D &rkV) const; + GbVector3D UnitCross(const GbVector3D &rkV) const; // Compute the barycentric coordinates of the point with respect to the // tetrahedron <V0,V1,V2,V3>, P = b0*V0 + b1*V1 + b2*V2 + b3*V3, where // b0 + b1 + b2 + b3 = 1. - void GetBarycentrics (const GbVector3D& rkV0, - const GbVector3D& rkV1, const GbVector3D& rkV2, - const GbVector3D& rkV3, double afBary[4]) const; + void GetBarycentrics(const GbVector3D &rkV0, const GbVector3D &rkV1, const GbVector3D &rkV2, const GbVector3D &rkV3, + double afBary[4]) const; // Gram-Schmidt orthonormalization. Take linearly independent vectors // U, V, and W and compute an orthonormal set (unit length, mutually // perpendicular). - static void Orthonormalize (GbVector3D& rkU, GbVector3D& rkV, GbVector3D& rkW); - static void Orthonormalize (GbVector3D* akV); + static void Orthonormalize(GbVector3D &rkU, GbVector3D &rkV, GbVector3D &rkW); + static void Orthonormalize(GbVector3D *akV); // Input W must be initialized to a nonzero vector, output is {U,V,W}, // an orthonormal basis. A hint is provided about whether or not W // is already unit length. - static void GenerateOrthonormalBasis (GbVector3D& rkU, GbVector3D& rkV, - GbVector3D& rkW, bool bUnitLengthW); + static void GenerateOrthonormalBasis(GbVector3D &rkU, GbVector3D &rkV, GbVector3D &rkW, bool bUnitLengthW); // special vectors static const GbVector3D ZERO; @@ -134,11 +132,11 @@ public: private: // support for comparisons - int CompareArrays (const GbVector3D& rkV) const; + int CompareArrays(const GbVector3D &rkV) const; double m_afTuple[3]; }; -GbVector3D operator* (const double& fScalar, const GbVector3D& rkV); +GbVector3D operator*(const double &fScalar, const GbVector3D &rkV); -#endif //GBVECTOR3D_H +#endif // GBVECTOR3D_H diff --git a/src/basics/geometry3d/GbVoxelMatrix3D.cpp b/src/basics/geometry3d/GbVoxelMatrix3D.cpp index 11c0f9d0d21485b8e24fd6568f90e451fc2e598d..bc2a89bc8cb7a78ba5c77b528ce48c7223d6698c 100644 --- a/src/basics/geometry3d/GbVoxelMatrix3D.cpp +++ b/src/basics/geometry3d/GbVoxelMatrix3D.cpp @@ -1,10 +1,10 @@ #include <geometry3d/GbVoxelMatrix3D.h> -#include <basics/utilities/UbMath.h> #include <basics/utilities/UbFileInputASCII.h> -#include <geometry3d/GbTriangle3D.h> #include <basics/utilities/UbFileOutputASCII.h> +#include <basics/utilities/UbMath.h> #include <geometry3d/CoordinateTransformation3D.h> +#include <geometry3d/GbTriangle3D.h> #include <basics/utilities/UbSystem.h> @@ -17,985 +17,950 @@ using namespace std; const float GbVoxelMatrix3D::SOLID = 1.0f; const float GbVoxelMatrix3D::FLUID = 0.0f; - /*=======================================================*/ // Konstruktor GbVoxelMatrix3D::GbVoxelMatrix3D(int nx1, int nx2, int nx3, float initVal, double lowerThreshold, double upperThreshold) - : GbObject3D() - , lowerThreshold(lowerThreshold) - , upperThreshold(upperThreshold) - , nodesX1(nx1) - , nodesX2(nx2) - , nodesX3(nx3) - , voxelMatrix(Matrix3D(nx1, nx2, nx3, initVal)) + : GbObject3D(), lowerThreshold(lowerThreshold), upperThreshold(upperThreshold), nodesX1(nx1), nodesX2(nx2), + nodesX3(nx3), voxelMatrix(Matrix3D(nx1, nx2, nx3, initVal)) { - this->setName("VoxelMatrix3D"); + this->setName("VoxelMatrix3D"); } /*=======================================================*/ -GbVoxelMatrix3D::GbVoxelMatrix3D() - : GbObject3D() - -{ - this->setName("VoxelMatrix3D"); -} +GbVoxelMatrix3D::GbVoxelMatrix3D() : GbObject3D() { this->setName("VoxelMatrix3D"); } /*=======================================================*/ -GbVoxelMatrix3D::GbVoxelMatrix3D(const Matrix3D& voxelMatrix, double lowerThreshold, double upperThreshold) - : GbObject3D() - , nodesX1((int)voxelMatrix.getNX1()) - , nodesX2((int)voxelMatrix.getNX2()) - , nodesX3((int)voxelMatrix.getNX3()) - , lowerThreshold(lowerThreshold) - , upperThreshold(upperThreshold) - , voxelMatrix(voxelMatrix) +GbVoxelMatrix3D::GbVoxelMatrix3D(const Matrix3D &voxelMatrix, double lowerThreshold, double upperThreshold) + : GbObject3D(), nodesX1((int)voxelMatrix.getNX1()), nodesX2((int)voxelMatrix.getNX2()), + nodesX3((int)voxelMatrix.getNX3()), lowerThreshold(lowerThreshold), upperThreshold(upperThreshold), + voxelMatrix(voxelMatrix) { - this->setName("VoxelMatrix3D"); + this->setName("VoxelMatrix3D"); } /*=======================================================*/ -GbVoxelMatrix3D* GbVoxelMatrix3D::clone() +GbVoxelMatrix3D *GbVoxelMatrix3D::clone() { - GbVoxelMatrix3D* vm = new GbVoxelMatrix3D(voxelMatrix, lowerThreshold, upperThreshold); - vm->setVoxelMatrixMininum(minX1, minX2, minX3); - vm->setVoxelMatrixDelta(deltaX1, deltaX2, deltaX3); - return vm; + GbVoxelMatrix3D *vm = new GbVoxelMatrix3D(voxelMatrix, lowerThreshold, upperThreshold); + vm->setVoxelMatrixMininum(minX1, minX2, minX3); + vm->setVoxelMatrixDelta(deltaX1, deltaX2, deltaX3); + return vm; } /*=======================================================*/ -void GbVoxelMatrix3D::setCenterCoordinates(const double& x1, const double& x2, const double& x3) +void GbVoxelMatrix3D::setCenterCoordinates(const double &x1, const double &x2, const double &x3) { - this->translate(x1-getX1Centroid(), x2-getX2Centroid(), x3-getX3Centroid()); + this->translate(x1 - getX1Centroid(), x2 - getX2Centroid(), x3 - getX3Centroid()); } /*=======================================================*/ -void GbVoxelMatrix3D::translate(const double& tx1, const double& tx2, const double& tx3) +void GbVoxelMatrix3D::translate(const double &tx1, const double &tx2, const double &tx3) { - this->minX1 += tx1; - this->minX2 += tx2; - this->minX3 += tx3; - this->notifyObserversObjectChanged(); + this->minX1 += tx1; + this->minX2 += tx2; + this->minX3 += tx3; + this->notifyObserversObjectChanged(); } /*=======================================================*/ void GbVoxelMatrix3D::setClosedVoidSpaceToSolid() { - voxelMatrixTemp = Matrix3D(nodesX1, nodesX2, nodesX3, SOLID); - flagMatrix = CbArray3D<char>(nodesX1, nodesX2, nodesX3, 0); - - for (int x3 = 0; x3<nodesX3; x3++) - { - for (int x2 = 0; x2<nodesX2; x2++) - { - for (int x1 = 0; x1<nodesX1; x1++) - { - if (voxelMatrix(x1, x2, x3)==FLUID) - { - UBLOG(logINFO, "setClosedVoidSpaceToSolid:start"); - x1Nbr.push_back(x1); - x2Nbr.push_back(x2); - x3Nbr.push_back(x3); - int size = (int)x1Nbr.size(); - while (size>0) - { - for (int i = 0; i<size; i++) - { - findFluidNeighbor(x1Nbr[i], x2Nbr[i], x3Nbr[i]); - } - - swap(x1Nbr, x1NbrTemp); - swap(x2Nbr, x2NbrTemp); - swap(x3Nbr, x3NbrTemp); - - x1NbrTemp.clear(); - x2NbrTemp.clear(); - x3NbrTemp.clear(); - size = (int)x1Nbr.size(); - } - UBLOG(logINFO, "setClosedVoidSpaceToSolid:end"); - voxelMatrix = voxelMatrixTemp; - return; + voxelMatrixTemp = Matrix3D(nodesX1, nodesX2, nodesX3, SOLID); + flagMatrix = CbArray3D<char>(nodesX1, nodesX2, nodesX3, 0); + + for (int x3 = 0; x3 < nodesX3; x3++) { + for (int x2 = 0; x2 < nodesX2; x2++) { + for (int x1 = 0; x1 < nodesX1; x1++) { + if (voxelMatrix(x1, x2, x3) == FLUID) { + UBLOG(logINFO, "setClosedVoidSpaceToSolid:start"); + x1Nbr.push_back(x1); + x2Nbr.push_back(x2); + x3Nbr.push_back(x3); + int size = (int)x1Nbr.size(); + while (size > 0) { + for (int i = 0; i < size; i++) { + findFluidNeighbor(x1Nbr[i], x2Nbr[i], x3Nbr[i]); + } + + swap(x1Nbr, x1NbrTemp); + swap(x2Nbr, x2NbrTemp); + swap(x3Nbr, x3NbrTemp); + + x1NbrTemp.clear(); + x2NbrTemp.clear(); + x3NbrTemp.clear(); + size = (int)x1Nbr.size(); + } + UBLOG(logINFO, "setClosedVoidSpaceToSolid:end"); + voxelMatrix = voxelMatrixTemp; + return; + } } - - } - } - } + } + } } /*=======================================================*/ void GbVoxelMatrix3D::findFluidNeighbor(int x1, int x2, int x3) { - for (int k3 = -1; k3<=1; k3++) - { - for (int k2 = -1; k2<=1; k2++) - { - for (int k1 = -1; k1<=1; k1++) - { - int j1 = x1+k1; - int j2 = x2+k2; - int j3 = x3+k3; - if (j1>=0&&j1<nodesX1 && j2>=0&&j2<nodesX2 && j3>=0&&j3<nodesX3) - { - if (voxelMatrix(j1, j2, j3)==FLUID) - { - if (flagMatrix(j1, j2, j3)==0) - { - voxelMatrixTemp(j1, j2, j3) = FLUID; - flagMatrix(j1, j2, j3) = 1; - x1NbrTemp.push_back(j1); - x2NbrTemp.push_back(j2); - x3NbrTemp.push_back(j3); - } - } + for (int k3 = -1; k3 <= 1; k3++) { + for (int k2 = -1; k2 <= 1; k2++) { + for (int k1 = -1; k1 <= 1; k1++) { + int j1 = x1 + k1; + int j2 = x2 + k2; + int j3 = x3 + k3; + if (j1 >= 0 && j1 < nodesX1 && j2 >= 0 && j2 < nodesX2 && j3 >= 0 && j3 < nodesX3) { + if (voxelMatrix(j1, j2, j3) == FLUID) { + if (flagMatrix(j1, j2, j3) == 0) { + voxelMatrixTemp(j1, j2, j3) = FLUID; + flagMatrix(j1, j2, j3) = 1; + x1NbrTemp.push_back(j1); + x2NbrTemp.push_back(j2); + x3NbrTemp.push_back(j3); + } + } + } } - } - } - } + } + } } /*=======================================================*/ void GbVoxelMatrix3D::calculateNumberOfSolidAndFluid() { - numberOfSolid = 0; - - for (int x3 = 0; x3<nodesX3; x3++) - for (int x2 = 0; x2<nodesX2; x2++) - for (int x1 = 0; x1<nodesX1; x1++) - { - if (voxelMatrix(x1, x2, x3)==GbVoxelMatrix3D::SOLID) - { - numberOfSolid++; + numberOfSolid = 0; + + for (int x3 = 0; x3 < nodesX3; x3++) + for (int x2 = 0; x2 < nodesX2; x2++) + for (int x1 = 0; x1 < nodesX1; x1++) { + if (voxelMatrix(x1, x2, x3) == GbVoxelMatrix3D::SOLID) { + numberOfSolid++; + } } - } - numberOfFluid = (long)nodesX1*(long)nodesX2*(long)nodesX3-numberOfSolid; + numberOfFluid = (long)nodesX1 * (long)nodesX2 * (long)nodesX3 - numberOfSolid; } /*=======================================================*/ -long GbVoxelMatrix3D::getNumberOfSolid() -{ - return numberOfSolid; -} +long GbVoxelMatrix3D::getNumberOfSolid() { return numberOfSolid; } /*=======================================================*/ -long GbVoxelMatrix3D::getNumberOfFluid() -{ - return numberOfFluid; -} +long GbVoxelMatrix3D::getNumberOfFluid() { return numberOfFluid; } /*=======================================================*/ -double GbVoxelMatrix3D::getIntersectionRaytraceFactor(const double& x1, const double& x2, const double& x3, const double& rx1, const double& rx2, const double& rx3) -{ - if (!((UbMath::equal(rx1, 0.0)||UbMath::equal(fabs(rx1), 1.0)||UbMath::equal(fabs(rx1), UbMath::one_over_sqrt2)||UbMath::equal(fabs(rx1), UbMath::one_over_sqrt3)) - &&(UbMath::equal(rx2, 0.0)||UbMath::equal(fabs(rx2), 1.0)||UbMath::equal(fabs(rx2), UbMath::one_over_sqrt2)||UbMath::equal(fabs(rx2), UbMath::one_over_sqrt3)) - &&(UbMath::equal(rx3, 0.0)||UbMath::equal(fabs(rx3), 1.0)||UbMath::equal(fabs(rx3), UbMath::one_over_sqrt2)||UbMath::equal(fabs(rx3), UbMath::one_over_sqrt3)))) - { - throw UbException(UB_EXARGS, "nur fuer diskrete Boltzmannrichungen implementiert!!!"); - } - - //nachbarindex ermitteln - int ndx1 = 0, ndx2 = 0, ndx3 = 0; - if (UbMath::greater(rx1, 0.0)) ndx1 = 1; - else if (UbMath::less(rx1, 0.0)) ndx1 = -1; - if (UbMath::greater(rx2, 0.0)) ndx2 = 1; - else if (UbMath::less(rx2, 0.0)) ndx2 = -1; - if (UbMath::greater(rx3, 0.0)) ndx3 = 1; - else if (UbMath::less(rx3, 0.0)) ndx3 = -1; - - int nix1 = UbMath::integerRounding((x1-minX1)/deltaX1)+ndx1; - int nix2 = UbMath::integerRounding((x2-minX2)/deltaX2)+ndx2; - int nix3 = UbMath::integerRounding((x3-minX3)/deltaX3)+ndx3; - - //test ob nachbar solid - if (nix1>=0 - &&nix2>=0 - &&nix3>=0 - &&nix1<voxelMatrix.getNX1() - &&nix2<voxelMatrix.getNX2() - &&nix3<voxelMatrix.getNX3()) - { - if (UbMath::equal(voxelMatrix(nix1, nix2, nix3), SOLID)) - { - //return halber abstand der beiden knoten - return 0.5*sqrt((ndx1*deltaX1)*(ndx1*deltaX1) - +(ndx2*deltaX2)*(ndx2*deltaX2) - +(ndx3*deltaX3)*(ndx3*deltaX3)); - } - } - - return 0.0; +double GbVoxelMatrix3D::getIntersectionRaytraceFactor(const double &x1, const double &x2, const double &x3, + const double &rx1, const double &rx2, const double &rx3) +{ + if (!((UbMath::equal(rx1, 0.0) || UbMath::equal(fabs(rx1), 1.0) || + UbMath::equal(fabs(rx1), UbMath::one_over_sqrt2) || UbMath::equal(fabs(rx1), UbMath::one_over_sqrt3)) && + (UbMath::equal(rx2, 0.0) || UbMath::equal(fabs(rx2), 1.0) || + UbMath::equal(fabs(rx2), UbMath::one_over_sqrt2) || UbMath::equal(fabs(rx2), UbMath::one_over_sqrt3)) && + (UbMath::equal(rx3, 0.0) || UbMath::equal(fabs(rx3), 1.0) || + UbMath::equal(fabs(rx3), UbMath::one_over_sqrt2) || UbMath::equal(fabs(rx3), UbMath::one_over_sqrt3)))) { + throw UbException(UB_EXARGS, "nur fuer diskrete Boltzmannrichungen implementiert!!!"); + } + + // nachbarindex ermitteln + int ndx1 = 0, ndx2 = 0, ndx3 = 0; + if (UbMath::greater(rx1, 0.0)) + ndx1 = 1; + else if (UbMath::less(rx1, 0.0)) + ndx1 = -1; + if (UbMath::greater(rx2, 0.0)) + ndx2 = 1; + else if (UbMath::less(rx2, 0.0)) + ndx2 = -1; + if (UbMath::greater(rx3, 0.0)) + ndx3 = 1; + else if (UbMath::less(rx3, 0.0)) + ndx3 = -1; + + int nix1 = UbMath::integerRounding((x1 - minX1) / deltaX1) + ndx1; + int nix2 = UbMath::integerRounding((x2 - minX2) / deltaX2) + ndx2; + int nix3 = UbMath::integerRounding((x3 - minX3) / deltaX3) + ndx3; + + // test ob nachbar solid + if (nix1 >= 0 && nix2 >= 0 && nix3 >= 0 && nix1 < voxelMatrix.getNX1() && nix2 < voxelMatrix.getNX2() && + nix3 < voxelMatrix.getNX3()) { + if (UbMath::equal(voxelMatrix(nix1, nix2, nix3), SOLID)) { + // return halber abstand der beiden knoten + return 0.5 * sqrt((ndx1 * deltaX1) * (ndx1 * deltaX1) + (ndx2 * deltaX2) * (ndx2 * deltaX2) + + (ndx3 * deltaX3) * (ndx3 * deltaX3)); + } + } + + return 0.0; } /*=======================================================*/ -bool GbVoxelMatrix3D::isPointInGbObject3D(const double& x1p, const double& x2p, const double& x3p) +bool GbVoxelMatrix3D::isPointInGbObject3D(const double &x1p, const double &x2p, const double &x3p) { - //index ermitteln - int ix1 = UbMath::integerRounding((x1p-minX1)/deltaX1); - int ix2 = UbMath::integerRounding((x2p-minX2)/deltaX2); - int ix3 = UbMath::integerRounding((x3p-minX3)/deltaX3); - - if (ix1>=0 - &&ix2>=0 - &&ix3>=0 - &&ix1<voxelMatrix.getNX1() - &&ix2<voxelMatrix.getNX2() - &&ix3<voxelMatrix.getNX3()) - { - if (UbMath::equal(voxelMatrix(ix1, ix2, ix3), SOLID)) return true; - } - - return false; + // index ermitteln + int ix1 = UbMath::integerRounding((x1p - minX1) / deltaX1); + int ix2 = UbMath::integerRounding((x2p - minX2) / deltaX2); + int ix3 = UbMath::integerRounding((x3p - minX3) / deltaX3); + + if (ix1 >= 0 && ix2 >= 0 && ix3 >= 0 && ix1 < voxelMatrix.getNX1() && ix2 < voxelMatrix.getNX2() && + ix3 < voxelMatrix.getNX3()) { + if (UbMath::equal(voxelMatrix(ix1, ix2, ix3), SOLID)) + return true; + } + + return false; } /*=======================================================*/ -bool GbVoxelMatrix3D::isPointInGbObject3D(const double& x1p, const double& x2p, const double& x3p, bool& pointIsOnBoundary) +bool GbVoxelMatrix3D::isPointInGbObject3D(const double &x1p, const double &x2p, const double &x3p, + bool &pointIsOnBoundary) { - pointIsOnBoundary = false; + pointIsOnBoundary = false; - return isPointInGbObject3D(x1p, x2p, x3p); + return isPointInGbObject3D(x1p, x2p, x3p); } /*=======================================================*/ -bool GbVoxelMatrix3D::isCellInsideGbObject3D(const double& /*x1p1*/, const double& /*x2p1*/, const double& /*x3p1*/, const double& /*x1p2*/, const double& /*x2p2*/, const double& /*x3p2*/) +bool GbVoxelMatrix3D::isCellInsideGbObject3D(const double & /*x1p1*/, const double & /*x2p1*/, const double & /*x3p1*/, + const double & /*x1p2*/, const double & /*x2p2*/, const double & /*x3p2*/) { - return false; - //FIXME: unreachable cide - ////dass haengt von der Konfigration ab, aber meist ist der Block groesser wie etliche Poren ... - - // //indizes ermitteln - //int startix1 = (int)std::floor((x1p1-minX1)/deltaX1+1E-13); - //int startix2 = (int)std::floor((x2p1-minX2)/deltaX2+1E-13); - //int startix3 = (int)std::floor((x3p1-minX3)/deltaX3+1E-13); - - //if (startix1<0) return false; - //if (startix2<0) return false; - //if (startix3<0) return false; - - //int maxiX1 = (int)voxelMatrix.getNX1()-1; - //int maxiX2 = (int)voxelMatrix.getNX2()-1; - //int maxiX3 = (int)voxelMatrix.getNX3()-1; - - //int endix1 = (int)std::ceil((x1p2-minX1)/deltaX1-1E-13); - //int endix2 = (int)std::ceil((x2p2-minX2)/deltaX2-1E-13); - //int endix3 = (int)std::ceil((x3p2-minX3)/deltaX3-1E-13); - - //if (endix1>maxiX1) return false; - //if (endix2>maxiX2) return false; - //if (endix3>maxiX3) return false; - - //for (int ix3 = startix3; ix3<=endix3; ix3++) - // for (int ix2 = startix2; ix2<=endix2; ix2++) - // for (int ix1 = startix1; ix1<=endix1; ix1++) - // if (UbMath::equal(voxelMatrix(ix1, ix2, ix3), FLUID)) - // return false; - //return true; + return false; + // FIXME: unreachable cide + ////dass haengt von der Konfigration ab, aber meist ist der Block groesser wie etliche Poren ... + + // //indizes ermitteln + // int startix1 = (int)std::floor((x1p1-minX1)/deltaX1+1E-13); + // int startix2 = (int)std::floor((x2p1-minX2)/deltaX2+1E-13); + // int startix3 = (int)std::floor((x3p1-minX3)/deltaX3+1E-13); + + // if (startix1<0) return false; + // if (startix2<0) return false; + // if (startix3<0) return false; + + // int maxiX1 = (int)voxelMatrix.getNX1()-1; + // int maxiX2 = (int)voxelMatrix.getNX2()-1; + // int maxiX3 = (int)voxelMatrix.getNX3()-1; + + // int endix1 = (int)std::ceil((x1p2-minX1)/deltaX1-1E-13); + // int endix2 = (int)std::ceil((x2p2-minX2)/deltaX2-1E-13); + // int endix3 = (int)std::ceil((x3p2-minX3)/deltaX3-1E-13); + + // if (endix1>maxiX1) return false; + // if (endix2>maxiX2) return false; + // if (endix3>maxiX3) return false; + + // for (int ix3 = startix3; ix3<=endix3; ix3++) + // for (int ix2 = startix2; ix2<=endix2; ix2++) + // for (int ix1 = startix1; ix1<=endix1; ix1++) + // if (UbMath::equal(voxelMatrix(ix1, ix2, ix3), FLUID)) + // return false; + // return true; } /*=======================================================*/ -bool GbVoxelMatrix3D::isCellCuttingGbObject3D(const double& x1a, const double& x2a, const double& x3a, const double& x1b, const double& x2b, const double& x3b) -//Merksatz: cell oder deren Volumen schneidet oder beinhaltet komplette oder Teile der CuboidUmrandung -//returns true: +bool GbVoxelMatrix3D::isCellCuttingGbObject3D(const double &x1a, const double &x2a, const double &x3a, + const double &x1b, const double &x2b, const double &x3b) +// Merksatz: cell oder deren Volumen schneidet oder beinhaltet komplette oder Teile der CuboidUmrandung +// returns true: // - cell cuts GbVoxelMatrix3D // - cell boxes GbVoxelMatrix3D -//returns false: -// - cell completely inside GbVoxelMatrix3D +// returns false: +// - cell completely inside GbVoxelMatrix3D // - cell und cuboid3D haben kein gemeinsames Volumen { - //erstmal die dumm Loesung - if (!(this->isCellInsideGbObject3D(x1a, x2a, x3a, x1b, x2b, x3b)) - &&this->isCellInsideOrCuttingGbObject3D(x1a, x2a, x3a, x1b, x2b, x3b)) - { - return true; - } - - return false; + // erstmal die dumm Loesung + if (!(this->isCellInsideGbObject3D(x1a, x2a, x3a, x1b, x2b, x3b)) && + this->isCellInsideOrCuttingGbObject3D(x1a, x2a, x3a, x1b, x2b, x3b)) { + return true; + } + + return false; } /*=======================================================*/ -bool GbVoxelMatrix3D::isCellInsideOrCuttingGbObject3D(const double& x1a, const double& x2a, const double& x3a, const double& x1b, const double& x2b, const double& x3b) -//returns true: +bool GbVoxelMatrix3D::isCellInsideOrCuttingGbObject3D(const double &x1a, const double &x2a, const double &x3a, + const double &x1b, const double &x2b, const double &x3b) +// returns true: // - cell completely inside cuboid3D ( = cuboid3D boxes cell) // - cell cuts cuboid3D // - cell boxes cuboid3D -//returns false: +// returns false: // - cell und cuboid3D haben kein gemeinsames Volumen { - //simpler check, da unser GbCuboid3D ein AABB is: - // anfA midA endA anfB midB endB - // | x<-- dxA -->| |<-dxB->x | - // |<----------------- T --------------->| - //ist |T| <= dxA + dxB -> overlap! + // simpler check, da unser GbCuboid3D ein AABB is: + // anfA midA endA anfB midB endB + // | x<-- dxA -->| |<-dxB->x | + // |<----------------- T --------------->| + // ist |T| <= dxA + dxB -> overlap! - if (UbMath::lessEqual(std::fabs(this->getX1Centroid()-0.5*(x1b+x1a) /*Tx1*/) - , 0.5*(this->getLengthX1()+std::fabs(x1b-x1a) /*dx1A+dx1B*/)) + if (UbMath::lessEqual(std::fabs(this->getX1Centroid() - 0.5 * (x1b + x1a) /*Tx1*/), + 0.5 * (this->getLengthX1() + std::fabs(x1b - x1a) /*dx1A+dx1B*/)) - &&UbMath::lessEqual(std::fabs(this->getX2Centroid()-0.5*(x2b+x2a) /*Tx2*/) - , 0.5*(this->getLengthX2()+std::fabs(x2b-x2a) /*dx2A+dx2B*/)) + && UbMath::lessEqual(std::fabs(this->getX2Centroid() - 0.5 * (x2b + x2a) /*Tx2*/), + 0.5 * (this->getLengthX2() + std::fabs(x2b - x2a) /*dx2A+dx2B*/)) - &&UbMath::lessEqual(std::fabs(this->getX3Centroid()-0.5*(x3b+x3a) /*Tx3*/) - , 0.5*(this->getLengthX3()+std::fabs(x3b-x3a) /*dx3A+dx3B*/))) - { - return true; - } + && UbMath::lessEqual(std::fabs(this->getX3Centroid() - 0.5 * (x3b + x3a) /*Tx3*/), + 0.5 * (this->getLengthX3() + std::fabs(x3b - x3a) /*dx3A+dx3B*/))) { + return true; + } - return false; + return false; } /*=======================================================*/ -vector<GbTriangle3D*> GbVoxelMatrix3D::getSurfaceTriangleSet() +vector<GbTriangle3D *> GbVoxelMatrix3D::getSurfaceTriangleSet() { - vector<GbTriangle3D*> triangles; + vector<GbTriangle3D *> triangles; #ifdef MC_CUBES - //MC - typedef McCubes::Matrix3DWrapper< Matrix3D > McMatrixWrapper; - typedef McCubes::MarchingCubes< McMatrixWrapper > McMarchingCubesGenerator; - typedef McMarchingCubesGenerator::Vertex McVertex; - typedef McMarchingCubesGenerator::Triangle McTriangle; - - McMatrixWrapper wrapper(&voxelMatrix);//,0,0,0,voxelMatrix.getNX1()-1,voxelMatrix.getNX2()-1,voxelMatrix.getNX3()-1); - McMarchingCubesGenerator mc(wrapper); - - mc.init_all(); - mc.run(0.5); - - //const int nofVertices = mc.nverts(); - const int nofTriangles = mc.ntrigs(); - - McVertex* mcvertices = mc.vertices(); - McTriangle* mctriangles = mc.triangles(); - - for (int t = 0; t<nofTriangles; t++) - { - triangles.push_back(new GbTriangle3D(new GbPoint3D(minX1+deltaX1 * (mcvertices[mctriangles[t].v1].x /*-1*/) - , minX2+deltaX2 * (mcvertices[mctriangles[t].v1].y /*-1*/) - , minX3+deltaX3 * (mcvertices[mctriangles[t].v1].z /*-1*/)) - , new GbPoint3D(minX1+deltaX1 * (mcvertices[mctriangles[t].v2].x /*-1*/) - , minX2+deltaX2 * (mcvertices[mctriangles[t].v2].y /*-1*/) - , minX3+deltaX3 * (mcvertices[mctriangles[t].v2].z /*-1*/)) - , new GbPoint3D(minX1+deltaX1 * (mcvertices[mctriangles[t].v3].x /*-1*/) - , minX2+deltaX2 * (mcvertices[mctriangles[t].v3].y /*-1*/) - , minX3+deltaX3 * (mcvertices[mctriangles[t].v3].z /*-1*/)))); - } + // MC + typedef McCubes::Matrix3DWrapper<Matrix3D> McMatrixWrapper; + typedef McCubes::MarchingCubes<McMatrixWrapper> McMarchingCubesGenerator; + typedef McMarchingCubesGenerator::Vertex McVertex; + typedef McMarchingCubesGenerator::Triangle McTriangle; + + McMatrixWrapper wrapper( + &voxelMatrix); //,0,0,0,voxelMatrix.getNX1()-1,voxelMatrix.getNX2()-1,voxelMatrix.getNX3()-1); + McMarchingCubesGenerator mc(wrapper); + + mc.init_all(); + mc.run(0.5); + + // const int nofVertices = mc.nverts(); + const int nofTriangles = mc.ntrigs(); + + McVertex *mcvertices = mc.vertices(); + McTriangle *mctriangles = mc.triangles(); + + for (int t = 0; t < nofTriangles; t++) { + triangles.push_back( + new GbTriangle3D(new GbPoint3D(minX1 + deltaX1 * (mcvertices[mctriangles[t].v1].x /*-1*/), + minX2 + deltaX2 * (mcvertices[mctriangles[t].v1].y /*-1*/), + minX3 + deltaX3 * (mcvertices[mctriangles[t].v1].z /*-1*/)), + new GbPoint3D(minX1 + deltaX1 * (mcvertices[mctriangles[t].v2].x /*-1*/), + minX2 + deltaX2 * (mcvertices[mctriangles[t].v2].y /*-1*/), + minX3 + deltaX3 * (mcvertices[mctriangles[t].v2].z /*-1*/)), + new GbPoint3D(minX1 + deltaX1 * (mcvertices[mctriangles[t].v3].x /*-1*/), + minX2 + deltaX2 * (mcvertices[mctriangles[t].v3].y /*-1*/), + minX3 + deltaX3 * (mcvertices[mctriangles[t].v3].z /*-1*/)))); + } #else - cerr<<"vector<GbTriangle3D*> GbVoxelMatrix3D::getSurfaceTriangleSet() - benoetigt MARCHING_CUBE paket aus 3rdParty"<<endl; + cerr + << "vector<GbTriangle3D*> GbVoxelMatrix3D::getSurfaceTriangleSet() - benoetigt MARCHING_CUBE paket aus 3rdParty" + << endl; #endif // MC_CUBES - return triangles; + return triangles; } /*=======================================================*/ -void GbVoxelMatrix3D::addSurfaceTriangleSet(vector<UbTupleFloat3>& /*nodes*/, vector<UbTupleInt3>& /*triangles*/) +void GbVoxelMatrix3D::addSurfaceTriangleSet(vector<UbTupleFloat3> & /*nodes*/, vector<UbTupleInt3> & /*triangles*/) { - UBLOG(logINFO, " GbVoxelMatrix3D addSurfaceTriangleSet start") - if (!this->addSurfaceTriangleSetFlag) - { - UBLOG(logINFO, " GbVoxelMatrix3D addSurfaceTriangleSet end without TriangleSetCreation") - return; - } + UBLOG(logINFO, " GbVoxelMatrix3D addSurfaceTriangleSet start") + if (!this->addSurfaceTriangleSetFlag) { + UBLOG(logINFO, " GbVoxelMatrix3D addSurfaceTriangleSet end without TriangleSetCreation") + return; + } #ifdef MC_CUBES - UBLOG(logDEBUG1, " GbVoxelMatrix3D addSurfaceTriangleSet MC defined") - - typedef McCubes::Matrix3DWrapper< Matrix3D > McMatrixWrapper; - typedef McCubes::MarchingCubes< McMatrixWrapper > McMarchingCubesGenerator; - typedef McMarchingCubesGenerator::Vertex McVertex; - typedef McMarchingCubesGenerator::Triangle McTriangle; - - //MC - { //standard( fuer voxelmatrix) - McMatrixWrapper wrapper(&voxelMatrix); - McMarchingCubesGenerator mc(wrapper); - - UBLOG(logDEBUG1, " GbVoxelMatrix3D addSurfaceTriangleSet McMarchingCubesGenerator") - - UBLOG(logDEBUG1, " GbVoxelMatrix3D addSurfaceTriangleSet mc.init") - mc.init_all(); - UBLOG(logDEBUG1, " GbVoxelMatrix3D addSurfaceTriangleSet mc.run") - mc.run(0.5); - UBLOG(logDEBUG1, " GbVoxelMatrix3D addSurfaceTriangleSet mc.run done") - - const int nofVertices = mc.nverts(); - const int nofTriangles = mc.ntrigs(); - - McVertex* mcvertices = mc.vertices(); - McTriangle* mctriangles = mc.triangles(); - - UBLOG(logDEBUG1, " GbVoxelMatrix3D node tuple") - for (int n = 0; n<nofVertices; n++) - nodes.push_back(makeUbTuple((float)(minX1+deltaX1 * (mcvertices[n].x /*-1*/)), //Anm: kein -1, da man durch manipulation der indices die dreiecke um eins versetzt bekommt - (float)(minX2+deltaX2 * (mcvertices[n].y /*-1*/)), - (float)(minX3+deltaX3 * (mcvertices[n].z /*-1*/)))); - UBLOG(logDEBUG1, " GbVoxelMatrix3D triangles tuple") - for (int t = 0; t<nofTriangles; t++) + UBLOG(logDEBUG1, " GbVoxelMatrix3D addSurfaceTriangleSet MC defined") + + typedef McCubes::Matrix3DWrapper<Matrix3D> McMatrixWrapper; + typedef McCubes::MarchingCubes<McMatrixWrapper> McMarchingCubesGenerator; + typedef McMarchingCubesGenerator::Vertex McVertex; + typedef McMarchingCubesGenerator::Triangle McTriangle; + + // MC + { // standard( fuer voxelmatrix) + McMatrixWrapper wrapper(&voxelMatrix); + McMarchingCubesGenerator mc(wrapper); + + UBLOG(logDEBUG1, " GbVoxelMatrix3D addSurfaceTriangleSet McMarchingCubesGenerator") + + UBLOG(logDEBUG1, " GbVoxelMatrix3D addSurfaceTriangleSet mc.init") + mc.init_all(); + UBLOG(logDEBUG1, " GbVoxelMatrix3D addSurfaceTriangleSet mc.run") + mc.run(0.5); + UBLOG(logDEBUG1, " GbVoxelMatrix3D addSurfaceTriangleSet mc.run done") + + const int nofVertices = mc.nverts(); + const int nofTriangles = mc.ntrigs(); + + McVertex *mcvertices = mc.vertices(); + McTriangle *mctriangles = mc.triangles(); + + UBLOG(logDEBUG1, " GbVoxelMatrix3D node tuple") + for (int n = 0; n < nofVertices; n++) + nodes.push_back(makeUbTuple( + (float)(minX1 + deltaX1 * (mcvertices[n].x /*-1*/)), // Anm: kein -1, da man durch manipulation der + // indices die dreiecke um eins versetzt bekommt + (float)(minX2 + deltaX2 * (mcvertices[n].y /*-1*/)), + (float)(minX3 + deltaX3 * (mcvertices[n].z /*-1*/)))); + UBLOG(logDEBUG1, " GbVoxelMatrix3D triangles tuple") + for (int t = 0; t < nofTriangles; t++) triangles.push_back(makeUbTuple(mctriangles[t].v1, mctriangles[t].v2, mctriangles[t].v3)); - UBLOG(logDEBUG1, " GbVoxelMatrix3D triangles tuple done") - } - - //false - das scheint probleme bei der asphaltprobe zu machen 1500x600x100 - // da lief es bis C - evtl. memory voll - if (false) //extension... um die raender koerrekt abzubilden muesste man eine dummy FLUID reihe um - { //die matrix legen( lsg1: temp matrix mit 2 reihen pro richtung mehr -> zuviel speicher, 500^3 = 500MB - // lsg2: fuer jede flaeche eine dummy matrix -> wie folgt: - int nx1 = (int)voxelMatrix.getNX1(); - int nx2 = (int)voxelMatrix.getNX2(); - int nx3 = (int)voxelMatrix.getNX3(); - UBLOG(logINFO, " A ") - Matrix3D tmpX1Min(2, nx2+2, nx3+2, FLUID); - Matrix3D tmpX1Max(2, nx2+2, nx3+2, FLUID); - for (int x3 = 0; x3<nx3; x3++) - for (int x2 = 0; x2<nx2; x2++) - { - tmpX1Min(1, x2+1, x3+1) = voxelMatrix(0, x2, x3); - tmpX1Max(0, x2+1, x3+1) = voxelMatrix(nx1-1, x2, x3); - } - UBLOG(logINFO, " B") - Matrix3D tmpX2Min(nx1+2, 2, nx3+2, FLUID); - Matrix3D tmpX2Max(nx1+2, 2, nx3+2, FLUID); - for (int x3 = 0; x3<nx3; x3++) - for (int x1 = 0; x1<nx1; x1++) - { - tmpX2Min(x1+1, 1, x3+1) = voxelMatrix(x1, 0, x3); - tmpX2Max(x1+1, 0, x3+1) = voxelMatrix(x1, nx2-1, x3); - } - UBLOG(logINFO, " C ") - Matrix3D tmpX3Min(nx1+2, nx3+2, 2, FLUID); - Matrix3D tmpX3Max(nx1+2, nx3+2, 2, FLUID); - for (int x2 = 0; x2<nx2; x2++) - for (int x1 = 0; x1<nx1; x1++) - { - tmpX3Min(x1+1, x2+1, 1) = voxelMatrix(x1, x2, 0); - tmpX3Max(x1+1, x2+1, 0) = voxelMatrix(x1, x2, nx3-1); - } - UBLOG(logINFO, " D") - Matrix3D* matrices[] = { &tmpX1Min, &tmpX1Max, &tmpX2Min, &tmpX2Max, &tmpX3Min, &tmpX3Max }; - int dx1[] = { -1, nx1-1, -1, -1, -1, -1 }; - int dx2[] = { -1, -1, -1, nx2-1, -1, -1 }; - int dx3[] = { -1, -1, -1, -1, -1, nx3-1 }; - UBLOG(logINFO, " E") - for (int i = 0; i<6; i++) - { + UBLOG(logDEBUG1, " GbVoxelMatrix3D triangles tuple done") + } + + // false - das scheint probleme bei der asphaltprobe zu machen 1500x600x100 + // da lief es bis C - evtl. memory voll + if (false) // extension... um die raender koerrekt abzubilden muesste man eine dummy FLUID reihe um + { // die matrix legen( lsg1: temp matrix mit 2 reihen pro richtung mehr -> zuviel speicher, 500^3 = 500MB + // lsg2: fuer jede flaeche eine dummy matrix -> wie folgt: + int nx1 = (int)voxelMatrix.getNX1(); + int nx2 = (int)voxelMatrix.getNX2(); + int nx3 = (int)voxelMatrix.getNX3(); + UBLOG(logINFO, " A ") + Matrix3D tmpX1Min(2, nx2 + 2, nx3 + 2, FLUID); + Matrix3D tmpX1Max(2, nx2 + 2, nx3 + 2, FLUID); + for (int x3 = 0; x3 < nx3; x3++) + for (int x2 = 0; x2 < nx2; x2++) { + tmpX1Min(1, x2 + 1, x3 + 1) = voxelMatrix(0, x2, x3); + tmpX1Max(0, x2 + 1, x3 + 1) = voxelMatrix(nx1 - 1, x2, x3); + } + UBLOG(logINFO, " B") + Matrix3D tmpX2Min(nx1 + 2, 2, nx3 + 2, FLUID); + Matrix3D tmpX2Max(nx1 + 2, 2, nx3 + 2, FLUID); + for (int x3 = 0; x3 < nx3; x3++) + for (int x1 = 0; x1 < nx1; x1++) { + tmpX2Min(x1 + 1, 1, x3 + 1) = voxelMatrix(x1, 0, x3); + tmpX2Max(x1 + 1, 0, x3 + 1) = voxelMatrix(x1, nx2 - 1, x3); + } + UBLOG(logINFO, " C ") + Matrix3D tmpX3Min(nx1 + 2, nx3 + 2, 2, FLUID); + Matrix3D tmpX3Max(nx1 + 2, nx3 + 2, 2, FLUID); + for (int x2 = 0; x2 < nx2; x2++) + for (int x1 = 0; x1 < nx1; x1++) { + tmpX3Min(x1 + 1, x2 + 1, 1) = voxelMatrix(x1, x2, 0); + tmpX3Max(x1 + 1, x2 + 1, 0) = voxelMatrix(x1, x2, nx3 - 1); + } + UBLOG(logINFO, " D") + Matrix3D *matrices[] = { &tmpX1Min, &tmpX1Max, &tmpX2Min, &tmpX2Max, &tmpX3Min, &tmpX3Max }; + int dx1[] = { -1, nx1 - 1, -1, -1, -1, -1 }; + int dx2[] = { -1, -1, -1, nx2 - 1, -1, -1 }; + int dx3[] = { -1, -1, -1, -1, -1, nx3 - 1 }; + UBLOG(logINFO, " E") + for (int i = 0; i < 6; i++) { McMatrixWrapper wrapper(matrices[i]); McMarchingCubesGenerator mc(wrapper); mc.init_all(); mc.run(0.5); - McVertex* mcvertices = mc.vertices(); - McTriangle* mctriangles = mc.triangles(); + McVertex *mcvertices = mc.vertices(); + McTriangle *mctriangles = mc.triangles(); int deltaNodeNr = (int)nodes.size(); UBLOG(logINFO, " GbVoxelMatrix3D node tuple") - for (int n = 0; n<mc.nverts(); n++) - nodes.push_back(makeUbTuple((float)(minX1+deltaX1 * (mcvertices[n].x+dx1[i])), //Anm: kein -1, da man durch manipulation der indices die dreiecke um eins versetzt bekommt - (float)(minX2+deltaX2 * (mcvertices[n].y+dx2[i])), - (float)(minX3+deltaX3 * (mcvertices[n].z+dx3[i])))); - for (int t = 0; t<mc.ntrigs(); t++) - triangles.push_back(makeUbTuple(deltaNodeNr+mctriangles[t].v1, deltaNodeNr+mctriangles[t].v2, deltaNodeNr+mctriangles[t].v3)); - } - } + for (int n = 0; n < mc.nverts(); n++) + nodes.push_back( + makeUbTuple((float)(minX1 + deltaX1 * (mcvertices[n].x + + dx1[i])), // Anm: kein -1, da man durch manipulation der + // indices die dreiecke um eins versetzt bekommt + (float)(minX2 + deltaX2 * (mcvertices[n].y + dx2[i])), + (float)(minX3 + deltaX3 * (mcvertices[n].z + dx3[i])))); + for (int t = 0; t < mc.ntrigs(); t++) + triangles.push_back(makeUbTuple(deltaNodeNr + mctriangles[t].v1, deltaNodeNr + mctriangles[t].v2, + deltaNodeNr + mctriangles[t].v3)); + } + } #else - cerr<<"void GbVoxelMatrix3D.addSurfaceTriangleSet - benoetigt MARCHING_CUBE paket aus 3rdParty"<<endl; + cerr << "void GbVoxelMatrix3D.addSurfaceTriangleSet - benoetigt MARCHING_CUBE paket aus 3rdParty" << endl; #endif // MC_CUBES - UBLOG(logINFO, " GbVoxelMatrix3D addSurfaceTriangleSet end") + UBLOG(logINFO, " GbVoxelMatrix3D addSurfaceTriangleSet end") } /*=======================================================*/ -string GbVoxelMatrix3D::toString() -{ - return "GbVoxelMatrix3D"; -} +string GbVoxelMatrix3D::toString() { return "GbVoxelMatrix3D"; } /*=======================================================*/ void GbVoxelMatrix3D::readMatrixFromVtiASCIIFile(std::string filename) { - //UBLOG(logINFO," - create GbVoxelMatrix3D"); - UbFileInputASCII in(filename); - //ifstream in(filename.c_str(), ios::binary); - if (!in) throw UbException(UB_EXARGS, "could not open file "+filename); - in.readLine(); - in.readLine(); - in.readLine(); - in.readLine(); - in.readLine(); - - voxelMatrix = Matrix3D(nodesX1, nodesX2, nodesX3, GbVoxelMatrix3D::FLUID); - - //UBLOG(logINFO," - init values"); - int val; - for (int x3 = 0; x3<nodesX3; x3++) - for (int x2 = 0; x2<nodesX2; x2++) - for (int x1 = 0; x1<nodesX1; x1++) - { - val = in.readInteger(); - //if( !UbMath::equal(val, 0.0f) ) - //if( UbMath::greater(val, threshold) ) - if ((double)val>=lowerThreshold&&(double)val<=upperThreshold) - { - (voxelMatrix)(x1, x2, x3) = GbVoxelMatrix3D::SOLID; + // UBLOG(logINFO," - create GbVoxelMatrix3D"); + UbFileInputASCII in(filename); + // ifstream in(filename.c_str(), ios::binary); + if (!in) + throw UbException(UB_EXARGS, "could not open file " + filename); + in.readLine(); + in.readLine(); + in.readLine(); + in.readLine(); + in.readLine(); + + voxelMatrix = Matrix3D(nodesX1, nodesX2, nodesX3, GbVoxelMatrix3D::FLUID); + + // UBLOG(logINFO," - init values"); + int val; + for (int x3 = 0; x3 < nodesX3; x3++) + for (int x2 = 0; x2 < nodesX2; x2++) + for (int x1 = 0; x1 < nodesX1; x1++) { + val = in.readInteger(); + // if( !UbMath::equal(val, 0.0f) ) + // if( UbMath::greater(val, threshold) ) + if ((double)val >= lowerThreshold && (double)val <= upperThreshold) { + (voxelMatrix)(x1, x2, x3) = GbVoxelMatrix3D::SOLID; + } } - } - //UBLOG(logINFO," - create GbVoxelMatrix3D done"); + // UBLOG(logINFO," - create GbVoxelMatrix3D done"); } ////////////////////////////////////////////////////////////////////////// -void GbVoxelMatrix3D::rotate90aroundX(double /*cX1*/, double cX2, double cX3) +void GbVoxelMatrix3D::rotate90aroundX(double /*cX1*/, double cX2, double cX3) { -// double tempMinPunktX1 = minX1-cX1; - double tempMinPunktX2 = minX2-cX2; - double tempMinPunktX3 = getX3Maximum()-cX3; - -// double tempMinPunktX1tf = tempMinPunktX1; - double tempMinPunktX2tf = -tempMinPunktX3; - double tempMinPunktX3tf = tempMinPunktX2; - -// double minX1_temp = tempMinPunktX1tf+cX1; - double minX2_temp = tempMinPunktX2tf+cX2; - double minX3_temp = tempMinPunktX3tf+cX3; - - minX2 = minX2_temp; - minX3 = minX3_temp; - - int nx1 = (int)voxelMatrix.getNX1(); - int nx2 = (int)voxelMatrix.getNX2(); - int nx3 = (int)voxelMatrix.getNX3(); - - int nx1_new = nx1; - int nx2_new = nx3; - int nx3_new = nx2; - - double delta_temp = deltaX2; - deltaX2 = deltaX3; - deltaX3 = delta_temp; - - GbVoxelMatrix3D::Matrix3D voxelMatrix_temp(nx1_new, nx2_new, nx3_new); - - for (int x3 = 0; x3<nx3; x3++) { - for (int x2 = 0; x2<nx2; x2++) { - for (int x1 = 0; x1<nx1; x1++) - { - voxelMatrix_temp(x1, nx3-x3-1, x2) = this->voxelMatrix(x1, x2, x3); - } - } - } - std::swap(this->voxelMatrix, voxelMatrix_temp); + // double tempMinPunktX1 = minX1-cX1; + double tempMinPunktX2 = minX2 - cX2; + double tempMinPunktX3 = getX3Maximum() - cX3; + + // double tempMinPunktX1tf = tempMinPunktX1; + double tempMinPunktX2tf = -tempMinPunktX3; + double tempMinPunktX3tf = tempMinPunktX2; + + // double minX1_temp = tempMinPunktX1tf+cX1; + double minX2_temp = tempMinPunktX2tf + cX2; + double minX3_temp = tempMinPunktX3tf + cX3; + + minX2 = minX2_temp; + minX3 = minX3_temp; + + int nx1 = (int)voxelMatrix.getNX1(); + int nx2 = (int)voxelMatrix.getNX2(); + int nx3 = (int)voxelMatrix.getNX3(); + + int nx1_new = nx1; + int nx2_new = nx3; + int nx3_new = nx2; + + double delta_temp = deltaX2; + deltaX2 = deltaX3; + deltaX3 = delta_temp; + + GbVoxelMatrix3D::Matrix3D voxelMatrix_temp(nx1_new, nx2_new, nx3_new); + + for (int x3 = 0; x3 < nx3; x3++) { + for (int x2 = 0; x2 < nx2; x2++) { + for (int x1 = 0; x1 < nx1; x1++) { + voxelMatrix_temp(x1, nx3 - x3 - 1, x2) = this->voxelMatrix(x1, x2, x3); + } + } + } + std::swap(this->voxelMatrix, voxelMatrix_temp); } ////////////////////////////////////////////////////////////////////////// void GbVoxelMatrix3D::rotate90aroundX() { - double cX1 = this->getX1Centroid(); - double cX2 = this->getX2Centroid(); - double cX3 = this->getX3Centroid(); + double cX1 = this->getX1Centroid(); + double cX2 = this->getX2Centroid(); + double cX3 = this->getX3Centroid(); - rotate90aroundX(cX1, cX2, cX3); + rotate90aroundX(cX1, cX2, cX3); } ////////////////////////////////////////////////////////////////////////// -void GbVoxelMatrix3D::rotate90aroundY(double cX1, double /*cX2*/, double cX3) +void GbVoxelMatrix3D::rotate90aroundY(double cX1, double /*cX2*/, double cX3) { - double tempMinPunktX1 = getX1Maximum()-cX1; -// double tempMinPunktX2 = minX2-cX2; - double tempMinPunktX3 = minX3-cX3; - - double tempMinPunktX1tf = tempMinPunktX3; -// double tempMinPunktX2tf = tempMinPunktX2; - double tempMinPunktX3tf = -tempMinPunktX1; - - double minX1_temp = tempMinPunktX1tf+cX1; -// double minX2_temp = tempMinPunktX2tf+cX2; - double minX3_temp = tempMinPunktX3tf+cX3; - - minX1 = minX1_temp; - minX3 = minX3_temp; - - int nx1 = (int)voxelMatrix.getNX1(); - int nx2 = (int)voxelMatrix.getNX2(); - int nx3 = (int)voxelMatrix.getNX3(); - - int nx1_new = nx3; - int nx2_new = nx2; - int nx3_new = nx1; - - double delta_temp = deltaX1; - deltaX1 = deltaX3; - deltaX3 = delta_temp; - - GbVoxelMatrix3D::Matrix3D voxelMatrix_temp(nx1_new, nx2_new, nx3_new); - - for (int x3 = 0; x3<nx3; x3++) { - for (int x2 = 0; x2<nx2; x2++) { - for (int x1 = 0; x1<nx1; x1++) - { - voxelMatrix_temp(x3, x2, nx1-x1-1) = this->voxelMatrix(x1, x2, x3); - } - } - } - std::swap(this->voxelMatrix, voxelMatrix_temp); + double tempMinPunktX1 = getX1Maximum() - cX1; + // double tempMinPunktX2 = minX2-cX2; + double tempMinPunktX3 = minX3 - cX3; + + double tempMinPunktX1tf = tempMinPunktX3; + // double tempMinPunktX2tf = tempMinPunktX2; + double tempMinPunktX3tf = -tempMinPunktX1; + + double minX1_temp = tempMinPunktX1tf + cX1; + // double minX2_temp = tempMinPunktX2tf+cX2; + double minX3_temp = tempMinPunktX3tf + cX3; + + minX1 = minX1_temp; + minX3 = minX3_temp; + + int nx1 = (int)voxelMatrix.getNX1(); + int nx2 = (int)voxelMatrix.getNX2(); + int nx3 = (int)voxelMatrix.getNX3(); + + int nx1_new = nx3; + int nx2_new = nx2; + int nx3_new = nx1; + + double delta_temp = deltaX1; + deltaX1 = deltaX3; + deltaX3 = delta_temp; + + GbVoxelMatrix3D::Matrix3D voxelMatrix_temp(nx1_new, nx2_new, nx3_new); + + for (int x3 = 0; x3 < nx3; x3++) { + for (int x2 = 0; x2 < nx2; x2++) { + for (int x1 = 0; x1 < nx1; x1++) { + voxelMatrix_temp(x3, x2, nx1 - x1 - 1) = this->voxelMatrix(x1, x2, x3); + } + } + } + std::swap(this->voxelMatrix, voxelMatrix_temp); } ////////////////////////////////////////////////////////////////////////// void GbVoxelMatrix3D::rotate90aroundY() { - double cX1 = this->getX1Centroid(); - double cX2 = this->getX2Centroid(); - double cX3 = this->getX3Centroid(); + double cX1 = this->getX1Centroid(); + double cX2 = this->getX2Centroid(); + double cX3 = this->getX3Centroid(); - rotate90aroundY(cX1, cX2, cX3); + rotate90aroundY(cX1, cX2, cX3); } ////////////////////////////////////////////////////////////////////////// -void GbVoxelMatrix3D::rotate90aroundZ(double cX1, double cX2, double /*cX3*/) +void GbVoxelMatrix3D::rotate90aroundZ(double cX1, double cX2, double /*cX3*/) { - double tempMinPunktX1 = minX1-cX1; - double tempMinPunktX2 = getX2Maximum()-cX2; -// double tempMinPunktX3 = minX3-cX3; - - double tempMinPunktX1tf = -tempMinPunktX2; - double tempMinPunktX2tf = tempMinPunktX1; -// double tempMinPunktX3tf = tempMinPunktX3; - - double minX1_temp = tempMinPunktX1tf+cX1; - double minX2_temp = tempMinPunktX2tf+cX2; -// double minX3_temp = tempMinPunktX3tf+cX3; - - minX1 = minX1_temp; - minX2 = minX2_temp; - - int nx1 = (int)voxelMatrix.getNX1(); - int nx2 = (int)voxelMatrix.getNX2(); - int nx3 = (int)voxelMatrix.getNX3(); - - int nx1_new = nx2; - int nx2_new = nx1; - int nx3_new = nx3; - - double delta_temp = deltaX1; - deltaX1 = deltaX2; - deltaX2 = delta_temp; - - GbVoxelMatrix3D::Matrix3D voxelMatrix_temp(nx1_new, nx2_new, nx3_new); - - for (int x3 = 0; x3<nx3; x3++) { - for (int x2 = 0; x2<nx2; x2++) { - for (int x1 = 0; x1<nx1; x1++) - { - voxelMatrix_temp(nx2-x2-1, x1, x3) = this->voxelMatrix(x1, x2, x3); - } - } - } - std::swap(this->voxelMatrix, voxelMatrix_temp); + double tempMinPunktX1 = minX1 - cX1; + double tempMinPunktX2 = getX2Maximum() - cX2; + // double tempMinPunktX3 = minX3-cX3; + + double tempMinPunktX1tf = -tempMinPunktX2; + double tempMinPunktX2tf = tempMinPunktX1; + // double tempMinPunktX3tf = tempMinPunktX3; + + double minX1_temp = tempMinPunktX1tf + cX1; + double minX2_temp = tempMinPunktX2tf + cX2; + // double minX3_temp = tempMinPunktX3tf+cX3; + + minX1 = minX1_temp; + minX2 = minX2_temp; + + int nx1 = (int)voxelMatrix.getNX1(); + int nx2 = (int)voxelMatrix.getNX2(); + int nx3 = (int)voxelMatrix.getNX3(); + + int nx1_new = nx2; + int nx2_new = nx1; + int nx3_new = nx3; + + double delta_temp = deltaX1; + deltaX1 = deltaX2; + deltaX2 = delta_temp; + + GbVoxelMatrix3D::Matrix3D voxelMatrix_temp(nx1_new, nx2_new, nx3_new); + + for (int x3 = 0; x3 < nx3; x3++) { + for (int x2 = 0; x2 < nx2; x2++) { + for (int x1 = 0; x1 < nx1; x1++) { + voxelMatrix_temp(nx2 - x2 - 1, x1, x3) = this->voxelMatrix(x1, x2, x3); + } + } + } + std::swap(this->voxelMatrix, voxelMatrix_temp); } ////////////////////////////////////////////////////////////////////////// void GbVoxelMatrix3D::rotate90aroundZ() { - double cX1 = this->getX1Centroid(); - double cX2 = this->getX2Centroid(); - double cX3 = this->getX3Centroid(); + double cX1 = this->getX1Centroid(); + double cX2 = this->getX2Centroid(); + double cX3 = this->getX3Centroid(); - rotate90aroundZ(cX1, cX2, cX3); + rotate90aroundZ(cX1, cX2, cX3); } ////////////////////////////////////////////////////////////////////////// void GbVoxelMatrix3D::mirrorX() { - int nx1 = (int)voxelMatrix.getNX1(); - int nx2 = (int)voxelMatrix.getNX2(); - int nx3 = (int)voxelMatrix.getNX3(); - - GbVoxelMatrix3D::Matrix3D voxelMatrix_temp(nx1, nx2, nx3); - - for (int x3 = 0; x3<nx3; x3++) { - for (int x2 = 0; x2<nx2; x2++) { - for (int x1 = 0; x1<nx1; x1++) - { - voxelMatrix_temp(nx1-x1-1, x2, x3) = this->voxelMatrix(x1, x2, x3); - } - } - } - std::swap(this->voxelMatrix, voxelMatrix_temp); + int nx1 = (int)voxelMatrix.getNX1(); + int nx2 = (int)voxelMatrix.getNX2(); + int nx3 = (int)voxelMatrix.getNX3(); + + GbVoxelMatrix3D::Matrix3D voxelMatrix_temp(nx1, nx2, nx3); + + for (int x3 = 0; x3 < nx3; x3++) { + for (int x2 = 0; x2 < nx2; x2++) { + for (int x1 = 0; x1 < nx1; x1++) { + voxelMatrix_temp(nx1 - x1 - 1, x2, x3) = this->voxelMatrix(x1, x2, x3); + } + } + } + std::swap(this->voxelMatrix, voxelMatrix_temp); } ////////////////////////////////////////////////////////////////////////// void GbVoxelMatrix3D::mirrorY() { - int nx1 = (int)voxelMatrix.getNX1(); - int nx2 = (int)voxelMatrix.getNX2(); - int nx3 = (int)voxelMatrix.getNX3(); - - GbVoxelMatrix3D::Matrix3D voxelMatrix_temp(nx1, nx2, nx3); - - for (int x3 = 0; x3<nx3; x3++) { - for (int x2 = 0; x2<nx2; x2++) { - for (int x1 = 0; x1<nx1; x1++) - { - voxelMatrix_temp(x1, nx2-x2-1, x3) = this->voxelMatrix(x1, x2, x3); - } - } - } - std::swap(this->voxelMatrix, voxelMatrix_temp); + int nx1 = (int)voxelMatrix.getNX1(); + int nx2 = (int)voxelMatrix.getNX2(); + int nx3 = (int)voxelMatrix.getNX3(); + + GbVoxelMatrix3D::Matrix3D voxelMatrix_temp(nx1, nx2, nx3); + + for (int x3 = 0; x3 < nx3; x3++) { + for (int x2 = 0; x2 < nx2; x2++) { + for (int x1 = 0; x1 < nx1; x1++) { + voxelMatrix_temp(x1, nx2 - x2 - 1, x3) = this->voxelMatrix(x1, x2, x3); + } + } + } + std::swap(this->voxelMatrix, voxelMatrix_temp); } ////////////////////////////////////////////////////////////////////////// void GbVoxelMatrix3D::mirrorZ() { - int nx1 = (int)voxelMatrix.getNX1(); - int nx2 = (int)voxelMatrix.getNX2(); - int nx3 = (int)voxelMatrix.getNX3(); - - GbVoxelMatrix3D::Matrix3D voxelMatrix_temp(nx1, nx2, nx3); - - for (int x3 = 0; x3<nx3; x3++) { - for (int x2 = 0; x2<nx2; x2++) { - for (int x1 = 0; x1<nx1; x1++) - { - voxelMatrix_temp(x1, x2, nx3-x3-1) = this->voxelMatrix(x1, x2, x3); - } - } - } - std::swap(this->voxelMatrix, voxelMatrix_temp); + int nx1 = (int)voxelMatrix.getNX1(); + int nx2 = (int)voxelMatrix.getNX2(); + int nx3 = (int)voxelMatrix.getNX3(); + + GbVoxelMatrix3D::Matrix3D voxelMatrix_temp(nx1, nx2, nx3); + + for (int x3 = 0; x3 < nx3; x3++) { + for (int x2 = 0; x2 < nx2; x2++) { + for (int x1 = 0; x1 < nx1; x1++) { + voxelMatrix_temp(x1, x2, nx3 - x3 - 1) = this->voxelMatrix(x1, x2, x3); + } + } + } + std::swap(this->voxelMatrix, voxelMatrix_temp); } ////////////////////////////////////////////////////////////////////////// void GbVoxelMatrix3D::rotateAroundY(double theta) { - int nx1 = (int)voxelMatrix.getNX1(); - int nx2 = (int)voxelMatrix.getNX2(); - int nx3 = (int)voxelMatrix.getNX3(); - - GbVoxelMatrix3D::Matrix3D voxelMatrix_temp(nx1, nx2, nx3, FLUID); - - for (int x3 = 0; x3<nx3; x3++) { - for (int x2 = 0; x2<nx2; x2++) { - for (int x1 = 0; x1<nx1; x1++) - { - if (voxelMatrix(x1, x2, x3)==SOLID) - { - double rcX1 = minX1+deltaX1*x1; - double rcX3 = minX3+deltaX3*x3; - - double nrcX1 = cos(theta)*rcX1+sin(theta)*rcX3; - double nrcX3 = -sin(theta)*rcX1+cos(theta)*rcX3; - - int newX1 = UbMath::integerRounding((nrcX1-minX1)/deltaX1); - int newX2 = x2; - int newX3 = UbMath::integerRounding((nrcX3-minX3)/deltaX3); - - if (newX1>0 && newX3>0 && newX1<nx1 && newX3<nx3) - { - voxelMatrix_temp(newX1, newX2, newX3) = voxelMatrix(x1, x2, x3); - } - - //int ix1, ix2, ix3; - //double ixx1 = (abs(nrcX1-minX1)/deltaX1); - //ix2 = x2; - //double ixx3 = (abs(nrcX3-minX3)/deltaX3); - //if (ixx1-(int)ixx1>.9999999999) ix1 = (int)ixx1+1; else ix1 = (int)ixx1; - ////if (ixx2-(int)ixx2>.9999999999) ix2 = (int)ixx2+1; else ix2 = (int)ixx2; - //if (ixx3-(int)ixx3>.9999999999) ix3 = (int)ixx3+1; else ix3 = (int)ixx3; - - //if (ix1>=0 && ix3>=0 && ix1<nx1 && ix3<nx3) - //{ - // voxelMatrix_temp(ix1, ix2, ix3) = voxelMatrix(x1, x2, x3); - //} + int nx1 = (int)voxelMatrix.getNX1(); + int nx2 = (int)voxelMatrix.getNX2(); + int nx3 = (int)voxelMatrix.getNX3(); + + GbVoxelMatrix3D::Matrix3D voxelMatrix_temp(nx1, nx2, nx3, FLUID); + + for (int x3 = 0; x3 < nx3; x3++) { + for (int x2 = 0; x2 < nx2; x2++) { + for (int x1 = 0; x1 < nx1; x1++) { + if (voxelMatrix(x1, x2, x3) == SOLID) { + double rcX1 = minX1 + deltaX1 * x1; + double rcX3 = minX3 + deltaX3 * x3; + + double nrcX1 = cos(theta) * rcX1 + sin(theta) * rcX3; + double nrcX3 = -sin(theta) * rcX1 + cos(theta) * rcX3; + + int newX1 = UbMath::integerRounding((nrcX1 - minX1) / deltaX1); + int newX2 = x2; + int newX3 = UbMath::integerRounding((nrcX3 - minX3) / deltaX3); + + if (newX1 > 0 && newX3 > 0 && newX1 < nx1 && newX3 < nx3) { + voxelMatrix_temp(newX1, newX2, newX3) = voxelMatrix(x1, x2, x3); + } + + // int ix1, ix2, ix3; + // double ixx1 = (abs(nrcX1-minX1)/deltaX1); + // ix2 = x2; + // double ixx3 = (abs(nrcX3-minX3)/deltaX3); + // if (ixx1-(int)ixx1>.9999999999) ix1 = (int)ixx1+1; else ix1 = (int)ixx1; + ////if (ixx2-(int)ixx2>.9999999999) ix2 = (int)ixx2+1; else ix2 = (int)ixx2; + // if (ixx3-(int)ixx3>.9999999999) ix3 = (int)ixx3+1; else ix3 = (int)ixx3; + + // if (ix1>=0 && ix3>=0 && ix1<nx1 && ix3<nx3) + //{ + // voxelMatrix_temp(ix1, ix2, ix3) = voxelMatrix(x1, x2, x3); + //} + } } - - } - } - } - std::swap(voxelMatrix, voxelMatrix_temp); - - for (int x3 = 0; x3<nx3; x3++) - for (int x2 = 0; x2<nx2; x2++) - for (int x1 = 0; x1<nx1; x1++) - { - int count = 0; - for (int k3 = -1; k3<=1; k3++) - for (int k1 = -1; k1<=1; k1++) - { - int j1 = x1+k1; - int j3 = x3+k3; - if (j1>=0 && j3>=0 && j1<nx1 && j3<nx3) - { - if (voxelMatrix(j1, x2, j3)==SOLID) - { - count++; - } - } - - } - if (count == 8) - { - voxelMatrix(x1, x2, x3) = SOLID; + } + } + std::swap(voxelMatrix, voxelMatrix_temp); + + for (int x3 = 0; x3 < nx3; x3++) + for (int x2 = 0; x2 < nx2; x2++) + for (int x1 = 0; x1 < nx1; x1++) { + int count = 0; + for (int k3 = -1; k3 <= 1; k3++) + for (int k1 = -1; k1 <= 1; k1++) { + int j1 = x1 + k1; + int j3 = x3 + k3; + if (j1 >= 0 && j3 >= 0 && j1 < nx1 && j3 < nx3) { + if (voxelMatrix(j1, x2, j3) == SOLID) { + count++; + } + } + } + if (count == 8) { + voxelMatrix(x1, x2, x3) = SOLID; + } } - } } ////////////////////////////////////////////////////////////////////////// -void GbVoxelMatrix3D::writeToLegacyVTKASCII(const std::string& fileName) -{ - string fn = fileName+".ascii.vtk"; - - FILE *file; - file = fopen(fn.c_str(), "w"); - - if (file==NULL) - { - std::string pathf = UbSystem::getPathFromString(fn); - if (fn.size()>0) { UbSystem::makeDirectory(pathf); file = fopen(fn.c_str(), "w"); } - if (file==NULL) throw UbException(UB_EXARGS, "can not open "+fn); - } - - if (file==NULL) - throw UbException(UB_EXARGS, "can not open "+fn); - - int nx1 = (int)voxelMatrix.getNX1(); - int nx2 = (int)voxelMatrix.getNX2(); - int nx3 = (int)voxelMatrix.getNX3(); - - int nn = nx1*nx2*nx3; - - fprintf(file, "# vtk DataFile Version 2.0\n"); - fprintf(file, "vtk output\n"); - fprintf(file, "ASCII\n"); - fprintf(file, "DATASET STRUCTURED_POINTS\n"); - fprintf(file, "DIMENSIONS %d %d %d\n", nx1, nx2, nx3); - fprintf(file, "ORIGIN %g %g %g\n", minX1, minX2, minX3); - fprintf(file, "SPACING %g %g %g\n", deltaX1, deltaX2, deltaX3); - fprintf(file, "POINT_DATA %d\n", nn); - fprintf(file, "SCALARS Geo float\n"); - fprintf(file, "LOOKUP_TABLE default\n"); - - for (int k = 0; k<nx3; k++) { - for (int j = 0; j<nx2; j++) { - for (int i = 0; i<nx1; i++) { - fprintf(file, "%g ", voxelMatrix(i, j, k)); - } - } - } - - fprintf(file, "\n"); - - fclose(file); +void GbVoxelMatrix3D::writeToLegacyVTKASCII(const std::string &fileName) +{ + string fn = fileName + ".ascii.vtk"; + + FILE *file; + file = fopen(fn.c_str(), "w"); + + if (file == NULL) { + std::string pathf = UbSystem::getPathFromString(fn); + if (fn.size() > 0) { + UbSystem::makeDirectory(pathf); + file = fopen(fn.c_str(), "w"); + } + if (file == NULL) + throw UbException(UB_EXARGS, "can not open " + fn); + } + + if (file == NULL) + throw UbException(UB_EXARGS, "can not open " + fn); + + int nx1 = (int)voxelMatrix.getNX1(); + int nx2 = (int)voxelMatrix.getNX2(); + int nx3 = (int)voxelMatrix.getNX3(); + + int nn = nx1 * nx2 * nx3; + + fprintf(file, "# vtk DataFile Version 2.0\n"); + fprintf(file, "vtk output\n"); + fprintf(file, "ASCII\n"); + fprintf(file, "DATASET STRUCTURED_POINTS\n"); + fprintf(file, "DIMENSIONS %d %d %d\n", nx1, nx2, nx3); + fprintf(file, "ORIGIN %g %g %g\n", minX1, minX2, minX3); + fprintf(file, "SPACING %g %g %g\n", deltaX1, deltaX2, deltaX3); + fprintf(file, "POINT_DATA %d\n", nn); + fprintf(file, "SCALARS Geo float\n"); + fprintf(file, "LOOKUP_TABLE default\n"); + + for (int k = 0; k < nx3; k++) { + for (int j = 0; j < nx2; j++) { + for (int i = 0; i < nx1; i++) { + fprintf(file, "%g ", voxelMatrix(i, j, k)); + } + } + } + + fprintf(file, "\n"); + + fclose(file); } ////////////////////////////////////////////////////////////////////////// -void GbVoxelMatrix3D::writeToLegacyVTKBinary(const std::string& fileName) -{ - string fn = fileName+".binary.vtk"; - - FILE *file; - file = fopen(fn.c_str(), "w"); - - if (file==NULL) - { - std::string pathf = UbSystem::getPathFromString(fn); - if (fn.size()>0) { UbSystem::makeDirectory(pathf); file = fopen(fn.c_str(), "w"); } - if (file==NULL) throw UbException(UB_EXARGS, "can not open "+fn); - } - - int nx1 = (int)voxelMatrix.getNX1(); - int nx2 = (int)voxelMatrix.getNX2(); - int nx3 = (int)voxelMatrix.getNX3(); - - int nn = nx1*nx2*nx3; - - char LF = 0x0A; - - fprintf(file, "# vtk DataFile Version 3.0\n"); - fprintf(file, "vtk output\n"); - fprintf(file, "BINARY\n"); - fprintf(file, "DATASET STRUCTURED_POINTS\n"); - fprintf(file, "DIMENSIONS %d %d %d\n", nx1, nx2, nx3); - fprintf(file, "ORIGIN %g %g %g\n", minX1, minX2, minX3); - fprintf(file, "SPACING %g %g %g\n", deltaX1, deltaX2, deltaX3); - fprintf(file, "POINT_DATA %d\n", nn); - fprintf(file, "SCALARS Geo float\n"); - fprintf(file, "LOOKUP_TABLE default"); - fclose(file); - - GbVoxelMatrix3D::Matrix3D voxelMatrix_temp(nx1, nx2, nx3); - - if (UbSystem::isLittleEndian()) - { - for (int x3 = 0; x3<nx3; x3++) { - for (int x2 = 0; x2<nx2; x2++) { - for (int x1 = 0; x1<nx1; x1++) - { - float tmp = this->voxelMatrix(x1, x2, x3); - UbSystem::swapByteOrder((unsigned char*)(&(tmp)), sizeof(float)); - voxelMatrix_temp(x1, x2, x3) = tmp; +void GbVoxelMatrix3D::writeToLegacyVTKBinary(const std::string &fileName) +{ + string fn = fileName + ".binary.vtk"; + + FILE *file; + file = fopen(fn.c_str(), "w"); + + if (file == NULL) { + std::string pathf = UbSystem::getPathFromString(fn); + if (fn.size() > 0) { + UbSystem::makeDirectory(pathf); + file = fopen(fn.c_str(), "w"); + } + if (file == NULL) + throw UbException(UB_EXARGS, "can not open " + fn); + } + + int nx1 = (int)voxelMatrix.getNX1(); + int nx2 = (int)voxelMatrix.getNX2(); + int nx3 = (int)voxelMatrix.getNX3(); + + int nn = nx1 * nx2 * nx3; + + char LF = 0x0A; + + fprintf(file, "# vtk DataFile Version 3.0\n"); + fprintf(file, "vtk output\n"); + fprintf(file, "BINARY\n"); + fprintf(file, "DATASET STRUCTURED_POINTS\n"); + fprintf(file, "DIMENSIONS %d %d %d\n", nx1, nx2, nx3); + fprintf(file, "ORIGIN %g %g %g\n", minX1, minX2, minX3); + fprintf(file, "SPACING %g %g %g\n", deltaX1, deltaX2, deltaX3); + fprintf(file, "POINT_DATA %d\n", nn); + fprintf(file, "SCALARS Geo float\n"); + fprintf(file, "LOOKUP_TABLE default"); + fclose(file); + + GbVoxelMatrix3D::Matrix3D voxelMatrix_temp(nx1, nx2, nx3); + + if (UbSystem::isLittleEndian()) { + for (int x3 = 0; x3 < nx3; x3++) { + for (int x2 = 0; x2 < nx2; x2++) { + for (int x1 = 0; x1 < nx1; x1++) { + float tmp = this->voxelMatrix(x1, x2, x3); + UbSystem::swapByteOrder((unsigned char *)(&(tmp)), sizeof(float)); + voxelMatrix_temp(x1, x2, x3) = tmp; + } } - } - } - } + } + } - file = fopen(fn.c_str(), "ab"); + file = fopen(fn.c_str(), "ab"); - fwrite(&LF, sizeof(char), 1, file); - fwrite(voxelMatrix_temp.getStartAdressOfSortedArray(0, 0, 0), sizeof(float), voxelMatrix_temp.getDataVector().size(), file); - fwrite(&LF, sizeof(char), 1, file); - fclose(file); + fwrite(&LF, sizeof(char), 1, file); + fwrite(voxelMatrix_temp.getStartAdressOfSortedArray(0, 0, 0), sizeof(float), + voxelMatrix_temp.getDataVector().size(), file); + fwrite(&LF, sizeof(char), 1, file); + fclose(file); } ////////////////////////////////////////////////////////////////////////// -void GbVoxelMatrix3D::writeToVTKImageDataASCII(const std::string& fileName) -{ - int nx1 = (int)voxelMatrix.getNX1(); - int nx2 = (int)voxelMatrix.getNX2(); - int nx3 = (int)voxelMatrix.getNX3(); - - string fn = fileName+".ascii.vti"; - - FILE *file; - file = fopen(fn.c_str(), "w"); - - if (file==NULL) - { - std::string pathf = UbSystem::getPathFromString(fn); - if (fn.size()>0) { UbSystem::makeDirectory(pathf); file = fopen(fn.c_str(), "w"); } - if (file==NULL) throw UbException(UB_EXARGS, "can not open "+fn); - } - - fprintf(file, "<VTKFile type=\"ImageData\" version=\"1.0\" byte_order=\"LittleEndian\" header_type=\"UInt64\">\n"); //paraview 4.1 - //fprintf(file,"<VTKFile type=\"ImageData\" version=\"0.1\" byte_order=\"LittleEndian\">\n"); //paraview 3.1 - fprintf(file, " <ImageData WholeExtent=\"%d %d %d %d %d %d\" Origin=\"%g %g %g\" Spacing=\"%g %g %g\">\n", 0, nx1-1, 0, nx2-1, 0, nx3-1, minX1, minX2, minX3, deltaX1, deltaX2, deltaX3); - fprintf(file, " <Piece Extent=\"%d %d %d %d %d %d\">\n", 0, nx1-1, 0, nx2-1, 0, nx3-1); - fprintf(file, " <PointData Scalars=\"VoxelMatrix\">\n"); - fprintf(file, " <DataArray type=\"Float32\" Name=\"VoxelMatrix\" format=\"ascii\" RangeMin=\"0\" RangeMax=\"1\">\n "); - - for (int k = 0; k<nx3; k++) { - for (int j = 0; j<nx2; j++) { - for (int i = 0; i<nx1; i++) { - fprintf(file, "%g ", voxelMatrix(i, j, k)); - } - } - } - - fprintf(file, "\n </DataArray>\n"); - fprintf(file, " </PointData>\n"); - fprintf(file, " <CellData>\n"); - fprintf(file, " </CellData>\n"); - fprintf(file, " </Piece>\n"); - fprintf(file, " </ImageData>\n"); - fprintf(file, "</VTKFile>\n"); - - fclose(file); +void GbVoxelMatrix3D::writeToVTKImageDataASCII(const std::string &fileName) +{ + int nx1 = (int)voxelMatrix.getNX1(); + int nx2 = (int)voxelMatrix.getNX2(); + int nx3 = (int)voxelMatrix.getNX3(); + + string fn = fileName + ".ascii.vti"; + + FILE *file; + file = fopen(fn.c_str(), "w"); + + if (file == NULL) { + std::string pathf = UbSystem::getPathFromString(fn); + if (fn.size() > 0) { + UbSystem::makeDirectory(pathf); + file = fopen(fn.c_str(), "w"); + } + if (file == NULL) + throw UbException(UB_EXARGS, "can not open " + fn); + } + + fprintf(file, + "<VTKFile type=\"ImageData\" version=\"1.0\" byte_order=\"LittleEndian\" header_type=\"UInt64\">\n"); // paraview + // 4.1 + // fprintf(file,"<VTKFile type=\"ImageData\" version=\"0.1\" byte_order=\"LittleEndian\">\n"); //paraview 3.1 + fprintf(file, " <ImageData WholeExtent=\"%d %d %d %d %d %d\" Origin=\"%g %g %g\" Spacing=\"%g %g %g\">\n", 0, + nx1 - 1, 0, nx2 - 1, 0, nx3 - 1, minX1, minX2, minX3, deltaX1, deltaX2, deltaX3); + fprintf(file, " <Piece Extent=\"%d %d %d %d %d %d\">\n", 0, nx1 - 1, 0, nx2 - 1, 0, nx3 - 1); + fprintf(file, " <PointData Scalars=\"VoxelMatrix\">\n"); + fprintf(file, " <DataArray type=\"Float32\" Name=\"VoxelMatrix\" format=\"ascii\" RangeMin=\"0\" " + "RangeMax=\"1\">\n "); + + for (int k = 0; k < nx3; k++) { + for (int j = 0; j < nx2; j++) { + for (int i = 0; i < nx1; i++) { + fprintf(file, "%g ", voxelMatrix(i, j, k)); + } + } + } + + fprintf(file, "\n </DataArray>\n"); + fprintf(file, " </PointData>\n"); + fprintf(file, " <CellData>\n"); + fprintf(file, " </CellData>\n"); + fprintf(file, " </Piece>\n"); + fprintf(file, " </ImageData>\n"); + fprintf(file, "</VTKFile>\n"); + + fclose(file); } ////////////////////////////////////////////////////////////////////////// -void GbVoxelMatrix3D::writeToVTKImageDataAppended(const std::string& fileName) -{ - int nx1 = (int)voxelMatrix.getNX1(); - int nx2 = (int)voxelMatrix.getNX2(); - int nx3 = (int)voxelMatrix.getNX3(); - - string fn = fileName+".appended.vti"; - - FILE *file; - file = fopen(fn.c_str(), "w"); - - if (file==NULL) - { - std::string pathf = UbSystem::getPathFromString(fn); - if (fn.size()>0) { UbSystem::makeDirectory(pathf); file = fopen(fn.c_str(), "w"); } - if (file==NULL) throw UbException(UB_EXARGS, "can not open "+fn); - } - - fprintf(file, "<VTKFile type=\"ImageData\" version=\"1.0\" byte_order=\"LittleEndian\" header_type=\"UInt64\">\n"); //paraview 4.1 - fprintf(file, " <ImageData WholeExtent=\"%d %d %d %d %d %d\" Origin=\"%g %g %g\" Spacing=\"%g %g %g\">\n", 0, nx1-1, 0, nx2-1, 0, nx3-1, minX1, minX2, minX3, deltaX1, deltaX2, deltaX3); - fprintf(file, " <Piece Extent=\"%d %d %d %d %d %d\">\n", 0, nx1-1, 0, nx2-1, 0, nx3-1); - fprintf(file, " <PointData Scalars=\"VoxelMatrix\">\n"); - fprintf(file, " <DataArray type=\"Float32\" Name=\"VoxelMatrix\" format=\"appended\" RangeMin=\"0\" RangeMax=\"1\" offset=\"0\" />\n"); - fprintf(file, " </PointData>\n"); - fprintf(file, " <CellData>\n"); - fprintf(file, " </CellData>\n"); - fprintf(file, " </Piece>\n"); - fprintf(file, " </ImageData>\n"); - fprintf(file, " <AppendedData encoding=\"raw\">\n"); - fprintf(file, " _"); - fclose(file); - - file = fopen(fn.c_str(), "ab"); - unsigned long long size = (unsigned long long)voxelMatrix.getDataVector().size()*sizeof(float); - fwrite(&size, sizeof(unsigned long long), 1, file); - fwrite(voxelMatrix.getStartAdressOfSortedArray(0, 0, 0), sizeof(float), voxelMatrix.getDataVector().size(), file); - fclose(file); - - file = fopen(fn.c_str(), "a"); - fprintf(file, "\n"); - fprintf(file, " </AppendedData>\n"); - fprintf(file, "</VTKFile>\n"); - fclose(file); +void GbVoxelMatrix3D::writeToVTKImageDataAppended(const std::string &fileName) +{ + int nx1 = (int)voxelMatrix.getNX1(); + int nx2 = (int)voxelMatrix.getNX2(); + int nx3 = (int)voxelMatrix.getNX3(); + + string fn = fileName + ".appended.vti"; + + FILE *file; + file = fopen(fn.c_str(), "w"); + + if (file == NULL) { + std::string pathf = UbSystem::getPathFromString(fn); + if (fn.size() > 0) { + UbSystem::makeDirectory(pathf); + file = fopen(fn.c_str(), "w"); + } + if (file == NULL) + throw UbException(UB_EXARGS, "can not open " + fn); + } + + fprintf(file, + "<VTKFile type=\"ImageData\" version=\"1.0\" byte_order=\"LittleEndian\" header_type=\"UInt64\">\n"); // paraview + // 4.1 + fprintf(file, " <ImageData WholeExtent=\"%d %d %d %d %d %d\" Origin=\"%g %g %g\" Spacing=\"%g %g %g\">\n", 0, + nx1 - 1, 0, nx2 - 1, 0, nx3 - 1, minX1, minX2, minX3, deltaX1, deltaX2, deltaX3); + fprintf(file, " <Piece Extent=\"%d %d %d %d %d %d\">\n", 0, nx1 - 1, 0, nx2 - 1, 0, nx3 - 1); + fprintf(file, " <PointData Scalars=\"VoxelMatrix\">\n"); + fprintf(file, " <DataArray type=\"Float32\" Name=\"VoxelMatrix\" format=\"appended\" RangeMin=\"0\" " + "RangeMax=\"1\" offset=\"0\" />\n"); + fprintf(file, " </PointData>\n"); + fprintf(file, " <CellData>\n"); + fprintf(file, " </CellData>\n"); + fprintf(file, " </Piece>\n"); + fprintf(file, " </ImageData>\n"); + fprintf(file, " <AppendedData encoding=\"raw\">\n"); + fprintf(file, " _"); + fclose(file); + + file = fopen(fn.c_str(), "ab"); + unsigned long long size = (unsigned long long)voxelMatrix.getDataVector().size() * sizeof(float); + fwrite(&size, sizeof(unsigned long long), 1, file); + fwrite(voxelMatrix.getStartAdressOfSortedArray(0, 0, 0), sizeof(float), voxelMatrix.getDataVector().size(), file); + fclose(file); + + file = fopen(fn.c_str(), "a"); + fprintf(file, "\n"); + fprintf(file, " </AppendedData>\n"); + fprintf(file, "</VTKFile>\n"); + fclose(file); } - - diff --git a/src/basics/geometry3d/GbVoxelMatrix3D.h b/src/basics/geometry3d/GbVoxelMatrix3D.h index 69af1e54795606f2251063370f8b2f75908d8ffa..ba4b3b420e7ac25c79b870d6472716e392409437 100644 --- a/src/basics/geometry3d/GbVoxelMatrix3D.h +++ b/src/basics/geometry3d/GbVoxelMatrix3D.h @@ -7,13 +7,12 @@ #ifndef GBVOXELMATRIX3D_H #define GBVOXELMATRIX3D_H - -#include <vector> #include <cmath> +#include <vector> -#include <geometry3d/GbObject3D.h> -#include <basics/utilities/UbObserver.h> #include <basics/container/CbArray3D.h> +#include <basics/utilities/UbObserver.h> +#include <geometry3d/GbObject3D.h> #include <PointerDefinitions.h> @@ -24,279 +23,302 @@ class GbObject3DCreator; class GbVoxelMatrix3D : public GbObject3D, public UbObserver { public: - using Matrix3D = CbArray3D<float>; - static const float SOLID; - static const float FLUID; - enum Endian { BigEndian, LittleEndian }; - - GbVoxelMatrix3D(); - GbVoxelMatrix3D(int nx1, int nx2, int nx3, float initVal, double lowerThreshold = 0, double upperThreshold = 0); - GbVoxelMatrix3D(const Matrix3D& voxelMatrix, double lowerThreshold = 0, double upperThreshold = 0); - ~GbVoxelMatrix3D() override = default; - - void finalize() override {}; - GbVoxelMatrix3D* clone() override; - - /*=======================================================================*/ - Matrix3D::reference operator() (const Matrix3D::size_type& x1, const Matrix3D::size_type& x2, const Matrix3D::size_type& x3) - { - return voxelMatrix(x1, x2, x3); - } - /*=======================================================================*/ - Matrix3D::const_reference operator() (const Matrix3D::size_type& x1, const Matrix3D::size_type& x2, const Matrix3D::size_type& x3) const - { - return voxelMatrix(x1, x2, x3); - } - /*=======================================================================*/ - void setTransferViaFilename(bool transferViaFilename, std::string filename) - { - this->filename = filename; - this->transferViaFilename = transferViaFilename; - } - void setThreshold(double lowerThreshold, double upperThreshold) { this->lowerThreshold = lowerThreshold; this->upperThreshold = upperThreshold; } - void setAddSurfaceTriangleSetFlag(bool flag) { this->addSurfaceTriangleSetFlag = flag; } - - /*=======================================================================*/ - void setVoxelMatrixMininum(double minX1, double minX2, double minX3) { this->minX1 = minX1; this->minX2 = minX2; this->minX3 = minX3; } - void setVoxelMatrixMinX1(double minX1) { this->minX1 = minX1; } - void setVoxelMatrixMinX2(double minX2) { this->minX2 = minX2; } - void setVoxelMatrixMinX3(double minX3) { this->minX3 = minX3; } - - /*=======================================================================*/ - void setVoxelMatrixDelta(double deltaX1, double deltaX2, double deltaX3) { this->deltaX1 = deltaX1; this->deltaX2 = deltaX2; this->deltaX3 = deltaX3; } - void setVoxelMatrixDeltaX1(double deltaX1) { this->deltaX1 = deltaX1; } - void setVoxelMatrixDeltaX2(double deltaX2) { this->deltaX2 = deltaX2; } - void setVoxelMatrixDeltaX3(double deltaX3) { this->deltaX3 = deltaX3; } - - /*=======================================================================*/ - double getX1Centroid() override { return 0.5 * (minX1+this->getX1Maximum()); } - double getX1Minimum() override { return minX1; } - double getX1Maximum() override { return minX1+deltaX1*voxelMatrix.getNX1(); } - - double getX2Centroid() override { return 0.5 * (minX2+this->getX2Maximum()); } - double getX2Minimum() override { return minX2; } - double getX2Maximum() override { return minX2+deltaX2*voxelMatrix.getNX2(); } - - double getX3Centroid() override { return 0.5 * (this->getX3Minimum()+this->getX3Maximum()); } - double getX3Minimum() override { return minX3; } - double getX3Maximum() override { return minX3+deltaX3*voxelMatrix.getNX3(); } - - double getLengthX1() { return this->getX1Maximum()-minX1; } - double getLengthX2() { return this->getX2Maximum()-minX2; } - double getLengthX3() { return this->getX3Maximum()-minX3; } - - void setCenterCoordinates(const double& x1, const double& x2, const double& x3) override; - void translate(const double& tx1, const double& tx2, const double& tx3) override; - - bool isPointInGbObject3D(const double& x1p, const double& x2p, const double& x3p, bool& pointIsOnBoundary) override; - bool isPointInGbObject3D(const double& x1p, const double& x2p, const double& x3p) override; - bool isCellInsideGbObject3D(const double& x1a, const double& x2a, const double& x3a, const double& x1b, const double& x2b, const double& x3b) override; - bool isCellCuttingGbObject3D(const double& x1a, const double& x2a, const double& x3a, const double& x1b, const double& x2b, const double& x3b) override; - bool isCellInsideOrCuttingGbObject3D(const double& x1a, const double& x2a, const double& x3a, const double& x1b, const double& x2b, const double& x3b) override; - //double getCellVolumeInsideGbObject3D(const double& x1a,const double& x2a,const double& x3a,const double& x1b,const double& x2b,const double& x3b); - - GbPoint3D* calculateInterSectionPoint3D(GbPoint3D& /*point1*/, GbPoint3D & /*point2*/) { throw UbException(__FILE__, __LINE__, UB_FUNCTION, "not implemented"); } - GbLine3D* createClippedLine3D(GbPoint3D& /*point1*/, GbPoint3D& /*point2*/) override { throw UbException(__FILE__, __LINE__, UB_FUNCTION, "not implemented"); } - - std::vector<GbTriangle3D*> getSurfaceTriangleSet() override; - void addSurfaceTriangleSet(std::vector<UbTupleFloat3>& nodes, std::vector<UbTupleInt3>& triangles) override; - - bool hasRaytracing() override { return true; } - /*|r| must be 1! einheitsvector!!*/ - double getIntersectionRaytraceFactor(const double& x1, const double& x2, const double& x3, const double& rx1, const double& rx2, const double& rx3) override; - - std::string toString() override; - - //virtuelle Methoden von UbObserver - void objectChanged(UbObservable* changedObject) override {} - void objectWillBeDeleted(UbObservable* objectForDeletion) override {} - - template <class T> - void readMatrixFromRawFile(std::string filename, GbVoxelMatrix3D::Endian endian); - template <class T> - void readBufferedMatrixFromRawFile(std::string filename, GbVoxelMatrix3D::Endian endian); - void readMatrixFromVtiASCIIFile(std::string filename); - - void rotate90aroundX(); - void rotate90aroundY(); - void rotate90aroundZ(); - void rotate90aroundX(double cX1, double cX2, double cX3); - void rotate90aroundY(double cX1, double cX2, double cX3); - void rotate90aroundZ(double cX1, double cX2, double cX3); - void mirrorX(); - void mirrorY(); - void mirrorZ(); - - void rotateAroundY(double theta); - - void writeToLegacyVTKASCII(const std::string& fileName); - void writeToLegacyVTKBinary(const std::string& fileName); - void writeToVTKImageDataASCII(const std::string& fileName); - void writeToVTKImageDataAppended(const std::string& fileName); - - void setClosedVoidSpaceToSolid(); - - void calculateNumberOfSolidAndFluid(); - long getNumberOfSolid(); - long getNumberOfFluid(); + using Matrix3D = CbArray3D<float>; + static const float SOLID; + static const float FLUID; + enum Endian { BigEndian, LittleEndian }; + + GbVoxelMatrix3D(); + GbVoxelMatrix3D(int nx1, int nx2, int nx3, float initVal, double lowerThreshold = 0, double upperThreshold = 0); + GbVoxelMatrix3D(const Matrix3D &voxelMatrix, double lowerThreshold = 0, double upperThreshold = 0); + ~GbVoxelMatrix3D() override = default; + + void finalize() override{}; + GbVoxelMatrix3D *clone() override; + + /*=======================================================================*/ + Matrix3D::reference operator()(const Matrix3D::size_type &x1, const Matrix3D::size_type &x2, + const Matrix3D::size_type &x3) + { + return voxelMatrix(x1, x2, x3); + } + /*=======================================================================*/ + Matrix3D::const_reference operator()(const Matrix3D::size_type &x1, const Matrix3D::size_type &x2, + const Matrix3D::size_type &x3) const + { + return voxelMatrix(x1, x2, x3); + } + /*=======================================================================*/ + void setTransferViaFilename(bool transferViaFilename, std::string filename) + { + this->filename = filename; + this->transferViaFilename = transferViaFilename; + } + void setThreshold(double lowerThreshold, double upperThreshold) + { + this->lowerThreshold = lowerThreshold; + this->upperThreshold = upperThreshold; + } + void setAddSurfaceTriangleSetFlag(bool flag) { this->addSurfaceTriangleSetFlag = flag; } + + /*=======================================================================*/ + void setVoxelMatrixMininum(double minX1, double minX2, double minX3) + { + this->minX1 = minX1; + this->minX2 = minX2; + this->minX3 = minX3; + } + void setVoxelMatrixMinX1(double minX1) { this->minX1 = minX1; } + void setVoxelMatrixMinX2(double minX2) { this->minX2 = minX2; } + void setVoxelMatrixMinX3(double minX3) { this->minX3 = minX3; } + + /*=======================================================================*/ + void setVoxelMatrixDelta(double deltaX1, double deltaX2, double deltaX3) + { + this->deltaX1 = deltaX1; + this->deltaX2 = deltaX2; + this->deltaX3 = deltaX3; + } + void setVoxelMatrixDeltaX1(double deltaX1) { this->deltaX1 = deltaX1; } + void setVoxelMatrixDeltaX2(double deltaX2) { this->deltaX2 = deltaX2; } + void setVoxelMatrixDeltaX3(double deltaX3) { this->deltaX3 = deltaX3; } + + /*=======================================================================*/ + double getX1Centroid() override { return 0.5 * (minX1 + this->getX1Maximum()); } + double getX1Minimum() override { return minX1; } + double getX1Maximum() override { return minX1 + deltaX1 * voxelMatrix.getNX1(); } + + double getX2Centroid() override { return 0.5 * (minX2 + this->getX2Maximum()); } + double getX2Minimum() override { return minX2; } + double getX2Maximum() override { return minX2 + deltaX2 * voxelMatrix.getNX2(); } + + double getX3Centroid() override { return 0.5 * (this->getX3Minimum() + this->getX3Maximum()); } + double getX3Minimum() override { return minX3; } + double getX3Maximum() override { return minX3 + deltaX3 * voxelMatrix.getNX3(); } + + double getLengthX1() { return this->getX1Maximum() - minX1; } + double getLengthX2() { return this->getX2Maximum() - minX2; } + double getLengthX3() { return this->getX3Maximum() - minX3; } + + void setCenterCoordinates(const double &x1, const double &x2, const double &x3) override; + void translate(const double &tx1, const double &tx2, const double &tx3) override; + + bool isPointInGbObject3D(const double &x1p, const double &x2p, const double &x3p, bool &pointIsOnBoundary) override; + bool isPointInGbObject3D(const double &x1p, const double &x2p, const double &x3p) override; + bool isCellInsideGbObject3D(const double &x1a, const double &x2a, const double &x3a, const double &x1b, + const double &x2b, const double &x3b) override; + bool isCellCuttingGbObject3D(const double &x1a, const double &x2a, const double &x3a, const double &x1b, + const double &x2b, const double &x3b) override; + bool isCellInsideOrCuttingGbObject3D(const double &x1a, const double &x2a, const double &x3a, const double &x1b, + const double &x2b, const double &x3b) override; + // double getCellVolumeInsideGbObject3D(const double& x1a,const double& x2a,const double& x3a,const double& + // x1b,const double& x2b,const double& x3b); + + GbPoint3D *calculateInterSectionPoint3D(GbPoint3D & /*point1*/, GbPoint3D & /*point2*/) + { + throw UbException(__FILE__, __LINE__, UB_FUNCTION, "not implemented"); + } + GbLine3D *createClippedLine3D(GbPoint3D & /*point1*/, GbPoint3D & /*point2*/) override + { + throw UbException(__FILE__, __LINE__, UB_FUNCTION, "not implemented"); + } + + std::vector<GbTriangle3D *> getSurfaceTriangleSet() override; + void addSurfaceTriangleSet(std::vector<UbTupleFloat3> &nodes, std::vector<UbTupleInt3> &triangles) override; + + bool hasRaytracing() override { return true; } + /*|r| must be 1! einheitsvector!!*/ + double getIntersectionRaytraceFactor(const double &x1, const double &x2, const double &x3, const double &rx1, + const double &rx2, const double &rx3) override; + + std::string toString() override; + + // virtuelle Methoden von UbObserver + void objectChanged(UbObservable *changedObject) override {} + void objectWillBeDeleted(UbObservable *objectForDeletion) override {} + + template <class T> + void readMatrixFromRawFile(std::string filename, GbVoxelMatrix3D::Endian endian); + template <class T> + void readBufferedMatrixFromRawFile(std::string filename, GbVoxelMatrix3D::Endian endian); + void readMatrixFromVtiASCIIFile(std::string filename); + + void rotate90aroundX(); + void rotate90aroundY(); + void rotate90aroundZ(); + void rotate90aroundX(double cX1, double cX2, double cX3); + void rotate90aroundY(double cX1, double cX2, double cX3); + void rotate90aroundZ(double cX1, double cX2, double cX3); + void mirrorX(); + void mirrorY(); + void mirrorZ(); + + void rotateAroundY(double theta); + + void writeToLegacyVTKASCII(const std::string &fileName); + void writeToLegacyVTKBinary(const std::string &fileName); + void writeToVTKImageDataASCII(const std::string &fileName); + void writeToVTKImageDataAppended(const std::string &fileName); + + void setClosedVoidSpaceToSolid(); + + void calculateNumberOfSolidAndFluid(); + long getNumberOfSolid(); + long getNumberOfFluid(); protected: - void findFluidNeighbor(int cx1, int cx2, int cx3); - Matrix3D voxelMatrixTemp; - CbArray3D<char> flagMatrix; + void findFluidNeighbor(int cx1, int cx2, int cx3); + Matrix3D voxelMatrixTemp; + CbArray3D<char> flagMatrix; - std::vector<int> x1Nbr; - std::vector<int> x2Nbr; - std::vector<int> x3Nbr; + std::vector<int> x1Nbr; + std::vector<int> x2Nbr; + std::vector<int> x3Nbr; - std::vector<int> x1NbrTemp; - std::vector<int> x2NbrTemp; - std::vector<int> x3NbrTemp; - - using GbObject3D::isPointInGbObject3D; //Grund: dadurch muss man hier isPointInGbObject3D(GbPoint3D*) nicht ausprogrammieren, welche sonst hier "ueberdeckt" waere + std::vector<int> x1NbrTemp; + std::vector<int> x2NbrTemp; + std::vector<int> x3NbrTemp; + using GbObject3D::isPointInGbObject3D; // Grund: dadurch muss man hier isPointInGbObject3D(GbPoint3D*) nicht + // ausprogrammieren, welche sonst hier "ueberdeckt" waere protected: - //for transfer - std::string filename; - bool transferViaFilename{false}; - - bool addSurfaceTriangleSetFlag{true}; + // for transfer + std::string filename; + bool transferViaFilename{ false }; - int nodesX1{0}; - int nodesX2{0}; - int nodesX3{0}; - double lowerThreshold{0.0}, upperThreshold{0.0}; + bool addSurfaceTriangleSetFlag{ true }; - double minX1{0.0}; - double minX2{0.0}; - double minX3{0.0}; - double deltaX1{1.0}; - double deltaX2{1.0}; - double deltaX3{1.0}; + int nodesX1{ 0 }; + int nodesX2{ 0 }; + int nodesX3{ 0 }; + double lowerThreshold{ 0.0 }, upperThreshold{ 0.0 }; - Matrix3D voxelMatrix; + double minX1{ 0.0 }; + double minX2{ 0.0 }; + double minX3{ 0.0 }; + double deltaX1{ 1.0 }; + double deltaX2{ 1.0 }; + double deltaX3{ 1.0 }; - long numberOfSolid; - long numberOfFluid; + Matrix3D voxelMatrix; + long numberOfSolid; + long numberOfFluid; }; ////////////////////////////////////////////////////////////////////////// template <class T> void GbVoxelMatrix3D::readMatrixFromRawFile(std::string filename, GbVoxelMatrix3D::Endian endian) { - using namespace std; - //UBLOG(logINFO,"GbVoxelMatrix3D::readMatrixFromFile \""<<filename<<"\" nodes("<<nodesX1<<"/"<<nodesX2<<"/"<<nodesX3<<") - start"); - ifstream in(filename.c_str(), ios::binary); - if (!in) throw UbException(UB_EXARGS, "could not open file "+filename); - - in.seekg(0, ios::end); //Ende springen - fstream::off_type length = in.tellg(); //Position abfragen - in.seekg(0, ios::beg); //An den Anfang springen - - //UBLOG(logINFO,"number of nodes = "<<nodesX1*nodesX2*nodesX3*sizeof(T)<<" file size = "<<(long)length); - //if( (nodesX1*nodesX2*nodesX3)*sizeof(float) != (long)length ) - unsigned long long nofn = (unsigned long long)nodesX1*(unsigned long long)nodesX2*(unsigned long long)nodesX3*(unsigned long long)sizeof(T); - if (nofn!=(unsigned long long)length) - { - throw UbException(UB_EXARGS, "number of nodes("+UbSystem::toString(nofn)+") doesn't match file size("+UbSystem::toString((long)length)+")"); - } - - //UBLOG(logINFO," - create GbVoxelMatrix3D"); - //GbVoxelMatrix3D* voxelGeo = new GbVoxelMatrix3D(nodesX1,nodesX2,nodesX3,GbVoxelMatrix3D::FLUID); - voxelMatrix = Matrix3D(nodesX1, nodesX2, nodesX3, GbVoxelMatrix3D::FLUID); - - //UBLOG(logINFO," - init values"); - //float val; - T val; - for (int x3 = 0; x3<nodesX3; x3++) - for (int x2 = 0; x2<nodesX2; x2++) - for (int x1 = 0; x1<nodesX1; x1++) - { - //in.read((char*)&val,sizeof(float)); - in.read((char*)&val, sizeof(T)); - if (endian==BigEndian) - UbSystem::swapByteOrder((unsigned char*)(&(val)), sizeof(T)); - //if( UbMath::equal((double)val, threshold) ) - //if( UbMath::greater((double)val, threshold) ) - if ((double)val>=lowerThreshold&&(double)val<=upperThreshold) - { - (voxelMatrix)(x1, x2, x3) = GbVoxelMatrix3D::SOLID; + using namespace std; + // UBLOG(logINFO,"GbVoxelMatrix3D::readMatrixFromFile \""<<filename<<"\" + // nodes("<<nodesX1<<"/"<<nodesX2<<"/"<<nodesX3<<") - start"); + ifstream in(filename.c_str(), ios::binary); + if (!in) + throw UbException(UB_EXARGS, "could not open file " + filename); + + in.seekg(0, ios::end); // Ende springen + fstream::off_type length = in.tellg(); // Position abfragen + in.seekg(0, ios::beg); // An den Anfang springen + + // UBLOG(logINFO,"number of nodes = "<<nodesX1*nodesX2*nodesX3*sizeof(T)<<" file size = "<<(long)length); + // if( (nodesX1*nodesX2*nodesX3)*sizeof(float) != (long)length ) + unsigned long long nofn = (unsigned long long)nodesX1 * (unsigned long long)nodesX2 * (unsigned long long)nodesX3 * + (unsigned long long)sizeof(T); + if (nofn != (unsigned long long)length) { + throw UbException(UB_EXARGS, "number of nodes(" + UbSystem::toString(nofn) + ") doesn't match file size(" + + UbSystem::toString((long)length) + ")"); + } + + // UBLOG(logINFO," - create GbVoxelMatrix3D"); + // GbVoxelMatrix3D* voxelGeo = new GbVoxelMatrix3D(nodesX1,nodesX2,nodesX3,GbVoxelMatrix3D::FLUID); + voxelMatrix = Matrix3D(nodesX1, nodesX2, nodesX3, GbVoxelMatrix3D::FLUID); + + // UBLOG(logINFO," - init values"); + // float val; + T val; + for (int x3 = 0; x3 < nodesX3; x3++) + for (int x2 = 0; x2 < nodesX2; x2++) + for (int x1 = 0; x1 < nodesX1; x1++) { + // in.read((char*)&val,sizeof(float)); + in.read((char *)&val, sizeof(T)); + if (endian == BigEndian) + UbSystem::swapByteOrder((unsigned char *)(&(val)), sizeof(T)); + // if( UbMath::equal((double)val, threshold) ) + // if( UbMath::greater((double)val, threshold) ) + if ((double)val >= lowerThreshold && (double)val <= upperThreshold) { + (voxelMatrix)(x1, x2, x3) = GbVoxelMatrix3D::SOLID; + } + //(voxelMatrix)(x1, x2, x3) = (float)val; } - //(voxelMatrix)(x1, x2, x3) = (float)val; - } - //UBLOG(logINFO,"GbVoxelMatrix3D::readMatrixFromFile \""<<filename<<"\" nodes("<<nodesX1<<"/"<<nodesX2<<"/"<<nodesX3<<") - end"); + // UBLOG(logINFO,"GbVoxelMatrix3D::readMatrixFromFile \""<<filename<<"\" + // nodes("<<nodesX1<<"/"<<nodesX2<<"/"<<nodesX3<<") - end"); } ////////////////////////////////////////////////////////////////////////// template <class T> void GbVoxelMatrix3D::readBufferedMatrixFromRawFile(std::string filename, GbVoxelMatrix3D::Endian endian) { - using namespace std; - UBLOG(logINFO, "GbVoxelMatrix3D::readMatrixFromRawFile \""<<filename<<"\" nodes("<<nodesX1<<"/"<<nodesX2<<"/"<<nodesX3<<") - start"); - - FILE *file; - file = fopen(filename.c_str(), "rb"); - if (file==NULL) - { - throw UbException(UB_EXARGS, "Could not open file "+filename); - } - - // obtain file size: - fseek(file, 0, SEEK_END); - unsigned long int length = ftell(file); - rewind(file); - - UBLOG(logINFO, "number of nodes = "<<(long)nodesX1*(long)nodesX2*(long)nodesX3<<" file size = "<<length); - - unsigned long int nofn = (long)nodesX1*(long)nodesX2*(long)nodesX3*(long)sizeof(T); - if (nofn!=length) - { - //throw UbException(UB_EXARGS, "number of nodes("+UbSystem::toString(nofn)+") doesn't match file size("+UbSystem::toString(length)+")"); - } - - UBLOG(logINFO, " - create GbVoxelMatrix3D"); - voxelMatrix = Matrix3D(nodesX1, nodesX2, nodesX3, GbVoxelMatrix3D::FLUID); - - CbArray3D<T> readMatrix(nodesX1, nodesX2, nodesX3); - - UBLOG(logINFO, " - read file to matrix"); - fread(readMatrix.getStartAdressOfSortedArray(0, 0, 0), sizeof(T), readMatrix.getDataVector().size(), file); - fclose(file); - - UBLOG(logINFO, " - init values"); - - numberOfSolid = 0; - T val; - for (int x3 = 0; x3<nodesX3; x3++) - for (int x2 = 0; x2<nodesX2; x2++) - for (int x1 = 0; x1<nodesX1; x1++) - { - val = readMatrix(x1, x2, x3); - - if (endian==BigEndian) - { - UbSystem::swapByteOrder((unsigned char*)(&(val)), sizeof(T)); - } - - if ((double)val>=lowerThreshold&&(double)val<=upperThreshold) - { - voxelMatrix(x1, x2, x3) = GbVoxelMatrix3D::SOLID; + using namespace std; + UBLOG(logINFO, "GbVoxelMatrix3D::readMatrixFromRawFile \"" << filename << "\" nodes(" << nodesX1 << "/" << nodesX2 + << "/" << nodesX3 << ") - start"); + + FILE *file; + file = fopen(filename.c_str(), "rb"); + if (file == NULL) { + throw UbException(UB_EXARGS, "Could not open file " + filename); + } + + // obtain file size: + fseek(file, 0, SEEK_END); + unsigned long int length = ftell(file); + rewind(file); + + UBLOG(logINFO, "number of nodes = " << (long)nodesX1 * (long)nodesX2 * (long)nodesX3 << " file size = " << length); + + unsigned long int nofn = (long)nodesX1 * (long)nodesX2 * (long)nodesX3 * (long)sizeof(T); + if (nofn != length) { + // throw UbException(UB_EXARGS, "number of nodes("+UbSystem::toString(nofn)+") doesn't match file + // size("+UbSystem::toString(length)+")"); + } + + UBLOG(logINFO, " - create GbVoxelMatrix3D"); + voxelMatrix = Matrix3D(nodesX1, nodesX2, nodesX3, GbVoxelMatrix3D::FLUID); + + CbArray3D<T> readMatrix(nodesX1, nodesX2, nodesX3); + + UBLOG(logINFO, " - read file to matrix"); + fread(readMatrix.getStartAdressOfSortedArray(0, 0, 0), sizeof(T), readMatrix.getDataVector().size(), file); + fclose(file); + + UBLOG(logINFO, " - init values"); + + numberOfSolid = 0; + T val; + for (int x3 = 0; x3 < nodesX3; x3++) + for (int x2 = 0; x2 < nodesX2; x2++) + for (int x1 = 0; x1 < nodesX1; x1++) { + val = readMatrix(x1, x2, x3); + + if (endian == BigEndian) { + UbSystem::swapByteOrder((unsigned char *)(&(val)), sizeof(T)); + } + + if ((double)val >= lowerThreshold && (double)val <= upperThreshold) { + voxelMatrix(x1, x2, x3) = GbVoxelMatrix3D::SOLID; + } } - } - UBLOG(logINFO, "GbVoxelMatrix3D::readMatrixFromRawFile \""<<filename<<"\" nodes("<<nodesX1<<"/"<<nodesX2<<"/"<<nodesX3<<") - end"); + UBLOG(logINFO, "GbVoxelMatrix3D::readMatrixFromRawFile \"" << filename << "\" nodes(" << nodesX1 << "/" << nodesX2 + << "/" << nodesX3 << ") - end"); } - - //#if defined(RCF_USE_SF_SERIALIZATION) && !defined(SWIG) -//UB_AUTO_RUN_NAMED(SF::registerType<GbVoxelMatrix3D>("GbVoxelMatrix3D"), SF_GbVoxelMatrix3D); -//UB_AUTO_RUN_NAMED((SF::registerBaseAndDerived< GbObject3D, GbVoxelMatrix3D >()), SF_GbVoxelMatrix3D_BD1); -//UB_AUTO_RUN_NAMED((SF::registerBaseAndDerived< UbObserver, GbVoxelMatrix3D>()), SF_GbVoxelMatrix3D_BD2); +// UB_AUTO_RUN_NAMED(SF::registerType<GbVoxelMatrix3D>("GbVoxelMatrix3D"), SF_GbVoxelMatrix3D); +// UB_AUTO_RUN_NAMED((SF::registerBaseAndDerived< GbObject3D, GbVoxelMatrix3D >()), SF_GbVoxelMatrix3D_BD1); +// UB_AUTO_RUN_NAMED((SF::registerBaseAndDerived< UbObserver, GbVoxelMatrix3D>()), SF_GbVoxelMatrix3D_BD2); //#endif //RCF_USE_SF_SERIALIZATION - -#endif +#endif diff --git a/src/basics/geometry3d/KdTree/KdNode.h b/src/basics/geometry3d/KdTree/KdNode.h index 0ccacc6e1c83423bbea0901da0b5ab19be769fab..eef1eb69614b9167fe9710d56f2766c1de4eab13 100644 --- a/src/basics/geometry3d/KdTree/KdNode.h +++ b/src/basics/geometry3d/KdTree/KdNode.h @@ -3,85 +3,94 @@ #include <basics/memory/MbSmartPtr.h> -#include <basics/utilities/UbMath.h> -#include <basics/utilities/UbTuple.h> #include <basics/utilities/UbException.h> #include <basics/utilities/UbKeys.h> +#include <basics/utilities/UbMath.h> +#include <basics/utilities/UbTuple.h> #include <geometry3d/GbTriFaceMesh3D.h> -#include <geometry3d/KdTree/KdUtilities.h> #include <geometry3d/KdTree/KdRay.h> #include <geometry3d/KdTree/KdSplitCandidate.h> -#include <geometry3d/KdTree/splitalgorithms/KdSplitAlgorithm.h> +#include <geometry3d/KdTree/KdUtilities.h> #include <geometry3d/KdTree/intersectionhandler/KdLineIntersectionHandler.h> #include <geometry3d/KdTree/intersectionhandler/KdRayIntersectionHandler.h> +#include <geometry3d/KdTree/splitalgorithms/KdSplitAlgorithm.h> - -#include <vector> #include <string> +#include <vector> namespace Kd { - template< typename T > - class Node - { - public: - Node( const T& x1, const T& y1, const T& z1 - , const T& x2, const T& y2, const T& z2 - , const MbSmartPtr< std::vector<GbTriFaceMesh3D::TriFace> > triFaces - , std::vector<GbTriFaceMesh3D::Vertex>* ptrNodes ) - : child1(NULL) - , child2(NULL) - , triFaces(triFaces) - , ptrNodes(ptrNodes) - { - if( x1 < x2 ) { this->x[0] = x1; this->x[1] = x2; } - else { this->x[0] = x2; this->x[1] = x1; } +template <typename T> +class Node +{ +public: + Node(const T &x1, const T &y1, const T &z1, const T &x2, const T &y2, const T &z2, + const MbSmartPtr<std::vector<GbTriFaceMesh3D::TriFace>> triFaces, + std::vector<GbTriFaceMesh3D::Vertex> *ptrNodes) + : child1(NULL), child2(NULL), triFaces(triFaces), ptrNodes(ptrNodes) + { + if (x1 < x2) { + this->x[0] = x1; + this->x[1] = x2; + } else { + this->x[0] = x2; + this->x[1] = x1; + } - if( y1 < y2 ) { this->y[0] = y1; this->y[1] = y2; } - else { this->y[0] = y2; this->y[1] = y1; } + if (y1 < y2) { + this->y[0] = y1; + this->y[1] = y2; + } else { + this->y[0] = y2; + this->y[1] = y1; + } - if( z1 < z2 ) { this->z[0] = z1; this->z[1] = z2; } - else { this->z[0] = z2; this->z[1] = z1; } - } - /* ======================================================================================= */ - ~Node() - { - if(child1) { delete child1; child1 = NULL; } - if(child2) { delete child2; child2 = NULL; } - } - /* ======================================================================================= */ - bool isLeaf() - { - return child1 == NULL && child2 == NULL; - } - /* ======================================================================================= */ - void deleteTriFaces() - { - triFaces = MbSmartPtr< std::vector<GbTriFaceMesh3D::TriFace> >(); - } - /* ======================================================================================= */ - const MbSmartPtr< std::vector<GbTriFaceMesh3D::TriFace> >& getTriFaces() - { - return triFaces; - } - /* ======================================================================================= */ - std::vector<GbTriFaceMesh3D::Vertex>& getNodes() - { - if(!ptrNodes) throw UbException(UB_EXARGS,"ups,no nodes"); - return *ptrNodes; - } + if (z1 < z2) { + this->z[0] = z1; + this->z[1] = z2; + } else { + this->z[0] = z2; + this->z[1] = z1; + } + } + /* ======================================================================================= */ + ~Node() + { + if (child1) { + delete child1; + child1 = NULL; + } + if (child2) { + delete child2; + child2 = NULL; + } + } + /* ======================================================================================= */ + bool isLeaf() { return child1 == NULL && child2 == NULL; } + /* ======================================================================================= */ + void deleteTriFaces() { triFaces = MbSmartPtr<std::vector<GbTriFaceMesh3D::TriFace>>(); } + /* ======================================================================================= */ + const MbSmartPtr<std::vector<GbTriFaceMesh3D::TriFace>> &getTriFaces() { return triFaces; } + /* ======================================================================================= */ + std::vector<GbTriFaceMesh3D::Vertex> &getNodes() + { + if (!ptrNodes) + throw UbException(UB_EXARGS, "ups,no nodes"); + return *ptrNodes; + } - /* ======================================================================================= */ - void buildTree(const int& level, const int& maxLevel, const SplitAlgorithm<T>& splitAlg) - { - SplitCandidate<T> splitCandidate = splitAlg.findBestSplitCandidate(level, maxLevel, *this); + /* ======================================================================================= */ + void buildTree(const int &level, const int &maxLevel, const SplitAlgorithm<T> &splitAlg) + { + SplitCandidate<T> splitCandidate = splitAlg.findBestSplitCandidate(level, maxLevel, *this); - if( splitCandidate.isValid ) - { + if (splitCandidate.isValid) { - MbSmartPtr< std::vector<GbTriFaceMesh3D::TriFace> > triFacesForChild1( new std::vector<GbTriFaceMesh3D::TriFace> ); - MbSmartPtr< std::vector<GbTriFaceMesh3D::TriFace> > triFacesForChild2( new std::vector<GbTriFaceMesh3D::TriFace> ); + MbSmartPtr<std::vector<GbTriFaceMesh3D::TriFace>> triFacesForChild1( + new std::vector<GbTriFaceMesh3D::TriFace>); + MbSmartPtr<std::vector<GbTriFaceMesh3D::TriFace>> triFacesForChild2( + new std::vector<GbTriFaceMesh3D::TriFace>); splitAlg.distributeTriFaces(splitCandidate, *triFacesForChild1, *triFacesForChild2, *this); @@ -92,185 +101,183 @@ namespace Kd T x1_r = x[0], y1_r = y[0], z1_r = z[0]; T x2_r = x[1], y2_r = y[1], z2_r = z[1]; - if (splitCandidate.axis == Axis::X) - { - x2_l = splitCandidate.position; - x1_r = splitCandidate.position; - } - else if (splitCandidate.axis == Axis::Y) - { - y2_l = splitCandidate.position; - y1_r = splitCandidate.position; - } - else - { - z2_l = splitCandidate.position; - z1_r = splitCandidate.position; + if (splitCandidate.axis == Axis::X) { + x2_l = splitCandidate.position; + x1_r = splitCandidate.position; + } else if (splitCandidate.axis == Axis::Y) { + y2_l = splitCandidate.position; + y1_r = splitCandidate.position; + } else { + z2_l = splitCandidate.position; + z1_r = splitCandidate.position; } // ---------------------------------------------------------------------- // ---------------------------------------------------------------------- - if (triFacesForChild1->size() > 0) - { - if( this->child1 ) delete this->child1; - this->child1 = new Node(x1_l, y1_l, z1_l, x2_l, y2_l, z2_l, triFacesForChild1, ptrNodes); - this->child1->buildTree(level + 1, maxLevel, splitAlg); + if (triFacesForChild1->size() > 0) { + if (this->child1) + delete this->child1; + this->child1 = new Node(x1_l, y1_l, z1_l, x2_l, y2_l, z2_l, triFacesForChild1, ptrNodes); + this->child1->buildTree(level + 1, maxLevel, splitAlg); } - - if (triFacesForChild2->size() > 0) - { - if( this->child2 ) delete this->child2; - this->child2 = new Node(x1_r, y1_r, z1_r, x2_r, y2_r, z2_r, triFacesForChild2, ptrNodes); - this->child2->buildTree(level + 1, maxLevel, splitAlg); + + if (triFacesForChild2->size() > 0) { + if (this->child2) + delete this->child2; + this->child2 = new Node(x1_r, y1_r, z1_r, x2_r, y2_r, z2_r, triFacesForChild2, ptrNodes); + this->child2->buildTree(level + 1, maxLevel, splitAlg); } - } - } - /* ======================================================================================= */ - int intersectLineBoundingBox(const UbTuple<T,T,T>& n1, const UbTuple<T,T,T>& n2) - { - const T& n1X = val<1>(n1); - const T& n1Y = val<2>(n1); - const T& n1Z = val<3>(n1); + } + } + /* ======================================================================================= */ + int intersectLineBoundingBox(const UbTuple<T, T, T> &n1, const UbTuple<T, T, T> &n2) + { + const T &n1X = val<1>(n1); + const T &n1Y = val<2>(n1); + const T &n1Z = val<3>(n1); - const T& n2X = val<1>(n2); - const T& n2Y = val<2>(n2); - const T& n2Z = val<3>(n2); + const T &n2X = val<1>(n2); + const T &n2Y = val<2>(n2); + const T &n2Z = val<3>(n2); - if ( UbMath::greater( UbMath::max( ( (n1X <= n2X ? x[0] : x[1]) - n1X) / (n2X - n1X) - , ( (n1Y <= n2Y ? y[0] : y[1]) - n1Y) / (n2Y - n1Y) - , ( (n1Z <= n2Z ? z[0] : z[1]) - n1Z) / (n2Z - n1Z) ) - , UbMath::min( ( (n1X > n2X ? x[0] : x[1]) - n1X) / (n2X - n1X) - , ( (n1Y > n2Y ? y[0] : y[1]) - n1Y) / (n2Y - n1Y) - , ( (n1Z > n2Z ? z[0] : z[1]) - n1Z) / (n2Z - n1Z) ) ) ) - { + if (UbMath::greater(UbMath::max(((n1X <= n2X ? x[0] : x[1]) - n1X) / (n2X - n1X), + ((n1Y <= n2Y ? y[0] : y[1]) - n1Y) / (n2Y - n1Y), + ((n1Z <= n2Z ? z[0] : z[1]) - n1Z) / (n2Z - n1Z)), + UbMath::min(((n1X > n2X ? x[0] : x[1]) - n1X) / (n2X - n1X), + ((n1Y > n2Y ? y[0] : y[1]) - n1Y) / (n2Y - n1Y), + ((n1Z > n2Z ? z[0] : z[1]) - n1Z) / (n2Z - n1Z)))) { return Intersection::NO_INTERSECTION; - } - else - { + } else { return Intersection::INTERSECTION; - } - } - /* ======================================================================================= */ - int intersectRayBoundingBox(const Ray<T>& ray) - { - T tmin = (x[ ray.signX] - ray.originX) * ray.inv_directionX; - T tmax = (x[1-ray.signX] - ray.originX) * ray.inv_directionX; - - T tymin = (y[ ray.signY] - ray.originY) * ray.inv_directionY; - T tymax = (y[1-ray.signY] - ray.originY) * ray.inv_directionY; - - if( (tmin > tymax) || (tymin > tmax) ) - { + } + } + /* ======================================================================================= */ + int intersectRayBoundingBox(const Ray<T> &ray) + { + T tmin = (x[ray.signX] - ray.originX) * ray.inv_directionX; + T tmax = (x[1 - ray.signX] - ray.originX) * ray.inv_directionX; + + T tymin = (y[ray.signY] - ray.originY) * ray.inv_directionY; + T tymax = (y[1 - ray.signY] - ray.originY) * ray.inv_directionY; + + if ((tmin > tymax) || (tymin > tmax)) { return false; - } - if( tymin > tmin ) tmin = tymin; - if( tymax < tmax ) tmax = tymax; + } + if (tymin > tmin) + tmin = tymin; + if (tymax < tmax) + tmax = tymax; + + T tzmin = (z[ray.signZ] - ray.originZ) * ray.inv_directionZ; + T tzmax = (z[1 - ray.signZ] - ray.originZ) * ray.inv_directionZ; - T tzmin = (z[ ray.signZ] - ray.originZ) * ray.inv_directionZ; - T tzmax = (z[1-ray.signZ] - ray.originZ) * ray.inv_directionZ; - - //if( (UbMath::greater( tmin, tzmax) ) || ( UbMath::greater( tzmin, tmax) ) ) - if( ( tmin > tzmax) || ( tzmin > tmax) ) - { + // if( (UbMath::greater( tmin, tzmax) ) || ( UbMath::greater( tzmin, tmax) ) ) + if ((tmin > tzmax) || (tzmin > tmax)) { return false; - } - //if(tzmin > tmin) tmin = tzmin; - if(tzmax < tmax) tmax = tzmax; - - //return ( (tmin =< t1) && (tmax >= t0) ); - if( UbMath::greaterEqual( tmax, T(0.0) ) ) - { + } + // if(tzmin > tmin) tmin = tzmin; + if (tzmax < tmax) + tmax = tzmax; + + // return ( (tmin =< t1) && (tmax >= t0) ); + if (UbMath::greaterEqual(tmax, T(0.0))) { return Intersection::INTERSECTION; - } - else - { + } else { return Intersection::NO_INTERSECTION; - } - } - /* ======================================================================================= */ - bool intersectLine(const UbTuple<T,T,T>& n1, const UbTuple<T,T,T>& n2, const LineIntersectionHandler<T>& iHandler) - { - return iHandler.intersectLine(n1, n2, *this, child1, child2); - } - /* ======================================================================================= */ - int intersectRay(const Ray<T>& ray, const RayIntersectionHandler<T>& iHandler, std::set< UbKeys::Key3<int> >& mailbox) - { - return iHandler.intersectRay(ray, *this, child1, child2, mailbox); - } - /* ======================================================================================= */ - int getNumOfTriFaces() - { - if(!child1 && !child2) - { - if(triFaces) return (int)triFaces->size(); - else return 0; - } - else - { + } + } + /* ======================================================================================= */ + bool intersectLine(const UbTuple<T, T, T> &n1, const UbTuple<T, T, T> &n2, + const LineIntersectionHandler<T> &iHandler) + { + return iHandler.intersectLine(n1, n2, *this, child1, child2); + } + /* ======================================================================================= */ + int intersectRay(const Ray<T> &ray, const RayIntersectionHandler<T> &iHandler, std::set<UbKeys::Key3<int>> &mailbox) + { + return iHandler.intersectRay(ray, *this, child1, child2, mailbox); + } + /* ======================================================================================= */ + int getNumOfTriFaces() + { + if (!child1 && !child2) { + if (triFaces) + return (int)triFaces->size(); + else + return 0; + } else { int sum = 0; - if(child1) sum += child1->getNumOfTriFaces(); - if(child2) sum += child2->getNumOfTriFaces(); + if (child1) + sum += child1->getNumOfTriFaces(); + if (child2) + sum += child2->getNumOfTriFaces(); return sum; - } - } - /* ======================================================================================= */ - int getNumOfNodes() - { - if( !child1 && !child2) - { + } + } + /* ======================================================================================= */ + int getNumOfNodes() + { + if (!child1 && !child2) { return 1; - } - else - { + } else { int sum = 0; - if(child1) sum += child1->getNumOfNodes(); - if(child2) sum += child2->getNumOfNodes(); + if (child1) + sum += child1->getNumOfNodes(); + if (child2) + sum += child2->getNumOfNodes(); return 1 + sum; - } - } - /* ======================================================================================= */ - std::string toString() - { - return "";//"[" + x1 + "," + y1 + "," + z1 + "] -" + " [" + x2 + "," + y2 + "," + z2 + "]"; - } - /* ======================================================================================= */ - void addCubeInfo(std::vector< UbTupleFloat3 >& nodes, std::vector< UbTupleInt8 >& cells, std::vector<std::string >& datanames, std::vector<std::vector<double > >& celldata) - { - nodes.push_back( makeUbTuple(float(x[0]), float(y[0]), float(z[0]) ) ); - nodes.push_back( makeUbTuple(float(x[1]), float(y[0]), float(z[0]) ) ); - nodes.push_back( makeUbTuple(float(x[1]), float(y[1]), float(z[0]) ) ); - nodes.push_back( makeUbTuple(float(x[0]), float(y[1]), float(z[0]) ) ); - - nodes.push_back( makeUbTuple(float(x[0]), float(y[0]), float(z[1]) ) ); - nodes.push_back( makeUbTuple(float(x[1]), float(y[0]), float(z[1]) ) ); - nodes.push_back( makeUbTuple(float(x[1]), float(y[1]), float(z[1]) ) ); - nodes.push_back( makeUbTuple(float(x[0]), float(y[1]), float(z[1]) ) ); + } + } + /* ======================================================================================= */ + std::string toString() + { + return ""; //"[" + x1 + "," + y1 + "," + z1 + "] -" + " [" + x2 + "," + y2 + "," + z2 + "]"; + } + /* ======================================================================================= */ + void addCubeInfo(std::vector<UbTupleFloat3> &nodes, std::vector<UbTupleInt8> &cells, + std::vector<std::string> &datanames, std::vector<std::vector<double>> &celldata) + { + nodes.push_back(makeUbTuple(float(x[0]), float(y[0]), float(z[0]))); + nodes.push_back(makeUbTuple(float(x[1]), float(y[0]), float(z[0]))); + nodes.push_back(makeUbTuple(float(x[1]), float(y[1]), float(z[0]))); + nodes.push_back(makeUbTuple(float(x[0]), float(y[1]), float(z[0]))); + + nodes.push_back(makeUbTuple(float(x[0]), float(y[0]), float(z[1]))); + nodes.push_back(makeUbTuple(float(x[1]), float(y[0]), float(z[1]))); + nodes.push_back(makeUbTuple(float(x[1]), float(y[1]), float(z[1]))); + nodes.push_back(makeUbTuple(float(x[0]), float(y[1]), float(z[1]))); - cells.push_back( makeUbTuple( int(nodes.size()-8), int(nodes.size()-7), int(nodes.size()-6), int(nodes.size()-5), - int(nodes.size()-4), int(nodes.size()-3), int(nodes.size()-2), int(nodes.size()-1) ) ); - datanames.resize(1); - datanames[0] = "childs"; - celldata.resize( datanames.size() ); - if ( child1 && child2 ) celldata[0].push_back(2); - else if( child1 || child2 ) celldata[0].push_back(1); - else celldata[0].push_back(0); + cells.push_back(makeUbTuple(int(nodes.size() - 8), int(nodes.size() - 7), int(nodes.size() - 6), + int(nodes.size() - 5), int(nodes.size() - 4), int(nodes.size() - 3), + int(nodes.size() - 2), int(nodes.size() - 1))); + datanames.resize(1); + datanames[0] = "childs"; + celldata.resize(datanames.size()); + if (child1 && child2) + celldata[0].push_back(2); + else if (child1 || child2) + celldata[0].push_back(1); + else + celldata[0].push_back(0); - if(child1) child1->addCubeInfo(nodes, cells, datanames, celldata); - if(child2) child2->addCubeInfo(nodes, cells, datanames, celldata); - } + if (child1) + child1->addCubeInfo(nodes, cells, datanames, celldata); + if (child2) + child2->addCubeInfo(nodes, cells, datanames, celldata); + } - public: - T x[2], y[2], z[2]; +public: + T x[2], y[2], z[2]; - private: - Node* child1; - Node* child2; +private: + Node *child1; + Node *child2; - MbSmartPtr< std::vector<GbTriFaceMesh3D::TriFace> > triFaces; - std::vector<GbTriFaceMesh3D::Vertex>* ptrNodes; //lediglich f�r Zugriff auf die Knoten!!! - }; -} -#endif //KDNODE_H + MbSmartPtr<std::vector<GbTriFaceMesh3D::TriFace>> triFaces; + std::vector<GbTriFaceMesh3D::Vertex> *ptrNodes; // lediglich f�r Zugriff auf die Knoten!!! +}; +} // namespace Kd +#endif // KDNODE_H diff --git a/src/basics/geometry3d/KdTree/KdRay.h b/src/basics/geometry3d/KdTree/KdRay.h index 8465b83083ddc06fc1c1f965e02c74987cb02e2d..b37e30ce6666fdc8d061a4341dce810a077644f4 100644 --- a/src/basics/geometry3d/KdTree/KdRay.h +++ b/src/basics/geometry3d/KdTree/KdRay.h @@ -4,66 +4,70 @@ #include <basics/utilities/UbException.h> #include <basics/utilities/UbMath.h> - namespace Kd { - /* - * Ray class, for use with the optimized ray-box intersection test - * described in: - * - * Amy Williams, Steve Barrus, R. Keith Morley, and Peter Shirley - * "An Efficient and Robust Ray-Box Intersection Algorithm" - * Journal of graphics tools, 10(1):49-54, 2005 - * - */ - template< typename T> - class Ray - { - public: - Ray( const T& originX , const T& originY , const T& originZ - , const T& directionX, const T& directionY, const T& directionZ ) - { - this->originX = originX; - this->originY = originY; - this->originZ = originZ; +/* + * Ray class, for use with the optimized ray-box intersection test + * described in: + * + * Amy Williams, Steve Barrus, R. Keith Morley, and Peter Shirley + * "An Efficient and Robust Ray-Box Intersection Algorithm" + * Journal of graphics tools, 10(1):49-54, 2005 + * + */ +template <typename T> +class Ray +{ +public: + Ray(const T &originX, const T &originY, const T &originZ, const T &directionX, const T &directionY, + const T &directionZ) + { + this->originX = originX; + this->originY = originY; + this->originZ = originZ; + + // normierung (fuer ray-triangle-intersection) + T oneOverLength = + T(1.0 / std::sqrt(directionX * directionX + directionY * directionY + directionZ * directionZ)); + + this->directionX = directionX * oneOverLength; + this->directionY = directionY * oneOverLength; + this->directionZ = directionZ * oneOverLength; + + this->inv_directionX = T(1.0 / this->directionX); // ACHTUNG: BEWUSST KEINE ==0 Abfrage + this->inv_directionY = T(1.0 / this->directionY); // Alg verwendet exlitzit INF + this->inv_directionZ = T(1.0 / this->directionZ); + + if (this->inv_directionX < 0.0) + this->signX = 1; + else + this->signX = 0; + if (this->inv_directionY < 0.0) + this->signY = 1; + else + this->signY = 0; + if (this->inv_directionZ < 0.0) + this->signZ = 1; + else + this->signZ = 0; + } - //normierung (fuer ray-triangle-intersection) - T oneOverLength = T(1.0/std::sqrt( directionX*directionX - + directionY*directionY - + directionZ*directionZ ) ); + T originX; + T originY; + T originZ; - this->directionX = directionX*oneOverLength; - this->directionY = directionY*oneOverLength; - this->directionZ = directionZ*oneOverLength; + T directionX; + T directionY; + T directionZ; - this->inv_directionX = T(1.0/this->directionX); //ACHTUNG: BEWUSST KEINE ==0 Abfrage - this->inv_directionY = T(1.0/this->directionY); //Alg verwendet exlitzit INF - this->inv_directionZ = T(1.0/this->directionZ); - - if(this->inv_directionX < 0.0) this->signX = 1; - else this->signX = 0; - if(this->inv_directionY < 0.0) this->signY = 1; - else this->signY = 0; - if(this->inv_directionZ < 0.0) this->signZ = 1; - else this->signZ = 0; - } + T inv_directionX; + T inv_directionY; + T inv_directionZ; - T originX; - T originY; - T originZ; - - T directionX; - T directionY; - T directionZ; - - T inv_directionX; - T inv_directionY; - T inv_directionZ; - - int signX; - int signY; - int signZ; - }; -} //namespace Kd + int signX; + int signY; + int signZ; +}; +} // namespace Kd -#endif //KDRAY_H +#endif // KDRAY_H diff --git a/src/basics/geometry3d/KdTree/KdSplitCandidate.h b/src/basics/geometry3d/KdTree/KdSplitCandidate.h index b7719ebf388cb1359653887ee9e409677d3886d4..b937a1235b732d420483f1fb8580ce396a874641 100644 --- a/src/basics/geometry3d/KdTree/KdSplitCandidate.h +++ b/src/basics/geometry3d/KdTree/KdSplitCandidate.h @@ -5,46 +5,39 @@ namespace Kd { - template< typename T > - class SplitCandidate - { - public: - SplitCandidate() = default; - /* ======================================================================================= */ - SplitCandidate(const int& axis, const T& position, const int& starting, const int& ending, const int& insidePlane) : - axis(axis) - , position(position) - , starting(starting) - , ending(ending) - , np(insidePlane) - , isValid(true) //FIXME: isValid default false is correct? - { - } - /* ======================================================================================= */ - bool operator!() const - { - return isValid; - } - /* ======================================================================================= */ - friend inline bool operator< (const SplitCandidate& lhs, const SplitCandidate& rhs) - { - return lhs.position < rhs.position; - } - /* ======================================================================================= */ +template <typename T> +class SplitCandidate +{ +public: + SplitCandidate() = default; + /* ======================================================================================= */ + SplitCandidate(const int &axis, const T &position, const int &starting, const int &ending, const int &insidePlane) + : axis(axis), position(position), starting(starting), ending(ending), np(insidePlane), + isValid(true) // FIXME: isValid default false is correct? + { + } + /* ======================================================================================= */ + bool operator!() const { return isValid; } + /* ======================================================================================= */ + friend inline bool operator<(const SplitCandidate &lhs, const SplitCandidate &rhs) + { + return lhs.position < rhs.position; + } + /* ======================================================================================= */ - public: - int axis{0}; - T Cn {0.0}; - T position {0.0}; - int nl{0}; - int nr{0}; - int np; - int starting{0}; - int ending{0}; - bool np_left{false}; - bool np_right{false}; - bool isValid{false}; - }; -} +public: + int axis{ 0 }; + T Cn{ 0.0 }; + T position{ 0.0 }; + int nl{ 0 }; + int nr{ 0 }; + int np; + int starting{ 0 }; + int ending{ 0 }; + bool np_left{ false }; + bool np_right{ false }; + bool isValid{ false }; +}; +} // namespace Kd -#endif //KDSPLITCANDIDATE_H +#endif // KDSPLITCANDIDATE_H diff --git a/src/basics/geometry3d/KdTree/KdSplitCandidateManager.h b/src/basics/geometry3d/KdTree/KdSplitCandidateManager.h index f107bac602c658527f943c13c1dacd64a9cc506c..cf32711b14a6acfc0d5fb2c1afc37aeda68e504a 100644 --- a/src/basics/geometry3d/KdTree/KdSplitCandidateManager.h +++ b/src/basics/geometry3d/KdTree/KdSplitCandidateManager.h @@ -3,70 +3,66 @@ #include <geometry3d/KdTree/KdSplitCandidate.h> +#include <algorithm> #include <map> #include <vector> -#include <algorithm> - namespace Kd { - template< typename T > - class SplitCandidateManager - { - public: - SplitCandidateManager() - - = default; - /* ======================================================================================= */ - SplitCandidate<T>& operator[] (const std::size_t& i) - { - #ifdef DEBUG - return splitCandidatesVec.at(i); - #else - return splitCandidatesVec[i]; - #endif - } - /* ======================================================================================= */ - typename std::vector< SplitCandidate< T > >::size_type size() - { - return splitCandidatesVec.size(); - } - /* ======================================================================================= */ - void add(const T& pos, const int& axis, const int& starting, const int& ending, const int& np) - { - typename std::map<T, SplitCandidate<T> >::iterator it = splitCandidates.find(pos); - if ( it != splitCandidates.end() ) //split candidate is already available -> increase parameter (starting, ending and np) - { - SplitCandidate<T>& sc = it->second; - sc.np += np; +template <typename T> +class SplitCandidateManager +{ +public: + SplitCandidateManager() + + = default; + /* ======================================================================================= */ + SplitCandidate<T> &operator[](const std::size_t &i) + { +#ifdef DEBUG + return splitCandidatesVec.at(i); +#else + return splitCandidatesVec[i]; +#endif + } + /* ======================================================================================= */ + typename std::vector<SplitCandidate<T>>::size_type size() { return splitCandidatesVec.size(); } + /* ======================================================================================= */ + void add(const T &pos, const int &axis, const int &starting, const int &ending, const int &np) + { + typename std::map<T, SplitCandidate<T>>::iterator it = splitCandidates.find(pos); + if (it != splitCandidates + .end()) // split candidate is already available -> increase parameter (starting, ending and np) + { + SplitCandidate<T> &sc = it->second; + sc.np += np; sc.starting += starting; - sc.ending += ending; - } - else // split candidate is not available -> add new split candidate - { + sc.ending += ending; + } else // split candidate is not available -> add new split candidate + { this->splitCandidates[pos] = SplitCandidate<T>(axis, pos, starting, ending, np); - } - } - /* ======================================================================================= */ - void createSortedArray() - { - splitCandidatesVec.clear(); - typename std::map<T, SplitCandidate<T> >::iterator it; - for( it=splitCandidates.begin(); it!=splitCandidates.end(); ++it) + } + } + /* ======================================================================================= */ + void createSortedArray() + { + splitCandidatesVec.clear(); + typename std::map<T, SplitCandidate<T>>::iterator it; + for (it = splitCandidates.begin(); it != splitCandidates.end(); ++it) splitCandidatesVec.push_back(it->second); - splitCandidates.clear(); - std::sort(splitCandidatesVec.begin(), splitCandidatesVec.end(), std::less< SplitCandidate<T> >() ); - } - /* ======================================================================================= */ + splitCandidates.clear(); + std::sort(splitCandidatesVec.begin(), splitCandidatesVec.end(), std::less<SplitCandidate<T>>()); + } + /* ======================================================================================= */ - public: - int objects_starting_outside_left{0}; - int objects_fully_outside_node{0}; +public: + int objects_starting_outside_left{ 0 }; + int objects_fully_outside_node{ 0 }; - private: - std::map<T, SplitCandidate<T> > splitCandidates; - std::vector< SplitCandidate<T> > splitCandidatesVec; - }; -} +private: + std::map<T, SplitCandidate<T>> splitCandidates; + std::vector<SplitCandidate<T>> splitCandidatesVec; +}; +} // namespace Kd -#endif //KDSPLITCANDIDATEMANAGER_H +#endif // KDSPLITCANDIDATEMANAGER_H diff --git a/src/basics/geometry3d/KdTree/KdTree.h b/src/basics/geometry3d/KdTree/KdTree.h index c3f76d22bcff4f5b04d5032a4f72037d0091a733..42c337f66cdddb450108e973fc0a75323512a149 100644 --- a/src/basics/geometry3d/KdTree/KdTree.h +++ b/src/basics/geometry3d/KdTree/KdTree.h @@ -1,100 +1,103 @@ #ifndef KDTREE_H #define KDTREE_H +#include <basics/utilities/UbKeys.h> #include <basics/writer/WbWriterVtkXmlBinary.h> #include <geometry3d/GbTriFaceMesh3D.h> -#include <basics/utilities/UbKeys.h> #include <geometry3d/KdTree/KdNode.h> #include <geometry3d/KdTree/KdRay.h> #include <geometry3d/KdTree/KdSplitCandidate.h> #include <geometry3d/KdTree/splitalgorithms/KdSplitAlgorithm.h> -#include <string> #include <cmath> +#include <string> namespace Kd { - template< typename T > - class Tree - { - public: - /* ======================================================================================= */ - Tree(GbTriFaceMesh3D& mesh, const SplitAlgorithm<T>& splitAlg) - : rootNode(NULL) - { - this->buildTree(mesh, splitAlg); - } - /* ======================================================================================= */ - ~Tree() - { - if(rootNode) { delete rootNode; rootNode = NULL; } - } - /* ======================================================================================= */ - // the IntersectionHandler specifies how to handle the intersection - bool intersectLine(const UbTuple< T, T, T >& n1, const UbTuple< T, T, T >& n2, const LineIntersectionHandler<T>& iHandler) - { - return rootNode->intersectLine(n1, n2, iHandler); - } - /* ======================================================================================= */ - // the IntersectionHandler specifies how to handle the intersection - int intersectRay(const Ray<T>& ray, const RayIntersectionHandler<T>& iHandler) - { - std::set< UbKeys::Key3<int> > mailbox; - return rootNode->intersectRay(ray, iHandler, mailbox); - } - /* ======================================================================================= */ - int getNumOfNodes() - { - if(rootNode) return rootNode->getNumOfNodes(); - return 0; - } - /* ======================================================================================= */ - int getNumOfTriFaces() - { - if(rootNode) return rootNode->getNumOfTriFaces(); - return 0; - } - /* ======================================================================================= */ - std::string toString() - { - return "";//Tree:: num of nodes: " + rootNode.getNumOfNodes() + ", primitives:" + rootNode.getNumOfPrimitives() + ", root_primitives:" + getNumOfPrimitives() + ", max_level:" + max_level; - } - /* ======================================================================================= */ - void buildTree(GbTriFaceMesh3D& mesh, const SplitAlgorithm<T>& splitAlg ) - { - if(rootNode) delete rootNode; - - // create a copy of triangles - MbSmartPtr< std::vector<GbTriFaceMesh3D::TriFace> > triFaces(new std::vector<GbTriFaceMesh3D::TriFace>(*mesh.getTriangles() ) ); +template <typename T> +class Tree +{ +public: + /* ======================================================================================= */ + Tree(GbTriFaceMesh3D &mesh, const SplitAlgorithm<T> &splitAlg) : rootNode(NULL) { this->buildTree(mesh, splitAlg); } + /* ======================================================================================= */ + ~Tree() + { + if (rootNode) { + delete rootNode; + rootNode = NULL; + } + } + /* ======================================================================================= */ + // the IntersectionHandler specifies how to handle the intersection + bool intersectLine(const UbTuple<T, T, T> &n1, const UbTuple<T, T, T> &n2, + const LineIntersectionHandler<T> &iHandler) + { + return rootNode->intersectLine(n1, n2, iHandler); + } + /* ======================================================================================= */ + // the IntersectionHandler specifies how to handle the intersection + int intersectRay(const Ray<T> &ray, const RayIntersectionHandler<T> &iHandler) + { + std::set<UbKeys::Key3<int>> mailbox; + return rootNode->intersectRay(ray, iHandler, mailbox); + } + /* ======================================================================================= */ + int getNumOfNodes() + { + if (rootNode) + return rootNode->getNumOfNodes(); + return 0; + } + /* ======================================================================================= */ + int getNumOfTriFaces() + { + if (rootNode) + return rootNode->getNumOfTriFaces(); + return 0; + } + /* ======================================================================================= */ + std::string toString() + { + return ""; // Tree:: num of nodes: " + rootNode.getNumOfNodes() + ", primitives:" + + // rootNode.getNumOfPrimitives() + ", root_primitives:" + getNumOfPrimitives() + ", max_level:" + + // max_level; + } + /* ======================================================================================= */ + void buildTree(GbTriFaceMesh3D &mesh, const SplitAlgorithm<T> &splitAlg) + { + if (rootNode) + delete rootNode; + + // create a copy of triangles + MbSmartPtr<std::vector<GbTriFaceMesh3D::TriFace>> triFaces( + new std::vector<GbTriFaceMesh3D::TriFace>(*mesh.getTriangles())); - const int maxLevel = static_cast<int>(lround(8.0 + 1.3 * std::log( (double)triFaces->size() ))); //TODO: remove magic numbers + const int maxLevel = + static_cast<int>(lround(8.0 + 1.3 * std::log((double)triFaces->size()))); // TODO: remove magic numbers - rootNode = new Node<T>( T( mesh.getX1Minimum() ) - , T( mesh.getX2Minimum() ) - , T( mesh.getX3Minimum() ) - , T( mesh.getX1Maximum() ) - , T( mesh.getX2Maximum() ) - , T( mesh.getX3Maximum() ) - , triFaces, mesh.getNodes() ); + rootNode = + new Node<T>(T(mesh.getX1Minimum()), T(mesh.getX2Minimum()), T(mesh.getX3Minimum()), T(mesh.getX1Maximum()), + T(mesh.getX2Maximum()), T(mesh.getX3Maximum()), triFaces, mesh.getNodes()); - rootNode->buildTree(0, maxLevel, splitAlg); - } - void writeTree(const std::string& filename, WbWriter* writer = WbWriterVtkXmlBinary::getInstance()) - { - if(rootNode) - { - std::vector<UbTupleFloat3 > nodes; - std::vector<UbTupleInt8 > cubes; - std::vector<std::string > datanames; - std::vector<std::vector<double > > cubesdata; + rootNode->buildTree(0, maxLevel, splitAlg); + } + void writeTree(const std::string &filename, WbWriter *writer = WbWriterVtkXmlBinary::getInstance()) + { + if (rootNode) { + std::vector<UbTupleFloat3> nodes; + std::vector<UbTupleInt8> cubes; + std::vector<std::string> datanames; + std::vector<std::vector<double>> cubesdata; rootNode->addCubeInfo(nodes, cubes, datanames, cubesdata); - writer->writeOctsWithCellData(filename,nodes,cubes,datanames,cubesdata); - } - } - private: - Node<T>* rootNode; - }; -} + writer->writeOctsWithCellData(filename, nodes, cubes, datanames, cubesdata); + } + } + +private: + Node<T> *rootNode; +}; +} // namespace Kd -#endif //KDTREE_H +#endif // KDTREE_H diff --git a/src/basics/geometry3d/KdTree/KdUtilities.cpp b/src/basics/geometry3d/KdTree/KdUtilities.cpp index 3eca9f3562b7947d6dde8b94b248c26b84f25fb5..b2b56b0912297cbfb355d97a4a120f54820828ab 100644 --- a/src/basics/geometry3d/KdTree/KdUtilities.cpp +++ b/src/basics/geometry3d/KdTree/KdUtilities.cpp @@ -2,12 +2,12 @@ namespace Kd { - const int Axis::X = 0; - const int Axis::Y = 1; - const int Axis::Z = 2; +const int Axis::X = 0; +const int Axis::Y = 1; +const int Axis::Z = 2; - const int Intersection::ON_BOUNDARY = -2; - const int Intersection::INTERSECT_EDGE = -1; - const int Intersection::INTERSECTION = 1; -const int Intersection::NO_INTERSECTION = 0; -} //namespace Kd +const int Intersection::ON_BOUNDARY = -2; +const int Intersection::INTERSECT_EDGE = -1; +const int Intersection::INTERSECTION = 1; +const int Intersection::NO_INTERSECTION = 0; +} // namespace Kd diff --git a/src/basics/geometry3d/KdTree/KdUtilities.h b/src/basics/geometry3d/KdTree/KdUtilities.h index 2c56652d2be8c30afb481834b9fe84e4f815d088..bf02ee4443f24782875478d4e30431fcb8910b9b 100644 --- a/src/basics/geometry3d/KdTree/KdUtilities.h +++ b/src/basics/geometry3d/KdTree/KdUtilities.h @@ -2,8 +2,8 @@ #define KDUTILIES_H #include <basics/utilities/UbException.h> -#include <basics/utilities/UbTuple.h> #include <basics/utilities/UbMath.h> +#include <basics/utilities/UbTuple.h> #include <geometry3d/GbTriFaceMesh3D.h> @@ -12,153 +12,153 @@ namespace Kd { - struct Axis - { - static const int X;// = 0; - static const int Y;// = 1; - static const int Z;// = 2; - }; - /* ======================================================================================= */ - struct Intersection - { - static const int ON_BOUNDARY; // = -2; - static const int INTERSECT_EDGE; // = -1; - static const int INTERSECTION; // = 1; - static const int NO_INTERSECTION;// = 0; - }; - /* ======================================================================================= */ - template< typename T> - inline void project2Axis(GbTriFaceMesh3D::TriFace& triFace, std::vector<GbTriFaceMesh3D::Vertex>& nodes, const int& axis, std::vector<T>& projection) - { - projection.resize(3); - - if(axis==Axis::X) - { - projection[0] = triFace.getV1x(nodes); - projection[1] = triFace.getV2x(nodes); - projection[2] = triFace.getV3x(nodes); - } - else if(axis==Axis::Y) - { - projection[0] = triFace.getV1y(nodes); - projection[1] = triFace.getV2y(nodes); - projection[2] = triFace.getV3y(nodes); - } - else if(axis==Axis::Z) - { - projection[0] = triFace.getV1z(nodes); - projection[1] = triFace.getV2z(nodes); - projection[2] = triFace.getV3z(nodes); - } - else throw UbException(UB_EXARGS,"unknown axis"); - - std::sort( projection.begin(), projection.end(), std::less<>() ); - } - /* ======================================================================================= */ - template< typename T> - inline bool isPointOnPlane(const T& px, const T& py, const T& pz, const T& precision, GbTriFaceMesh3D::Vertex& pointOfTriFace, GbTriFaceMesh3D::TriFace& triFace) - { - return std::fabs( (px - pointOfTriFace.x) * triFace.nx + (py - pointOfTriFace.y) * triFace.ny + (pz - pointOfTriFace.z) * triFace.nz ) < precision; - } - /* ======================================================================================= */ - template< typename T> - inline bool isPointOnTriangle( const T& px, const T& py, const T& pz, const T& precision - , GbTriFaceMesh3D::Vertex& p1, GbTriFaceMesh3D::Vertex& p2, GbTriFaceMesh3D::Vertex& p3 - , GbTriFaceMesh3D::TriFace& triFace ) - { - if( Kd::isPointOnPlane(px, py, pz, precision, p1, triFace) ) - { - T a_x = p1.x - px; - T a_y = p1.y - py; - T a_z = p1.z - pz; - T b_x = p2.x - px; - T b_y = p2.y - py; - T b_z = p2.z - pz; - T c_x = p3.x - px; - T c_y = p3.y - py; - T c_z = p3.z - pz; - - const T factor = 0.5; - T Q1_x = (a_y * b_z - a_z * b_y) * factor; - T Q1_y = (a_z * b_x - a_x * b_z) * factor; - T Q1_z = (a_x * b_y - a_y * b_x) * factor; - - T Q2_x = (b_y * c_z - b_z * c_y) * factor; - T Q2_y = (b_z * c_x - b_x * c_z) * factor; - T Q2_z = (b_x * c_y - b_y * c_x) * factor; - - T Q3_x = (c_y * a_z - c_z * a_y) * factor; - T Q3_y = (c_z * a_x - c_x * a_z) * factor; - T Q3_z = (c_x * a_y - c_y * a_x) * factor; - - T Q_x = Q1_x + Q2_x + Q3_x; - T Q_y = Q1_y + Q2_y + Q3_y; - T Q_z = Q1_z + Q2_z + Q3_z; - - - if ( UbMath::zero(Q_x * Q1_x + Q_y * Q1_y + Q_z * Q1_z ) ) return true; - else if( UbMath::zero(Q_x * Q2_x + Q_y * Q2_y + Q_z * Q2_z ) ) return true; - else if( UbMath::zero(Q_x * Q3_x + Q_y * Q3_y + Q_z * Q3_z ) ) return true; - else if( UbMath::less(Q_x * Q1_x + Q_y * Q1_y + Q_z * Q1_z, T(0.0) ) ) return false; - else if( UbMath::less(Q_x * Q2_x + Q_y * Q2_y + Q_z * Q2_z, T(0.0) ) ) return false; - else if( UbMath::less(Q_x * Q3_x + Q_y * Q3_y + Q_z * Q3_z, T(0.0) ) ) return false; - - return true; - } - - return false; - } - /* ======================================================================================= */ - template< typename T> - inline bool intersectLine(const UbTuple<T,T,T>& n1, const UbTuple<T,T,T>& n2, GbTriFaceMesh3D::TriFace& triFace, std::vector<GbTriFaceMesh3D::Vertex>& nodes) - { - GbTriFaceMesh3D::Vertex& p0=triFace.getNode(0,nodes); - - const T& n1X = val<1>(n1); - const T& n1Y = val<2>(n1); - const T& n1Z = val<3>(n1); - - const T& n2X = val<1>(n2); - const T& n2Y = val<2>(n2); - const T& n2Z = val<3>(n2); - - //if( Kd::isPointOnPlane(n1X, n1Y, n1Z, T(1.0E-6), p0, triFace) - // && Kd::isPointOnPlane(n2X, n2Y, n2Z, T(1.0E-6), p0, triFace)) - //{ - // return true; - //} - - T denom = ( n2X - n1X ) * triFace.nx + ( n2Y - n1Y ) * triFace.ny + ( n2Z - n1Z ) * triFace.nz; - - if( UbMath::zero( denom ) ) //line does not intersect the plane of the triangle ! - { - return false; - } - else - { - T d = - triFace.nx * p0.x - triFace.ny * p0.y - triFace.nz * p0.z; - T mu = T(-1.0 * (d + n1X * triFace.nx + n1Y * triFace.ny + n1Z * triFace.nz ) / denom); - - if( !UbMath::inClosedInterval( mu, T(0.0), T(1.0)) ) // Point of intersection of line and plane does not lie on the triangle - { +struct Axis { + static const int X; // = 0; + static const int Y; // = 1; + static const int Z; // = 2; +}; +/* ======================================================================================= */ +struct Intersection { + static const int ON_BOUNDARY; // = -2; + static const int INTERSECT_EDGE; // = -1; + static const int INTERSECTION; // = 1; + static const int NO_INTERSECTION; // = 0; +}; +/* ======================================================================================= */ +template <typename T> +inline void project2Axis(GbTriFaceMesh3D::TriFace &triFace, std::vector<GbTriFaceMesh3D::Vertex> &nodes, + const int &axis, std::vector<T> &projection) +{ + projection.resize(3); + + if (axis == Axis::X) { + projection[0] = triFace.getV1x(nodes); + projection[1] = triFace.getV2x(nodes); + projection[2] = triFace.getV3x(nodes); + } else if (axis == Axis::Y) { + projection[0] = triFace.getV1y(nodes); + projection[1] = triFace.getV2y(nodes); + projection[2] = triFace.getV3y(nodes); + } else if (axis == Axis::Z) { + projection[0] = triFace.getV1z(nodes); + projection[1] = triFace.getV2z(nodes); + projection[2] = triFace.getV3z(nodes); + } else + throw UbException(UB_EXARGS, "unknown axis"); + + std::sort(projection.begin(), projection.end(), std::less<>()); +} +/* ======================================================================================= */ +template <typename T> +inline bool isPointOnPlane(const T &px, const T &py, const T &pz, const T &precision, + GbTriFaceMesh3D::Vertex &pointOfTriFace, GbTriFaceMesh3D::TriFace &triFace) +{ + return std::fabs((px - pointOfTriFace.x) * triFace.nx + (py - pointOfTriFace.y) * triFace.ny + + (pz - pointOfTriFace.z) * triFace.nz) < precision; +} +/* ======================================================================================= */ +template <typename T> +inline bool isPointOnTriangle(const T &px, const T &py, const T &pz, const T &precision, GbTriFaceMesh3D::Vertex &p1, + GbTriFaceMesh3D::Vertex &p2, GbTriFaceMesh3D::Vertex &p3, + GbTriFaceMesh3D::TriFace &triFace) +{ + if (Kd::isPointOnPlane(px, py, pz, precision, p1, triFace)) { + T a_x = p1.x - px; + T a_y = p1.y - py; + T a_z = p1.z - pz; + T b_x = p2.x - px; + T b_y = p2.y - py; + T b_z = p2.z - pz; + T c_x = p3.x - px; + T c_y = p3.y - py; + T c_z = p3.z - pz; + + const T factor = 0.5; + T Q1_x = (a_y * b_z - a_z * b_y) * factor; + T Q1_y = (a_z * b_x - a_x * b_z) * factor; + T Q1_z = (a_x * b_y - a_y * b_x) * factor; + + T Q2_x = (b_y * c_z - b_z * c_y) * factor; + T Q2_y = (b_z * c_x - b_x * c_z) * factor; + T Q2_z = (b_x * c_y - b_y * c_x) * factor; + + T Q3_x = (c_y * a_z - c_z * a_y) * factor; + T Q3_y = (c_z * a_x - c_x * a_z) * factor; + T Q3_z = (c_x * a_y - c_y * a_x) * factor; + + T Q_x = Q1_x + Q2_x + Q3_x; + T Q_y = Q1_y + Q2_y + Q3_y; + T Q_z = Q1_z + Q2_z + Q3_z; + + if (UbMath::zero(Q_x * Q1_x + Q_y * Q1_y + Q_z * Q1_z)) + return true; + else if (UbMath::zero(Q_x * Q2_x + Q_y * Q2_y + Q_z * Q2_z)) + return true; + else if (UbMath::zero(Q_x * Q3_x + Q_y * Q3_y + Q_z * Q3_z)) + return true; + else if (UbMath::less(Q_x * Q1_x + Q_y * Q1_y + Q_z * Q1_z, T(0.0))) + return false; + else if (UbMath::less(Q_x * Q2_x + Q_y * Q2_y + Q_z * Q2_z, T(0.0))) + return false; + else if (UbMath::less(Q_x * Q3_x + Q_y * Q3_y + Q_z * Q3_z, T(0.0))) + return false; + + return true; + } + + return false; +} +/* ======================================================================================= */ +template <typename T> +inline bool intersectLine(const UbTuple<T, T, T> &n1, const UbTuple<T, T, T> &n2, GbTriFaceMesh3D::TriFace &triFace, + std::vector<GbTriFaceMesh3D::Vertex> &nodes) +{ + GbTriFaceMesh3D::Vertex &p0 = triFace.getNode(0, nodes); + + const T &n1X = val<1>(n1); + const T &n1Y = val<2>(n1); + const T &n1Z = val<3>(n1); + + const T &n2X = val<1>(n2); + const T &n2Y = val<2>(n2); + const T &n2Z = val<3>(n2); + + // if( Kd::isPointOnPlane(n1X, n1Y, n1Z, T(1.0E-6), p0, triFace) + // && Kd::isPointOnPlane(n2X, n2Y, n2Z, T(1.0E-6), p0, triFace)) + //{ + // return true; + //} + + T denom = (n2X - n1X) * triFace.nx + (n2Y - n1Y) * triFace.ny + (n2Z - n1Z) * triFace.nz; + + if (UbMath::zero(denom)) // line does not intersect the plane of the triangle ! + { + return false; + } else { + T d = -triFace.nx * p0.x - triFace.ny * p0.y - triFace.nz * p0.z; + T mu = T(-1.0 * (d + n1X * triFace.nx + n1Y * triFace.ny + n1Z * triFace.nz) / denom); + + if (!UbMath::inClosedInterval(mu, T(0.0), + T(1.0))) // Point of intersection of line and plane does not lie on the triangle + { return false; - } - else - { - // intersection with plane - - //Test whether Point lies inside the triangle or not - GbTriFaceMesh3D::Vertex& p1=triFace.getNode(1,nodes); - GbTriFaceMesh3D::Vertex& p2=triFace.getNode(2,nodes); - - return Kd::isPointOnTriangle( n1X + ( (n2X - n1X) * mu ) //intersectionPointX - , n1Y + ( (n2Y - n1Y) * mu ) //intersectionPointY - , n1Z + ( (n2Z - n1Z) * mu ) //intersectionPointZ - , T(0.001) - , p0, p1, p2, triFace ); - } - } - } -} //namespace Kd - -#endif //KDUTILIES_H + } else { + // intersection with plane + + // Test whether Point lies inside the triangle or not + GbTriFaceMesh3D::Vertex &p1 = triFace.getNode(1, nodes); + GbTriFaceMesh3D::Vertex &p2 = triFace.getNode(2, nodes); + + return Kd::isPointOnTriangle(n1X + ((n2X - n1X) * mu) // intersectionPointX + , + n1Y + ((n2Y - n1Y) * mu) // intersectionPointY + , + n1Z + ((n2Z - n1Z) * mu) // intersectionPointZ + , + T(0.001), p0, p1, p2, triFace); + } + } +} +} // namespace Kd + +#endif // KDUTILIES_H diff --git a/src/basics/geometry3d/KdTree/intersectionhandler/KdCountLineIntersectionHandler.h b/src/basics/geometry3d/KdTree/intersectionhandler/KdCountLineIntersectionHandler.h index 89501b60ef3dee57446ea58aeef26e9544be1138..0e5a9eb02569e1408dceb2a04ca8fdf97e658260 100644 --- a/src/basics/geometry3d/KdTree/intersectionhandler/KdCountLineIntersectionHandler.h +++ b/src/basics/geometry3d/KdTree/intersectionhandler/KdCountLineIntersectionHandler.h @@ -1,8 +1,8 @@ #ifndef KDCOUNTLINEINTERSECTIONHANDLER_H #define KDCOUNTLINEINTERSECTIONHANDLER_H -#include <basics/utilities/UbTuple.h> #include <basics/utilities/UbKeys.h> +#include <basics/utilities/UbTuple.h> #include <geometry3d/GbTriFaceMesh3D.h> @@ -14,43 +14,40 @@ namespace Kd { - template< typename T > - class CountLineIntersectionHandler : public LineIntersectionHandler<T> - { - public: - bool intersectLine(const UbTuple<T,T,T>& n1, const UbTuple<T,T,T>& n2, Node<T>& parent, Node<T>*& child1, Node<T>*& child2) const override - { - if( parent.intersectLineBoundingBox(n1, n2) == Intersection::INTERSECTION) - { - if( parent.isLeaf() ) - { - std::vector<GbTriFaceMesh3D::TriFace>& triFaces = *parent.getTriFaces(); - std::vector<GbTriFaceMesh3D::Vertex>& nodes = parent.getNodes(); - - for( std::size_t i=0; i<triFaces.size(); i++ ) - { - GbTriFaceMesh3D::TriFace& triFace = triFaces[i]; - - if( Kd::intersectLine(n1, n2, triFace, nodes) ) return true; - } - return false; - } - else - { - if( child1 ) - { - if (child1->intersectLine(n1, n2, *this)) return true; - } - if( child2 ) - { - if (child2->intersectLine(n1, n2, *this)) return true; - } +template <typename T> +class CountLineIntersectionHandler : public LineIntersectionHandler<T> +{ +public: + bool intersectLine(const UbTuple<T, T, T> &n1, const UbTuple<T, T, T> &n2, Node<T> &parent, Node<T> *&child1, + Node<T> *&child2) const override + { + if (parent.intersectLineBoundingBox(n1, n2) == Intersection::INTERSECTION) { + if (parent.isLeaf()) { + std::vector<GbTriFaceMesh3D::TriFace> &triFaces = *parent.getTriFaces(); + std::vector<GbTriFaceMesh3D::Vertex> &nodes = parent.getNodes(); + + for (std::size_t i = 0; i < triFaces.size(); i++) { + GbTriFaceMesh3D::TriFace &triFace = triFaces[i]; + + if (Kd::intersectLine(n1, n2, triFace, nodes)) + return true; + } + return false; + } else { + if (child1) { + if (child1->intersectLine(n1, n2, *this)) + return true; + } + if (child2) { + if (child2->intersectLine(n1, n2, *this)) + return true; + } } - } - return false; - } - /* ======================================================================================= */ - }; -} - -#endif //KDCOUNTLINEINTERSECTIONHANDLER_H + } + return false; + } + /* ======================================================================================= */ +}; +} // namespace Kd + +#endif // KDCOUNTLINEINTERSECTIONHANDLER_H diff --git a/src/basics/geometry3d/KdTree/intersectionhandler/KdCountRayIntersectionHandler.h b/src/basics/geometry3d/KdTree/intersectionhandler/KdCountRayIntersectionHandler.h index 460ec2174e592950157c04b5d9c6632fe2079975..2fab632ff78b60cd7d6dd2f595aba3562d1f9804 100644 --- a/src/basics/geometry3d/KdTree/intersectionhandler/KdCountRayIntersectionHandler.h +++ b/src/basics/geometry3d/KdTree/intersectionhandler/KdCountRayIntersectionHandler.h @@ -1,8 +1,8 @@ #ifndef KDCOUNTRAYINTERSECTIONHANDLER_H #define KDCOUNTRAYINTERSECTIONHANDLER_H -#include <basics/utilities/UbTuple.h> #include <basics/utilities/UbKeys.h> +#include <basics/utilities/UbTuple.h> #include <geometry3d/GbTriFaceMesh3D.h> @@ -14,151 +14,146 @@ namespace Kd { - template< typename T > - class CountRayIntersectionHandler : public RayIntersectionHandler<T> - { - public: - int intersectRay(const Ray<T>& ray, Node<T>& parent, Node<T>*& child1, Node<T>*& child2, std::set< UbKeys::Key3<int> >& mailbox) const override - { - if( parent.intersectRayBoundingBox(ray) == Intersection::INTERSECTION) - { - if( parent.isLeaf() ) - { - return this->checkIntersectionWithTriFaces(ray, *parent.getTriFaces(), parent.getNodes(), mailbox); - } - else - { - int sum = 0; - if( child1 ) - { - int erg = child1->intersectRay(ray, *this, mailbox); - if(erg < 0) - { - return erg; - } - sum += erg; - } - if( child2 ) - { - int erg = child2->intersectRay(ray, *this, mailbox); - if(erg < 0) - { - return erg; - } - sum += erg; - } - return sum; +template <typename T> +class CountRayIntersectionHandler : public RayIntersectionHandler<T> +{ +public: + int intersectRay(const Ray<T> &ray, Node<T> &parent, Node<T> *&child1, Node<T> *&child2, + std::set<UbKeys::Key3<int>> &mailbox) const override + { + if (parent.intersectRayBoundingBox(ray) == Intersection::INTERSECTION) { + if (parent.isLeaf()) { + return this->checkIntersectionWithTriFaces(ray, *parent.getTriFaces(), parent.getNodes(), mailbox); + } else { + int sum = 0; + if (child1) { + int erg = child1->intersectRay(ray, *this, mailbox); + if (erg < 0) { + return erg; + } + sum += erg; + } + if (child2) { + int erg = child2->intersectRay(ray, *this, mailbox); + if (erg < 0) { + return erg; + } + sum += erg; + } + return sum; } - } - else - { + } else { return 0; - } - } - /* ======================================================================================= */ - - private: - int checkIntersectionWithTriFaces(const Ray<T>& ray, std::vector<GbTriFaceMesh3D::TriFace>& triFaces, std::vector<GbTriFaceMesh3D::Vertex>& nodes, std::set< UbKeys::Key3<int> >& mailbox) const - { - T e1x,e1y,e1z,e2x,e2y,e2z,px,py,pz,a,f,sx,sy,sz,u,qx,qy,qz,v,factor; - - int counter = 0; - - for(std::size_t i=0; i<triFaces.size(); i++ ) - { - GbTriFaceMesh3D::TriFace& triFace = triFaces[i]; - - if( mailbox.find( UbKeys::Key3<int>(triFace.getIndexVertex1(), triFace.getIndexVertex2(), triFace.getIndexVertex3() ) )==mailbox.end() ) - { - mailbox.insert( UbKeys::Key3<int>(triFace.getIndexVertex1(), triFace.getIndexVertex2(), triFace.getIndexVertex3() ) ); //schon hier rein, ansonsten muss man es unten bei JEDEm continue und am ende des ifs machen - - GbTriFaceMesh3D::Vertex& v1 = triFace.getNode(0, nodes); - GbTriFaceMesh3D::Vertex& v2 = triFace.getNode(1, nodes); - GbTriFaceMesh3D::Vertex& v3 = triFace.getNode(2, nodes); - - ////////////////////////////////////////////////////////////////////////// - //Raytracing - start( Anm.: pr�ft NUR in Strahlrichtung - // Grundidee: Schnittpunkt in Baryzentrischen Koordinaten besimmten - // t(u,v,w) = w*v0 + u*v1 + v*v2 - // mit w = 1.0-u-v, da fuer alle Punkte (u,v,w) im Dreick gilt u+v+w = 1 - // wenn u, v oder w == 0 -> Punkt liegt auf Kante - // wenn u, v oder w == 1 -> Punkt liegt auf Eckpunkt (-> die anderen Werte muessen 0 ) - - //e1 = v1 - v0 - e1x = v2.x-v1.x; - e1y = v2.y-v1.y; - e1z = v2.z-v1.z; - - //e2 = v2 - v0 - e2x = v3.x-v1.x; - e2y = v3.y-v1.y; - e2z = v3.z-v1.z; - - //p = d x e2 - px = ray.directionY*e2z - ray.directionZ*e2y; - py = ray.directionZ*e2x - ray.directionX*e2z; - pz = ray.directionX*e2y - ray.directionY*e2x; - - //a = e1 dot p - a = e1x*px + e1y*py + e1z*pz; - //if( fabs(a)<1.E-10 ) continue; - if( fabs(a) < UbMath::Epsilon<T>::val() ) continue; - f = T(1.0/a); - - //s = o - v0 - sx = ray.originX - v1.x; - sy = ray.originY - v1.y; - sz = ray.originZ - v1.z; - - //u = f * ( s dot p) - u = f * ( sx*px + sy*py + sz*pz ); - - //u ist nur gueltig in [0;1] - if( ( UbMath::less( u, T(0.0) ) ) || ( UbMath::greater(u, T(1.0) ) ) ) - { - continue; - } - - //q = s x e1 - qx = sy*e1z - sz*e1y; - qy = sz*e1x - sx*e1z; - qz = sx*e1y - sy*e1x; - - //v = f*(e2 dot q) - v = f * (ray.directionX*qx + ray.directionY*qy + ray.directionZ*qz); - - //v ist nur gueltig in [0;1] da aber v bereits gueltig ist -> u+v darf nicht > 1.0 sein ;-) - if( ( UbMath::less(v, T(0.0) ) ) || ( UbMath::greater(u+v, T(1.0) ) ) ) - { - continue; - } - - //t = f * (e2 dot q) - factor = f * (e2x*qx + e2y*qy + e2z*qz); - //Raytracing - end - ////////////////////////////////////////////////////////////////////////// - - if( UbMath::zero( factor ) ) - { - return Intersection::ON_BOUNDARY; //ray.Org liegt direkt auf einem dreieck --> boundary - } - if( factor < 0.0 ) - { - continue; //Schnittpunkt liegt in entgegengesetzter Strahlrichtung - } - - //edge tests - //wenn u, v oder w ==0 -> Punkt liegt auf Kante bzw. Eckpunkt - if( UbMath::zero(u) ) return Intersection::INTERSECT_EDGE; - if( UbMath::zero(v) ) return Intersection::INTERSECT_EDGE; - if( UbMath::zero(T(1.0)-u-v) ) return Intersection::INTERSECT_EDGE; - - counter++; + } + } + /* ======================================================================================= */ + +private: + int checkIntersectionWithTriFaces(const Ray<T> &ray, std::vector<GbTriFaceMesh3D::TriFace> &triFaces, + std::vector<GbTriFaceMesh3D::Vertex> &nodes, + std::set<UbKeys::Key3<int>> &mailbox) const + { + T e1x, e1y, e1z, e2x, e2y, e2z, px, py, pz, a, f, sx, sy, sz, u, qx, qy, qz, v, factor; + + int counter = 0; + + for (std::size_t i = 0; i < triFaces.size(); i++) { + GbTriFaceMesh3D::TriFace &triFace = triFaces[i]; + + if (mailbox.find(UbKeys::Key3<int>(triFace.getIndexVertex1(), triFace.getIndexVertex2(), + triFace.getIndexVertex3())) == mailbox.end()) { + mailbox.insert( + UbKeys::Key3<int>(triFace.getIndexVertex1(), triFace.getIndexVertex2(), + triFace.getIndexVertex3())); // schon hier rein, ansonsten muss man es unten bei + // JEDEm continue und am ende des ifs machen + + GbTriFaceMesh3D::Vertex &v1 = triFace.getNode(0, nodes); + GbTriFaceMesh3D::Vertex &v2 = triFace.getNode(1, nodes); + GbTriFaceMesh3D::Vertex &v3 = triFace.getNode(2, nodes); + + ////////////////////////////////////////////////////////////////////////// + // Raytracing - start( Anm.: pr�ft NUR in Strahlrichtung + // Grundidee: Schnittpunkt in Baryzentrischen Koordinaten besimmten + // t(u,v,w) = w*v0 + u*v1 + v*v2 + // mit w = 1.0-u-v, da fuer alle Punkte (u,v,w) im Dreick gilt u+v+w = 1 + // wenn u, v oder w == 0 -> Punkt liegt auf Kante + // wenn u, v oder w == 1 -> Punkt liegt auf Eckpunkt (-> die anderen Werte muessen 0 ) + + // e1 = v1 - v0 + e1x = v2.x - v1.x; + e1y = v2.y - v1.y; + e1z = v2.z - v1.z; + + // e2 = v2 - v0 + e2x = v3.x - v1.x; + e2y = v3.y - v1.y; + e2z = v3.z - v1.z; + + // p = d x e2 + px = ray.directionY * e2z - ray.directionZ * e2y; + py = ray.directionZ * e2x - ray.directionX * e2z; + pz = ray.directionX * e2y - ray.directionY * e2x; + + // a = e1 dot p + a = e1x * px + e1y * py + e1z * pz; + // if( fabs(a)<1.E-10 ) continue; + if (fabs(a) < UbMath::Epsilon<T>::val()) + continue; + f = T(1.0 / a); + + // s = o - v0 + sx = ray.originX - v1.x; + sy = ray.originY - v1.y; + sz = ray.originZ - v1.z; + + // u = f * ( s dot p) + u = f * (sx * px + sy * py + sz * pz); + + // u ist nur gueltig in [0;1] + if ((UbMath::less(u, T(0.0))) || (UbMath::greater(u, T(1.0)))) { + continue; + } + + // q = s x e1 + qx = sy * e1z - sz * e1y; + qy = sz * e1x - sx * e1z; + qz = sx * e1y - sy * e1x; + + // v = f*(e2 dot q) + v = f * (ray.directionX * qx + ray.directionY * qy + ray.directionZ * qz); + + // v ist nur gueltig in [0;1] da aber v bereits gueltig ist -> u+v darf nicht > 1.0 sein ;-) + if ((UbMath::less(v, T(0.0))) || (UbMath::greater(u + v, T(1.0)))) { + continue; + } + + // t = f * (e2 dot q) + factor = f * (e2x * qx + e2y * qy + e2z * qz); + // Raytracing - end + ////////////////////////////////////////////////////////////////////////// + + if (UbMath::zero(factor)) { + return Intersection::ON_BOUNDARY; // ray.Org liegt direkt auf einem dreieck --> boundary + } + if (factor < 0.0) { + continue; // Schnittpunkt liegt in entgegengesetzter Strahlrichtung + } + + // edge tests + // wenn u, v oder w ==0 -> Punkt liegt auf Kante bzw. Eckpunkt + if (UbMath::zero(u)) + return Intersection::INTERSECT_EDGE; + if (UbMath::zero(v)) + return Intersection::INTERSECT_EDGE; + if (UbMath::zero(T(1.0) - u - v)) + return Intersection::INTERSECT_EDGE; + + counter++; } - } - return counter; - } - }; -} + } + return counter; + } +}; +} // namespace Kd -#endif //KDCOUNTRAYLINEINTERSECTIONHANDLER_H +#endif // KDCOUNTRAYLINEINTERSECTIONHANDLER_H diff --git a/src/basics/geometry3d/KdTree/intersectionhandler/KdLineIntersectionHandler.h b/src/basics/geometry3d/KdTree/intersectionhandler/KdLineIntersectionHandler.h index 156dd720b4719a62423efc50bd616a249fe2a516..61d4800d22fa6b8e204c1325f781b9fbf411c057 100644 --- a/src/basics/geometry3d/KdTree/intersectionhandler/KdLineIntersectionHandler.h +++ b/src/basics/geometry3d/KdTree/intersectionhandler/KdLineIntersectionHandler.h @@ -11,20 +11,21 @@ // #end namespace Kd { - template< typename T> - class Node; +template <typename T> +class Node; - template< typename T> - class LineIntersectionHandler - { - public: - virtual bool intersectLine(const UbTuple<T,T,T>& n1, const UbTuple<T,T,T>& n2, Node<T>& parent, Node<T>*& child1, Node<T>*& child2) const = 0; - virtual ~LineIntersectionHandler() = default; - }; -} +template <typename T> +class LineIntersectionHandler +{ +public: + virtual bool intersectLine(const UbTuple<T, T, T> &n1, const UbTuple<T, T, T> &n2, Node<T> &parent, + Node<T> *&child1, Node<T> *&child2) const = 0; + virtual ~LineIntersectionHandler() = default; +}; +} // namespace Kd // #if defined(RCF_USE_SF_SERIALIZATION) && !defined(SWIG) // SF_NO_CTOR(Kd::LineIntersectionHandler<float>); // SF_NO_CTOR(Kd::LineIntersectionHandler<double>); // #endif //RCF_USE_SF_SERIALIZATI -#endif //KDLINEINTERSECTIONHANDLER_H +#endif // KDLINEINTERSECTIONHANDLER_H diff --git a/src/basics/geometry3d/KdTree/intersectionhandler/KdRayIntersectionHandler.h b/src/basics/geometry3d/KdTree/intersectionhandler/KdRayIntersectionHandler.h index 99803aa152b41033c638b84500f1f2911c6b142d..2965b0b393c5e324af0a7d3dea593f703f208db1 100644 --- a/src/basics/geometry3d/KdTree/intersectionhandler/KdRayIntersectionHandler.h +++ b/src/basics/geometry3d/KdTree/intersectionhandler/KdRayIntersectionHandler.h @@ -8,13 +8,14 @@ namespace Kd { - template< typename T> - class RayIntersectionHandler - { - public: - virtual int intersectRay(const Ray<T>& ray, Node<T>& parent, Node<T>*& child1, Node<T>*& child2, std::set< UbKeys::Key3<int> >& mailbox) const = 0; - virtual ~RayIntersectionHandler() = default; - }; -} +template <typename T> +class RayIntersectionHandler +{ +public: + virtual int intersectRay(const Ray<T> &ray, Node<T> &parent, Node<T> *&child1, Node<T> *&child2, + std::set<UbKeys::Key3<int>> &mailbox) const = 0; + virtual ~RayIntersectionHandler() = default; +}; +} // namespace Kd -#endif //KDRAYINTERSECTIONHANDLER_H +#endif // KDRAYINTERSECTIONHANDLER_H diff --git a/src/basics/geometry3d/KdTree/splitalgorithms/KdSAHSplit.cpp b/src/basics/geometry3d/KdTree/splitalgorithms/KdSAHSplit.cpp index 98fc024dbfc4612f99cef66afe5c9d74d5eeaf67..31cfa74d8bc32628e87a8db5e184b9df5134b3a8 100644 --- a/src/basics/geometry3d/KdTree/splitalgorithms/KdSAHSplit.cpp +++ b/src/basics/geometry3d/KdTree/splitalgorithms/KdSAHSplit.cpp @@ -1,10 +1,7 @@ //#include <geometry3d/KdTree/SAHSplit.h> - // namespace Kd // { // const double SAHSplit::Ct = 3.0; //traversal cost // const double SAHSplit::Ci = 4.0; //ray-patch-intersection-cost // } - - diff --git a/src/basics/geometry3d/KdTree/splitalgorithms/KdSAHSplit.h b/src/basics/geometry3d/KdTree/splitalgorithms/KdSAHSplit.h index 07e9013cbe3e318f702f739825f41ec448778cba..c828f5f7fdc95000f64a83e964c0697649e31f97 100644 --- a/src/basics/geometry3d/KdTree/splitalgorithms/KdSAHSplit.h +++ b/src/basics/geometry3d/KdTree/splitalgorithms/KdSAHSplit.h @@ -2,286 +2,254 @@ #define KDSAHSPLIT_H #include <basics/utilities/UbException.h> -#include <basics/utilities/UbMath.h> #include <basics/utilities/UbInfinity.h> +#include <basics/utilities/UbMath.h> #include <geometry3d/GbTriFaceMesh3D.h> #include <geometry3d/KdTree/KdNode.h> -#include <geometry3d/KdTree/KdUtilities.h> #include <geometry3d/KdTree/KdSplitCandidateManager.h> +#include <geometry3d/KdTree/KdUtilities.h> #include <geometry3d/KdTree/splitalgorithms/KdSplitAlgorithm.h> -#include <vector> #include <cmath> +#include <vector> namespace Kd { - template< typename T > - class SAHSplit : public SplitAlgorithm<T> - { - public: - /* ======================================================================================= */ - SplitCandidate<T> findBestSplitCandidate(const int& level, const int& maxLevel, Node<T>& node ) const override - { - if( !node.getTriFaces() ) throw UbException(UB_EXARGS, "triFace NULL pointer"); - - if( node.getTriFaces()->size() <= 1 //max triangles in node - || level >= maxLevel ) - { +template <typename T> +class SAHSplit : public SplitAlgorithm<T> +{ +public: + /* ======================================================================================= */ + SplitCandidate<T> findBestSplitCandidate(const int &level, const int &maxLevel, Node<T> &node) const override + { + if (!node.getTriFaces()) + throw UbException(UB_EXARGS, "triFace NULL pointer"); + + if (node.getTriFaces()->size() <= 1 // max triangles in node + || level >= maxLevel) { return SplitCandidate<T>(); - } + } - SplitCandidate<T> bestSplitCandidate; - T minCN = Ub::inf; + SplitCandidate<T> bestSplitCandidate; + T minCN = Ub::inf; - for(int splitAxis = 0; splitAxis < 3; splitAxis++) - { + for (int splitAxis = 0; splitAxis < 3; splitAxis++) { SplitCandidateManager<T> sc; findPossibleSplitCandidates(splitAxis, node, sc); // incremental sweep to find best split position - for( std::size_t i = 0; i < sc.size(); i++) - { - if (i == 0) - { - sc[i].nl = sc.objects_starting_outside_left + sc.objects_fully_outside_node; - sc[i].nr = int(node.getTriFaces()->size()) - sc[0].np - sc[0].ending; - } - else - { - sc[i].nl = sc[i - 1].nl + sc[i - 1].starting + sc[i - 1].np; - sc[i].nr = sc[i - 1].nr - sc[i ].ending - sc[i ].np; - } - - this->calcSAH(sc[i], node); - - if (sc[i].Cn < minCN) - { - minCN = sc[i].Cn; - bestSplitCandidate = sc[i]; - } + for (std::size_t i = 0; i < sc.size(); i++) { + if (i == 0) { + sc[i].nl = sc.objects_starting_outside_left + sc.objects_fully_outside_node; + sc[i].nr = int(node.getTriFaces()->size()) - sc[0].np - sc[0].ending; + } else { + sc[i].nl = sc[i - 1].nl + sc[i - 1].starting + sc[i - 1].np; + sc[i].nr = sc[i - 1].nr - sc[i].ending - sc[i].np; + } + + this->calcSAH(sc[i], node); + + if (sc[i].Cn < minCN) { + minCN = sc[i].Cn; + bestSplitCandidate = sc[i]; + } } - } + } - // automatic termination criterion (SAH) - if ( bestSplitCandidate.isValid && bestSplitCandidate.Cn >= node.getTriFaces()->size() * Ci) - { + // automatic termination criterion (SAH) + if (bestSplitCandidate.isValid && bestSplitCandidate.Cn >= node.getTriFaces()->size() * Ci) { return SplitCandidate<T>(); - } - - return bestSplitCandidate; - } - /* ======================================================================================= */ - void distributeTriFaces(const SplitCandidate<T>& candidate, std::vector<GbTriFaceMesh3D::TriFace>& triFacesForChild1, std::vector<GbTriFaceMesh3D::TriFace>& triFacesForChild2, Node<T>& node) const override - { - if( !node.getTriFaces() ) throw UbException(UB_EXARGS, "null pointer at triface list"); - - std::vector<GbTriFaceMesh3D::TriFace>& srcTriFaces = *node.getTriFaces(); - std::vector<GbTriFaceMesh3D::Vertex>& srcNodes = node.getNodes(); - std::vector<T> projection; - - for(std::size_t i=0; i<srcTriFaces.size(); i++) - { - GbTriFaceMesh3D::TriFace& triFace = srcTriFaces[i]; + } + + return bestSplitCandidate; + } + /* ======================================================================================= */ + void distributeTriFaces(const SplitCandidate<T> &candidate, + std::vector<GbTriFaceMesh3D::TriFace> &triFacesForChild1, + std::vector<GbTriFaceMesh3D::TriFace> &triFacesForChild2, Node<T> &node) const override + { + if (!node.getTriFaces()) + throw UbException(UB_EXARGS, "null pointer at triface list"); + + std::vector<GbTriFaceMesh3D::TriFace> &srcTriFaces = *node.getTriFaces(); + std::vector<GbTriFaceMesh3D::Vertex> &srcNodes = node.getNodes(); + std::vector<T> projection; + + for (std::size_t i = 0; i < srcTriFaces.size(); i++) { + GbTriFaceMesh3D::TriFace &triFace = srcTriFaces[i]; Kd::project2Axis(triFace, srcNodes, candidate.axis, projection); - T& min = projection[0]; - T& max = projection[2]; + T &min = projection[0]; + T &max = projection[2]; // --------------------------------------------------- // // case 1 : object inside plane - if( UbMath::equal(min, max) ) - { - if( UbMath::equal(min, candidate.position) ) - { - if(candidate.np_left) - { - triFacesForChild1.push_back(triFace); - } - else if(candidate.np_right) - { - triFacesForChild2.push_back(triFace); - } - } - else if( UbMath::less(min, candidate.position) ) - { - triFacesForChild1.push_back(triFace); - } - else //if( UbMath::greater(min, candidate.position) - { - triFacesForChild2.push_back(triFace); - } + if (UbMath::equal(min, max)) { + if (UbMath::equal(min, candidate.position)) { + if (candidate.np_left) { + triFacesForChild1.push_back(triFace); + } else if (candidate.np_right) { + triFacesForChild2.push_back(triFace); + } + } else if (UbMath::less(min, candidate.position)) { + triFacesForChild1.push_back(triFace); + } else // if( UbMath::greater(min, candidate.position) + { + triFacesForChild2.push_back(triFace); + } } // // --------------------------------------------------- // // case 2 : object on left side of plane - else if( UbMath::lessEqual(max,candidate.position) ) - { - triFacesForChild1.push_back(triFace); + else if (UbMath::lessEqual(max, candidate.position)) { + triFacesForChild1.push_back(triFace); } // --------------------------------------------------- // // case 3 : object on right side of plane - else if ( UbMath::greaterEqual( min, candidate.position) ) - { - triFacesForChild2.push_back(triFace); - }// + else if (UbMath::greaterEqual(min, candidate.position)) { + triFacesForChild2.push_back(triFace); + } // // --------------------------------------------------- // // case 4 : object in both nodes - else - { - triFacesForChild1.push_back(triFace); - triFacesForChild2.push_back(triFace); - }// - // --------------------------------------------------- // - } - - node.deleteTriFaces(); - } - - - private: - /* ======================================================================================= */ - // cost function - inline T calcCosts(const int& nl, const int& nr, const T& SA_VL, const T& SA_VR, const T& SA_V) const - { - return Ct + Ci * (nl * SA_VL / SA_V + nr * SA_VR / SA_V); - } - /* ======================================================================================= */ - void findPossibleSplitCandidates(const int& splitAxis, Node<T>& node, SplitCandidateManager<T>& splitCandidateManager) const - { - T p1_node = (splitAxis == Axis::X ? node.x[0] : splitAxis == Axis::Y ? node.y[0] : node.z[0]); - T p2_node = (splitAxis == Axis::X ? node.x[1] : splitAxis == Axis::Y ? node.y[1] : node.z[1]); - - if( !node.getTriFaces() ) throw UbException(UB_EXARGS, "null pointer"); - - std::vector<GbTriFaceMesh3D::TriFace>& srcTriFaces = *node.getTriFaces(); - std::vector<GbTriFaceMesh3D::Vertex >& srcNodes = node.getNodes(); - std::vector<T> projection; - - for(std::size_t i=0; i<srcTriFaces.size(); i++) - { - GbTriFaceMesh3D::TriFace& triFace = srcTriFaces[i]; + else { + triFacesForChild1.push_back(triFace); + triFacesForChild2.push_back(triFace); + } // + // --------------------------------------------------- // + } + + node.deleteTriFaces(); + } + +private: + /* ======================================================================================= */ + // cost function + inline T calcCosts(const int &nl, const int &nr, const T &SA_VL, const T &SA_VR, const T &SA_V) const + { + return Ct + Ci * (nl * SA_VL / SA_V + nr * SA_VR / SA_V); + } + /* ======================================================================================= */ + void findPossibleSplitCandidates(const int &splitAxis, Node<T> &node, + SplitCandidateManager<T> &splitCandidateManager) const + { + T p1_node = (splitAxis == Axis::X ? node.x[0] : splitAxis == Axis::Y ? node.y[0] : node.z[0]); + T p2_node = (splitAxis == Axis::X ? node.x[1] : splitAxis == Axis::Y ? node.y[1] : node.z[1]); + + if (!node.getTriFaces()) + throw UbException(UB_EXARGS, "null pointer"); + + std::vector<GbTriFaceMesh3D::TriFace> &srcTriFaces = *node.getTriFaces(); + std::vector<GbTriFaceMesh3D::Vertex> &srcNodes = node.getNodes(); + std::vector<T> projection; + + for (std::size_t i = 0; i < srcTriFaces.size(); i++) { + GbTriFaceMesh3D::TriFace &triFace = srcTriFaces[i]; // project object to axis - Kd::project2Axis(triFace,srcNodes,splitAxis, projection); + Kd::project2Axis(triFace, srcNodes, splitAxis, projection); // left point - T& p1 = projection[0]; + T &p1 = projection[0]; // right point - T& p2 = projection[2]; + T &p2 = projection[2]; // --------------------------------------------------- // // --------------------------------------------------- // // case 1 : object is fully inside the current node - if( UbMath::greaterEqual(p1, p1_node) - && UbMath::lessEqual(p2, p2_node) ) - { - if( UbMath::equal(p1, p2) ) - { - // object is inside the plane - splitCandidateManager.add(p1, splitAxis, 0, 0, 1); - } - else - { - splitCandidateManager.add(p1, splitAxis, 1, 0, 0); - splitCandidateManager.add(p2, splitAxis, 0, 1, 0); - } + if (UbMath::greaterEqual(p1, p1_node) && UbMath::lessEqual(p2, p2_node)) { + if (UbMath::equal(p1, p2)) { + // object is inside the plane + splitCandidateManager.add(p1, splitAxis, 0, 0, 1); + } else { + splitCandidateManager.add(p1, splitAxis, 1, 0, 0); + splitCandidateManager.add(p2, splitAxis, 0, 1, 0); + } } // // --------------------------------------------------- // // --------------------------------------------------- // // case 2 : just the right point (p2) is inside the current node - else if( UbMath::less(p1, p1_node) - && UbMath::lessEqual(p2,p2_node) - && UbMath::greaterEqual(p2, p1_node) ) - { - splitCandidateManager.add(p2, splitAxis, 0, 1, 0); - splitCandidateManager.objects_starting_outside_left++; + else if (UbMath::less(p1, p1_node) && UbMath::lessEqual(p2, p2_node) && UbMath::greaterEqual(p2, p1_node)) { + splitCandidateManager.add(p2, splitAxis, 0, 1, 0); + splitCandidateManager.objects_starting_outside_left++; } // // --------------------------------------------------- // // --------------------------------------------------- // // case 3 : just the left point (p1) is inside the current node - else if( UbMath::greaterEqual(p1, p1_node) - && UbMath::greater(p2, p2_node) - && UbMath::lessEqual(p1, p2_node) ) - { - splitCandidateManager.add(p1, splitAxis, 1, 0, 0); + else if (UbMath::greaterEqual(p1, p1_node) && UbMath::greater(p2, p2_node) && + UbMath::lessEqual(p1, p2_node)) { + splitCandidateManager.add(p1, splitAxis, 1, 0, 0); } // // --------------------------------------------------- // // --------------------------------------------------- // // case 4 : left and right point are outside the current node - else if( UbMath::less(p1, p1_node) - && UbMath::greater(p2, p2_node) ) - { - splitCandidateManager.objects_fully_outside_node++; + else if (UbMath::less(p1, p1_node) && UbMath::greater(p2, p2_node)) { + splitCandidateManager.objects_fully_outside_node++; } // - // --------------------------------------------------- // - // --------------------------------------------------- // - } - - splitCandidateManager.createSortedArray(); - } + // --------------------------------------------------- // + // --------------------------------------------------- // + } + splitCandidateManager.createSortedArray(); + } - /* ======================================================================================= */ - // calculates the costs for a given splitCandidate based on the Surface Area Heuristic (SAH) - void calcSAH(SplitCandidate<T>& candidate, Node<T>& node) const - { - T p1_node = (candidate.axis == Axis::X ? node.x[0] : candidate.axis == Axis::Y ? node.y[0] : node.z[0]); + /* ======================================================================================= */ + // calculates the costs for a given splitCandidate based on the Surface Area Heuristic (SAH) + void calcSAH(SplitCandidate<T> &candidate, Node<T> &node) const + { + T p1_node = (candidate.axis == Axis::X ? node.x[0] : candidate.axis == Axis::Y ? node.y[0] : node.z[0]); - // edges of (root) voxel - T dx = std::fabs(node.x[1] - node.x[0]); - T dy = std::fabs(node.y[1] - node.y[0]); - T dz = std::fabs(node.z[1] - node.z[0]); + // edges of (root) voxel + T dx = std::fabs(node.x[1] - node.x[0]); + T dy = std::fabs(node.y[1] - node.y[0]); + T dz = std::fabs(node.z[1] - node.z[0]); - // surface area (root) voxel - T SA_V = T((2.0 * dx * dy) + (2.0 * dx * dz) + (2.0 * dy * dz)); + // surface area (root) voxel + T SA_V = T((2.0 * dx * dy) + (2.0 * dx * dz) + (2.0 * dy * dz)); - T delta = (candidate.axis == Axis::X ? dx : candidate.axis == Axis::Y ? dy : dz); - T deltaL = std::fabs(candidate.position - p1_node); - T deltaR = std::fabs(delta - deltaL); + T delta = (candidate.axis == Axis::X ? dx : candidate.axis == Axis::Y ? dy : dz); + T deltaL = std::fabs(candidate.position - p1_node); + T deltaR = std::fabs(delta - deltaL); - // edges of sub voxel left - T dx_l = (candidate.axis == Axis::X ? deltaL : dx), dy_l = (candidate.axis == Axis::Y ? deltaL : dy), dz_l = (candidate.axis == Axis::Z ? deltaL : dz); + // edges of sub voxel left + T dx_l = (candidate.axis == Axis::X ? deltaL : dx), dy_l = (candidate.axis == Axis::Y ? deltaL : dy), + dz_l = (candidate.axis == Axis::Z ? deltaL : dz); - // surface area sub voxel left - T SA_VL = T( (2.0 * dx_l * dy_l) + (2.0 * dx_l * dz_l) + (2.0 * dy_l * dz_l) ); + // surface area sub voxel left + T SA_VL = T((2.0 * dx_l * dy_l) + (2.0 * dx_l * dz_l) + (2.0 * dy_l * dz_l)); - // edges of sub voxel right - T dx_r = (candidate.axis == Axis::X ? deltaR : dx), dy_r = (candidate.axis == Axis::Y ? deltaR : dy), dz_r = (candidate.axis == Axis::Z ? deltaR : dz); + // edges of sub voxel right + T dx_r = (candidate.axis == Axis::X ? deltaR : dx), dy_r = (candidate.axis == Axis::Y ? deltaR : dy), + dz_r = (candidate.axis == Axis::Z ? deltaR : dz); - // surface area sub voxel right - T SA_VR = T( (2.0 * dx_r * dy_r) + (2.0 * dx_r * dz_r) + (2.0 * dy_r * dz_r) ); + // surface area sub voxel right + T SA_VR = T((2.0 * dx_r * dy_r) + (2.0 * dx_r * dz_r) + (2.0 * dy_r * dz_r)); - if (candidate.np == 0) - { + if (candidate.np == 0) { candidate.Cn = calcCosts(candidate.nl, candidate.nr, SA_VL, SA_VR, SA_V); return; - } - - // once putting np with nl, and once with nr - and select the one with lowest cost - // see: Wald, Havran: "On building fast kd-Trees for Ray Tracing, and doing that in O(N log N)", 2006 - T CP_L = calcCosts(candidate.nl + candidate.np, candidate.nr , SA_VL, SA_VR, SA_V); - T CP_R = calcCosts(candidate.nl , candidate.nr + candidate.np, SA_VL, SA_VR, SA_V); - - if(CP_L < CP_R) - { + } + + // once putting np with nl, and once with nr - and select the one with lowest cost + // see: Wald, Havran: "On building fast kd-Trees for Ray Tracing, and doing that in O(N log N)", 2006 + T CP_L = calcCosts(candidate.nl + candidate.np, candidate.nr, SA_VL, SA_VR, SA_V); + T CP_R = calcCosts(candidate.nl, candidate.nr + candidate.np, SA_VL, SA_VR, SA_V); + + if (CP_L < CP_R) { candidate.Cn = CP_L; candidate.np_right = true; - } - else - { + } else { candidate.Cn = CP_R; candidate.np_left = true; - } - } - /* ======================================================================================= */ - - protected: - static const T Ct;// = 3.0; traversal cost - static const T Ci;// = 4.0; ray-patch-intersection-cost - }; - - - template< typename T> - const T SAHSplit<T>::Ct = 3.0; //traversal cost - template< typename T> - const T SAHSplit<T>::Ci = 4.0; //ray-patch-intersection-cost -} - -#endif //KDSAHSPLIT_H + } + } + /* ======================================================================================= */ + +protected: + static const T Ct; // = 3.0; traversal cost + static const T Ci; // = 4.0; ray-patch-intersection-cost +}; + +template <typename T> +const T SAHSplit<T>::Ct = 3.0; // traversal cost +template <typename T> +const T SAHSplit<T>::Ci = 4.0; // ray-patch-intersection-cost +} // namespace Kd + +#endif // KDSAHSPLIT_H diff --git a/src/basics/geometry3d/KdTree/splitalgorithms/KdSpatiallMedianSplit.h b/src/basics/geometry3d/KdTree/splitalgorithms/KdSpatiallMedianSplit.h index a2c32fdf9b798280778885853de70abf8aca9064..518ac967ae1f26d6c67cd6946fbaf8ce1360c4bc 100644 --- a/src/basics/geometry3d/KdTree/splitalgorithms/KdSpatiallMedianSplit.h +++ b/src/basics/geometry3d/KdTree/splitalgorithms/KdSpatiallMedianSplit.h @@ -8,83 +8,76 @@ namespace Kd { - template< typename T > - class SpatialMedianSplit : public SplitAlgorithm<T> - { - /* ======================================================================================= */ - SplitCandidate<T> findBestSplitCandidate(const int& level, const int& maxLevel, Node<T>& node ) const override - { - if( node.getTriFaces()->size() <= 24 //max triangles in node - || level >= maxLevel ) - { +template <typename T> +class SpatialMedianSplit : public SplitAlgorithm<T> +{ + /* ======================================================================================= */ + SplitCandidate<T> findBestSplitCandidate(const int &level, const int &maxLevel, Node<T> &node) const override + { + if (node.getTriFaces()->size() <= 24 // max triangles in node + || level >= maxLevel) { return SplitCandidate<T>(); - } - - T dx = std::fabs(node.x[1] - node.x[0]); - T dy = std::fabs(node.y[1] - node.y[0]); - T dz = std::fabs(node.z[1] - node.z[0]); + } - if ( UbMath::equal(dx, UbMath::max(dx, dy, dz) ) ) return SplitCandidate<T>(Axis::X, node.x[0] + 0.5 * dx, 0, 0, 0); - else if( UbMath::equal(dy, UbMath::max(dy, dz ) ) ) return SplitCandidate<T>(Axis::Y, node.y[0] + 0.5 * dy, 0, 0, 0); + T dx = std::fabs(node.x[1] - node.x[0]); + T dy = std::fabs(node.y[1] - node.y[0]); + T dz = std::fabs(node.z[1] - node.z[0]); - return SplitCandidate<T>(Axis::Z, node.z[0] + 0.5 * dz, 0, 0, 0); + if (UbMath::equal(dx, UbMath::max(dx, dy, dz))) + return SplitCandidate<T>(Axis::X, node.x[0] + 0.5 * dx, 0, 0, 0); + else if (UbMath::equal(dy, UbMath::max(dy, dz))) + return SplitCandidate<T>(Axis::Y, node.y[0] + 0.5 * dy, 0, 0, 0); - } - /* ======================================================================================= */ - void distributeTriFaces(const SplitCandidate<T>& candidate, std::vector<GbTriFaceMesh3D::TriFace>& primitives_child1, std::vector<GbTriFaceMesh3D::TriFace>& primitives_child2, Node<T>& node) const override - { - if( !node.getTriFaces() ) throw UbException(UB_EXARGS, "null pointer"); + return SplitCandidate<T>(Axis::Z, node.z[0] + 0.5 * dz, 0, 0, 0); + } + /* ======================================================================================= */ + void distributeTriFaces(const SplitCandidate<T> &candidate, + std::vector<GbTriFaceMesh3D::TriFace> &primitives_child1, + std::vector<GbTriFaceMesh3D::TriFace> &primitives_child2, Node<T> &node) const override + { + if (!node.getTriFaces()) + throw UbException(UB_EXARGS, "null pointer"); - std::vector<GbTriFaceMesh3D::TriFace>& srcTriFaces = *node.getTriFaces(); - std::vector<GbTriFaceMesh3D::Vertex>& srcNodes = node.getNodes(); - std::vector<T> projection; + std::vector<GbTriFaceMesh3D::TriFace> &srcTriFaces = *node.getTriFaces(); + std::vector<GbTriFaceMesh3D::Vertex> &srcNodes = node.getNodes(); + std::vector<T> projection; - for(std::size_t i=0; i<srcTriFaces.size(); i++) - { - GbTriFaceMesh3D::TriFace& triFace = srcTriFaces[i]; + for (std::size_t i = 0; i < srcTriFaces.size(); i++) { + GbTriFaceMesh3D::TriFace &triFace = srcTriFaces[i]; Kd::project2Axis(triFace, srcNodes, candidate.axis, projection); - T& min = projection[0]; - T& max = projection[2]; - + T &min = projection[0]; + T &max = projection[2]; + // case 1 : object inside plane - if( UbMath::equal(min,max) ) - { - if( UbMath::equal(min,candidate.position) ) - { - primitives_child1.push_back(triFace); - primitives_child2.push_back(triFace); - } - else if( UbMath::less(min, candidate.position) ) - { - primitives_child1.push_back(triFace); - } - else if( UbMath::greater(min, candidate.position) ) - { - primitives_child2.push_back(triFace); - } - } + if (UbMath::equal(min, max)) { + if (UbMath::equal(min, candidate.position)) { + primitives_child1.push_back(triFace); + primitives_child2.push_back(triFace); + } else if (UbMath::less(min, candidate.position)) { + primitives_child1.push_back(triFace); + } else if (UbMath::greater(min, candidate.position)) { + primitives_child2.push_back(triFace); + } + } // case 2 : object on left side of plane - else if( UbMath::lessEqual(max, candidate.position) ) - { - primitives_child1.push_back(triFace); - } + else if (UbMath::lessEqual(max, candidate.position)) { + primitives_child1.push_back(triFace); + } // case 3 : object on right side of plane - else if( UbMath::greaterEqual(min, candidate.position) ) - { - primitives_child2.push_back(triFace); + else if (UbMath::greaterEqual(min, candidate.position)) { + primitives_child2.push_back(triFace); } // case 4 : object in both nodes - else - { - primitives_child1.push_back(triFace); - primitives_child2.push_back(triFace); + else { + primitives_child1.push_back(triFace); + primitives_child2.push_back(triFace); } - } + } - node.deleteTriFaces(); - } - }; -} + node.deleteTriFaces(); + } +}; +} // namespace Kd -#endif //SPATIALLMEDIANSPLIT_H +#endif // SPATIALLMEDIANSPLIT_H diff --git a/src/basics/geometry3d/KdTree/splitalgorithms/KdSplitAlgorithm.h b/src/basics/geometry3d/KdTree/splitalgorithms/KdSplitAlgorithm.h index 4a8caa6975e1e3d007c9df25f6e6d65788503629..c767a0c0d1013441610e6b1eb20501796c42c78e 100644 --- a/src/basics/geometry3d/KdTree/splitalgorithms/KdSplitAlgorithm.h +++ b/src/basics/geometry3d/KdTree/splitalgorithms/KdSplitAlgorithm.h @@ -9,18 +9,19 @@ namespace Kd { - template< typename T > - class Node; - - template< typename T > - class SplitAlgorithm - { - public: - virtual SplitCandidate<T> findBestSplitCandidate(const int& level, const int& maxLevel, Node<T>& node ) const = 0; - virtual void distributeTriFaces(const SplitCandidate<T>& candidate, std::vector<GbTriFaceMesh3D::TriFace>& triFacesForChild1, std::vector<GbTriFaceMesh3D::TriFace>& triFacesForChild2, Node<T>& node) const=0; - virtual ~SplitAlgorithm() = default; - }; -} +template <typename T> +class Node; +template <typename T> +class SplitAlgorithm +{ +public: + virtual SplitCandidate<T> findBestSplitCandidate(const int &level, const int &maxLevel, Node<T> &node) const = 0; + virtual void distributeTriFaces(const SplitCandidate<T> &candidate, + std::vector<GbTriFaceMesh3D::TriFace> &triFacesForChild1, + std::vector<GbTriFaceMesh3D::TriFace> &triFacesForChild2, Node<T> &node) const = 0; + virtual ~SplitAlgorithm() = default; +}; +} // namespace Kd -#endif //KDSPLITALGORITHM_H +#endif // KDSPLITALGORITHM_H diff --git a/src/cpu/DemCoupling/CreateDemObjectsCoProcessor.cpp b/src/cpu/DemCoupling/CreateDemObjectsCoProcessor.cpp index 6e99b35f56625dcf3b50d9bcf342e4b971826fcb..dacf8cfc870566455d1c91d94fd27e17239690e9 100644 --- a/src/cpu/DemCoupling/CreateDemObjectsCoProcessor.cpp +++ b/src/cpu/DemCoupling/CreateDemObjectsCoProcessor.cpp @@ -1,119 +1,121 @@ #include "CreateDemObjectsCoProcessor.h" -#include "UbScheduler.h" +#include "Communicator.h" #include "DemCoProcessor.h" +#include "EquilibriumReconstructor.h" +#include "ExtrapolationReconstructor.h" #include "GbSphere3D.h" +#include "Grid3D.h" +#include "LBMReconstructor.h" +#include "MovableObjectInteractor.h" #include "NoSlipBCAlgorithm.h" +#include "PePhysicsEngineMaterialAdapter.h" +#include "PhysicsEngineMaterialAdapter.h" +#include "SetBcBlocksBlockVisitor.h" +#include "UbScheduler.h" #include "VelocityBCAdapter.h" -#include "VelocityWithDensityBCAlgorithm.h" #include "VelocityBCAlgorithm.h" -#include "MovableObjectInteractor.h" -#include "LBMReconstructor.h" -#include "EquilibriumReconstructor.h" #include "VelocityBcReconstructor.h" -#include "ExtrapolationReconstructor.h" -#include "PePhysicsEngineMaterialAdapter.h" +#include "VelocityWithDensityBCAlgorithm.h" #include "muParser.h" -#include "PhysicsEngineMaterialAdapter.h" -#include "SetBcBlocksBlockVisitor.h" -#include "Grid3D.h" -#include "Communicator.h" - - -CreateDemObjectsCoProcessor::CreateDemObjectsCoProcessor(SPtr<Grid3D> grid, SPtr<UbScheduler> s, std::shared_ptr<Communicator> comm, SPtr<DemCoProcessor> demCoProcessor, SPtr<PhysicsEngineMaterialAdapter> demObjectMaterial, double tolerance) : - CoProcessor(grid, s), - comm(comm), - demCoProcessor(demCoProcessor), - demObjectMaterial(demObjectMaterial), - tolerance(tolerance) +CreateDemObjectsCoProcessor::CreateDemObjectsCoProcessor(SPtr<Grid3D> grid, SPtr<UbScheduler> s, + std::shared_ptr<Communicator> comm, + SPtr<DemCoProcessor> demCoProcessor, + SPtr<PhysicsEngineMaterialAdapter> demObjectMaterial, + double tolerance) + : CoProcessor(grid, s), comm(comm), demCoProcessor(demCoProcessor), demObjectMaterial(demObjectMaterial), + tolerance(tolerance) { - mu::Parser fct; - fct.SetExpr("U"); - fct.DefineConst("U", 0.0); - velocityBcParticleAdapter = SPtr<BCAdapter>(new VelocityBCAdapter(true, false, false, fct, 0, BCFunction::INFCONST)); - velocityBcParticleAdapter->setBcAlgorithm(SPtr<BCAlgorithm>(new VelocityWithDensityBCAlgorithm())); - - //const std::shared_ptr<Reconstructor> velocityReconstructor(new VelocityBcReconstructor()); - std::shared_ptr<Reconstructor> equilibriumReconstructor(new EquilibriumReconstructor()); - //const std::shared_ptr<Reconstructor> lbmReconstructor(new LBMReconstructor(false)); - extrapolationReconstructor = SPtr<Reconstructor>(new ExtrapolationReconstructor(equilibriumReconstructor)); - demCounter = 0; + mu::Parser fct; + fct.SetExpr("U"); + fct.DefineConst("U", 0.0); + velocityBcParticleAdapter = + SPtr<BCAdapter>(new VelocityBCAdapter(true, false, false, fct, 0, BCFunction::INFCONST)); + velocityBcParticleAdapter->setBcAlgorithm(SPtr<BCAlgorithm>(new VelocityWithDensityBCAlgorithm())); + + // const std::shared_ptr<Reconstructor> velocityReconstructor(new VelocityBcReconstructor()); + std::shared_ptr<Reconstructor> equilibriumReconstructor(new EquilibriumReconstructor()); + // const std::shared_ptr<Reconstructor> lbmReconstructor(new LBMReconstructor(false)); + extrapolationReconstructor = SPtr<Reconstructor>(new ExtrapolationReconstructor(equilibriumReconstructor)); + demCounter = 0; } ////////////////////////////////////////////////////////////////////////// void CreateDemObjectsCoProcessor::process(double step) { - if (scheduler->isDue(step)) - { - int istep = static_cast<int>(step); - + if (scheduler->isDue(step)) { + int istep = static_cast<int>(step); #ifdef TIMING - if (comm->isRoot()) UBLOG(logINFO, "CreateDemObjectsCoProcessor::process start step: " << istep); - timer.resetAndStart(); + if (comm->isRoot()) + UBLOG(logINFO, "CreateDemObjectsCoProcessor::process start step: " << istep); + timer.resetAndStart(); #endif - - createGeoObjects(); + + createGeoObjects(); #ifdef TIMING -// if (comm->isRoot()) UBLOG(logINFO, "createGeoObjects() time = "<<timer.stop()<<" s"); -// if (comm->isRoot()) UBLOG(logINFO, "number of objects = "<<(int)(geoObjectPrototypeVector.size())); -// if (comm->isRoot()) UBLOG(logINFO, "total number of objects = "<<demCounter); - if (comm->isRoot()) UBLOG(logINFO, "CreateDemObjectsCoProcessor::process stop step: " << istep); + // if (comm->isRoot()) UBLOG(logINFO, "createGeoObjects() time = "<<timer.stop()<<" s"); + // if (comm->isRoot()) UBLOG(logINFO, "number of objects = "<<(int)(geoObjectPrototypeVector.size())); + // if (comm->isRoot()) UBLOG(logINFO, "total number of objects = "<<demCounter); + if (comm->isRoot()) + UBLOG(logINFO, "CreateDemObjectsCoProcessor::process stop step: " << istep); #endif - - //demCoProcessor->distributeIDs(); -//#ifdef TIMING -// if (comm->isRoot()) UBLOG(logINFO, "demCoProcessor->distributeIDs() time = "<<timer.stop()<<" s"); -//#endif + // demCoProcessor->distributeIDs(); - - } + //#ifdef TIMING + // if (comm->isRoot()) UBLOG(logINFO, "demCoProcessor->distributeIDs() time = "<<timer.stop()<<" s"); + //#endif + } } ////////////////////////////////////////////////////////////////////////// -void CreateDemObjectsCoProcessor::addGeoObject(SPtr<GbObject3D> geoObjectPrototype, Vector3D initalVelocity) +void CreateDemObjectsCoProcessor::addGeoObject(SPtr<GbObject3D> geoObjectPrototype, Vector3D initalVelocity) { - geoObjectPrototypeVector.push_back(geoObjectPrototype); - this->initalVelocity.push_back(initalVelocity); + geoObjectPrototypeVector.push_back(geoObjectPrototype); + this->initalVelocity.push_back(initalVelocity); } void CreateDemObjectsCoProcessor::clearGeoObjects() { - geoObjectPrototypeVector.clear(); - initalVelocity.clear(); + geoObjectPrototypeVector.clear(); + initalVelocity.clear(); } void CreateDemObjectsCoProcessor::createGeoObjects() { - int size = (int)(geoObjectPrototypeVector.size()); + int size = (int)(geoObjectPrototypeVector.size()); - std::vector< std::shared_ptr<Block3D> > blockVector; + std::vector<std::shared_ptr<Block3D>> blockVector; - for (int i = 0; i < size; i++) - { - SPtr<GbSphere3D> sphere = std::dynamic_pointer_cast<GbSphere3D>(geoObjectPrototypeVector[i]); - if (demCoProcessor->isSpheresIntersection(sphere->getX1Centroid(), sphere->getX2Centroid(), sphere->getX3Centroid(), sphere->getRadius()*2.0*(1.0-tolerance))) - { - continue; - } + for (int i = 0; i < size; i++) { + SPtr<GbSphere3D> sphere = std::dynamic_pointer_cast<GbSphere3D>(geoObjectPrototypeVector[i]); + if (demCoProcessor->isSpheresIntersection(sphere->getX1Centroid(), sphere->getX2Centroid(), + sphere->getX3Centroid(), + sphere->getRadius() * 2.0 * (1.0 - tolerance))) { + continue; + } - SPtr<GbObject3D> geoObject((GbObject3D*)(geoObjectPrototypeVector[i]->clone())); - SPtr<MovableObjectInteractor> geoObjectInt = SPtr<MovableObjectInteractor>(new MovableObjectInteractor(geoObject, grid, velocityBcParticleAdapter, Interactor3D::SOLID, extrapolationReconstructor, State::UNPIN)); - demCoProcessor->addInteractor(geoObjectInt, demObjectMaterial, initalVelocity[i]); - demCounter++; - } + SPtr<GbObject3D> geoObject((GbObject3D *)(geoObjectPrototypeVector[i]->clone())); + SPtr<MovableObjectInteractor> geoObjectInt = SPtr<MovableObjectInteractor>(new MovableObjectInteractor( + geoObject, grid, velocityBcParticleAdapter, Interactor3D::SOLID, extrapolationReconstructor, State::UNPIN)); + demCoProcessor->addInteractor(geoObjectInt, demObjectMaterial, initalVelocity[i]); + demCounter++; + } #ifdef TIMING - if (comm->isRoot()) UBLOG(logINFO, "createGeoObjects() time = "<<timer.stop()<<" s"); - if (comm->isRoot()) UBLOG(logINFO, "number of objects = "<<(int)(geoObjectPrototypeVector.size())); - if (comm->isRoot()) UBLOG(logINFO, "total number of objects = "<<demCounter); - //if (comm->isRoot()) UBLOG(logINFO, "CreateDemObjectsCoProcessor::process stop step: " << istep); + if (comm->isRoot()) + UBLOG(logINFO, "createGeoObjects() time = " << timer.stop() << " s"); + if (comm->isRoot()) + UBLOG(logINFO, "number of objects = " << (int)(geoObjectPrototypeVector.size())); + if (comm->isRoot()) + UBLOG(logINFO, "total number of objects = " << demCounter); + // if (comm->isRoot()) UBLOG(logINFO, "CreateDemObjectsCoProcessor::process stop step: " << istep); #endif - demCoProcessor->distributeIDs(); + demCoProcessor->distributeIDs(); #ifdef TIMING - if (comm->isRoot()) UBLOG(logINFO, "demCoProcessor->distributeIDs() time = "<<timer.stop()<<" s"); + if (comm->isRoot()) + UBLOG(logINFO, "demCoProcessor->distributeIDs() time = " << timer.stop() << " s"); #endif } - diff --git a/src/cpu/DemCoupling/CreateDemObjectsCoProcessor.h b/src/cpu/DemCoupling/CreateDemObjectsCoProcessor.h index 38ce7c2f583f14a47468af6ac3aa1b6a37220a56..c8ecc6842ee0f77142ad05e5cb90ed71baaa5d64 100644 --- a/src/cpu/DemCoupling/CreateDemObjectsCoProcessor.h +++ b/src/cpu/DemCoupling/CreateDemObjectsCoProcessor.h @@ -3,9 +3,8 @@ #include "CoProcessor.h" #include "Vector3D.h" -#include <vector> #include <array> - +#include <vector> //#define TIMING @@ -13,7 +12,6 @@ #include "UbTiming.h" #endif - class Grid3D; class UbScheduler; class Communicator; @@ -23,30 +21,32 @@ class BCAdapter; class Reconstructor; class PhysicsEngineMaterialAdapter; - class CreateDemObjectsCoProcessor : public CoProcessor { public: - CreateDemObjectsCoProcessor(SPtr<Grid3D> grid, SPtr<UbScheduler> s, std::shared_ptr<Communicator> comm, SPtr<DemCoProcessor> demCoProcessor, SPtr<PhysicsEngineMaterialAdapter> geoObjectMaterial, double tolerance = 0); - void process(double step) override; - void addGeoObject(SPtr<GbObject3D> geoObjectPrototype, Vector3D initalVelocity); - void clearGeoObjects(); - void createGeoObjects(); - double getToleranz() const { return tolerance; } - void setToleranz(double val) { tolerance = val; } + CreateDemObjectsCoProcessor(SPtr<Grid3D> grid, SPtr<UbScheduler> s, std::shared_ptr<Communicator> comm, + SPtr<DemCoProcessor> demCoProcessor, + SPtr<PhysicsEngineMaterialAdapter> geoObjectMaterial, double tolerance = 0); + void process(double step) override; + void addGeoObject(SPtr<GbObject3D> geoObjectPrototype, Vector3D initalVelocity); + void clearGeoObjects(); + void createGeoObjects(); + double getToleranz() const { return tolerance; } + void setToleranz(double val) { tolerance = val; } + protected: private: - SPtr<Communicator> comm; - SPtr<DemCoProcessor> demCoProcessor; - std::vector< SPtr<GbObject3D> > geoObjectPrototypeVector; - SPtr<PhysicsEngineMaterialAdapter> demObjectMaterial; - std::vector<Vector3D> initalVelocity; - SPtr<BCAdapter> velocityBcParticleAdapter; - SPtr<Reconstructor> extrapolationReconstructor; - int demCounter; - double tolerance; + SPtr<Communicator> comm; + SPtr<DemCoProcessor> demCoProcessor; + std::vector<SPtr<GbObject3D>> geoObjectPrototypeVector; + SPtr<PhysicsEngineMaterialAdapter> demObjectMaterial; + std::vector<Vector3D> initalVelocity; + SPtr<BCAdapter> velocityBcParticleAdapter; + SPtr<Reconstructor> extrapolationReconstructor; + int demCounter; + double tolerance; #ifdef TIMING - UbTimer timer; + UbTimer timer; #endif }; #endif // CreateSphereCoProcessor_h__ diff --git a/src/cpu/DemCoupling/DemCoProcessor.cpp b/src/cpu/DemCoupling/DemCoProcessor.cpp index 09deb916534e8ce7fd95ad0446c6b2be69f9ec50..554ffaa6c76f36ad0b5834854c88b8f14864efe8 100644 --- a/src/cpu/DemCoupling/DemCoProcessor.cpp +++ b/src/cpu/DemCoupling/DemCoProcessor.cpp @@ -1,516 +1,515 @@ #include "DemCoProcessor.h" -#include "GbSphere3D.h" -#include "MovableObjectInteractor.h" +#include "BCProcessor.h" #include "Communicator.h" +#include "DataSet3D.h" +#include "DistributionArray3D.h" #include "ForceCalculator.h" +#include "GbSphere3D.h" #include "Grid3D.h" -#include "UbScheduler.h" #include "ILBMKernel.h" -#include "DistributionArray3D.h" -#include "BCProcessor.h" -#include "DataSet3D.h" +#include "MovableObjectInteractor.h" #include "SetBcBlocksBlockVisitor.h" +#include "UbScheduler.h" -#include "PhysicsEngineMaterialAdapter.h" +#include "PePhysicsEngineGeometryAdapter.h" +#include "PePhysicsEngineSolverAdapter.h" #include "PhysicsEngineGeometryAdapter.h" +#include "PhysicsEngineMaterialAdapter.h" #include "PhysicsEngineSolverAdapter.h" -#include "PePhysicsEngineSolverAdapter.h" -#include "PePhysicsEngineGeometryAdapter.h" -#include "BoundaryConditions.h" -#include "Block3D.h" #include "BCArray3D.h" -#include "MPICommunicator.h" +#include "Block3D.h" +#include "BoundaryConditions.h" #include "BoundaryConditionsBlockVisitor.h" +#include "MPICommunicator.h" #include "UbLogger.h" - #include <array> #include <functional> -DemCoProcessor::DemCoProcessor(SPtr<Grid3D> grid, SPtr<UbScheduler> s, SPtr<Communicator> comm, std::shared_ptr<ForceCalculator> forceCalculator, std::shared_ptr<PhysicsEngineSolverAdapter> physicsEngineSolver, double intermediatePeSteps) : - CoProcessor(grid, s), comm(comm), forceCalculator(forceCalculator), physicsEngineSolver(std::dynamic_pointer_cast<PePhysicsEngineSolverAdapter>(physicsEngineSolver)), intermediateDemSteps(intermediatePeSteps) +DemCoProcessor::DemCoProcessor(SPtr<Grid3D> grid, SPtr<UbScheduler> s, SPtr<Communicator> comm, + std::shared_ptr<ForceCalculator> forceCalculator, + std::shared_ptr<PhysicsEngineSolverAdapter> physicsEngineSolver, + double intermediatePeSteps) + : CoProcessor(grid, s), comm(comm), forceCalculator(forceCalculator), + physicsEngineSolver(std::dynamic_pointer_cast<PePhysicsEngineSolverAdapter>(physicsEngineSolver)), + intermediateDemSteps(intermediatePeSteps) { #ifdef TIMING - timer.resetAndStart(); + timer.resetAndStart(); #endif - std::shared_ptr<walberla::blockforest::BlockForest> forest = std::dynamic_pointer_cast<PePhysicsEngineSolverAdapter>(physicsEngineSolver)->getBlockForest(); - std::shared_ptr<walberla::domain_decomposition::BlockDataID> storageId = std::dynamic_pointer_cast<PePhysicsEngineSolverAdapter>(physicsEngineSolver)->getStorageId(); - - - for (auto blockIt = forest->begin(); blockIt != forest->end(); ++blockIt) - { - walberla::pe::Storage* storage = blockIt->getData< walberla::pe::Storage >(*storageId.get()); - walberla::pe::BodyStorage* bodyStorage = &(*storage)[0]; - walberla::pe::BodyStorage* bodyStorageShadowCopies = &(*storage)[1]; - - bodyStorage->registerAddCallback("DemCoProcessor", std::bind1st(std::mem_fun(&DemCoProcessor::addPeGeo), this)); - bodyStorage->registerRemoveCallback("DemCoProcessor", std::bind1st(std::mem_fun(&DemCoProcessor::removePeGeo), this)); - - bodyStorageShadowCopies->registerAddCallback("DemCoProcessor", std::bind1st(std::mem_fun(&DemCoProcessor::addPeShadowGeo), this)); - bodyStorageShadowCopies->registerRemoveCallback("DemCoProcessor", std::bind1st(std::mem_fun(&DemCoProcessor::removePeShadowGeo), this)); - } + std::shared_ptr<walberla::blockforest::BlockForest> forest = + std::dynamic_pointer_cast<PePhysicsEngineSolverAdapter>(physicsEngineSolver)->getBlockForest(); + std::shared_ptr<walberla::domain_decomposition::BlockDataID> storageId = + std::dynamic_pointer_cast<PePhysicsEngineSolverAdapter>(physicsEngineSolver)->getStorageId(); + + for (auto blockIt = forest->begin(); blockIt != forest->end(); ++blockIt) { + walberla::pe::Storage *storage = blockIt->getData<walberla::pe::Storage>(*storageId.get()); + walberla::pe::BodyStorage *bodyStorage = &(*storage)[0]; + walberla::pe::BodyStorage *bodyStorageShadowCopies = &(*storage)[1]; + + bodyStorage->registerAddCallback("DemCoProcessor", std::bind1st(std::mem_fun(&DemCoProcessor::addPeGeo), this)); + bodyStorage->registerRemoveCallback("DemCoProcessor", + std::bind1st(std::mem_fun(&DemCoProcessor::removePeGeo), this)); + + bodyStorageShadowCopies->registerAddCallback("DemCoProcessor", + std::bind1st(std::mem_fun(&DemCoProcessor::addPeShadowGeo), this)); + bodyStorageShadowCopies->registerRemoveCallback( + "DemCoProcessor", std::bind1st(std::mem_fun(&DemCoProcessor::removePeShadowGeo), this)); + } } DemCoProcessor::~DemCoProcessor() { - std::shared_ptr<walberla::blockforest::BlockForest> forest = std::dynamic_pointer_cast<PePhysicsEngineSolverAdapter>(physicsEngineSolver)->getBlockForest(); - std::shared_ptr<walberla::domain_decomposition::BlockDataID> storageId = std::dynamic_pointer_cast<PePhysicsEngineSolverAdapter>(physicsEngineSolver)->getStorageId(); - - for (auto& currentBlock : *forest) - { - walberla::pe::Storage * storage = currentBlock.getData< walberla::pe::Storage >(*storageId.get()); - walberla::pe::BodyStorage& localStorage = (*storage)[0]; - walberla::pe::BodyStorage& shadowStorage = (*storage)[1]; - - localStorage.clearAddCallbacks(); - localStorage.clearRemoveCallbacks(); - - shadowStorage.clearAddCallbacks(); - shadowStorage.clearRemoveCallbacks(); - } + std::shared_ptr<walberla::blockforest::BlockForest> forest = + std::dynamic_pointer_cast<PePhysicsEngineSolverAdapter>(physicsEngineSolver)->getBlockForest(); + std::shared_ptr<walberla::domain_decomposition::BlockDataID> storageId = + std::dynamic_pointer_cast<PePhysicsEngineSolverAdapter>(physicsEngineSolver)->getStorageId(); + + for (auto ¤tBlock : *forest) { + walberla::pe::Storage *storage = currentBlock.getData<walberla::pe::Storage>(*storageId.get()); + walberla::pe::BodyStorage &localStorage = (*storage)[0]; + walberla::pe::BodyStorage &shadowStorage = (*storage)[1]; + + localStorage.clearAddCallbacks(); + localStorage.clearRemoveCallbacks(); + + shadowStorage.clearAddCallbacks(); + shadowStorage.clearRemoveCallbacks(); + } } -void DemCoProcessor::addInteractor(std::shared_ptr<MovableObjectInteractor> interactor, std::shared_ptr<PhysicsEngineMaterialAdapter> physicsEngineMaterial, Vector3D initalVelocity) +void DemCoProcessor::addInteractor(std::shared_ptr<MovableObjectInteractor> interactor, + std::shared_ptr<PhysicsEngineMaterialAdapter> physicsEngineMaterial, + Vector3D initalVelocity) { - interactors.push_back(interactor); - const int id = static_cast<int>(interactors.size()-1); - interactor->setID(id); - const auto peGeometryAdapter = this->createPhysicsEngineGeometryAdapter(interactor, physicsEngineMaterial); - if (std::dynamic_pointer_cast<PePhysicsEngineGeometryAdapter>(peGeometryAdapter)->isActive()) - { - peGeometryAdapter->setLinearVelolocity(initalVelocity); - geoIdMap.insert(std::make_pair(std::dynamic_pointer_cast<PePhysicsEngineGeometryAdapter>(peGeometryAdapter)->getSystemID(), std::dynamic_pointer_cast<PePhysicsEngineGeometryAdapter>(peGeometryAdapter))); - } - SetBcBlocksBlockVisitor setBcVisitor(interactor); - grid->accept(setBcVisitor); - - //std::vector< std::shared_ptr<Block3D> > blockVector; - //UbTupleInt3 blockNX=grid->getBlockNX(); - //SPtr<GbObject3D> geoObject(interactor->getGbObject3D()); - //double ext = 0.0; - //std::array<double, 6> AABB ={ geoObject->getX1Minimum(),geoObject->getX2Minimum(),geoObject->getX3Minimum(),geoObject->getX1Maximum(),geoObject->getX2Maximum(),geoObject->getX3Maximum() }; - //grid->getBlocksByCuboid(AABB[0]-(double)val<1>(blockNX)*ext, AABB[1]-(double)val<2>(blockNX)*ext, AABB[2]-(double)val<3>(blockNX)*ext, AABB[3]+(double)val<1>(blockNX)*ext, AABB[4]+(double)val<2>(blockNX)*ext, AABB[5]+(double)val<3>(blockNX)*ext, blockVector); - //for (std::shared_ptr<Block3D> block : blockVector) - //{ - // if (block->getKernel()) - // { - // interactor->setBCBlock(block); - // //UBLOG(logINFO, "DemCoProcessor::addInteractor() rank = "<<comm->getProcessID()); - // } - //} - - interactor->initInteractor(); - - physicsEngineGeometrieAdapters.push_back(peGeometryAdapter); + interactors.push_back(interactor); + const int id = static_cast<int>(interactors.size() - 1); + interactor->setID(id); + const auto peGeometryAdapter = this->createPhysicsEngineGeometryAdapter(interactor, physicsEngineMaterial); + if (std::dynamic_pointer_cast<PePhysicsEngineGeometryAdapter>(peGeometryAdapter)->isActive()) { + peGeometryAdapter->setLinearVelolocity(initalVelocity); + geoIdMap.insert( + std::make_pair(std::dynamic_pointer_cast<PePhysicsEngineGeometryAdapter>(peGeometryAdapter)->getSystemID(), + std::dynamic_pointer_cast<PePhysicsEngineGeometryAdapter>(peGeometryAdapter))); + } + SetBcBlocksBlockVisitor setBcVisitor(interactor); + grid->accept(setBcVisitor); + + // std::vector< std::shared_ptr<Block3D> > blockVector; + // UbTupleInt3 blockNX=grid->getBlockNX(); + // SPtr<GbObject3D> geoObject(interactor->getGbObject3D()); + // double ext = 0.0; + // std::array<double, 6> AABB ={ + // geoObject->getX1Minimum(),geoObject->getX2Minimum(),geoObject->getX3Minimum(),geoObject->getX1Maximum(),geoObject->getX2Maximum(),geoObject->getX3Maximum() + // }; grid->getBlocksByCuboid(AABB[0]-(double)val<1>(blockNX)*ext, AABB[1]-(double)val<2>(blockNX)*ext, + // AABB[2]-(double)val<3>(blockNX)*ext, AABB[3]+(double)val<1>(blockNX)*ext, AABB[4]+(double)val<2>(blockNX)*ext, + // AABB[5]+(double)val<3>(blockNX)*ext, blockVector); for (std::shared_ptr<Block3D> block : blockVector) + //{ + // if (block->getKernel()) + // { + // interactor->setBCBlock(block); + // //UBLOG(logINFO, "DemCoProcessor::addInteractor() rank = "<<comm->getProcessID()); + // } + //} + + interactor->initInteractor(); + + physicsEngineGeometrieAdapters.push_back(peGeometryAdapter); } - -std::shared_ptr<PhysicsEngineGeometryAdapter> DemCoProcessor::createPhysicsEngineGeometryAdapter(std::shared_ptr<MovableObjectInteractor> interactor, std::shared_ptr<PhysicsEngineMaterialAdapter> physicsEngineMaterial) const +std::shared_ptr<PhysicsEngineGeometryAdapter> DemCoProcessor::createPhysicsEngineGeometryAdapter( + std::shared_ptr<MovableObjectInteractor> interactor, + std::shared_ptr<PhysicsEngineMaterialAdapter> physicsEngineMaterial) const { - const int id = static_cast<int>(interactors.size()-1); - SPtr<GbSphere3D> vfSphere = std::static_pointer_cast<GbSphere3D>(interactor->getGbObject3D()); - const Vector3D position(vfSphere->getX1Centroid(), vfSphere->getX2Centroid(), vfSphere->getX3Centroid()); - auto peGeometryAdapter = this->physicsEngineSolver->createPhysicsEngineGeometryAdapter(id, position, vfSphere->getRadius(), physicsEngineMaterial); - interactor->setPhysicsEngineGeometry(peGeometryAdapter); - return peGeometryAdapter; + const int id = static_cast<int>(interactors.size() - 1); + SPtr<GbSphere3D> vfSphere = std::static_pointer_cast<GbSphere3D>(interactor->getGbObject3D()); + const Vector3D position(vfSphere->getX1Centroid(), vfSphere->getX2Centroid(), vfSphere->getX3Centroid()); + auto peGeometryAdapter = this->physicsEngineSolver->createPhysicsEngineGeometryAdapter( + id, position, vfSphere->getRadius(), physicsEngineMaterial); + interactor->setPhysicsEngineGeometry(peGeometryAdapter); + return peGeometryAdapter; } void DemCoProcessor::process(double actualTimeStep) { #ifdef TIMING - timer.resetAndStart(); + timer.resetAndStart(); #endif - this->applyForcesOnGeometries(); + this->applyForcesOnGeometries(); #ifdef TIMING - if (comm->isRoot()) UBLOG(logINFO, "DemCoProcessor::process start step: " << actualTimeStep); - if (comm->isRoot()) UBLOG(logINFO, "DemCoProcessor::applyForcesOnGeometries() time = "<<timer.stop()<<" s"); + if (comm->isRoot()) + UBLOG(logINFO, "DemCoProcessor::process start step: " << actualTimeStep); + if (comm->isRoot()) + UBLOG(logINFO, "DemCoProcessor::applyForcesOnGeometries() time = " << timer.stop() << " s"); #endif - if (scheduler->isDue(actualTimeStep)) - { - //UBLOG(logINFO, "DemCoProcessor::update - START - timestep = " << actualTimeStep); - const double demTimeStepsPerIteration = scheduler->getMinStep(); + if (scheduler->isDue(actualTimeStep)) { + // UBLOG(logINFO, "DemCoProcessor::update - START - timestep = " << actualTimeStep); + const double demTimeStepsPerIteration = scheduler->getMinStep(); - if (demTimeStepsPerIteration != 1) - this->scaleForcesAndTorques(1.0 / demTimeStepsPerIteration); + if (demTimeStepsPerIteration != 1) + this->scaleForcesAndTorques(1.0 / demTimeStepsPerIteration); #ifdef TIMING - if (comm->isRoot()) UBLOG(logINFO, "DemCoProcessor::scaleForcesAndTorques() time = "<<timer.stop()<<" s"); - if (comm->isRoot()) UBLOG(logINFO, "DemCoProcessor::calculateDemTimeStep():"); + if (comm->isRoot()) + UBLOG(logINFO, "DemCoProcessor::scaleForcesAndTorques() time = " << timer.stop() << " s"); + if (comm->isRoot()) + UBLOG(logINFO, "DemCoProcessor::calculateDemTimeStep():"); #endif - if (this->intermediateDemSteps == 1) - this->calculateDemTimeStep(demTimeStepsPerIteration); - - //#ifdef TIMING - // if (comm->isRoot()) UBLOG(logINFO, "DemCoProcessor::calculateDemTimeStep() time = "<<timer.stop()<<" s"); - //#endif - //if ((int)actualTimeStep % 100 == 0) - //{ - // if (std::dynamic_pointer_cast<PePhysicsEngineGeometryAdapter>(physicsEngineGeometries[0])->isActive()) - // { - // //UBLOG(logINFO, "v: (x,y,z) " << physicsEngineGeometries[0]->getLinearVelocity() << " actualTimeStep = " << UbSystem::toString(actualTimeStep)); - // } - //} - - // during the intermediate time steps of the collision response, the currently acting forces - // (interaction forces, gravitational force, ...) have to remain constant. - // Since they are reset after the call to collision response, they have to be stored explicitly before. - // Then they are set again after each intermediate step. - - this->moveVfGeoObjects(); + if (this->intermediateDemSteps == 1) + this->calculateDemTimeStep(demTimeStepsPerIteration); + + //#ifdef TIMING + // if (comm->isRoot()) UBLOG(logINFO, "DemCoProcessor::calculateDemTimeStep() time = "<<timer.stop()<<" + // s"); + //#endif + // if ((int)actualTimeStep % 100 == 0) + //{ + // if (std::dynamic_pointer_cast<PePhysicsEngineGeometryAdapter>(physicsEngineGeometries[0])->isActive()) + // { + // //UBLOG(logINFO, "v: (x,y,z) " << physicsEngineGeometries[0]->getLinearVelocity() << " actualTimeStep + // = " << UbSystem::toString(actualTimeStep)); + // } + //} + + // during the intermediate time steps of the collision response, the currently acting forces + // (interaction forces, gravitational force, ...) have to remain constant. + // Since they are reset after the call to collision response, they have to be stored explicitly before. + // Then they are set again after each intermediate step. + + this->moveVfGeoObjects(); #ifdef TIMING - if (comm->isRoot()) UBLOG(logINFO, "DemCoProcessor::moveVfGeoObject() time = "<<timer.stop()<<" s"); + if (comm->isRoot()) + UBLOG(logINFO, "DemCoProcessor::moveVfGeoObject() time = " << timer.stop() << " s"); #endif - grid->accept(*boundaryConditionsBlockVisitor.get()); + grid->accept(*boundaryConditionsBlockVisitor.get()); #ifdef TIMING - if (comm->isRoot()) UBLOG(logINFO, "grid->accept(*boundaryConditionsBlockVisitor.get()) time = "<<timer.stop()<<" s"); + if (comm->isRoot()) + UBLOG(logINFO, "grid->accept(*boundaryConditionsBlockVisitor.get()) time = " << timer.stop() << " s"); #endif - //UBLOG(logINFO, "DemCoProcessor::update - END - timestep = " << actualTimeStep); - } + // UBLOG(logINFO, "DemCoProcessor::update - END - timestep = " << actualTimeStep); + } #ifdef TIMING - if (comm->isRoot()) UBLOG(logINFO, "DemCoProcessor::process stop step: " << actualTimeStep); + if (comm->isRoot()) + UBLOG(logINFO, "DemCoProcessor::process stop step: " << actualTimeStep); #endif } ////////////////////////////////////////////////////////////////////////// -std::shared_ptr<PhysicsEngineSolverAdapter> DemCoProcessor::getPhysicsEngineSolver() -{ - return physicsEngineSolver; -} +std::shared_ptr<PhysicsEngineSolverAdapter> DemCoProcessor::getPhysicsEngineSolver() { return physicsEngineSolver; } void DemCoProcessor::applyForcesOnGeometries() { - for (int i = 0; i < physicsEngineGeometrieAdapters.size(); i++) - { - if (std::dynamic_pointer_cast<PePhysicsEngineGeometryAdapter>(physicsEngineGeometrieAdapters[i])->isActive()) - { - this->setForcesToObject(grid, interactors[i], physicsEngineGeometrieAdapters[i]); - - //physicsEngineGeometries[i]->setLinearVelolocity(Vector3D(-0.001, 0.0, 0.0)); - //physicsEngineGeometries[i]->setAngularVelocity(Vector3D(0.01, 0.01, 0.01)); - //UBLOG(logINFO, "v: (x,y,z) " << physicsEngineGeometries[i]->getLinearVelocity()); - } - } + for (int i = 0; i < physicsEngineGeometrieAdapters.size(); i++) { + if (std::dynamic_pointer_cast<PePhysicsEngineGeometryAdapter>(physicsEngineGeometrieAdapters[i])->isActive()) { + this->setForcesToObject(grid, interactors[i], physicsEngineGeometrieAdapters[i]); + + // physicsEngineGeometries[i]->setLinearVelolocity(Vector3D(-0.001, 0.0, 0.0)); + // physicsEngineGeometries[i]->setAngularVelocity(Vector3D(0.01, 0.01, 0.01)); + // UBLOG(logINFO, "v: (x,y,z) " << physicsEngineGeometries[i]->getLinearVelocity()); + } + } } -void DemCoProcessor::setForcesToObject(SPtr<Grid3D> grid, SPtr<MovableObjectInteractor> interactor, std::shared_ptr<PhysicsEngineGeometryAdapter> physicsEngineGeometry) +void DemCoProcessor::setForcesToObject(SPtr<Grid3D> grid, SPtr<MovableObjectInteractor> interactor, + std::shared_ptr<PhysicsEngineGeometryAdapter> physicsEngineGeometry) { - for (BcNodeIndicesMap::value_type t : interactor->getBcNodeIndicesMap()) - { - SPtr<Block3D> block = t.first; - SPtr<ILBMKernel> kernel = block->getKernel(); - SPtr<BCArray3D> bcArray = kernel->getBCProcessor()->getBCArray(); - SPtr<DistributionArray3D> distributions = kernel->getDataSet()->getFdistributions(); - distributions->swap(); - - std::set< std::vector<int> >& transNodeIndicesSet = t.second; - for (std::vector<int> node : transNodeIndicesSet) - { - int x1 = node[0]; - int x2 = node[1]; - int x3 = node[2]; - - if (kernel->isInsideOfDomain(x1, x2, x3) && bcArray->isFluid(x1, x2, x3)) - { - //TODO: calculate assumed boundary position - - const Vector3D worldCoordinates = grid->getNodeCoordinates(block, x1, x2, x3); - const auto boundaryVelocity = physicsEngineGeometry->getVelocityAtPosition(worldCoordinates); - - SPtr<BoundaryConditions> bc = bcArray->getBC(x1, x2, x3); - const Vector3D force = forceCalculator->getForces(x1, x2, x3, distributions, bc, boundaryVelocity); - physicsEngineGeometry->addForceAtPosition(force, worldCoordinates); - } - } - distributions->swap(); - } + for (BcNodeIndicesMap::value_type t : interactor->getBcNodeIndicesMap()) { + SPtr<Block3D> block = t.first; + SPtr<ILBMKernel> kernel = block->getKernel(); + SPtr<BCArray3D> bcArray = kernel->getBCProcessor()->getBCArray(); + SPtr<DistributionArray3D> distributions = kernel->getDataSet()->getFdistributions(); + distributions->swap(); + + std::set<std::vector<int>> &transNodeIndicesSet = t.second; + for (std::vector<int> node : transNodeIndicesSet) { + int x1 = node[0]; + int x2 = node[1]; + int x3 = node[2]; + + if (kernel->isInsideOfDomain(x1, x2, x3) && bcArray->isFluid(x1, x2, x3)) { + // TODO: calculate assumed boundary position + + const Vector3D worldCoordinates = grid->getNodeCoordinates(block, x1, x2, x3); + const auto boundaryVelocity = physicsEngineGeometry->getVelocityAtPosition(worldCoordinates); + + SPtr<BoundaryConditions> bc = bcArray->getBC(x1, x2, x3); + const Vector3D force = forceCalculator->getForces(x1, x2, x3, distributions, bc, boundaryVelocity); + physicsEngineGeometry->addForceAtPosition(force, worldCoordinates); + } + } + distributions->swap(); + } } - void DemCoProcessor::scaleForcesAndTorques(double scalingFactor) { - for (int i = 0; i < physicsEngineGeometrieAdapters.size(); i++) - { - if (std::dynamic_pointer_cast<PePhysicsEngineGeometryAdapter>(physicsEngineGeometrieAdapters[i])->isActive()) - { - const Vector3D force = physicsEngineGeometrieAdapters[i]->getForce() * scalingFactor; - const Vector3D torque = physicsEngineGeometrieAdapters[i]->getTorque() * scalingFactor; - - physicsEngineGeometrieAdapters[i]->resetForceAndTorque(); - - physicsEngineGeometrieAdapters[i]->setForce(force); - physicsEngineGeometrieAdapters[i]->setTorque(torque); - - //UBLOG(logINFO, "F: (x,y,z) " << force); - //UBLOG(logINFO, "T: (x,y,z) " << torque); - } - } -} + for (int i = 0; i < physicsEngineGeometrieAdapters.size(); i++) { + if (std::dynamic_pointer_cast<PePhysicsEngineGeometryAdapter>(physicsEngineGeometrieAdapters[i])->isActive()) { + const Vector3D force = physicsEngineGeometrieAdapters[i]->getForce() * scalingFactor; + const Vector3D torque = physicsEngineGeometrieAdapters[i]->getTorque() * scalingFactor; + + physicsEngineGeometrieAdapters[i]->resetForceAndTorque(); + physicsEngineGeometrieAdapters[i]->setForce(force); + physicsEngineGeometrieAdapters[i]->setTorque(torque); + + // UBLOG(logINFO, "F: (x,y,z) " << force); + // UBLOG(logINFO, "T: (x,y,z) " << torque); + } + } +} void DemCoProcessor::calculateDemTimeStep(double step) { - physicsEngineSolver->runTimestep(step); + physicsEngineSolver->runTimestep(step); #ifdef TIMING - if (comm->isRoot()) UBLOG(logINFO, " physicsEngineSolver->runTimestep() time = "<< timer.stop() <<" s"); + if (comm->isRoot()) + UBLOG(logINFO, " physicsEngineSolver->runTimestep() time = " << timer.stop() << " s"); #endif } void DemCoProcessor::moveVfGeoObjects() { - for (int i = 0; i < interactors.size(); i++) - { - if (std::dynamic_pointer_cast<PePhysicsEngineGeometryAdapter>(physicsEngineGeometrieAdapters[i])->isActive()) - { - if (std::dynamic_pointer_cast<PePhysicsEngineGeometryAdapter>(physicsEngineGeometrieAdapters[i])->getSemiactive()) - { - walberla::pe::RigidBody* peGeoObject = getPeGeoObject(std::dynamic_pointer_cast<PePhysicsEngineGeometryAdapter>(physicsEngineGeometrieAdapters[i])->getSystemID()); - if (peGeoObject != nullptr) - { - std::dynamic_pointer_cast<PePhysicsEngineGeometryAdapter>(physicsEngineGeometrieAdapters[i])->setGeometry(peGeoObject); - interactors[i]->moveGbObjectTo(physicsEngineGeometrieAdapters[i]->getPosition()); - std::dynamic_pointer_cast<PePhysicsEngineGeometryAdapter>(physicsEngineGeometrieAdapters[i])->setSemiactive(false); - } - else - { - std::dynamic_pointer_cast<PePhysicsEngineGeometryAdapter>(physicsEngineGeometrieAdapters[i])->setInactive(); + for (int i = 0; i < interactors.size(); i++) { + if (std::dynamic_pointer_cast<PePhysicsEngineGeometryAdapter>(physicsEngineGeometrieAdapters[i])->isActive()) { + if (std::dynamic_pointer_cast<PePhysicsEngineGeometryAdapter>(physicsEngineGeometrieAdapters[i]) + ->getSemiactive()) { + walberla::pe::RigidBody *peGeoObject = getPeGeoObject( + std::dynamic_pointer_cast<PePhysicsEngineGeometryAdapter>(physicsEngineGeometrieAdapters[i]) + ->getSystemID()); + if (peGeoObject != nullptr) { + std::dynamic_pointer_cast<PePhysicsEngineGeometryAdapter>(physicsEngineGeometrieAdapters[i]) + ->setGeometry(peGeoObject); + interactors[i]->moveGbObjectTo(physicsEngineGeometrieAdapters[i]->getPosition()); + std::dynamic_pointer_cast<PePhysicsEngineGeometryAdapter>(physicsEngineGeometrieAdapters[i]) + ->setSemiactive(false); + } else { + std::dynamic_pointer_cast<PePhysicsEngineGeometryAdapter>(physicsEngineGeometrieAdapters[i]) + ->setInactive(); + } + } else { + interactors[i]->moveGbObjectTo(physicsEngineGeometrieAdapters[i]->getPosition()); } - } - else - { - interactors[i]->moveGbObjectTo(physicsEngineGeometrieAdapters[i]->getPosition()); - } - } - } + } + } } -bool DemCoProcessor::isDemObjectInAABB(std::array<double, 6> AABB) +bool DemCoProcessor::isDemObjectInAABB(std::array<double, 6> AABB) { - bool result = false; - for (int i = 0; i < interactors.size(); i++) - { - if (std::dynamic_pointer_cast<PePhysicsEngineGeometryAdapter>(physicsEngineGeometrieAdapters[i])->isActive()) - { - SPtr<GbObject3D> geoObject = interactors[i]->getGbObject3D(); - std::array <double, 2> minMax1; - std::array <double, 2> minMax2; - std::array <double, 2> minMax3; - minMax1[0] = geoObject->getX1Minimum(); - minMax2[0] = geoObject->getX2Minimum(); - minMax3[0] = geoObject->getX3Minimum(); - minMax1[1] = geoObject->getX1Maximum(); - minMax2[1] = geoObject->getX2Maximum(); - minMax3[1] = geoObject->getX3Maximum(); - - for (int x3 = 0; x3 < 2; x3++) - for (int x2 = 0; x2 < 2; x2++) - for (int x1 = 0; x1 < 2; x1++) - { - result = result || (minMax1[x1] >= AABB[0] && minMax2[x2] >= AABB[1] && minMax3[x3] >= AABB[2] && minMax1[x1] <= AABB[3] && minMax2[x2] <= AABB[4] && minMax3[x3] <= AABB[5]); - } - } - } - - std::vector<int> values; - values.push_back((int)result); - std::vector<int> rvalues = comm->gather(values); - - if (comm->isRoot()) - { - for (int i = 0; i < (int)rvalues.size(); i++) - { - result = result || (bool)rvalues[i]; - } - } - int iresult = (int)result; - comm->broadcast(iresult); - result = (bool)iresult; - - return result; + bool result = false; + for (int i = 0; i < interactors.size(); i++) { + if (std::dynamic_pointer_cast<PePhysicsEngineGeometryAdapter>(physicsEngineGeometrieAdapters[i])->isActive()) { + SPtr<GbObject3D> geoObject = interactors[i]->getGbObject3D(); + std::array<double, 2> minMax1; + std::array<double, 2> minMax2; + std::array<double, 2> minMax3; + minMax1[0] = geoObject->getX1Minimum(); + minMax2[0] = geoObject->getX2Minimum(); + minMax3[0] = geoObject->getX3Minimum(); + minMax1[1] = geoObject->getX1Maximum(); + minMax2[1] = geoObject->getX2Maximum(); + minMax3[1] = geoObject->getX3Maximum(); + + for (int x3 = 0; x3 < 2; x3++) + for (int x2 = 0; x2 < 2; x2++) + for (int x1 = 0; x1 < 2; x1++) { + result = + result || (minMax1[x1] >= AABB[0] && minMax2[x2] >= AABB[1] && minMax3[x3] >= AABB[2] && + minMax1[x1] <= AABB[3] && minMax2[x2] <= AABB[4] && minMax3[x3] <= AABB[5]); + } + } + } + + std::vector<int> values; + values.push_back((int)result); + std::vector<int> rvalues = comm->gather(values); + + if (comm->isRoot()) { + for (int i = 0; i < (int)rvalues.size(); i++) { + result = result || (bool)rvalues[i]; + } + } + int iresult = (int)result; + comm->broadcast(iresult); + result = (bool)iresult; + + return result; } -int DemCoProcessor::addSurfaceTriangleSet(std::vector<UbTupleFloat3>& nodes, std::vector<UbTupleInt3>& triangles) +int DemCoProcessor::addSurfaceTriangleSet(std::vector<UbTupleFloat3> &nodes, std::vector<UbTupleInt3> &triangles) { - for (int i = 0; i < interactors.size(); i++) - { - if (std::dynamic_pointer_cast<PePhysicsEngineGeometryAdapter>(physicsEngineGeometrieAdapters[i])->isActive()) - { - interactors[i]->getGbObject3D()->addSurfaceTriangleSet(nodes, triangles); - } - } - return (int)interactors.size(); + for (int i = 0; i < interactors.size(); i++) { + if (std::dynamic_pointer_cast<PePhysicsEngineGeometryAdapter>(physicsEngineGeometrieAdapters[i])->isActive()) { + interactors[i]->getGbObject3D()->addSurfaceTriangleSet(nodes, triangles); + } + } + return (int)interactors.size(); } -void DemCoProcessor::getObjectsPropertiesVector(std::vector<double>& p) +void DemCoProcessor::getObjectsPropertiesVector(std::vector<double> &p) { - for (int i = 0; i < interactors.size(); i++) - { - if (std::dynamic_pointer_cast<PePhysicsEngineGeometryAdapter>(physicsEngineGeometrieAdapters[i])->isActive()) - { - p.push_back(i); - p.push_back(interactors[i]->getGbObject3D()->getX1Centroid()); - p.push_back(interactors[i]->getGbObject3D()->getX2Centroid()); - p.push_back(interactors[i]->getGbObject3D()->getX3Centroid()); - Vector3D v = physicsEngineGeometrieAdapters[i]->getLinearVelocity(); - p.push_back(v[0]); - p.push_back(v[1]); - p.push_back(v[2]); - } - } + for (int i = 0; i < interactors.size(); i++) { + if (std::dynamic_pointer_cast<PePhysicsEngineGeometryAdapter>(physicsEngineGeometrieAdapters[i])->isActive()) { + p.push_back(i); + p.push_back(interactors[i]->getGbObject3D()->getX1Centroid()); + p.push_back(interactors[i]->getGbObject3D()->getX2Centroid()); + p.push_back(interactors[i]->getGbObject3D()->getX3Centroid()); + Vector3D v = physicsEngineGeometrieAdapters[i]->getLinearVelocity(); + p.push_back(v[0]); + p.push_back(v[1]); + p.push_back(v[2]); + } + } } -void DemCoProcessor::addPeGeo(walberla::pe::RigidBody * peGeo) +void DemCoProcessor::addPeGeo(walberla::pe::RigidBody *peGeo) { - auto geometry = getPeGeoAdapter(peGeo->getSystemID()); - if (geometry != nullptr) - { - geometry->setActive(); - geometry->setGeometry(peGeo); - return; - } - else - return; + auto geometry = getPeGeoAdapter(peGeo->getSystemID()); + if (geometry != nullptr) { + geometry->setActive(); + geometry->setGeometry(peGeo); + return; + } else + return; } -void DemCoProcessor::removePeGeo(walberla::pe::RigidBody * peGeo) +void DemCoProcessor::removePeGeo(walberla::pe::RigidBody *peGeo) { - auto geometry = getPeGeoAdapter(peGeo->getSystemID()); - if (geometry != nullptr) - { - geometry->setSemiactive(true); - } - else - throw UbException(UB_EXARGS, "PeGeo SystemId="+UbSystem::toString(peGeo->getSystemID())+" is not matching geometry ID"); + auto geometry = getPeGeoAdapter(peGeo->getSystemID()); + if (geometry != nullptr) { + geometry->setSemiactive(true); + } else + throw UbException(UB_EXARGS, "PeGeo SystemId=" + UbSystem::toString(peGeo->getSystemID()) + + " is not matching geometry ID"); } -void DemCoProcessor::addPeShadowGeo(walberla::pe::RigidBody * peGeo) +void DemCoProcessor::addPeShadowGeo(walberla::pe::RigidBody *peGeo) { - auto geometry = getPeGeoAdapter(peGeo->getSystemID()); - if (geometry != nullptr) - { - geometry->setActive(); - geometry->setGeometry(peGeo); - return; - } - else - throw UbException(UB_EXARGS, "PeGeo ID="+UbSystem::toString(peGeo->getSystemID())+" is not matching geometry ID"); + auto geometry = getPeGeoAdapter(peGeo->getSystemID()); + if (geometry != nullptr) { + geometry->setActive(); + geometry->setGeometry(peGeo); + return; + } else + throw UbException(UB_EXARGS, + "PeGeo ID=" + UbSystem::toString(peGeo->getSystemID()) + " is not matching geometry ID"); } -void DemCoProcessor::removePeShadowGeo(walberla::pe::RigidBody * peGeo) +void DemCoProcessor::removePeShadowGeo(walberla::pe::RigidBody *peGeo) { - auto geometry = getPeGeoAdapter(peGeo->getSystemID()); - - if (geometry != nullptr) - { - geometry->setSemiactive(true); - } - else - throw UbException(UB_EXARGS, "PeGeo ID="+UbSystem::toString(peGeo->getSystemID())+" is not matching geometry ID"); + auto geometry = getPeGeoAdapter(peGeo->getSystemID()); + + if (geometry != nullptr) { + geometry->setSemiactive(true); + } else + throw UbException(UB_EXARGS, + "PeGeo ID=" + UbSystem::toString(peGeo->getSystemID()) + " is not matching geometry ID"); } bool DemCoProcessor::isSpheresIntersection(double centerX1, double centerX2, double centerX3, double d) { - bool result = false; - for (int i = 0; i < interactors.size(); i++) - { - if (std::dynamic_pointer_cast<PePhysicsEngineGeometryAdapter>(physicsEngineGeometrieAdapters[i])->isActive()) - { - SPtr<GbObject3D> sphere = interactors[i]->getGbObject3D(); - result = result || (sqrt(pow(sphere->getX1Centroid()-centerX1, 2.0)+pow(sphere->getX2Centroid()-centerX2, 2.0)+pow(sphere->getX3Centroid()-centerX3, 2.0)) <= d); - } - } - std::vector<int> values; - values.push_back((int)result); - std::vector<int> rvalues = comm->gather(values); - - if (comm->isRoot()) - { - for (int i = 0; i < (int)rvalues.size(); i++) - { - result = result || (bool)rvalues[i]; - } - } - int iresult = (int)result; - comm->broadcast(iresult); - result = (bool)iresult; - - return result; + bool result = false; + for (int i = 0; i < interactors.size(); i++) { + if (std::dynamic_pointer_cast<PePhysicsEngineGeometryAdapter>(physicsEngineGeometrieAdapters[i])->isActive()) { + SPtr<GbObject3D> sphere = interactors[i]->getGbObject3D(); + result = result || + (sqrt(pow(sphere->getX1Centroid() - centerX1, 2.0) + pow(sphere->getX2Centroid() - centerX2, 2.0) + + pow(sphere->getX3Centroid() - centerX3, 2.0)) <= d); + } + } + std::vector<int> values; + values.push_back((int)result); + std::vector<int> rvalues = comm->gather(values); + + if (comm->isRoot()) { + for (int i = 0; i < (int)rvalues.size(); i++) { + result = result || (bool)rvalues[i]; + } + } + int iresult = (int)result; + comm->broadcast(iresult); + result = (bool)iresult; + + return result; } void DemCoProcessor::distributeIDs() { - std::vector<unsigned long long> peIDsSend; - std::vector<int> vfIDsSend; - - for (int i = 0; i < interactors.size(); i++) - { - if (std::dynamic_pointer_cast<PePhysicsEngineGeometryAdapter>(physicsEngineGeometrieAdapters[i])->isActive()) - { - peIDsSend.push_back(std::dynamic_pointer_cast<PePhysicsEngineGeometryAdapter>(physicsEngineGeometrieAdapters[i])->getSystemID()); - vfIDsSend.push_back(interactors[i]->getID()); - } - } - - std::vector<unsigned long long> peIDsRecv; - std::vector<int> vfIDsRecv; - - comm->allGather(peIDsSend, peIDsRecv); - comm->allGather(vfIDsSend, vfIDsRecv); - - std::map<int, unsigned long long> idMap; - - for (int i = 0; i < peIDsRecv.size(); i++) - { - idMap.insert(std::make_pair(vfIDsRecv[i], peIDsRecv[i])); - } - - for (int i = 0; i < interactors.size(); i++) - { - std::map<int, unsigned long long>::const_iterator it; - if ((it=idMap.find(interactors[i]->getID())) == idMap.end()) - { - throw UbException(UB_EXARGS, "Interactor ID = "+UbSystem::toString(interactors[i]->getID())+" is invalid! The DEM object may be not in PE domain!"); - } - - std::dynamic_pointer_cast<PePhysicsEngineGeometryAdapter>(physicsEngineGeometrieAdapters[i])->setSystemID(it->second); - - geoIdMap.insert(std::make_pair(it->second, std::dynamic_pointer_cast<PePhysicsEngineGeometryAdapter>(physicsEngineGeometrieAdapters[i]))); - } + std::vector<unsigned long long> peIDsSend; + std::vector<int> vfIDsSend; + + for (int i = 0; i < interactors.size(); i++) { + if (std::dynamic_pointer_cast<PePhysicsEngineGeometryAdapter>(physicsEngineGeometrieAdapters[i])->isActive()) { + peIDsSend.push_back( + std::dynamic_pointer_cast<PePhysicsEngineGeometryAdapter>(physicsEngineGeometrieAdapters[i]) + ->getSystemID()); + vfIDsSend.push_back(interactors[i]->getID()); + } + } + + std::vector<unsigned long long> peIDsRecv; + std::vector<int> vfIDsRecv; + + comm->allGather(peIDsSend, peIDsRecv); + comm->allGather(vfIDsSend, vfIDsRecv); + + std::map<int, unsigned long long> idMap; + + for (int i = 0; i < peIDsRecv.size(); i++) { + idMap.insert(std::make_pair(vfIDsRecv[i], peIDsRecv[i])); + } + + for (int i = 0; i < interactors.size(); i++) { + std::map<int, unsigned long long>::const_iterator it; + if ((it = idMap.find(interactors[i]->getID())) == idMap.end()) { + throw UbException(UB_EXARGS, "Interactor ID = " + UbSystem::toString(interactors[i]->getID()) + + " is invalid! The DEM object may be not in PE domain!"); + } + + std::dynamic_pointer_cast<PePhysicsEngineGeometryAdapter>(physicsEngineGeometrieAdapters[i]) + ->setSystemID(it->second); + + geoIdMap.insert(std::make_pair( + it->second, std::dynamic_pointer_cast<PePhysicsEngineGeometryAdapter>(physicsEngineGeometrieAdapters[i]))); + } } ////////////////////////////////////////////////////////////////////////// void DemCoProcessor::setBlockVisitor(std::shared_ptr<BoundaryConditionsBlockVisitor> boundaryConditionsBlockVisitor) { - this->boundaryConditionsBlockVisitor = boundaryConditionsBlockVisitor; + this->boundaryConditionsBlockVisitor = boundaryConditionsBlockVisitor; } ////////////////////////////////////////////////////////////////////////// -walberla::pe::RigidBody* DemCoProcessor::getPeGeoObject(walberla::id_t id) +walberla::pe::RigidBody *DemCoProcessor::getPeGeoObject(walberla::id_t id) { - std::shared_ptr<walberla::blockforest::BlockForest> forest = std::dynamic_pointer_cast<PePhysicsEngineSolverAdapter>(physicsEngineSolver)->getBlockForest(); - std::shared_ptr<walberla::domain_decomposition::BlockDataID> storageId = std::dynamic_pointer_cast<PePhysicsEngineSolverAdapter>(physicsEngineSolver)->getStorageId(); - std::shared_ptr<walberla::pe::BodyStorage> globalBodyStorage = std::dynamic_pointer_cast<PePhysicsEngineSolverAdapter>(physicsEngineSolver)->getGlobalBodyStorage(); - - return walberla::pe::getBody(*globalBodyStorage, *forest, *storageId, id, walberla::pe::StorageSelect::LOCAL | walberla::pe::StorageSelect::SHADOW); + std::shared_ptr<walberla::blockforest::BlockForest> forest = + std::dynamic_pointer_cast<PePhysicsEngineSolverAdapter>(physicsEngineSolver)->getBlockForest(); + std::shared_ptr<walberla::domain_decomposition::BlockDataID> storageId = + std::dynamic_pointer_cast<PePhysicsEngineSolverAdapter>(physicsEngineSolver)->getStorageId(); + std::shared_ptr<walberla::pe::BodyStorage> globalBodyStorage = + std::dynamic_pointer_cast<PePhysicsEngineSolverAdapter>(physicsEngineSolver)->getGlobalBodyStorage(); + + return walberla::pe::getBody(*globalBodyStorage, *forest, *storageId, id, + walberla::pe::StorageSelect::LOCAL | walberla::pe::StorageSelect::SHADOW); } //////////////////////////////////////////////////////////////////////////// std::shared_ptr<PePhysicsEngineGeometryAdapter> DemCoProcessor::getPeGeoAdapter(unsigned long long systemId) { - std::map< unsigned long long, std::shared_ptr<PePhysicsEngineGeometryAdapter> >::const_iterator it; - if ((it=geoIdMap.find(systemId)) == geoIdMap.end()) - { - return nullptr; - } - else - return it->second; + std::map<unsigned long long, std::shared_ptr<PePhysicsEngineGeometryAdapter>>::const_iterator it; + if ((it = geoIdMap.find(systemId)) == geoIdMap.end()) { + return nullptr; + } else + return it->second; } diff --git a/src/cpu/DemCoupling/DemCoProcessor.h b/src/cpu/DemCoupling/DemCoProcessor.h index 74718a91191952da928fbf9f5d83e815024d4398..64fe2436128cb6eb5aabe118785213d1212ca296 100644 --- a/src/cpu/DemCoupling/DemCoProcessor.h +++ b/src/cpu/DemCoupling/DemCoProcessor.h @@ -5,9 +5,9 @@ #ifndef DEM_CO_PROCESSOR_H #define DEM_CO_PROCESSOR_H +#include <map> #include <memory> #include <vector> -#include <map> #include "Vector3D.h" @@ -19,9 +19,8 @@ //#define TIMING #ifdef TIMING - #include "UbTiming.h" +#include "UbTiming.h" #endif - class PhysicsEngineGeometryAdapter; class PhysicsEngineSolverAdapter; @@ -37,54 +36,60 @@ class MovableObjectInteractor; class Communicator; class BoundaryConditionsBlockVisitor; - class DemCoProcessor : public CoProcessor { public: - DemCoProcessor(std::shared_ptr<Grid3D> grid, std::shared_ptr<UbScheduler> s, std::shared_ptr<Communicator> comm, std::shared_ptr<ForceCalculator> forceCalculator, std::shared_ptr<PhysicsEngineSolverAdapter> physicsEngineSolver, double intermediatePeSteps = 1.0); + DemCoProcessor(std::shared_ptr<Grid3D> grid, std::shared_ptr<UbScheduler> s, std::shared_ptr<Communicator> comm, + std::shared_ptr<ForceCalculator> forceCalculator, + std::shared_ptr<PhysicsEngineSolverAdapter> physicsEngineSolver, double intermediatePeSteps = 1.0); virtual ~DemCoProcessor(); - void addInteractor(std::shared_ptr<MovableObjectInteractor> interactor, std::shared_ptr<PhysicsEngineMaterialAdapter> physicsEngineMaterial, Vector3D initalVelocity = Vector3D(0.0, 0.0, 0.0)); + void addInteractor(std::shared_ptr<MovableObjectInteractor> interactor, + std::shared_ptr<PhysicsEngineMaterialAdapter> physicsEngineMaterial, + Vector3D initalVelocity = Vector3D(0.0, 0.0, 0.0)); void process(double step) override; std::shared_ptr<PhysicsEngineSolverAdapter> getPhysicsEngineSolver(); void distributeIDs(); void setBlockVisitor(std::shared_ptr<BoundaryConditionsBlockVisitor> blockVisitor); - bool isDemObjectInAABB(std::array<double,6> AABB); - int addSurfaceTriangleSet(std::vector<UbTupleFloat3>& nodes, std::vector<UbTupleInt3>& triangles); - void getObjectsPropertiesVector(std::vector<double>& p); - void addPeGeo(walberla::pe::RigidBody* peGeo); - void removePeGeo(walberla::pe::RigidBody* peGeo); - void addPeShadowGeo(walberla::pe::RigidBody* peGeo); - void removePeShadowGeo(walberla::pe::RigidBody* peGeo); + bool isDemObjectInAABB(std::array<double, 6> AABB); + int addSurfaceTriangleSet(std::vector<UbTupleFloat3> &nodes, std::vector<UbTupleInt3> &triangles); + void getObjectsPropertiesVector(std::vector<double> &p); + void addPeGeo(walberla::pe::RigidBody *peGeo); + void removePeGeo(walberla::pe::RigidBody *peGeo); + void addPeShadowGeo(walberla::pe::RigidBody *peGeo); + void removePeShadowGeo(walberla::pe::RigidBody *peGeo); bool isSpheresIntersection(double centerX1, double centerX2, double centerX3, double d); - + private: - std::shared_ptr<PhysicsEngineGeometryAdapter> createPhysicsEngineGeometryAdapter(std::shared_ptr<MovableObjectInteractor> interactor, std::shared_ptr<PhysicsEngineMaterialAdapter> physicsEngineMaterial) const; + std::shared_ptr<PhysicsEngineGeometryAdapter> + createPhysicsEngineGeometryAdapter(std::shared_ptr<MovableObjectInteractor> interactor, + std::shared_ptr<PhysicsEngineMaterialAdapter> physicsEngineMaterial) const; void applyForcesOnGeometries(); - void setForcesToObject(SPtr<Grid3D> grid, std::shared_ptr<MovableObjectInteractor> interactor, std::shared_ptr<PhysicsEngineGeometryAdapter> physicsEngineGeometry); + void setForcesToObject(SPtr<Grid3D> grid, std::shared_ptr<MovableObjectInteractor> interactor, + std::shared_ptr<PhysicsEngineGeometryAdapter> physicsEngineGeometry); void scaleForcesAndTorques(double scalingFactor); void calculateDemTimeStep(double step); void moveVfGeoObjects(); - walberla::pe::RigidBody* getPeGeoObject(walberla::id_t id); + walberla::pe::RigidBody *getPeGeoObject(walberla::id_t id); std::shared_ptr<PePhysicsEngineGeometryAdapter> getPeGeoAdapter(unsigned long long systemId); + private: std::shared_ptr<Communicator> comm; - std::vector<std::shared_ptr<MovableObjectInteractor> > interactors; + std::vector<std::shared_ptr<MovableObjectInteractor>> interactors; std::shared_ptr<ForceCalculator> forceCalculator; std::shared_ptr<PePhysicsEngineSolverAdapter> physicsEngineSolver; - std::vector<std::shared_ptr<PhysicsEngineGeometryAdapter> > physicsEngineGeometrieAdapters; + std::vector<std::shared_ptr<PhysicsEngineGeometryAdapter>> physicsEngineGeometrieAdapters; double intermediateDemSteps; SPtr<BoundaryConditionsBlockVisitor> boundaryConditionsBlockVisitor; - //walberla::pe::BodyStorage* bodyStorage; //!< Reference to the central body storage. - //walberla::pe::BodyStorage* bodyStorageShadowCopies; //!< Reference to the body storage containing body shadow copies. + // walberla::pe::BodyStorage* bodyStorage; //!< Reference to the central body storage. + // walberla::pe::BodyStorage* bodyStorageShadowCopies; //!< Reference to the body storage containing body shadow + // copies. - std::map< unsigned long long, std::shared_ptr<PePhysicsEngineGeometryAdapter> > geoIdMap; + std::map<unsigned long long, std::shared_ptr<PePhysicsEngineGeometryAdapter>> geoIdMap; #ifdef TIMING UbTimer timer; #endif }; - #endif - diff --git a/src/cpu/DemCoupling/MovableObjectInteractor.cpp b/src/cpu/DemCoupling/MovableObjectInteractor.cpp index 49a9ece51edaf75989aaaccdc07a18118478d00c..17185c8bb1cdfedfca1d76fa799cc0810a3fb43d 100644 --- a/src/cpu/DemCoupling/MovableObjectInteractor.cpp +++ b/src/cpu/DemCoupling/MovableObjectInteractor.cpp @@ -1,19 +1,19 @@ #include "MovableObjectInteractor.h" -#include "UbLogger.h" #include "GbObject3D.h" +#include "UbLogger.h" #include "Vector3D.h" -#include "Block3D.h" -#include "Grid3D.h" -#include "BCArray3D.h" #include "BCAdapter.h" +#include "BCArray3D.h" #include "BCProcessor.h" -#include "ILBMKernel.h" +#include "Block3D.h" #include "CoordinateTransformation3D.h" +#include "Grid3D.h" +#include "ILBMKernel.h" -#include "SetBcBlocksBlockVisitor.h" #include "BoundaryConditionsBlockVisitor.h" +#include "SetBcBlocksBlockVisitor.h" #include "PhysicsEngineGeometryAdapter.h" #include "Reconstructor.h" @@ -23,30 +23,30 @@ //#define TIMING #ifdef TIMING - #include "UbTiming.h" +#include "UbTiming.h" #endif - -MovableObjectInteractor::MovableObjectInteractor(std::shared_ptr<GbObject3D> geoObject3D, std::shared_ptr<Grid3D> grid, std::shared_ptr<BCAdapter> bcAdapter, int type, std::shared_ptr<Reconstructor> reconstructor, State state) - : D3Q27Interactor(geoObject3D, grid, bcAdapter, type), reconstructor(reconstructor), state(state) +MovableObjectInteractor::MovableObjectInteractor(std::shared_ptr<GbObject3D> geoObject3D, std::shared_ptr<Grid3D> grid, + std::shared_ptr<BCAdapter> bcAdapter, int type, + std::shared_ptr<Reconstructor> reconstructor, State state) + : D3Q27Interactor(geoObject3D, grid, bcAdapter, type), reconstructor(reconstructor), state(state) { - //grid->getBlocks(0, grid->getRank(), true, blockVector); + // grid->getBlocks(0, grid->getRank(), true, blockVector); } -MovableObjectInteractor::~MovableObjectInteractor() -{ - -} +MovableObjectInteractor::~MovableObjectInteractor() {} -void MovableObjectInteractor::setPhysicsEngineGeometry(std::shared_ptr<PhysicsEngineGeometryAdapter> physicsEngineGeometry) +void MovableObjectInteractor::setPhysicsEngineGeometry( + std::shared_ptr<PhysicsEngineGeometryAdapter> physicsEngineGeometry) { this->physicsEngineGeometry = physicsEngineGeometry; physicsEngineGeometry->changeState(this->state); } -void MovableObjectInteractor::moveGbObjectTo(const Vector3D& position) +void MovableObjectInteractor::moveGbObjectTo(const Vector3D &position) { - //UBLOG(logINFO, "new position: (x,y,z) " << val<1>(position) << ", " << val<2>(position) << ", " << val<3>(position)); + // UBLOG(logINFO, "new position: (x,y,z) " << val<1>(position) << ", " << val<2>(position) << ", " << + // val<3>(position)); this->getGbObject3D()->setCenterCoordinates(UbTupleDouble3(position[0], position[1], position[2])); this->rearrangeGrid(); @@ -55,98 +55,94 @@ void MovableObjectInteractor::moveGbObjectTo(const Vector3D& position) void MovableObjectInteractor::rearrangeGrid() { #ifdef TIMING - UbTimer timer; - timer.resetAndStart(); + UbTimer timer; + timer.resetAndStart(); #endif #ifdef TIMING - UBLOG(logINFO, "MovableObjectInteractor::rearrangeGrid():start"); + UBLOG(logINFO, "MovableObjectInteractor::rearrangeGrid():start"); #endif this->reconstructDistributionOnSolidNodes(); #ifdef TIMING - UBLOG(logINFO, "reconstructDistributionOnSolidNodes() time = "<<timer.stop()<<" s"); + UBLOG(logINFO, "reconstructDistributionOnSolidNodes() time = " << timer.stop() << " s"); #endif this->setSolidNodesToFluid(); #ifdef TIMING - UBLOG(logINFO, "setSolidNodesToFluid() time = "<<timer.stop()<<" s"); + UBLOG(logINFO, "setSolidNodesToFluid() time = " << timer.stop() << " s"); #endif this->setBcNodesToFluid(); #ifdef TIMING - UBLOG(logINFO, "setBcNodesToFluid() time = "<<timer.stop()<<" s"); + UBLOG(logINFO, "setBcNodesToFluid() time = " << timer.stop() << " s"); #endif this->removeSolidBlocks(); #ifdef TIMING - UBLOG(logINFO, "removeSolidBlocks() time = "<<timer.stop()<<" s"); + UBLOG(logINFO, "removeSolidBlocks() time = " << timer.stop() << " s"); #endif this->removeBcBlocks(); #ifdef TIMING - UBLOG(logINFO, "removeBcBlocks() time = "<<timer.stop()<<" s"); + UBLOG(logINFO, "removeBcBlocks() time = " << timer.stop() << " s"); #endif this->setBcBlocks(); #ifdef TIMING - UBLOG(logINFO, "setBcBlocks() time = "<<timer.stop()<<" s"); + UBLOG(logINFO, "setBcBlocks() time = " << timer.stop() << " s"); #endif this->initInteractor(); #ifdef TIMING - UBLOG(logINFO, "initInteractor() time = "<<timer.stop()<<" s"); + UBLOG(logINFO, "initInteractor() time = " << timer.stop() << " s"); #endif this->updateVelocityBc(); #ifdef TIMING - UBLOG(logINFO, "updateVelocityBc() time = "<<timer.stop()<<" s"); + UBLOG(logINFO, "updateVelocityBc() time = " << timer.stop() << " s"); #endif } void MovableObjectInteractor::updateNodeLists() { - //for (BcNodeIndicesMap::value_type t : bcNodeIndicesMap) - //{ - // SPtr<Block3D> block = t.first; - // std::set< UbTupleInt3 >& bcNodeIndices = t.second; - + // for (BcNodeIndicesMap::value_type t : bcNodeIndicesMap) + //{ + // SPtr<Block3D> block = t.first; + // std::set< UbTupleInt3 >& bcNodeIndices = t.second; - // SPtr<ILBMKernel> kernel = block->getKernel(); + // SPtr<ILBMKernel> kernel = block->getKernel(); - // for (UbTupleInt3 node : bcNodeIndices) - // { + // for (UbTupleInt3 node : bcNodeIndices) + // { - // } - //} + // } + //} } void MovableObjectInteractor::reconstructDistributionOnSolidNodes() { - for(SolidNodeIndicesMap::value_type t : solidNodeIndicesMap) - { - SPtr<Block3D> block = t.first; - std::set< UbTupleInt3 >& solidNodeIndices = t.second; + for (SolidNodeIndicesMap::value_type t : solidNodeIndicesMap) { + SPtr<Block3D> block = t.first; + std::set<UbTupleInt3> &solidNodeIndices = t.second; - SPtr<ILBMKernel> kernel = block->getKernel(); - for (UbTupleInt3 node : solidNodeIndices) - { + for (UbTupleInt3 node : solidNodeIndices) { const int x1 = val<1>(node); const int x2 = val<2>(node); const int x3 = val<3>(node); const Vector3D worldCoordinates = this->grid.lock()->getNodeCoordinates(block, x1, x2, x3); - + if (kernel->isInsideOfDomain(x1, x2, x3)) reconstructor->reconstructNode(x1, x2, x3, worldCoordinates, physicsEngineGeometry, kernel); } @@ -155,10 +151,9 @@ void MovableObjectInteractor::reconstructDistributionOnSolidNodes() void MovableObjectInteractor::setSolidNodesToFluid() { - for (SolidNodeIndicesMap::value_type t : solidNodeIndicesMap) - { - SPtr<Block3D> block = t.first; - std::set< UbTupleInt3 >& solidNodeIndices = t.second; + for (SolidNodeIndicesMap::value_type t : solidNodeIndicesMap) { + SPtr<Block3D> block = t.first; + std::set<UbTupleInt3> &solidNodeIndices = t.second; SPtr<ILBMKernel> kernel = block->getKernel(); SPtr<BCArray3D> bcArray = kernel->getBCProcessor()->getBCArray(); @@ -170,17 +165,16 @@ void MovableObjectInteractor::setSolidNodesToFluid() void MovableObjectInteractor::setBcNodesToFluid() { - for (BcNodeIndicesMap::value_type t : bcNodeIndicesMap) - { - SPtr<Block3D> block = t.first; - std::set< std::vector<int> >& bcNodeIndices = t.second; + for (BcNodeIndicesMap::value_type t : bcNodeIndicesMap) { + SPtr<Block3D> block = t.first; + std::set<std::vector<int>> &bcNodeIndices = t.second; - SPtr<ILBMKernel> kernel = block->getKernel(); - SPtr<BCArray3D> bcArray = kernel->getBCProcessor()->getBCArray(); + SPtr<ILBMKernel> kernel = block->getKernel(); + SPtr<BCArray3D> bcArray = kernel->getBCProcessor()->getBCArray(); - for (std::vector<int> node : bcNodeIndices) - bcArray->setFluid(node[0], node[1], node[2]); - } + for (std::vector<int> node : bcNodeIndices) + bcArray->setFluid(node[0], node[1], node[2]); + } } void MovableObjectInteractor::setBcBlocks() @@ -189,72 +183,72 @@ void MovableObjectInteractor::setBcBlocks() this->grid.lock()->accept(v); ////////////////////////////////////////////////////////////////////////// - //SPtr<GbObject3D> geoObject = this->getGbObject3D(); - //std::array<double, 6> AABB ={ geoObject->getX1Minimum(),geoObject->getX2Minimum(),geoObject->getX3Minimum(),geoObject->getX1Maximum(),geoObject->getX2Maximum(),geoObject->getX3Maximum() }; - //blockVector.clear(); - //UbTupleInt3 blockNX=grid.lock()->getBlockNX(); - //double ext = 0.0; - //grid.lock()->getBlocksByCuboid(AABB[0]-(double)val<1>(blockNX)*ext, AABB[1]-(double)val<2>(blockNX)*ext, AABB[2]-(double)val<3>(blockNX)*ext, AABB[3]+(double)val<1>(blockNX)*ext, AABB[4]+(double)val<2>(blockNX)*ext, AABB[5]+(double)val<3>(blockNX)*ext, blockVector); - - //for(std::shared_ptr<Block3D> block : this->blockVector) - //{ - // if (block->getKernel()) - // { - // setBCBlock(block); - // } - //} - ////////////////////////////////////////////////////////////////////////// - //SPtr<GbObject3D> geoObject = this->getGbObject3D(); - //std::array <double, 2> minMax1; - //std::array <double, 2> minMax2; - //std::array <double, 2> minMax3; - //minMax1[0] = geoObject->getX1Minimum(); - //minMax2[0] = geoObject->getX2Minimum(); - //minMax3[0] = geoObject->getX3Minimum(); - //minMax1[1] = geoObject->getX1Maximum(); - //minMax2[1] = geoObject->getX2Maximum(); - //minMax3[1] = geoObject->getX3Maximum(); - - //SPtr<CoordinateTransformation3D> trafo = grid.lock()->getCoordinateTransformator(); - - //for (int x3 = 0; x3 < 2; x3++) - // for (int x2 = 0; x2 < 2; x2++) - // for (int x1 = 0; x1 < 2; x1++) - // { - // int ix1 = (int)trafo->transformForwardToX1Coordinate(minMax1[x1], minMax2[x2], minMax3[x3]); - // int ix2 = (int)trafo->transformForwardToX2Coordinate(minMax1[x1], minMax2[x2], minMax3[x3]); - // int ix3 = (int)trafo->transformForwardToX3Coordinate(minMax1[x1], minMax2[x2], minMax3[x3]); - // blockVector.push_back(grid.lock()->getBlock(ix1, ix2, ix3, 0)); - // } - //for(std::shared_ptr<Block3D> block : this->blockVector) - //{ - // if (block->getKernel()) - // { - // setBCBlock(block); - // } - //} + // SPtr<GbObject3D> geoObject = this->getGbObject3D(); + // std::array<double, 6> AABB ={ + // geoObject->getX1Minimum(),geoObject->getX2Minimum(),geoObject->getX3Minimum(),geoObject->getX1Maximum(),geoObject->getX2Maximum(),geoObject->getX3Maximum() + // }; blockVector.clear(); UbTupleInt3 blockNX=grid.lock()->getBlockNX(); double ext = 0.0; + // grid.lock()->getBlocksByCuboid(AABB[0]-(double)val<1>(blockNX)*ext, AABB[1]-(double)val<2>(blockNX)*ext, + // AABB[2]-(double)val<3>(blockNX)*ext, AABB[3]+(double)val<1>(blockNX)*ext, AABB[4]+(double)val<2>(blockNX)*ext, + // AABB[5]+(double)val<3>(blockNX)*ext, blockVector); + + // for(std::shared_ptr<Block3D> block : this->blockVector) + //{ + // if (block->getKernel()) + // { + // setBCBlock(block); + // } + //} + ////////////////////////////////////////////////////////////////////////// + // SPtr<GbObject3D> geoObject = this->getGbObject3D(); + // std::array <double, 2> minMax1; + // std::array <double, 2> minMax2; + // std::array <double, 2> minMax3; + // minMax1[0] = geoObject->getX1Minimum(); + // minMax2[0] = geoObject->getX2Minimum(); + // minMax3[0] = geoObject->getX3Minimum(); + // minMax1[1] = geoObject->getX1Maximum(); + // minMax2[1] = geoObject->getX2Maximum(); + // minMax3[1] = geoObject->getX3Maximum(); + + // SPtr<CoordinateTransformation3D> trafo = grid.lock()->getCoordinateTransformator(); + + // for (int x3 = 0; x3 < 2; x3++) + // for (int x2 = 0; x2 < 2; x2++) + // for (int x1 = 0; x1 < 2; x1++) + // { + // int ix1 = (int)trafo->transformForwardToX1Coordinate(minMax1[x1], minMax2[x2], minMax3[x3]); + // int ix2 = (int)trafo->transformForwardToX2Coordinate(minMax1[x1], minMax2[x2], minMax3[x3]); + // int ix3 = (int)trafo->transformForwardToX3Coordinate(minMax1[x1], minMax2[x2], minMax3[x3]); + // blockVector.push_back(grid.lock()->getBlock(ix1, ix2, ix3, 0)); + // } + // for(std::shared_ptr<Block3D> block : this->blockVector) + //{ + // if (block->getKernel()) + // { + // setBCBlock(block); + // } + //} } void MovableObjectInteractor::updateVelocityBc() { - for(BcNodeIndicesMap::value_type t : this->getBcNodeIndicesMap()) - { - SPtr<Block3D> block = t.first; - std::set< std::vector<int> >& bcNodeIndices = t.second; + for (BcNodeIndicesMap::value_type t : this->getBcNodeIndicesMap()) { + SPtr<Block3D> block = t.first; + std::set<std::vector<int>> &bcNodeIndices = t.second; SPtr<BCArray3D> bcArray = block->getKernel()->getBCProcessor()->getBCArray(); - for(std::vector<int> node : bcNodeIndices) + for (std::vector<int> node : bcNodeIndices) setGeometryVelocityToBoundaryCondition(node, block, bcArray); } } - -void MovableObjectInteractor::setGeometryVelocityToBoundaryCondition(std::vector<int> node, SPtr<Block3D> block, SPtr<BCArray3D> bcArray) const +void MovableObjectInteractor::setGeometryVelocityToBoundaryCondition(std::vector<int> node, SPtr<Block3D> block, + SPtr<BCArray3D> bcArray) const { const SPtr<BoundaryConditions> bc = bcArray->getBC(node[0], node[1], node[2]); - const Vector3D worldCoordinates = this->grid.lock()->getNodeCoordinates(block, node[0], node[1], node[2]); - const Vector3D velocity = this->physicsEngineGeometry->getVelocityAtPosition(worldCoordinates); + const Vector3D worldCoordinates = this->grid.lock()->getNodeCoordinates(block, node[0], node[1], node[2]); + const Vector3D velocity = this->physicsEngineGeometry->getVelocityAtPosition(worldCoordinates); bc->setBoundaryVelocity(velocity); } diff --git a/src/cpu/DemCoupling/MovableObjectInteractor.h b/src/cpu/DemCoupling/MovableObjectInteractor.h index 0aeb22bbdbd8003efb9d2a245aa013160114247e..e0e4343a066d5fd69ddb3cf68d2106337a51d031 100644 --- a/src/cpu/DemCoupling/MovableObjectInteractor.h +++ b/src/cpu/DemCoupling/MovableObjectInteractor.h @@ -1,7 +1,7 @@ /* -* Author: S. Peters -* mail: peters@irmb.tu-bs.de -*/ + * Author: S. Peters + * mail: peters@irmb.tu-bs.de + */ #ifndef D3Q27_MOVABLE_OBJECT_INTERACTOR_H #define D3Q27_MOVABLE_OBJECT_INTERACTOR_H @@ -10,9 +10,8 @@ #include "D3Q27Interactor.h" -#include "Vector3D.h" #include "PhysicsEngineGeometryAdapter.h" - +#include "Vector3D.h" class Grid3D; class Block3D; @@ -26,15 +25,18 @@ class Reconstructor; class MovableObjectInteractor : public D3Q27Interactor { public: - typedef std::map<SPtr<Block3D>, std::set< std::array<int,3> > > InBcNodeIndicesMap; - typedef std::map<SPtr<Block3D>, std::set< std::array<int,3> > > OutBcNodeIndicesMap; + typedef std::map<SPtr<Block3D>, std::set<std::array<int, 3>>> InBcNodeIndicesMap; + typedef std::map<SPtr<Block3D>, std::set<std::array<int, 3>>> OutBcNodeIndicesMap; + public: - MovableObjectInteractor(std::shared_ptr<GbObject3D> geoObject3D, std::shared_ptr<Grid3D> grid, std::shared_ptr<BCAdapter> bcAdapter, int type, std::shared_ptr<Reconstructor> reconstructor, State isPinned); + MovableObjectInteractor(std::shared_ptr<GbObject3D> geoObject3D, std::shared_ptr<Grid3D> grid, + std::shared_ptr<BCAdapter> bcAdapter, int type, + std::shared_ptr<Reconstructor> reconstructor, State isPinned); virtual ~MovableObjectInteractor(); void setPhysicsEngineGeometry(std::shared_ptr<PhysicsEngineGeometryAdapter> physicsEngineGeometry); - void moveGbObjectTo(const Vector3D& position); + void moveGbObjectTo(const Vector3D &position); private: void rearrangeGrid(); @@ -45,14 +47,14 @@ private: void setBcBlocks(); void updateVelocityBc(); - void setGeometryVelocityToBoundaryCondition(std::vector<int> node, std::shared_ptr<Block3D> block, std::shared_ptr<BCArray3D> bcArray) const; + void setGeometryVelocityToBoundaryCondition(std::vector<int> node, std::shared_ptr<Block3D> block, + std::shared_ptr<BCArray3D> bcArray) const; std::shared_ptr<PhysicsEngineGeometryAdapter> physicsEngineGeometry; std::shared_ptr<Reconstructor> reconstructor; State state; - std::vector< std::shared_ptr<Block3D> > blockVector; + std::vector<std::shared_ptr<Block3D>> blockVector; }; - #endif diff --git a/src/cpu/DemCoupling/PePartitioningGridVisitor.cpp b/src/cpu/DemCoupling/PePartitioningGridVisitor.cpp index b52d3ba575c361763b27eedf07903d68e82d08c6..8dbe680a89e913c71ce116e1203bb5d005d4bbdd 100644 --- a/src/cpu/DemCoupling/PePartitioningGridVisitor.cpp +++ b/src/cpu/DemCoupling/PePartitioningGridVisitor.cpp @@ -1,70 +1,64 @@ #if defined VF_METIS && defined VF_MPI -#include <shared_mutex> #include "PePartitioningGridVisitor.h" -#include <math.h> #include "Block3D.h" -#include "Grid3D.h" #include "Communicator.h" -#include "UbLogger.h" #include "CoordinateTransformation3D.h" +#include "Grid3D.h" +#include "UbLogger.h" +#include <math.h> +#include <shared_mutex> #include "DemCoProcessor.h" using namespace std; PePartitioningGridVisitor::PePartitioningGridVisitor(SPtr<Communicator> comm, std::shared_ptr<DemCoProcessor> dem) - : Grid3DVisitor(), - comm(comm), - dem(dem) + : Grid3DVisitor(), comm(comm), dem(dem) { - forest = dynamicPointerCast<PePhysicsEngineSolverAdapter>(dem->getPhysicsEngineSolver())->getForest(); + forest = dynamicPointerCast<PePhysicsEngineSolverAdapter>(dem->getPhysicsEngineSolver())->getForest(); } ////////////////////////////////////////////////////////////////////////// -PePartitioningGridVisitor::~PePartitioningGridVisitor() -{ - -} +PePartitioningGridVisitor::~PePartitioningGridVisitor() {} ////////////////////////////////////////////////////////////////////////// void PePartitioningGridVisitor::visit(SPtr<Grid3D> grid) { - UBLOG(logDEBUG1, "PePartitioningGridVisitor::visit() - start"); + UBLOG(logDEBUG1, "PePartitioningGridVisitor::visit() - start"); - collectData(grid); - distributePartitionData(grid); + collectData(grid); + distributePartitionData(grid); - UBLOG(logDEBUG1, "PePartitioningGridVisitor::visit() - end"); + UBLOG(logDEBUG1, "PePartitioningGridVisitor::visit() - end"); } ////////////////////////////////////////////////////////////////////////// void PePartitioningGridVisitor::collectData(SPtr<Grid3D> grid) { - //int minInitLevel = grid->getCoarsestInitializedLevel(); - //int maxInitLevel = grid->getFinestInitializedLevel(); - - walberla::uint_t peRank; - - for (auto blockIt = forest->begin(); blockIt != forest->end(); ++blockIt) - { - forest->getProcessRank(peRank, blockIt->getId()); - vector<SPtr<Block3D>> blocks; - walberla::AABB aabb = blockIt->getAABB(); - - //getBlocksByCuboid((double)aabb.xMin(), (double)aabb.yMin(), (double)aabb.zMin(), (double)aabb.xMax(), (double)aabb.yMax(), (double)aabb.zMax(), blocks, grid); - //for (SPtr<Block3D> block : blocks) - //{ - // ids.push_back(block->getGlobalID()); - // ranks.push_back((int)peRank); - //} - SPtr<Block3D> block = getBlockByMinUniform((double)aabb.xMin(), (double)aabb.yMin(), (double)aabb.zMin(), grid); - if (block) - { - ids.push_back(block->getGlobalID()); - ranks.push_back((int)peRank); - } - } + // int minInitLevel = grid->getCoarsestInitializedLevel(); + // int maxInitLevel = grid->getFinestInitializedLevel(); + + walberla::uint_t peRank; + + for (auto blockIt = forest->begin(); blockIt != forest->end(); ++blockIt) { + forest->getProcessRank(peRank, blockIt->getId()); + vector<SPtr<Block3D>> blocks; + walberla::AABB aabb = blockIt->getAABB(); + + // getBlocksByCuboid((double)aabb.xMin(), (double)aabb.yMin(), (double)aabb.zMin(), (double)aabb.xMax(), + // (double)aabb.yMax(), (double)aabb.zMax(), blocks, grid); for (SPtr<Block3D> block : blocks) + //{ + // ids.push_back(block->getGlobalID()); + // ranks.push_back((int)peRank); + //} + SPtr<Block3D> block = getBlockByMinUniform((double)aabb.xMin(), (double)aabb.yMin(), (double)aabb.zMin(), grid); + if (block) { + ids.push_back(block->getGlobalID()); + ranks.push_back((int)peRank); + } + } } ////////////////////////////////////////////////////////////////////////// -//void PePartitioningGridVisitor::getBlocksByCuboid(double minX1, double minX2, double minX3, double maxX1, double maxX2, double maxX3, std::vector<SPtr<Block3D>>& blocks, SPtr<Grid3D> grid) +// void PePartitioningGridVisitor::getBlocksByCuboid(double minX1, double minX2, double minX3, double maxX1, double +// maxX2, double maxX3, std::vector<SPtr<Block3D>>& blocks, SPtr<Grid3D> grid) //{ // int coarsestLevel = grid->getCoarsestInitializedLevel(); // int finestLevel = grid->getFinestInitializedLevel(); @@ -73,7 +67,7 @@ void PePartitioningGridVisitor::collectData(SPtr<Grid3D> grid) // // ////////////////////////////////////////////////////////////////////////// // //MINIMALE BLOCK-INDIZES BESTIMMEN -// // +// // // //min: // double dMinX1 = trafo->transformForwardToX1Coordinate(minX1, minX2, minX3)*(1<<finestLevel); // double dMinX2 = trafo->transformForwardToX2Coordinate(minX1, minX2, minX3)*(1<<finestLevel); @@ -118,39 +112,37 @@ void PePartitioningGridVisitor::collectData(SPtr<Grid3D> grid) // std::copy(blockset.begin(), blockset.end(), blocks.begin()); //} -SPtr<Block3D> PePartitioningGridVisitor::getBlockByMinUniform(double minX1, double minX2, double minX3, SPtr<Grid3D> grid) +SPtr<Block3D> PePartitioningGridVisitor::getBlockByMinUniform(double minX1, double minX2, double minX3, + SPtr<Grid3D> grid) { - SPtr<CoordinateTransformation3D> trafo = grid->getCoordinateTransformator(); + SPtr<CoordinateTransformation3D> trafo = grid->getCoordinateTransformator(); - int ix1 = (int)trafo->transformForwardToX1Coordinate(minX1, minX2, minX3); - int ix2 = (int)trafo->transformForwardToX2Coordinate(minX1, minX2, minX3); - int ix3 = (int)trafo->transformForwardToX3Coordinate(minX1, minX2, minX3); + int ix1 = (int)trafo->transformForwardToX1Coordinate(minX1, minX2, minX3); + int ix2 = (int)trafo->transformForwardToX2Coordinate(minX1, minX2, minX3); + int ix3 = (int)trafo->transformForwardToX3Coordinate(minX1, minX2, minX3); - return grid->getBlock(ix1, ix2, ix3, 0); + return grid->getBlock(ix1, ix2, ix3, 0); } ////////////////////////////////////////////////////////////////////////// void PePartitioningGridVisitor::distributePartitionData(SPtr<Grid3D> grid) { - std::vector<int> totalIDs; - std::vector<int> totalRanks; + std::vector<int> totalIDs; + std::vector<int> totalRanks; - assert(ids.size() != 0); - assert(ranks.size() != 0); + assert(ids.size() != 0); + assert(ranks.size() != 0); - comm->allGather(ids, totalIDs); - comm->allGather(ranks, totalRanks); + comm->allGather(ids, totalIDs); + comm->allGather(ranks, totalRanks); - - assert(totalIDs.size() == totalRanks.size()); - for (int i = 0; i < totalIDs.size(); i++) - { - SPtr<Block3D> block = grid->getBlock(totalIDs[i]); - if (block) block->setRank(totalRanks[i]); - } + assert(totalIDs.size() == totalRanks.size()); + for (int i = 0; i < totalIDs.size(); i++) { + SPtr<Block3D> block = grid->getBlock(totalIDs[i]); + if (block) + block->setRank(totalRanks[i]); + } } ////////////////////////////////////////////////////////////////////////// - - -#endif //VF_METIS +#endif // VF_METIS diff --git a/src/cpu/DemCoupling/PePartitioningGridVisitor.h b/src/cpu/DemCoupling/PePartitioningGridVisitor.h index bce2ca0d2059b4c2915ab30fc4baa87b09cf9bf8..ff97d531d7f6ccaebb8c7e3a1ab60c2c27177bf5 100644 --- a/src/cpu/DemCoupling/PePartitioningGridVisitor.h +++ b/src/cpu/DemCoupling/PePartitioningGridVisitor.h @@ -1,10 +1,10 @@ -#ifndef PePartitioningGridVisitor_h +#ifndef PePartitioningGridVisitor_h #define PePartitioningGridVisitor_h #if defined VF_MPI -#include <vector> #include <PointerDefinitions.h> +#include <vector> #include "Grid3DVisitor.h" @@ -20,37 +20,38 @@ class Communicator; class Grid3D; class Block3D; class DemCoProcessor; -//class walberla::blockforest::BlockForest; +// class walberla::blockforest::BlockForest; class PePartitioningGridVisitor : public Grid3DVisitor -{ +{ public: - //! This describe different types of decomposition - enum GraphType{LevelIntersected, LevelBased}; + //! This describe different types of decomposition + enum GraphType { LevelIntersected, LevelBased }; public: - //! Constructor - //! \param comm - communicator + //! Constructor + //! \param comm - communicator - PePartitioningGridVisitor(SPtr<Communicator> comm, std::shared_ptr<DemCoProcessor> dem); - virtual ~PePartitioningGridVisitor(); - void visit(SPtr<Grid3D> grid) override; + PePartitioningGridVisitor(SPtr<Communicator> comm, std::shared_ptr<DemCoProcessor> dem); + virtual ~PePartitioningGridVisitor(); + void visit(SPtr<Grid3D> grid) override; protected: - void collectData(SPtr<Grid3D> grid); - void distributePartitionData(SPtr<Grid3D> grid); - //void getBlocksByCuboid(double minX1, double minX2, double minX3, double maxX1, double maxX2, double maxX3, std::vector<SPtr<Block3D>>& blocks, SPtr<Grid3D> grid); - SPtr<Block3D> getBlockByMinUniform(double minX1, double minX2, double minX3, SPtr<Grid3D> grid); + void collectData(SPtr<Grid3D> grid); + void distributePartitionData(SPtr<Grid3D> grid); + // void getBlocksByCuboid(double minX1, double minX2, double minX3, double maxX1, double maxX2, double maxX3, + // std::vector<SPtr<Block3D>>& blocks, SPtr<Grid3D> grid); + SPtr<Block3D> getBlockByMinUniform(double minX1, double minX2, double minX3, SPtr<Grid3D> grid); private: - SPtr<Communicator> comm; - std::shared_ptr<DemCoProcessor> dem; + SPtr<Communicator> comm; + std::shared_ptr<DemCoProcessor> dem; - std::vector<int> ids; - std::vector<int> ranks; + std::vector<int> ids; + std::vector<int> ranks; - std::shared_ptr< walberla::blockforest::BlockForest > forest; + std::shared_ptr<walberla::blockforest::BlockForest> forest; }; -#endif //VF_MPI -#endif +#endif // VF_MPI +#endif diff --git a/src/cpu/DemCoupling/RestartDemObjectsCoProcessor.cpp b/src/cpu/DemCoupling/RestartDemObjectsCoProcessor.cpp index 1cc39ad6ebfb2879b3774b5e0f8d0956448e502f..1d018376319ce7bed6eca6e4ef7f4492237699fb 100644 --- a/src/cpu/DemCoupling/RestartDemObjectsCoProcessor.cpp +++ b/src/cpu/DemCoupling/RestartDemObjectsCoProcessor.cpp @@ -1,119 +1,119 @@ #include "RestartDemObjectsCoProcessor.h" -#include "Vector3D.h" #include "Communicator.h" -#include "UbScheduler.h" -#include "Grid3D.h" -#include "UbSystem.h" -#include "GbSphere3D.h" +#include "CreateDemObjectsCoProcessor.h" #include "DemCoProcessor.h" +#include "GbSphere3D.h" +#include "Grid3D.h" #include "UbFileInputBinary.h" #include "UbFileOutputBinary.h" -#include "CreateDemObjectsCoProcessor.h" +#include "UbScheduler.h" +#include "UbSystem.h" +#include "Vector3D.h" -RestartDemObjectsCoProcessor::RestartDemObjectsCoProcessor() -{ -} +RestartDemObjectsCoProcessor::RestartDemObjectsCoProcessor() {} -RestartDemObjectsCoProcessor::RestartDemObjectsCoProcessor(SPtr<Grid3D> grid, SPtr<UbScheduler> s, const std::string & path, SPtr<DemCoProcessor> demCoProcessor, SPtr<CreateDemObjectsCoProcessor> createDemObjectsCoProcessor, double radius, SPtr<Communicator> comm) : CoProcessor(grid, s), path(path), demCoProcessor(demCoProcessor), createDemObjectsCoProcessor(createDemObjectsCoProcessor), radius(radius), comm(comm) +RestartDemObjectsCoProcessor::RestartDemObjectsCoProcessor( + SPtr<Grid3D> grid, SPtr<UbScheduler> s, const std::string &path, SPtr<DemCoProcessor> demCoProcessor, + SPtr<CreateDemObjectsCoProcessor> createDemObjectsCoProcessor, double radius, SPtr<Communicator> comm) + : CoProcessor(grid, s), path(path), demCoProcessor(demCoProcessor), + createDemObjectsCoProcessor(createDemObjectsCoProcessor), radius(radius), comm(comm) { } void RestartDemObjectsCoProcessor::process(double step) { - if (scheduler->isDue(step)) - { - int istep = static_cast<int>(step); + if (scheduler->isDue(step)) { + int istep = static_cast<int>(step); - if (comm->isRoot()) - UBLOG(logINFO, "RestartDemObjectsCoProcessor::write step: " << istep); + if (comm->isRoot()) + UBLOG(logINFO, "RestartDemObjectsCoProcessor::write step: " << istep); - write(istep); - } + write(istep); + } } void RestartDemObjectsCoProcessor::restart(double step) { - if (comm->isRoot()) - UBLOG(logINFO, "RestartDemObjectsCoProcessor::read step: " << (int)step); + if (comm->isRoot()) + UBLOG(logINFO, "RestartDemObjectsCoProcessor::read step: " << (int)step); - read((int)step); + read((int)step); } void RestartDemObjectsCoProcessor::write(int step) { - if (comm->isRoot()) UBLOG(logINFO, "RestartDemObjectsCoProcessor::write start "); - std::vector<double> p; - - demCoProcessor->getObjectsPropertiesVector(p); - - //TODO implement getherv - std::vector<double> rvalues; - comm->allGather(p, rvalues); - - if (comm->isRoot()) - { - std::map< int, std::vector< double> > infMap; - int size = (int)rvalues.size(); - for (int i = 0; i < size; i += 7) - { - std::vector< double> infVector(6); - for (int j = 0; j < 6; j ++) - { - infVector[j] = rvalues[i+1+j]; - } - infMap.insert(std::make_pair((int)rvalues[i], infVector)); - } - std::vector< double> wvalues; - typedef std::map< int, std::vector< double> >::iterator it_type; - for (it_type iterator = infMap.begin(); iterator != infMap.end(); iterator++) - { - // iterator->first = key - // iterator->second = value - std::vector<double>::iterator it = wvalues.end(); - it = wvalues.insert(it, iterator->second.begin(), iterator->second.end()); - } - std::string subfolder = "dem_cp_"+UbSystem::toString(step); - std::string filePath = path+"/dem_cp/"+subfolder+"/dem_cp.bin"; - UbFileOutputBinary fo(filePath); - fo.writeInteger((int)wvalues.size()); - fo.writeVector<double>(wvalues); - UBLOG(logINFO, "RestartDemObjectsCoProcessor::write number of objects = " << wvalues.size()/6); - } - if (comm->isRoot()) UBLOG(logINFO, "RestartDemObjectsCoProcessor::write stop "); + if (comm->isRoot()) + UBLOG(logINFO, "RestartDemObjectsCoProcessor::write start "); + std::vector<double> p; + + demCoProcessor->getObjectsPropertiesVector(p); + + // TODO implement getherv + std::vector<double> rvalues; + comm->allGather(p, rvalues); + + if (comm->isRoot()) { + std::map<int, std::vector<double>> infMap; + int size = (int)rvalues.size(); + for (int i = 0; i < size; i += 7) { + std::vector<double> infVector(6); + for (int j = 0; j < 6; j++) { + infVector[j] = rvalues[i + 1 + j]; + } + infMap.insert(std::make_pair((int)rvalues[i], infVector)); + } + std::vector<double> wvalues; + typedef std::map<int, std::vector<double>>::iterator it_type; + for (it_type iterator = infMap.begin(); iterator != infMap.end(); iterator++) { + // iterator->first = key + // iterator->second = value + std::vector<double>::iterator it = wvalues.end(); + it = wvalues.insert(it, iterator->second.begin(), iterator->second.end()); + } + std::string subfolder = "dem_cp_" + UbSystem::toString(step); + std::string filePath = path + "/dem_cp/" + subfolder + "/dem_cp.bin"; + UbFileOutputBinary fo(filePath); + fo.writeInteger((int)wvalues.size()); + fo.writeVector<double>(wvalues); + UBLOG(logINFO, "RestartDemObjectsCoProcessor::write number of objects = " << wvalues.size() / 6); + } + if (comm->isRoot()) + UBLOG(logINFO, "RestartDemObjectsCoProcessor::write stop "); } void RestartDemObjectsCoProcessor::read(int step) { - if (comm->isRoot()) UBLOG(logINFO, "RestartDemObjectsCoProcessor::read start "); - std::vector<double> p; + if (comm->isRoot()) + UBLOG(logINFO, "RestartDemObjectsCoProcessor::read start "); + std::vector<double> p; - if (comm->isRoot()) - { - std::string subfolder = "dem_cp_"+UbSystem::toString(step); - std::string filePath = path+"/dem_cp/"+subfolder+"/dem_cp.bin"; - UbFileInputBinary fi(filePath); - int size = fi.readInteger(); - p.resize(size); - fi.readVector<double>(p); - } - comm->broadcast(p); + if (comm->isRoot()) { + std::string subfolder = "dem_cp_" + UbSystem::toString(step); + std::string filePath = path + "/dem_cp/" + subfolder + "/dem_cp.bin"; + UbFileInputBinary fi(filePath); + int size = fi.readInteger(); + p.resize(size); + fi.readVector<double>(p); + } + comm->broadcast(p); - if (comm->isRoot()) UBLOG(logINFO, "RestartDemObjectsCoProcessor::read number of objects = " << p.size()/6); + if (comm->isRoot()) + UBLOG(logINFO, "RestartDemObjectsCoProcessor::read number of objects = " << p.size() / 6); - createDemObjectsCoProcessor->clearGeoObjects(); + createDemObjectsCoProcessor->clearGeoObjects(); - int size = (int)p.size(); + int size = (int)p.size(); - for (int i = 0; i < size; i += 6) - { - SPtr<GbObject3D> sphere(new GbSphere3D(p[i], p[i+1], p[i+2], radius)); - createDemObjectsCoProcessor->addGeoObject(sphere, Vector3D(p[i+3], p[i+4], p[i+5])); - } + for (int i = 0; i < size; i += 6) { + SPtr<GbObject3D> sphere(new GbSphere3D(p[i], p[i + 1], p[i + 2], radius)); + createDemObjectsCoProcessor->addGeoObject(sphere, Vector3D(p[i + 3], p[i + 4], p[i + 5])); + } - createDemObjectsCoProcessor->createGeoObjects(); + createDemObjectsCoProcessor->createGeoObjects(); - createDemObjectsCoProcessor->clearGeoObjects(); + createDemObjectsCoProcessor->clearGeoObjects(); - if (comm->isRoot()) UBLOG(logINFO, "RestartDemObjectsCoProcessor::read stop "); + if (comm->isRoot()) + UBLOG(logINFO, "RestartDemObjectsCoProcessor::read stop "); } diff --git a/src/cpu/DemCoupling/RestartDemObjectsCoProcessor.h b/src/cpu/DemCoupling/RestartDemObjectsCoProcessor.h index 8a1fdb72177ae18624f87d1508cbad7576cac860..08fb70ef5821ceb3d53d8e4d1e0489519cc8f881 100644 --- a/src/cpu/DemCoupling/RestartDemObjectsCoProcessor.h +++ b/src/cpu/DemCoupling/RestartDemObjectsCoProcessor.h @@ -1,7 +1,7 @@ /* -* Author: K. Kutscher -* mail: kutscher@irmb.tu-bs.de -*/ + * Author: K. Kutscher + * mail: kutscher@irmb.tu-bs.de + */ #ifndef RestartDemObjectsCoProcessor_H #define RestartDemObjectsCoProcessor_H @@ -17,22 +17,25 @@ class UbScheduler; class DemCoProcessor; class CreateDemObjectsCoProcessor; -class RestartDemObjectsCoProcessor : public CoProcessor +class RestartDemObjectsCoProcessor : public CoProcessor { public: - RestartDemObjectsCoProcessor(); - RestartDemObjectsCoProcessor(SPtr<Grid3D> grid, SPtr<UbScheduler> s, const std::string& path, SPtr<DemCoProcessor> demCoProcessor, SPtr<CreateDemObjectsCoProcessor> createDemObjectsCoProcessor, double radius, SPtr<Communicator> comm); - ~RestartDemObjectsCoProcessor() {} - void process(double step) override; - void restart(double step); - void write(int step); - void read(int step); + RestartDemObjectsCoProcessor(); + RestartDemObjectsCoProcessor(SPtr<Grid3D> grid, SPtr<UbScheduler> s, const std::string &path, + SPtr<DemCoProcessor> demCoProcessor, + SPtr<CreateDemObjectsCoProcessor> createDemObjectsCoProcessor, double radius, + SPtr<Communicator> comm); + ~RestartDemObjectsCoProcessor() {} + void process(double step) override; + void restart(double step); + void write(int step); + void read(int step); private: - std::string path; - double radius; - SPtr<Communicator> comm; - SPtr<DemCoProcessor> demCoProcessor; - SPtr<CreateDemObjectsCoProcessor> createDemObjectsCoProcessor; + std::string path; + double radius; + SPtr<Communicator> comm; + SPtr<DemCoProcessor> demCoProcessor; + SPtr<CreateDemObjectsCoProcessor> createDemObjectsCoProcessor; }; #endif diff --git a/src/cpu/DemCoupling/WriteDemObjectsCoProcessor.cpp b/src/cpu/DemCoupling/WriteDemObjectsCoProcessor.cpp index 30b25c0de1d2be1ab6607bc307e523de339b4f18..03b0c278373a8eb1b74172f31cef044442cccae4 100644 --- a/src/cpu/DemCoupling/WriteDemObjectsCoProcessor.cpp +++ b/src/cpu/DemCoupling/WriteDemObjectsCoProcessor.cpp @@ -1,74 +1,63 @@ #include "WriteDemObjectsCoProcessor.h" -#include "basics/writer/WbWriterVtkXmlBinary.h" #include "basics/writer/WbWriterVtkXmlASCII.h" +#include "basics/writer/WbWriterVtkXmlBinary.h" #include "Communicator.h" -#include "UbScheduler.h" +#include "DemCoProcessor.h" #include "Grid3D.h" +#include "UbScheduler.h" #include "UbSystem.h" -#include "DemCoProcessor.h" - -WriteDemObjectsCoProcessor::WriteDemObjectsCoProcessor() -{ -} +WriteDemObjectsCoProcessor::WriteDemObjectsCoProcessor() {} ////////////////////////////////////////////////////////////////////////// -WriteDemObjectsCoProcessor::WriteDemObjectsCoProcessor(SPtr<Grid3D> grid, SPtr<UbScheduler> s, const std::string& path, WbWriter* const writer, SPtr<DemCoProcessor> demCoProcessor, SPtr<Communicator> comm) - : CoProcessor(grid, s), - path(path), - writer(writer), - demCoProcessor(demCoProcessor), - comm(comm) +WriteDemObjectsCoProcessor::WriteDemObjectsCoProcessor(SPtr<Grid3D> grid, SPtr<UbScheduler> s, const std::string &path, + WbWriter *const writer, SPtr<DemCoProcessor> demCoProcessor, + SPtr<Communicator> comm) + : CoProcessor(grid, s), path(path), writer(writer), demCoProcessor(demCoProcessor), comm(comm) { - } ////////////////////////////////////////////////////////////////////////// void WriteDemObjectsCoProcessor::process(double step) { - if (scheduler->isDue(step)) - { - std::vector<UbTupleFloat3> nodes; - std::vector<UbTupleInt3> triangles; - - int numObjcts = demCoProcessor->addSurfaceTriangleSet(nodes, triangles); - - int istep = static_cast<int>(step); - - std::string pfilePath, partPath, subfolder, cfilePath; - - subfolder = "dem"+UbSystem::toString(istep); - pfilePath = path+"/dem/"+subfolder; - cfilePath = path+"/dem/dem_collection"; - partPath = pfilePath+"/dem"+UbSystem::toString(comm->getProcessID())+ "_" + UbSystem::toString(istep); - - - std::string partName = writer->writeTriangles(partPath, nodes, triangles); - size_t found=partName.find_last_of("/"); - std::string piece = partName.substr(found+1); - piece = subfolder + "/" + piece; - - std::vector<std::string> datanames; - std::vector<std::string> cellDataNames; - std::vector<std::string> pieces = comm->gather(piece); - if (comm->isRoot()) - { - std::string pname = WbWriterVtkXmlASCII::getInstance()->writeParallelFile(pfilePath, pieces, datanames, cellDataNames); - found=pname.find_last_of("/"); - piece = pname.substr(found+1); - - std::vector<std::string> filenames; - filenames.push_back(piece); - if (step == CoProcessor::scheduler->getMinBegin()) - { - WbWriterVtkXmlASCII::getInstance()->writeCollection(cfilePath, filenames, istep, false); - } - else - { - WbWriterVtkXmlASCII::getInstance()->addFilesToCollection(cfilePath, filenames, istep, false); - } - UBLOG(logINFO, "WriteDemObjectsCoProcessor number of objects: " << numObjcts); - UBLOG(logINFO, "WriteDemObjectsCoProcessor step: " << istep); - } - } + if (scheduler->isDue(step)) { + std::vector<UbTupleFloat3> nodes; + std::vector<UbTupleInt3> triangles; + + int numObjcts = demCoProcessor->addSurfaceTriangleSet(nodes, triangles); + + int istep = static_cast<int>(step); + + std::string pfilePath, partPath, subfolder, cfilePath; + + subfolder = "dem" + UbSystem::toString(istep); + pfilePath = path + "/dem/" + subfolder; + cfilePath = path + "/dem/dem_collection"; + partPath = pfilePath + "/dem" + UbSystem::toString(comm->getProcessID()) + "_" + UbSystem::toString(istep); + + std::string partName = writer->writeTriangles(partPath, nodes, triangles); + size_t found = partName.find_last_of("/"); + std::string piece = partName.substr(found + 1); + piece = subfolder + "/" + piece; + + std::vector<std::string> datanames; + std::vector<std::string> cellDataNames; + std::vector<std::string> pieces = comm->gather(piece); + if (comm->isRoot()) { + std::string pname = + WbWriterVtkXmlASCII::getInstance()->writeParallelFile(pfilePath, pieces, datanames, cellDataNames); + found = pname.find_last_of("/"); + piece = pname.substr(found + 1); + + std::vector<std::string> filenames; + filenames.push_back(piece); + if (step == CoProcessor::scheduler->getMinBegin()) { + WbWriterVtkXmlASCII::getInstance()->writeCollection(cfilePath, filenames, istep, false); + } else { + WbWriterVtkXmlASCII::getInstance()->addFilesToCollection(cfilePath, filenames, istep, false); + } + UBLOG(logINFO, "WriteDemObjectsCoProcessor number of objects: " << numObjcts); + UBLOG(logINFO, "WriteDemObjectsCoProcessor step: " << istep); + } + } } diff --git a/src/cpu/DemCoupling/WriteDemObjectsCoProcessor.h b/src/cpu/DemCoupling/WriteDemObjectsCoProcessor.h index 93d87bcf88d0e90d14c407df76472bd07525181d..6c45b86322a792bcdb165b70082d5ae08b6cc496 100644 --- a/src/cpu/DemCoupling/WriteDemObjectsCoProcessor.h +++ b/src/cpu/DemCoupling/WriteDemObjectsCoProcessor.h @@ -1,7 +1,7 @@ /* -* Author: K. Kutscher -* mail: kutscher@irmb.tu-bs.de -*/ + * Author: K. Kutscher + * mail: kutscher@irmb.tu-bs.de + */ #ifndef WriteDemObjectsCoProcessor_H #define WriteDemObjectsCoProcessor_H @@ -17,17 +17,18 @@ class UbScheduler; class DemCoProcessor; class WbWriter; -class WriteDemObjectsCoProcessor : public CoProcessor +class WriteDemObjectsCoProcessor : public CoProcessor { public: WriteDemObjectsCoProcessor(); - WriteDemObjectsCoProcessor(SPtr<Grid3D> grid, SPtr<UbScheduler> s, const std::string& path, WbWriter* const writer, SPtr<DemCoProcessor> demCoProcessor, SPtr<Communicator> comm); - ~WriteDemObjectsCoProcessor() {} - void process(double step) override; + WriteDemObjectsCoProcessor(SPtr<Grid3D> grid, SPtr<UbScheduler> s, const std::string &path, WbWriter *const writer, + SPtr<DemCoProcessor> demCoProcessor, SPtr<Communicator> comm); + ~WriteDemObjectsCoProcessor() {} + void process(double step) override; private: std::string path; - WbWriter* writer; + WbWriter *writer; SPtr<Communicator> comm; SPtr<DemCoProcessor> demCoProcessor; }; diff --git a/src/cpu/DemCoupling/WritePeBlocksCoProcessor.cpp b/src/cpu/DemCoupling/WritePeBlocksCoProcessor.cpp index f46208ac9a3293d7ebdc2766de16516af778ef69..693a23c5cf6157dbdc3f3011330926ecae79b6bf 100644 --- a/src/cpu/DemCoupling/WritePeBlocksCoProcessor.cpp +++ b/src/cpu/DemCoupling/WritePeBlocksCoProcessor.cpp @@ -2,87 +2,77 @@ #include "basics/writer/WbWriterVtkXmlASCII.h" -#include "D3Q27System.h" #include "Block3D.h" -#include "UbScheduler.h" #include "Communicator.h" +#include "D3Q27System.h" #include "Grid3D.h" +#include "UbScheduler.h" -WritePeBlocksCoProcessor::WritePeBlocksCoProcessor(SPtr<Grid3D> grid, SPtr<UbScheduler> s, const std::string& path, WbWriter* const writer, SPtr<Communicator> comm, SPtr<walberla::blockforest::BlockForest> forest) : - CoProcessor(grid, s), - path(path), - writer(writer), - comm(comm), - forest(forest) +WritePeBlocksCoProcessor::WritePeBlocksCoProcessor(SPtr<Grid3D> grid, SPtr<UbScheduler> s, const std::string &path, + WbWriter *const writer, SPtr<Communicator> comm, + SPtr<walberla::blockforest::BlockForest> forest) + : CoProcessor(grid, s), path(path), writer(writer), comm(comm), forest(forest) { - } -WritePeBlocksCoProcessor::~WritePeBlocksCoProcessor() -{ - -} +WritePeBlocksCoProcessor::~WritePeBlocksCoProcessor() {} void WritePeBlocksCoProcessor::process(double step) { - if (scheduler->isDue(step)) - collectData(step); + if (scheduler->isDue(step)) + collectData(step); } void WritePeBlocksCoProcessor::collectData(double step) { - if (comm->getProcessID() == comm->getRoot()) - { - int istep = int(step); - std::vector<std::string> filenames; - std::vector< UbTupleFloat3 > nodes; - std::vector< UbTupleInt8 > cells; - std::vector<std::string> celldatanames; - - celldatanames.push_back("ID"); - celldatanames.push_back("rank"); - - walberla::uint_t rank = 0; - - - std::vector< std::vector< double > > celldata(celldatanames.size()); - - int nr=0; - - for (auto blockIt = forest->begin(); blockIt != forest->end(); ++blockIt) - { - walberla::AABB aabb = blockIt->getAABB(); - - nodes.push_back(makeUbTuple((float)aabb.xMin(), (float)aabb.yMin(), (float)aabb.zMin())); - nodes.push_back(makeUbTuple((float)aabb.xMax(), (float)aabb.yMin(), (float)aabb.zMin())); - nodes.push_back(makeUbTuple((float)aabb.xMax(), (float)aabb.yMax(), (float)aabb.zMin())); - nodes.push_back(makeUbTuple((float)aabb.xMin(), (float)aabb.yMax(), (float)aabb.zMin())); - nodes.push_back(makeUbTuple((float)aabb.xMin(), (float)aabb.yMin(), (float)aabb.zMax())); - nodes.push_back(makeUbTuple((float)aabb.xMax(), (float)aabb.yMin(), (float)aabb.zMax())); - nodes.push_back(makeUbTuple((float)aabb.xMax(), (float)aabb.yMax(), (float)aabb.zMax())); - nodes.push_back(makeUbTuple((float)aabb.xMin(), (float)aabb.yMax(), (float)aabb.zMax())); - cells.push_back(makeUbTuple(nr, nr+1, nr+2, nr+3, nr+4, nr+5, nr+6, nr+7)); - nr += 8; - - //data - celldata[0].push_back((double)blockIt->getId().getID()); - forest->getProcessRank(rank,blockIt->getId()); - celldata[1].push_back((double)rank); - } - - filenames.push_back(writer->writeOctsWithCellData(path+"/peBlocks/peBlocks_" + UbSystem::toString(grid->getRank()) + "_" + UbSystem::toString(istep), nodes, cells, celldatanames, celldata)); - - if (istep == CoProcessor::scheduler->getMinBegin()) - { - WbWriterVtkXmlASCII::getInstance()->writeCollection(path+"/peBlocks/peBlocks_collection", filenames, istep, false); - } - else - { - WbWriterVtkXmlASCII::getInstance()->addFilesToCollection(path + "/peBlocks/peBlocks_collection", filenames, istep, false); - } - - UBLOG(logINFO, "WritePeBlocksCoProcessor step: " << istep); - - } - + if (comm->getProcessID() == comm->getRoot()) { + int istep = int(step); + std::vector<std::string> filenames; + std::vector<UbTupleFloat3> nodes; + std::vector<UbTupleInt8> cells; + std::vector<std::string> celldatanames; + + celldatanames.push_back("ID"); + celldatanames.push_back("rank"); + + walberla::uint_t rank = 0; + + std::vector<std::vector<double>> celldata(celldatanames.size()); + + int nr = 0; + + for (auto blockIt = forest->begin(); blockIt != forest->end(); ++blockIt) { + walberla::AABB aabb = blockIt->getAABB(); + + nodes.push_back(makeUbTuple((float)aabb.xMin(), (float)aabb.yMin(), (float)aabb.zMin())); + nodes.push_back(makeUbTuple((float)aabb.xMax(), (float)aabb.yMin(), (float)aabb.zMin())); + nodes.push_back(makeUbTuple((float)aabb.xMax(), (float)aabb.yMax(), (float)aabb.zMin())); + nodes.push_back(makeUbTuple((float)aabb.xMin(), (float)aabb.yMax(), (float)aabb.zMin())); + nodes.push_back(makeUbTuple((float)aabb.xMin(), (float)aabb.yMin(), (float)aabb.zMax())); + nodes.push_back(makeUbTuple((float)aabb.xMax(), (float)aabb.yMin(), (float)aabb.zMax())); + nodes.push_back(makeUbTuple((float)aabb.xMax(), (float)aabb.yMax(), (float)aabb.zMax())); + nodes.push_back(makeUbTuple((float)aabb.xMin(), (float)aabb.yMax(), (float)aabb.zMax())); + cells.push_back(makeUbTuple(nr, nr + 1, nr + 2, nr + 3, nr + 4, nr + 5, nr + 6, nr + 7)); + nr += 8; + + // data + celldata[0].push_back((double)blockIt->getId().getID()); + forest->getProcessRank(rank, blockIt->getId()); + celldata[1].push_back((double)rank); + } + + filenames.push_back(writer->writeOctsWithCellData( + path + "/peBlocks/peBlocks_" + UbSystem::toString(grid->getRank()) + "_" + UbSystem::toString(istep), nodes, + cells, celldatanames, celldata)); + + if (istep == CoProcessor::scheduler->getMinBegin()) { + WbWriterVtkXmlASCII::getInstance()->writeCollection(path + "/peBlocks/peBlocks_collection", filenames, + istep, false); + } else { + WbWriterVtkXmlASCII::getInstance()->addFilesToCollection(path + "/peBlocks/peBlocks_collection", filenames, + istep, false); + } + + UBLOG(logINFO, "WritePeBlocksCoProcessor step: " << istep); + } } \ No newline at end of file diff --git a/src/cpu/DemCoupling/WritePeBlocksCoProcessor.h b/src/cpu/DemCoupling/WritePeBlocksCoProcessor.h index 6d10225668fa9431d538d2dc24e42bf37fed3d56..72334abd5e55fe4b9e4700540fca185db68f44b4 100644 --- a/src/cpu/DemCoupling/WritePeBlocksCoProcessor.h +++ b/src/cpu/DemCoupling/WritePeBlocksCoProcessor.h @@ -1,9 +1,9 @@ /* -* WritePeBlocksCoProcessor.h -* -* Created on: 07.09.2018 -* Author: K. Kutscher -*/ + * WritePeBlocksCoProcessor.h + * + * Created on: 07.09.2018 + * Author: K. Kutscher + */ #ifndef WritePeBlocksCoProcessor_H_ #define WritePeBlocksCoProcessor_H_ @@ -23,21 +23,19 @@ class WbWriter; class WritePeBlocksCoProcessor : public CoProcessor { public: - WritePeBlocksCoProcessor(SPtr<Grid3D> grid, SPtr<UbScheduler> s, const std::string& path, WbWriter* const writer, SPtr<Communicator> comm, SPtr<walberla::blockforest::BlockForest> forest); - virtual ~WritePeBlocksCoProcessor(); + WritePeBlocksCoProcessor(SPtr<Grid3D> grid, SPtr<UbScheduler> s, const std::string &path, WbWriter *const writer, + SPtr<Communicator> comm, SPtr<walberla::blockforest::BlockForest> forest); + virtual ~WritePeBlocksCoProcessor(); - void process(double step) override; + void process(double step) override; protected: - void collectData(double step); + void collectData(double step); - std::string path; - WbWriter* writer; - SPtr<Communicator> comm; - SPtr<walberla::blockforest::BlockForest> forest; + std::string path; + WbWriter *writer; + SPtr<Communicator> comm; + SPtr<walberla::blockforest::BlockForest> forest; }; - - -#endif - +#endif diff --git a/src/cpu/DemCoupling/physicsEngineAdapter/PhysicsEngineGeometryAdapter.h b/src/cpu/DemCoupling/physicsEngineAdapter/PhysicsEngineGeometryAdapter.h index a7eb5c6bcc0cee7c38aaa3d191c3f887644c1177..490c1f979eaba285f1c39f834396acf9646584d9 100644 --- a/src/cpu/DemCoupling/physicsEngineAdapter/PhysicsEngineGeometryAdapter.h +++ b/src/cpu/DemCoupling/physicsEngineAdapter/PhysicsEngineGeometryAdapter.h @@ -1,45 +1,40 @@ /* -* Author: S. Peters -* mail: peters@irmb.tu-bs.de -*/ + * Author: S. Peters + * mail: peters@irmb.tu-bs.de + */ #ifndef PHYSICS_ENGINE_GEOMETRY_ADAPTER_H #define PHYSICS_ENGINE_GEOMETRY_ADAPTER_H #include "Vector3D.h" -enum class State -{ - PIN, UNPIN -}; +enum class State { PIN, UNPIN }; class PhysicsEngineGeometryAdapter { public: virtual ~PhysicsEngineGeometryAdapter() {} - virtual void addForce(const Vector3D& force) = 0; - virtual void addTorque(const Vector3D& torque) = 0; + virtual void addForce(const Vector3D &force) = 0; + virtual void addTorque(const Vector3D &torque) = 0; - virtual void setForce(const Vector3D& force) = 0; - virtual void setTorque(const Vector3D& torque) = 0; + virtual void setForce(const Vector3D &force) = 0; + virtual void setTorque(const Vector3D &torque) = 0; - virtual void addForceAtPosition(const Vector3D& force, const Vector3D& position) = 0; - virtual void setLinearVelolocity(const Vector3D& velocity) = 0; - virtual void setAngularVelocity(const Vector3D& velocity) = 0; + virtual void addForceAtPosition(const Vector3D &force, const Vector3D &position) = 0; + virtual void setLinearVelolocity(const Vector3D &velocity) = 0; + virtual void setAngularVelocity(const Vector3D &velocity) = 0; virtual void resetForceAndTorque() = 0; - virtual Vector3D getPosition() const = 0; - virtual Vector3D getVelocityAtPosition(const Vector3D& position) const = 0; - virtual Vector3D getLinearVelocity() const = 0; - virtual Vector3D getAngularVelocity() const = 0; + virtual Vector3D getPosition() const = 0; + virtual Vector3D getVelocityAtPosition(const Vector3D &position) const = 0; + virtual Vector3D getLinearVelocity() const = 0; + virtual Vector3D getAngularVelocity() const = 0; - virtual Vector3D getForce() const = 0; + virtual Vector3D getForce() const = 0; virtual Vector3D getTorque() const = 0; virtual void changeState(State state) = 0; }; - #endif - diff --git a/src/cpu/DemCoupling/physicsEngineAdapter/PhysicsEngineMaterialAdapter.h b/src/cpu/DemCoupling/physicsEngineAdapter/PhysicsEngineMaterialAdapter.h index 1b887cda1cb5d5b28711d1f004223b7750c55151..30504bee98580f25f23e37030d5ec8180fce3ebc 100644 --- a/src/cpu/DemCoupling/physicsEngineAdapter/PhysicsEngineMaterialAdapter.h +++ b/src/cpu/DemCoupling/physicsEngineAdapter/PhysicsEngineMaterialAdapter.h @@ -1,7 +1,7 @@ /* -* Author: S. Peters -* mail: peters@irmb.tu-bs.de -*/ + * Author: S. Peters + * mail: peters@irmb.tu-bs.de + */ #ifndef PHYSICS_ENGINE_MATERIAL_ADAPTER_H #define PHYSICS_ENGINE_MATERIAL_ADAPTER_H @@ -10,16 +10,24 @@ class PhysicsEngineMaterialAdapter { public: - PhysicsEngineMaterialAdapter(std::string name, double density, double restitution, double staticFriction, double dynamicFriction, double poissonRatio, double youngModul, double stiffnessInNormalDirection, double dampingoefficientNormalDirection, double dampingTangentialDirection) - : name(name), density(density), restitution(restitution), staticFriction(staticFriction), dynamicFriction(dynamicFriction), poissonRatio(poissonRatio), youngModul(youngModul), stiffnessInNormalDirection(stiffnessInNormalDirection), dampingoefficientNormalDirection(dampingoefficientNormalDirection), dampingTangentialDirection(dampingTangentialDirection) - {} + PhysicsEngineMaterialAdapter(std::string name, double density, double restitution, double staticFriction, + double dynamicFriction, double poissonRatio, double youngModul, + double stiffnessInNormalDirection, double dampingoefficientNormalDirection, + double dampingTangentialDirection) + : name(name), density(density), restitution(restitution), staticFriction(staticFriction), + dynamicFriction(dynamicFriction), poissonRatio(poissonRatio), youngModul(youngModul), + stiffnessInNormalDirection(stiffnessInNormalDirection), + dampingoefficientNormalDirection(dampingoefficientNormalDirection), + dampingTangentialDirection(dampingTangentialDirection) + { + } virtual ~PhysicsEngineMaterialAdapter() {} protected: std::string name; double density; double restitution; - double staticFriction; // Note: pe doubles the input coefficient of friction for material-material contacts. + double staticFriction; // Note: pe doubles the input coefficient of friction for material-material contacts. double dynamicFriction; // Similar to static friction for low speed friction. double poissonRatio; double youngModul; @@ -28,6 +36,4 @@ protected: double dampingTangentialDirection; }; - #endif - diff --git a/src/cpu/DemCoupling/physicsEngineAdapter/PhysicsEngineSolverAdapter.h b/src/cpu/DemCoupling/physicsEngineAdapter/PhysicsEngineSolverAdapter.h index bb035ab312961294998d6ae55383c2d3450c98c8..8e03bf1d6e651f993012acc1e8297e309e993cc8 100644 --- a/src/cpu/DemCoupling/physicsEngineAdapter/PhysicsEngineSolverAdapter.h +++ b/src/cpu/DemCoupling/physicsEngineAdapter/PhysicsEngineSolverAdapter.h @@ -1,13 +1,12 @@ /* -* Author: S. Peters -* mail: peters@irmb.tu-bs.de -*/ + * Author: S. Peters + * mail: peters@irmb.tu-bs.de + */ #ifndef PHYSICS_ENGINE_SOLVER_ADAPTER_H #define PHYSICS_ENGINE_SOLVER_ADAPTER_H #include "Vector3D.h" - class PhysicsEngineGeometryAdapter; class PhysicsEngineMaterialAdapter; @@ -16,11 +15,10 @@ class PhysicsEngineSolverAdapter public: virtual ~PhysicsEngineSolverAdapter() {} - virtual std::shared_ptr<PhysicsEngineGeometryAdapter> createPhysicsEngineGeometryAdapter(int id, const Vector3D& position, double radius, std::shared_ptr<PhysicsEngineMaterialAdapter> material) const = 0; - virtual void runTimestep(double step) = 0; + virtual std::shared_ptr<PhysicsEngineGeometryAdapter> + createPhysicsEngineGeometryAdapter(int id, const Vector3D &position, double radius, + std::shared_ptr<PhysicsEngineMaterialAdapter> material) const = 0; + virtual void runTimestep(double step) = 0; }; - - #endif - diff --git a/src/cpu/DemCoupling/physicsEngineAdapter/dummy/DummyPhysicsEngineGeometryAdapter.cpp b/src/cpu/DemCoupling/physicsEngineAdapter/dummy/DummyPhysicsEngineGeometryAdapter.cpp index ababa676a26f2c0e7070368ac3b2b3b10aad3148..b18a57532880491a2419ff9d78bc0c64aac108f8 100644 --- a/src/cpu/DemCoupling/physicsEngineAdapter/dummy/DummyPhysicsEngineGeometryAdapter.cpp +++ b/src/cpu/DemCoupling/physicsEngineAdapter/dummy/DummyPhysicsEngineGeometryAdapter.cpp @@ -1,79 +1,31 @@ #include "DummyPhysicsEngineGeometryAdapter.h" +void DummyPhysicsEngineGeometryAdapter::addForce(const Vector3D &force) {} +void DummyPhysicsEngineGeometryAdapter::addTorque(const Vector3D &torque) {} -void DummyPhysicsEngineGeometryAdapter::addForce(const Vector3D& force) -{ +void DummyPhysicsEngineGeometryAdapter::setForce(const Vector3D &force) {} -} +void DummyPhysicsEngineGeometryAdapter::setTorque(const Vector3D &torque) {} -void DummyPhysicsEngineGeometryAdapter::addTorque(const Vector3D& torque) -{ +void DummyPhysicsEngineGeometryAdapter::addForceAtPosition(const Vector3D &force, const Vector3D &position) {} -} +void DummyPhysicsEngineGeometryAdapter::setLinearVelolocity(const Vector3D &velocity) { this->velocity = velocity; } -void DummyPhysicsEngineGeometryAdapter::setForce(const Vector3D& force) -{ +void DummyPhysicsEngineGeometryAdapter::setAngularVelocity(const Vector3D &velocity) {} -} +void DummyPhysicsEngineGeometryAdapter::resetForceAndTorque() {} -void DummyPhysicsEngineGeometryAdapter::setTorque(const Vector3D& torque) -{ +Vector3D DummyPhysicsEngineGeometryAdapter::getVelocityAtPosition(const Vector3D &position) const { return velocity; } -} +Vector3D DummyPhysicsEngineGeometryAdapter::getLinearVelocity() const { return Vector3D(); } -void DummyPhysicsEngineGeometryAdapter::addForceAtPosition(const Vector3D& force, const Vector3D& position) -{ +Vector3D DummyPhysicsEngineGeometryAdapter::getAngularVelocity() const { return Vector3D(); } -} +Vector3D DummyPhysicsEngineGeometryAdapter::getPosition() const { return Vector3D(); } -void DummyPhysicsEngineGeometryAdapter::setLinearVelolocity(const Vector3D& velocity) -{ - this->velocity = velocity; -} +Vector3D DummyPhysicsEngineGeometryAdapter::getForce() const { return Vector3D(); } -void DummyPhysicsEngineGeometryAdapter::setAngularVelocity(const Vector3D& velocity) -{ - -} - -void DummyPhysicsEngineGeometryAdapter::resetForceAndTorque() -{ - -} - -Vector3D DummyPhysicsEngineGeometryAdapter::getVelocityAtPosition(const Vector3D& position) const -{ - return velocity; -} - -Vector3D DummyPhysicsEngineGeometryAdapter::getLinearVelocity() const -{ - return Vector3D(); -} - -Vector3D DummyPhysicsEngineGeometryAdapter::getAngularVelocity() const -{ - return Vector3D(); -} - -Vector3D DummyPhysicsEngineGeometryAdapter::getPosition() const -{ - return Vector3D(); -} - -Vector3D DummyPhysicsEngineGeometryAdapter::getForce() const -{ - return Vector3D(); -} - -Vector3D DummyPhysicsEngineGeometryAdapter::getTorque() const -{ - return Vector3D(); -} - -void DummyPhysicsEngineGeometryAdapter::changeState(State state) -{ - -} +Vector3D DummyPhysicsEngineGeometryAdapter::getTorque() const { return Vector3D(); } +void DummyPhysicsEngineGeometryAdapter::changeState(State state) {} diff --git a/src/cpu/DemCoupling/physicsEngineAdapter/dummy/DummyPhysicsEngineGeometryAdapter.h b/src/cpu/DemCoupling/physicsEngineAdapter/dummy/DummyPhysicsEngineGeometryAdapter.h index 2f37f466b5eb2fc356c567d0b33f71c7acb342fe..70620d3c0681a2d2dc702c4a74f5c8d5a94141ea 100644 --- a/src/cpu/DemCoupling/physicsEngineAdapter/dummy/DummyPhysicsEngineGeometryAdapter.h +++ b/src/cpu/DemCoupling/physicsEngineAdapter/dummy/DummyPhysicsEngineGeometryAdapter.h @@ -1,7 +1,7 @@ /* -* Author: S. Peters -* mail: peters@irmb.tu-bs.de -*/ + * Author: S. Peters + * mail: peters@irmb.tu-bs.de + */ #ifndef DUMMY_PHYSICS_ENGINE_GEOMETRY_ADAPTER_H #define DUMMY_PHYSICS_ENGINE_GEOMETRY_ADAPTER_H @@ -9,27 +9,25 @@ #include "PhysicsEngineGeometryAdapter.h" - - class DummyPhysicsEngineGeometryAdapter : public PhysicsEngineGeometryAdapter { public: DummyPhysicsEngineGeometryAdapter() {} virtual ~DummyPhysicsEngineGeometryAdapter() {} - void addForce(const Vector3D& force) override; - void addTorque(const Vector3D& torque) override; + void addForce(const Vector3D &force) override; + void addTorque(const Vector3D &torque) override; - void setForce(const Vector3D& force) override; - void setTorque(const Vector3D& torque) override; + void setForce(const Vector3D &force) override; + void setTorque(const Vector3D &torque) override; - void addForceAtPosition(const Vector3D& force, const Vector3D& position) override; - void setLinearVelolocity(const Vector3D& velocity) override; - void setAngularVelocity(const Vector3D& velocity) override; + void addForceAtPosition(const Vector3D &force, const Vector3D &position) override; + void setLinearVelolocity(const Vector3D &velocity) override; + void setAngularVelocity(const Vector3D &velocity) override; void resetForceAndTorque() override; - Vector3D getVelocityAtPosition(const Vector3D& position) const override; + Vector3D getVelocityAtPosition(const Vector3D &position) const override; Vector3D getLinearVelocity() const override; Vector3D getAngularVelocity() const override; Vector3D getPosition() const override; @@ -37,9 +35,9 @@ public: Vector3D getTorque() const override; void changeState(State state) override; + private: Vector3D velocity; }; #endif - diff --git a/src/cpu/DemCoupling/physicsEngineAdapter/dummy/DummyPhysicsEngineMaterialAdapter.h b/src/cpu/DemCoupling/physicsEngineAdapter/dummy/DummyPhysicsEngineMaterialAdapter.h index c9b8a44a1b5bdaca5ed8b8194a122471ccc76bbf..e84e0f1089a017ed9135383995c96e55cdf0cee6 100644 --- a/src/cpu/DemCoupling/physicsEngineAdapter/dummy/DummyPhysicsEngineMaterialAdapter.h +++ b/src/cpu/DemCoupling/physicsEngineAdapter/dummy/DummyPhysicsEngineMaterialAdapter.h @@ -1,23 +1,25 @@ /* -* Author: S. Peters -* mail: peters@irmb.tu-bs.de -*/ + * Author: S. Peters + * mail: peters@irmb.tu-bs.de + */ #ifndef DUMMY_PHYSICS_ENGINE_MATERIAL_ADAPTER #define DUMMY_PHYSICS_ENGINE_MATERIAL_ADAPTER #include "PhysicsEngineMaterialAdapter.h" - class DummyPhysicsEngineMaterialAdapter : public PhysicsEngineMaterialAdapter { public: - DummyPhysicsEngineMaterialAdapter(std::string name, double density, double restitution, double staticFriction, double dynamicFriction, double poissonRatio, double youngModul, double stiffnessInNormalDirection, double dampingoefficientNormalDirection, double dampingTangentialDirection) - : PhysicsEngineMaterialAdapter(name, density, restitution, staticFriction, dynamicFriction, poissonRatio, youngModul, stiffnessInNormalDirection, dampingoefficientNormalDirection, dampingTangentialDirection) + DummyPhysicsEngineMaterialAdapter(std::string name, double density, double restitution, double staticFriction, + double dynamicFriction, double poissonRatio, double youngModul, + double stiffnessInNormalDirection, double dampingoefficientNormalDirection, + double dampingTangentialDirection) + : PhysicsEngineMaterialAdapter(name, density, restitution, staticFriction, dynamicFriction, poissonRatio, + youngModul, stiffnessInNormalDirection, dampingoefficientNormalDirection, + dampingTangentialDirection) { } virtual ~DummyPhysicsEngineMaterialAdapter() {} - }; #endif - diff --git a/src/cpu/DemCoupling/physicsEngineAdapter/dummy/DummyPhysicsEngineSolverAdapter.cpp b/src/cpu/DemCoupling/physicsEngineAdapter/dummy/DummyPhysicsEngineSolverAdapter.cpp index 8053942b916b4b45f7f906518fcaf1e295852817..321b523ead35a6a8d16d7b48b1fbb7cb66b0fdc8 100644 --- a/src/cpu/DemCoupling/physicsEngineAdapter/dummy/DummyPhysicsEngineSolverAdapter.cpp +++ b/src/cpu/DemCoupling/physicsEngineAdapter/dummy/DummyPhysicsEngineSolverAdapter.cpp @@ -2,13 +2,11 @@ #include "DummyPhysicsEngineGeometryAdapter.h" - -std::shared_ptr<PhysicsEngineGeometryAdapter> DummyPhysicsEngineSolverAdapter::createPhysicsEngineGeometryAdapter(int id, const Vector3D& position, double radius, std::shared_ptr<PhysicsEngineMaterialAdapter> material) const +std::shared_ptr<PhysicsEngineGeometryAdapter> DummyPhysicsEngineSolverAdapter::createPhysicsEngineGeometryAdapter( + int id, const Vector3D &position, double radius, std::shared_ptr<PhysicsEngineMaterialAdapter> material) const { - return std::static_pointer_cast<PhysicsEngineGeometryAdapter>(std::make_shared<DummyPhysicsEngineGeometryAdapter>()); + return std::static_pointer_cast<PhysicsEngineGeometryAdapter>( + std::make_shared<DummyPhysicsEngineGeometryAdapter>()); } -void DummyPhysicsEngineSolverAdapter::runTimestep(double step) -{ - -} +void DummyPhysicsEngineSolverAdapter::runTimestep(double step) {} diff --git a/src/cpu/DemCoupling/physicsEngineAdapter/dummy/DummyPhysicsEngineSolverAdapter.h b/src/cpu/DemCoupling/physicsEngineAdapter/dummy/DummyPhysicsEngineSolverAdapter.h index 38975727e8fc9761fb05d9ab0a80c23b1c1b40a4..38e9e7f055b415266cfd35c055951707ba4cda44 100644 --- a/src/cpu/DemCoupling/physicsEngineAdapter/dummy/DummyPhysicsEngineSolverAdapter.h +++ b/src/cpu/DemCoupling/physicsEngineAdapter/dummy/DummyPhysicsEngineSolverAdapter.h @@ -1,7 +1,7 @@ /* -* Author: S. Peters -* mail: peters@irmb.tu-bs.de -*/ + * Author: S. Peters + * mail: peters@irmb.tu-bs.de + */ #ifndef DUMMY_PHYSICS_ENGINE_SOLVER_ADAPTER_H #define DUMMY_PHYSICS_ENGINE_SOLVER_ADAPTER_H @@ -11,18 +11,16 @@ #include "PhysicsEngineSolverAdapter.h" - - class DummyPhysicsEngineSolverAdapter : public PhysicsEngineSolverAdapter { public: - DummyPhysicsEngineSolverAdapter() {}; + DummyPhysicsEngineSolverAdapter(){}; virtual ~DummyPhysicsEngineSolverAdapter() {} - std::shared_ptr<PhysicsEngineGeometryAdapter> createPhysicsEngineGeometryAdapter(int id, const Vector3D& position, double radius, std::shared_ptr<PhysicsEngineMaterialAdapter> material) const override; + std::shared_ptr<PhysicsEngineGeometryAdapter> + createPhysicsEngineGeometryAdapter(int id, const Vector3D &position, double radius, + std::shared_ptr<PhysicsEngineMaterialAdapter> material) const override; void runTimestep(double step) override; - }; #endif - diff --git a/src/cpu/DemCoupling/physicsEngineAdapter/pe/PeAdapter.h b/src/cpu/DemCoupling/physicsEngineAdapter/pe/PeAdapter.h index 6f041668521fff8c00ec3cd4bbc5b47f0838e7ab..0373281d60b6618555de3d48190816d79b9ade5b 100644 --- a/src/cpu/DemCoupling/physicsEngineAdapter/pe/PeAdapter.h +++ b/src/cpu/DemCoupling/physicsEngineAdapter/pe/PeAdapter.h @@ -1,28 +1,19 @@ /* -* Author: S. Peters -* mail: peters@irmb.tu-bs.de -*/ + * Author: S. Peters + * mail: peters@irmb.tu-bs.de + */ #ifndef PE_ADAPTER_H #define PE_ADAPTER_H -#include <pe/basic.h> #include "Vector3D.h" - +#include <pe/basic.h> class PeConverter { -public: - static Vector3D convert(walberla::pe::Vec3 vec3) - { - return Vector3D(vec3[0], vec3[1], vec3[2]); - } +public: + static Vector3D convert(walberla::pe::Vec3 vec3) { return Vector3D(vec3[0], vec3[1], vec3[2]); } - static walberla::pe::Vec3 convert(const Vector3D& vec3) - { - return walberla::pe::Vec3(vec3[0], vec3[1], vec3[2]); - } + static walberla::pe::Vec3 convert(const Vector3D &vec3) { return walberla::pe::Vec3(vec3[0], vec3[1], vec3[2]); } }; - #endif - diff --git a/src/cpu/DemCoupling/physicsEngineAdapter/pe/PeAdapterTest.cpp b/src/cpu/DemCoupling/physicsEngineAdapter/pe/PeAdapterTest.cpp index 1deffe629efa72670a8a485241032636f2134de5..a92127c3fd0e2b10ad2d73ee88e7fbd00b8ace85 100644 --- a/src/cpu/DemCoupling/physicsEngineAdapter/pe/PeAdapterTest.cpp +++ b/src/cpu/DemCoupling/physicsEngineAdapter/pe/PeAdapterTest.cpp @@ -6,7 +6,7 @@ //#include "UbTuple.h" // // -//TEST(PeAdapterTest, convert_WalberlaVec3_to_Vector3D) +// TEST(PeAdapterTest, convert_WalberlaVec3_to_Vector3D) //{ // walberla::pe::Vec3 walberlaVec(1.0, -2.0, 3.4); // Vector3D ubTuple = PeConverter::convert(walberlaVec); @@ -16,7 +16,7 @@ // EXPECT_THAT(ubTuple[2], testing::DoubleEq(walberlaVec[2])); //} // -//TEST(PeAdapterTest, convert_Vector3D_to_WalberlaVec3) +// TEST(PeAdapterTest, convert_Vector3D_to_WalberlaVec3) //{ // Vector3D ubTuple(1.0, -2.0, 3.4); // walberla::pe::Vec3 walberlaVec = PeConverter::convert(ubTuple); @@ -25,4 +25,3 @@ // EXPECT_THAT(ubTuple[1], testing::DoubleEq(walberlaVec[1])); // EXPECT_THAT(ubTuple[2], testing::DoubleEq(walberlaVec[2])); //} - diff --git a/src/cpu/DemCoupling/physicsEngineAdapter/pe/PeLoadBalancerAdapter.cpp b/src/cpu/DemCoupling/physicsEngineAdapter/pe/PeLoadBalancerAdapter.cpp index 75d2c285052f85ab94254ed511c759364d417376..6c597698d608a287cc3a8bd5db84fbf061539234 100644 --- a/src/cpu/DemCoupling/physicsEngineAdapter/pe/PeLoadBalancerAdapter.cpp +++ b/src/cpu/DemCoupling/physicsEngineAdapter/pe/PeLoadBalancerAdapter.cpp @@ -1,48 +1,47 @@ #include "PeLoadBalancerAdapter.h" -#include "Grid3D.h" #include "Block3D.h" #include "CoordinateTransformation3D.h" +#include "Grid3D.h" #include "UbLogger.h" #include "core/debug/CheckFunctions.h" - -PeLoadBalancerAdapter::PeLoadBalancerAdapter(SPtr<Grid3D> grid, unsigned numberOfProcesses, int rank) : grid(grid), numberOfProcesses(numberOfProcesses), rank(rank) +PeLoadBalancerAdapter::PeLoadBalancerAdapter(SPtr<Grid3D> grid, unsigned numberOfProcesses, int rank) + : grid(grid), numberOfProcesses(numberOfProcesses), rank(rank) { - } -walberla::uint_t PeLoadBalancerAdapter::operator()(walberla::SetupBlockForest & forest, const walberla::uint_t numberOfProcesses, const walberla::memory_t perProcessMemoryLimit) +walberla::uint_t PeLoadBalancerAdapter::operator()(walberla::SetupBlockForest &forest, + const walberla::uint_t numberOfProcesses, + const walberla::memory_t perProcessMemoryLimit) { - std::vector< walberla::SetupBlock * > peBlocks; - forest.getBlocks(peBlocks); - - for (auto peBlock = peBlocks.begin(); peBlock != peBlocks.end(); ++peBlock) - { - walberla::AABB aabb = (*peBlock)->getAABB(); - SPtr<Block3D> block = getBlockByMinUniform(aabb.xMin()+0.5*(aabb.xMax()-aabb.xMin()), aabb.yMin()+0.5*(aabb.yMax()-aabb.yMin()), aabb.zMin()+0.5*(aabb.zMax()-aabb.zMin()), grid); - if (block) - { - (*peBlock)->assignTargetProcess((walberla::uint_t)block->getRank()); - } - else - { - //TODO: the rank of pe blocks is not consistent with VF blocks - (*peBlock)->assignTargetProcess(0); - //UBLOG(logINFO, "PeLoadBalancerAdapter::operator() peBlockId="<<(*peBlock)->getId()); - } - } - - return numberOfProcesses; + std::vector<walberla::SetupBlock *> peBlocks; + forest.getBlocks(peBlocks); + + for (auto peBlock = peBlocks.begin(); peBlock != peBlocks.end(); ++peBlock) { + walberla::AABB aabb = (*peBlock)->getAABB(); + SPtr<Block3D> block = getBlockByMinUniform(aabb.xMin() + 0.5 * (aabb.xMax() - aabb.xMin()), + aabb.yMin() + 0.5 * (aabb.yMax() - aabb.yMin()), + aabb.zMin() + 0.5 * (aabb.zMax() - aabb.zMin()), grid); + if (block) { + (*peBlock)->assignTargetProcess((walberla::uint_t)block->getRank()); + } else { + // TODO: the rank of pe blocks is not consistent with VF blocks + (*peBlock)->assignTargetProcess(0); + // UBLOG(logINFO, "PeLoadBalancerAdapter::operator() peBlockId="<<(*peBlock)->getId()); + } + } + + return numberOfProcesses; } SPtr<Block3D> PeLoadBalancerAdapter::getBlockByMinUniform(double minX1, double minX2, double minX3, SPtr<Grid3D> grid) { - SPtr<CoordinateTransformation3D> trafo = grid->getCoordinateTransformator(); + SPtr<CoordinateTransformation3D> trafo = grid->getCoordinateTransformator(); - int ix1 = (int)trafo->transformForwardToX1Coordinate(minX1, minX2, minX3); - int ix2 = (int)trafo->transformForwardToX2Coordinate(minX1, minX2, minX3); - int ix3 = (int)trafo->transformForwardToX3Coordinate(minX1, minX2, minX3); + int ix1 = (int)trafo->transformForwardToX1Coordinate(minX1, minX2, minX3); + int ix2 = (int)trafo->transformForwardToX2Coordinate(minX1, minX2, minX3); + int ix3 = (int)trafo->transformForwardToX3Coordinate(minX1, minX2, minX3); - return grid->getBlock(ix1, ix2, ix3, 0); + return grid->getBlock(ix1, ix2, ix3, 0); } diff --git a/src/cpu/DemCoupling/physicsEngineAdapter/pe/PeLoadBalancerAdapter.h b/src/cpu/DemCoupling/physicsEngineAdapter/pe/PeLoadBalancerAdapter.h index 6b904d994de933052435190cb4436ada882e023f..9e1c64dd330cd9b1aa06857d4d441b736c8a39a1 100644 --- a/src/cpu/DemCoupling/physicsEngineAdapter/pe/PeLoadBalancerAdapter.h +++ b/src/cpu/DemCoupling/physicsEngineAdapter/pe/PeLoadBalancerAdapter.h @@ -1,8 +1,8 @@ #ifndef PeLoadBalancerAdapter_h__ #define PeLoadBalancerAdapter_h__ -#include "blockforest/SetupBlockForest.h" #include "PointerDefinitions.h" +#include "blockforest/SetupBlockForest.h" class Grid3D; class Block3D; @@ -10,16 +10,19 @@ class Block3D; class PeLoadBalancerAdapter { public: - PeLoadBalancerAdapter(SPtr<Grid3D> grid, unsigned numberOfProcesses, int rank); - walberla::uint_t operator()( walberla::SetupBlockForest & forest, const walberla::uint_t numberOfProcesses, const walberla::memory_t perProcessMemoryLimit ); - unsigned getNumberOfProcesses() const { return numberOfProcesses; } - int getRank() const { return rank; } + PeLoadBalancerAdapter(SPtr<Grid3D> grid, unsigned numberOfProcesses, int rank); + walberla::uint_t operator()(walberla::SetupBlockForest &forest, const walberla::uint_t numberOfProcesses, + const walberla::memory_t perProcessMemoryLimit); + unsigned getNumberOfProcesses() const { return numberOfProcesses; } + int getRank() const { return rank; } + protected: - SPtr<Block3D> getBlockByMinUniform(double minX1, double minX2, double minX3, SPtr<Grid3D> grid); + SPtr<Block3D> getBlockByMinUniform(double minX1, double minX2, double minX3, SPtr<Grid3D> grid); + private: - SPtr<Grid3D> grid; - unsigned numberOfProcesses; - int rank; + SPtr<Grid3D> grid; + unsigned numberOfProcesses; + int rank; }; #endif // PeLoadBalancerAdapter_h__ \ No newline at end of file diff --git a/src/cpu/DemCoupling/physicsEngineAdapter/pe/PePhysicsEngineGeometryAdapter.cpp b/src/cpu/DemCoupling/physicsEngineAdapter/pe/PePhysicsEngineGeometryAdapter.cpp index a044a6ea2dde5c3c6d352d20edb19e8e6e378360..9800d75b18a78b7eaf0b46c4193b93a55f3ff91b 100644 --- a/src/cpu/DemCoupling/physicsEngineAdapter/pe/PePhysicsEngineGeometryAdapter.cpp +++ b/src/cpu/DemCoupling/physicsEngineAdapter/pe/PePhysicsEngineGeometryAdapter.cpp @@ -4,8 +4,8 @@ #include "PeAdapter.h" - -//PePhysicsEngineGeometryAdapter::PePhysicsEngineGeometryAdapter(walberla::pe::RigidBody* peGeoObject) : peGeoObject(peGeoObject) +// PePhysicsEngineGeometryAdapter::PePhysicsEngineGeometryAdapter(walberla::pe::RigidBody* peGeoObject) : +// peGeoObject(peGeoObject) //{ // this->id = peGeoObject->getID(); // this->active = true; @@ -13,119 +13,93 @@ PePhysicsEngineGeometryAdapter::PePhysicsEngineGeometryAdapter() { - this->id = -999; - this->systemID = -999; - this->active = false; - this->semiactive = false; - shadowCounter = 0; - counter = 0; + this->id = -999; + this->systemID = -999; + this->active = false; + this->semiactive = false; + shadowCounter = 0; + counter = 0; } -void PePhysicsEngineGeometryAdapter::addForce(const Vector3D& force) +void PePhysicsEngineGeometryAdapter::addForce(const Vector3D &force) { - peGeoObject->addForce(PeConverter::convert(force)); + peGeoObject->addForce(PeConverter::convert(force)); } -void PePhysicsEngineGeometryAdapter::addTorque(const Vector3D& torque) +void PePhysicsEngineGeometryAdapter::addTorque(const Vector3D &torque) { - peGeoObject->addTorque(PeConverter::convert(torque)); + peGeoObject->addTorque(PeConverter::convert(torque)); } -void PePhysicsEngineGeometryAdapter::setForce(const Vector3D& force) +void PePhysicsEngineGeometryAdapter::setForce(const Vector3D &force) { - peGeoObject->setForce(PeConverter::convert(force)); + peGeoObject->setForce(PeConverter::convert(force)); } -void PePhysicsEngineGeometryAdapter::setTorque(const Vector3D& torque) +void PePhysicsEngineGeometryAdapter::setTorque(const Vector3D &torque) { - peGeoObject->setTorque(PeConverter::convert(torque)); + peGeoObject->setTorque(PeConverter::convert(torque)); } -void PePhysicsEngineGeometryAdapter::addForceAtPosition(const Vector3D& force, const Vector3D& position) +void PePhysicsEngineGeometryAdapter::addForceAtPosition(const Vector3D &force, const Vector3D &position) { - peGeoObject->addForceAtPos(PeConverter::convert(force), PeConverter::convert(position)); + peGeoObject->addForceAtPos(PeConverter::convert(force), PeConverter::convert(position)); } -void PePhysicsEngineGeometryAdapter::setLinearVelolocity(const Vector3D& velocity) +void PePhysicsEngineGeometryAdapter::setLinearVelolocity(const Vector3D &velocity) { - peGeoObject->setLinearVel(PeConverter::convert(velocity)); + peGeoObject->setLinearVel(PeConverter::convert(velocity)); } -void PePhysicsEngineGeometryAdapter::setAngularVelocity(const Vector3D& velocity) +void PePhysicsEngineGeometryAdapter::setAngularVelocity(const Vector3D &velocity) { - peGeoObject->setAngularVel(PeConverter::convert(velocity)); + peGeoObject->setAngularVel(PeConverter::convert(velocity)); } -void PePhysicsEngineGeometryAdapter::resetForceAndTorque() -{ - peGeoObject->resetForceAndTorque(); -} +void PePhysicsEngineGeometryAdapter::resetForceAndTorque() { peGeoObject->resetForceAndTorque(); } -Vector3D PePhysicsEngineGeometryAdapter::getVelocityAtPosition(const Vector3D& position) const +Vector3D PePhysicsEngineGeometryAdapter::getVelocityAtPosition(const Vector3D &position) const { - return PeConverter::convert(peGeoObject->velFromWF(PeConverter::convert(position))); + return PeConverter::convert(peGeoObject->velFromWF(PeConverter::convert(position))); } Vector3D PePhysicsEngineGeometryAdapter::getLinearVelocity() const { - return PeConverter::convert(peGeoObject->getLinearVel()); + return PeConverter::convert(peGeoObject->getLinearVel()); } Vector3D PePhysicsEngineGeometryAdapter::getAngularVelocity() const { - return PeConverter::convert(peGeoObject->getAngularVel()); + return PeConverter::convert(peGeoObject->getAngularVel()); } Vector3D PePhysicsEngineGeometryAdapter::getPosition() const { - return PeConverter::convert(peGeoObject->getPosition()); + return PeConverter::convert(peGeoObject->getPosition()); } -Vector3D PePhysicsEngineGeometryAdapter::getForce() const -{ - return PeConverter::convert(peGeoObject->getForce()); -} +Vector3D PePhysicsEngineGeometryAdapter::getForce() const { return PeConverter::convert(peGeoObject->getForce()); } -Vector3D PePhysicsEngineGeometryAdapter::getTorque() const -{ - return PeConverter::convert(peGeoObject->getTorque()); -} +Vector3D PePhysicsEngineGeometryAdapter::getTorque() const { return PeConverter::convert(peGeoObject->getTorque()); } void PePhysicsEngineGeometryAdapter::changeState(State state) { - if (state == State::PIN) - peGeoObject->setMassAndInertiaToInfinity(); + if (state == State::PIN) + peGeoObject->setMassAndInertiaToInfinity(); } -int PePhysicsEngineGeometryAdapter::getId() const -{ - return id; -} +int PePhysicsEngineGeometryAdapter::getId() const { return id; } -void PePhysicsEngineGeometryAdapter::setId(int id) -{ - this->id = id; -} +void PePhysicsEngineGeometryAdapter::setId(int id) { this->id = id; } -void PePhysicsEngineGeometryAdapter::setGeometry(walberla::pe::RigidBody* peGeoObject) +void PePhysicsEngineGeometryAdapter::setGeometry(walberla::pe::RigidBody *peGeoObject) { - this->peGeoObject = peGeoObject; + this->peGeoObject = peGeoObject; } ////////////////////////////////////////////////////////////////////////// -void PePhysicsEngineGeometryAdapter::setActive() -{ - active = true; -} +void PePhysicsEngineGeometryAdapter::setActive() { active = true; } ////////////////////////////////////////////////////////////////////////// -void PePhysicsEngineGeometryAdapter::setInactive() -{ - active = false; -} +void PePhysicsEngineGeometryAdapter::setInactive() { active = false; } ////////////////////////////////////////////////////////////////////////// -bool PePhysicsEngineGeometryAdapter::isActive() -{ - - - return active; -} +bool PePhysicsEngineGeometryAdapter::isActive() { return active; } diff --git a/src/cpu/DemCoupling/physicsEngineAdapter/pe/PePhysicsEngineGeometryAdapter.h b/src/cpu/DemCoupling/physicsEngineAdapter/pe/PePhysicsEngineGeometryAdapter.h index 13c830a41704e546f5833ca4697b299980c979e8..a8eaa7d33ede840f4d76ae90ffb44bef30139f99 100644 --- a/src/cpu/DemCoupling/physicsEngineAdapter/pe/PePhysicsEngineGeometryAdapter.h +++ b/src/cpu/DemCoupling/physicsEngineAdapter/pe/PePhysicsEngineGeometryAdapter.h @@ -1,42 +1,41 @@ /* -* Author: S. Peters -* mail: peters@irmb.tu-bs.de -*/ + * Author: S. Peters + * mail: peters@irmb.tu-bs.de + */ #ifndef PE_PHYSICS_ENGINE_GEOMETRY_ADAPTER_H #define PE_PHYSICS_ENGINE_GEOMETRY_ADAPTER_H - #include "PhysicsEngineGeometryAdapter.h" #include <core/DataTypes.h> namespace walberla { - namespace pe - { - class RigidBody; - } +namespace pe +{ +class RigidBody; } +} // namespace walberla class PePhysicsEngineGeometryAdapter : public PhysicsEngineGeometryAdapter { public: PePhysicsEngineGeometryAdapter(); - //PePhysicsEngineGeometryAdapter(walberla::pe::RigidBody* peGeoObject); + // PePhysicsEngineGeometryAdapter(walberla::pe::RigidBody* peGeoObject); virtual ~PePhysicsEngineGeometryAdapter() {} - void addForce(const Vector3D& force) override; - void addTorque(const Vector3D& torque) override; + void addForce(const Vector3D &force) override; + void addTorque(const Vector3D &torque) override; - void setForce(const Vector3D& force) override; - void setTorque(const Vector3D& torque) override; + void setForce(const Vector3D &force) override; + void setTorque(const Vector3D &torque) override; - void addForceAtPosition(const Vector3D& force, const Vector3D& position) override; - void setLinearVelolocity(const Vector3D& velocity) override; - void setAngularVelocity(const Vector3D& velocity) override; + void addForceAtPosition(const Vector3D &force, const Vector3D &position) override; + void setLinearVelolocity(const Vector3D &velocity) override; + void setAngularVelocity(const Vector3D &velocity) override; void resetForceAndTorque() override; - Vector3D getVelocityAtPosition(const Vector3D& position) const override; + Vector3D getVelocityAtPosition(const Vector3D &position) const override; Vector3D getLinearVelocity() const override; Vector3D getAngularVelocity() const override; Vector3D getPosition() const override; @@ -47,13 +46,13 @@ public: int getId() const; void setId(int id); - void setGeometry(walberla::pe::RigidBody* peGeoObject); + void setGeometry(walberla::pe::RigidBody *peGeoObject); void setActive(); void setInactive(); bool isActive(); - //void increaseShadowCounter(); - //void decreaseShad + // void increaseShadowCounter(); + // void decreaseShad int shadowCounter; int counter; @@ -61,15 +60,15 @@ public: void setSystemID(unsigned long long val) { systemID = val; } bool getSemiactive() const { return semiactive; } void setSemiactive(bool val) { semiactive = val; } + private: - walberla::pe::RigidBody* peGeoObject; - //unsigned long long id; + walberla::pe::RigidBody *peGeoObject; + // unsigned long long id; int id; - //walberla::id_t systemId; + // walberla::id_t systemId; unsigned long long systemID; bool active; bool semiactive; }; #endif - diff --git a/src/cpu/DemCoupling/physicsEngineAdapter/pe/PePhysicsEngineMaterialAdapter.cpp b/src/cpu/DemCoupling/physicsEngineAdapter/pe/PePhysicsEngineMaterialAdapter.cpp index fcd4e6eee82d07856d97b003cbfca710b2c0f80c..6a36fa1a3b6415e255e0083ec621f1bcea03e3de 100644 --- a/src/cpu/DemCoupling/physicsEngineAdapter/pe/PePhysicsEngineMaterialAdapter.cpp +++ b/src/cpu/DemCoupling/physicsEngineAdapter/pe/PePhysicsEngineMaterialAdapter.cpp @@ -1,10 +1,11 @@ #include "PePhysicsEngineMaterialAdapter.h" - walberla::pe::MaterialID PePhysicsEngineMaterialAdapter::getPeMaterial() const { if (walberla::pe::Material::find(name) != -1) return walberla::pe::Material::find(name); - return walberla::pe::createMaterial(name, density, restitution, staticFriction, dynamicFriction, poissonRatio, youngModul, stiffnessInNormalDirection, dampingoefficientNormalDirection, dampingTangentialDirection); + return walberla::pe::createMaterial(name, density, restitution, staticFriction, dynamicFriction, poissonRatio, + youngModul, stiffnessInNormalDirection, dampingoefficientNormalDirection, + dampingTangentialDirection); } diff --git a/src/cpu/DemCoupling/physicsEngineAdapter/pe/PePhysicsEngineMaterialAdapter.h b/src/cpu/DemCoupling/physicsEngineAdapter/pe/PePhysicsEngineMaterialAdapter.h index b99afaa38e86c9a1d5da335ff61a60879a14a835..6ebfa8d1d9ca67760bffb9e06cafec256b19cf4f 100644 --- a/src/cpu/DemCoupling/physicsEngineAdapter/pe/PePhysicsEngineMaterialAdapter.h +++ b/src/cpu/DemCoupling/physicsEngineAdapter/pe/PePhysicsEngineMaterialAdapter.h @@ -1,26 +1,28 @@ /* -* Author: S. Peters -* mail: peters@irmb.tu-bs.de -*/ + * Author: S. Peters + * mail: peters@irmb.tu-bs.de + */ #ifndef PE_PHYSICS_ENGINE_MATERIAL_ADAPTER #define PE_PHYSICS_ENGINE_MATERIAL_ADAPTER #include "../PhysicsEngineMaterialAdapter.h" #include <pe/basic.h> - class PePhysicsEngineMaterialAdapter : public PhysicsEngineMaterialAdapter { public: - PePhysicsEngineMaterialAdapter(std::string name, double density, double restitution, double staticFriction, double dynamicFriction, double poissonRatio, double youngModul, double stiffnessInNormalDirection, double dampingoefficientNormalDirection, double dampingTangentialDirection) - : PhysicsEngineMaterialAdapter(name, density, restitution, staticFriction, dynamicFriction, poissonRatio, youngModul, stiffnessInNormalDirection, dampingoefficientNormalDirection, dampingTangentialDirection) + PePhysicsEngineMaterialAdapter(std::string name, double density, double restitution, double staticFriction, + double dynamicFriction, double poissonRatio, double youngModul, + double stiffnessInNormalDirection, double dampingoefficientNormalDirection, + double dampingTangentialDirection) + : PhysicsEngineMaterialAdapter(name, density, restitution, staticFriction, dynamicFriction, poissonRatio, + youngModul, stiffnessInNormalDirection, dampingoefficientNormalDirection, + dampingTangentialDirection) { } virtual ~PePhysicsEngineMaterialAdapter() {} virtual walberla::pe::MaterialID getPeMaterial() const; - }; #endif - diff --git a/src/cpu/DemCoupling/physicsEngineAdapter/pe/PePhysicsEngineSolverAdapter.cpp b/src/cpu/DemCoupling/physicsEngineAdapter/pe/PePhysicsEngineSolverAdapter.cpp index 9aa16a08154fac59166a063a8588ce0e533dc242..dd78dc143fd0aa149663ae674146198491917644 100644 --- a/src/cpu/DemCoupling/physicsEngineAdapter/pe/PePhysicsEngineSolverAdapter.cpp +++ b/src/cpu/DemCoupling/physicsEngineAdapter/pe/PePhysicsEngineSolverAdapter.cpp @@ -2,21 +2,21 @@ #include <exception> -#include <pe/basic.h> -#include <pe/rigidbody/UnionFactory.h> #include "pe/rigidbody/BoxFactory.h" -#include "pe/rigidbody/SphereFactory.h" #include "pe/rigidbody/PlaneFactory.h" +#include "pe/rigidbody/SphereFactory.h" +#include <pe/basic.h> +#include <pe/rigidbody/UnionFactory.h> //#include "geometry/GeometricalFunctions.h" +#include "Communicator.h" #include "PeAdapter.h" +#include "PeLoadBalancerAdapter.h" #include "PePhysicsEngineGeometryAdapter.h" #include "PePhysicsEngineMaterialAdapter.h" -#include "PeLoadBalancerAdapter.h" -#include "Communicator.h" -#include "UbLogger.h" -#include <boost/tuple/tuple.hpp> #include "UbException.h" +#include "UbLogger.h" #include "UbSystem.h" +#include <boost/tuple/tuple.hpp> #include <memory> using namespace walberla; @@ -24,7 +24,9 @@ using namespace walberla::pe; typedef boost::tuple<walberla::pe::Box, walberla::pe::Sphere, walberla::pe::Plane> BodyTypeTuple; -PePhysicsEngineSolverAdapter::PePhysicsEngineSolverAdapter(std::shared_ptr<PeParameter> peParameter, std::shared_ptr<PeLoadBalancerAdapter> loadBalancer) : peParameter(peParameter), loadBalancer(loadBalancer) +PePhysicsEngineSolverAdapter::PePhysicsEngineSolverAdapter(std::shared_ptr<PeParameter> peParameter, + std::shared_ptr<PeLoadBalancerAdapter> loadBalancer) + : peParameter(peParameter), loadBalancer(loadBalancer) { this->initalizePeEnvironment(); } @@ -39,29 +41,28 @@ void PePhysicsEngineSolverAdapter::initalizePeEnvironment() this->initialPeChannel(); } - -std::shared_ptr<PhysicsEngineGeometryAdapter> PePhysicsEngineSolverAdapter::createPhysicsEngineGeometryAdapter(int id, const Vector3D& position, double radius, std::shared_ptr<PhysicsEngineMaterialAdapter> material) const +std::shared_ptr<PhysicsEngineGeometryAdapter> PePhysicsEngineSolverAdapter::createPhysicsEngineGeometryAdapter( + int id, const Vector3D &position, double radius, std::shared_ptr<PhysicsEngineMaterialAdapter> material) const { - const std::shared_ptr<PePhysicsEngineMaterialAdapter> peMaterial = std::dynamic_pointer_cast<PePhysicsEngineMaterialAdapter>(material); + const std::shared_ptr<PePhysicsEngineMaterialAdapter> peMaterial = + std::dynamic_pointer_cast<PePhysicsEngineMaterialAdapter>(material); std::shared_ptr<PePhysicsEngineGeometryAdapter> peGeometryAdapter(new PePhysicsEngineGeometryAdapter()); - //UBLOG(logINFO, "PePhysicsEngineSolverAdapter::createSphere():start"); - walberla::pe::GeomID peGeometry = createSphere(*globalBodyStorage, *forest, *storageId, id, PeConverter::convert(position), radius, peMaterial->getPeMaterial()); - //UBLOG(logINFO, "PePhysicsEngineSolverAdapter::createSphere():end"); - - if (peGeometry) - { - peGeometryAdapter->setId(id); - peGeometryAdapter->setSystemID(peGeometry->getSystemID()); - peGeometryAdapter->setActive(); - peGeometryAdapter->setGeometry(peGeometry); - return peGeometryAdapter; - } - else - { - peGeometryAdapter->setId(id); - peGeometryAdapter->setInactive(); - return peGeometryAdapter; + // UBLOG(logINFO, "PePhysicsEngineSolverAdapter::createSphere():start"); + walberla::pe::GeomID peGeometry = createSphere(*globalBodyStorage, *forest, *storageId, id, + PeConverter::convert(position), radius, peMaterial->getPeMaterial()); + // UBLOG(logINFO, "PePhysicsEngineSolverAdapter::createSphere():end"); + + if (peGeometry) { + peGeometryAdapter->setId(id); + peGeometryAdapter->setSystemID(peGeometry->getSystemID()); + peGeometryAdapter->setActive(); + peGeometryAdapter->setGeometry(peGeometry); + return peGeometryAdapter; + } else { + peGeometryAdapter->setId(id); + peGeometryAdapter->setInactive(); + return peGeometryAdapter; } walberla::pe::syncNextNeighbors<BodyTypeTuple>(*forest, *storageId); @@ -73,8 +74,6 @@ void PePhysicsEngineSolverAdapter::runTimestep(double step) walberla::pe::syncNextNeighbors<BodyTypeTuple>(*forest, *storageId); } - - void PePhysicsEngineSolverAdapter::initialPeBodyStorage() { globalBodyStorage = std::make_shared<walberla::pe::BodyStorage>(); @@ -83,48 +82,57 @@ void PePhysicsEngineSolverAdapter::initialPeBodyStorage() void PePhysicsEngineSolverAdapter::initialPeBlockForest() { - //walberla::SetupBlockForest sforest = walberla::blockforest::createUniformBlockGrid(walberla::AABB(peParameter->simulationDomain[0], peParameter->simulationDomain[1], peParameter->simulationDomain[2], - // peParameter->simulationDomain[3], peParameter->simulationDomain[4], peParameter->simulationDomain[5]), // simulationDomain - // walberla::uint_t(val<1>(peParameter->numberOfBlocks)), walberla::uint_t(val<2>(peParameter->numberOfBlocks)), walberla::uint_t(val<3>(peParameter->numberOfBlocks)),walberla::uint_t(10),walberla::uint_t(10),walberla::uint_t(10), 5.0,false); + // walberla::SetupBlockForest sforest = + // walberla::blockforest::createUniformBlockGrid(walberla::AABB(peParameter->simulationDomain[0], + // peParameter->simulationDomain[1], peParameter->simulationDomain[2], + // peParameter->simulationDomain[3], peParameter->simulationDomain[4], peParameter->simulationDomain[5]), // + // simulationDomain walberla::uint_t(val<1>(peParameter->numberOfBlocks)), + // walberla::uint_t(val<2>(peParameter->numberOfBlocks)), + // walberla::uint_t(val<3>(peParameter->numberOfBlocks)),walberla::uint_t(10),walberla::uint_t(10),walberla::uint_t(10), + // 5.0,false); walberla::SetupBlockForest sforest; - //sforest.addWorkloadMemorySUIDAssignmentFunction( uniformWorkloadAndMemoryAssignment ); - sforest.init(walberla::AABB(peParameter->simulationDomain[0], peParameter->simulationDomain[1], peParameter->simulationDomain[2], - peParameter->simulationDomain[3], peParameter->simulationDomain[4], peParameter->simulationDomain[5]), // simulationDomain - walberla::uint_t(val<1>(peParameter->numberOfBlocks)), walberla::uint_t(val<2>(peParameter->numberOfBlocks)), walberla::uint_t(val<3>(peParameter->numberOfBlocks)), // blocks in each direction - val<1>(peParameter->isPeriodic), val<2>(peParameter->isPeriodic), val<3>(peParameter->isPeriodic)); + // sforest.addWorkloadMemorySUIDAssignmentFunction( uniformWorkloadAndMemoryAssignment ); + sforest.init(walberla::AABB(peParameter->simulationDomain[0], peParameter->simulationDomain[1], + peParameter->simulationDomain[2], peParameter->simulationDomain[3], + peParameter->simulationDomain[4], peParameter->simulationDomain[5]), // simulationDomain + walberla::uint_t(val<1>(peParameter->numberOfBlocks)), + walberla::uint_t(val<2>(peParameter->numberOfBlocks)), + walberla::uint_t(val<3>(peParameter->numberOfBlocks)), // blocks in each direction + val<1>(peParameter->isPeriodic), val<2>(peParameter->isPeriodic), val<3>(peParameter->isPeriodic)); sforest.balanceLoad(*loadBalancer.get(), loadBalancer->getNumberOfProcesses()); - forest = std::shared_ptr< walberla::blockforest::BlockForest >( new walberla::blockforest::BlockForest( walberla::uint_c( loadBalancer->getRank() ), sforest) ); + forest = std::shared_ptr<walberla::blockforest::BlockForest>( + new walberla::blockforest::BlockForest(walberla::uint_c(loadBalancer->getRank()), sforest)); - auto mpiManager = walberla::MPIManager::instance(); - mpiManager->useWorldComm(); + auto mpiManager = walberla::MPIManager::instance(); + mpiManager->useWorldComm(); if (!forest) - throw std::runtime_error("No PE BlockForest created ... "); + throw std::runtime_error("No PE BlockForest created ... "); } void PePhysicsEngineSolverAdapter::initalBlockData() { - storageId = std::make_shared<walberla::domain_decomposition::BlockDataID> - ( - forest->addBlockData(walberla::pe::createStorageDataHandling<BodyTypeTuple>(), "Storage") - ); + storageId = std::make_shared<walberla::domain_decomposition::BlockDataID>( + forest->addBlockData(walberla::pe::createStorageDataHandling<BodyTypeTuple>(), "Storage")); } void PePhysicsEngineSolverAdapter::initalPeIntegrator() { - auto ccdID = forest->addBlockData(walberla::pe::ccd::createHashGridsDataHandling(globalBodyStorage, *storageId), "CCD"); - auto fcdID = forest->addBlockData(walberla::pe::fcd::createGenericFCDDataHandling<BodyTypeTuple, walberla::pe::fcd::AnalyticCollideFunctor>(), "FCD"); + auto ccdID = + forest->addBlockData(walberla::pe::ccd::createHashGridsDataHandling(globalBodyStorage, *storageId), "CCD"); + auto fcdID = forest->addBlockData( + walberla::pe::fcd::createGenericFCDDataHandling<BodyTypeTuple, walberla::pe::fcd::AnalyticCollideFunctor>(), + "FCD"); - cr = std::make_shared<walberla::pe::cr::HardContactSemiImplicitTimesteppingSolvers>(globalBodyStorage, forest, *storageId, ccdID, fcdID); + cr = std::make_shared<walberla::pe::cr::HardContactSemiImplicitTimesteppingSolvers>(globalBodyStorage, forest, + *storageId, ccdID, fcdID); cr->setMaxIterations(peParameter->maxPeIterations); - cr->setRelaxationModel(walberla::pe::cr::HardContactSemiImplicitTimesteppingSolvers::ApproximateInelasticCoulombContactByDecoupling); + cr->setRelaxationModel( + walberla::pe::cr::HardContactSemiImplicitTimesteppingSolvers::ApproximateInelasticCoulombContactByDecoupling); cr->setRelaxationParameter(walberla::real_t(peParameter->relaxationParameter)); cr->setGlobalLinearAcceleration(PeConverter::convert(peParameter->globalLinearAcceleration)); } -void PePhysicsEngineSolverAdapter::executePeBodyTypeTuple() -{ - walberla::pe::SetBodyTypeIDs<BodyTypeTuple>::execute(); -} +void PePhysicsEngineSolverAdapter::executePeBodyTypeTuple() { walberla::pe::SetBodyTypeIDs<BodyTypeTuple>::execute(); } void PePhysicsEngineSolverAdapter::initialPeChannel() const { @@ -132,94 +140,96 @@ void PePhysicsEngineSolverAdapter::initialPeChannel() const auto simulationDomain = forest->getDomain(); - //createPlane(*globalBodyStorage, 0, walberla::pe::Vec3(1, 0, 0), simulationDomain.minCorner(), material); - //createPlane(*globalBodyStorage, 0, walberla::pe::Vec3(-1, 0, 0), simulationDomain.maxCorner(), material); - //createPlane(*globalBodyStorage, 0, walberla::pe::Vec3(0, 1, 0), simulationDomain.minCorner(), material); - //createPlane(*globalBodyStorage, 0, walberla::pe::Vec3(0, -1, 0), simulationDomain.maxCorner(), material); - //createPlane(*globalBodyStorage, 0, walberla::pe::Vec3(0, 0, 1), simulationDomain.minCorner(), material); - //createPlane(*globalBodyStorage, 0, walberla::pe::Vec3(0, 0, -1), simulationDomain.maxCorner(), material); + // createPlane(*globalBodyStorage, 0, walberla::pe::Vec3(1, 0, 0), simulationDomain.minCorner(), material); + // createPlane(*globalBodyStorage, 0, walberla::pe::Vec3(-1, 0, 0), simulationDomain.maxCorner(), material); + // createPlane(*globalBodyStorage, 0, walberla::pe::Vec3(0, 1, 0), simulationDomain.minCorner(), material); + // createPlane(*globalBodyStorage, 0, walberla::pe::Vec3(0, -1, 0), simulationDomain.maxCorner(), material); + // createPlane(*globalBodyStorage, 0, walberla::pe::Vec3(0, 0, 1), simulationDomain.minCorner(), material); + // createPlane(*globalBodyStorage, 0, walberla::pe::Vec3(0, 0, -1), simulationDomain.maxCorner(), material); Vector3D minOffset = peParameter->minOffset; Vector3D maxOffset = peParameter->maxOffset; - walberla::pe::Vec3 minX1_Offset( minOffset.X1(), 0, 0); - walberla::pe::Vec3 maxX1_Offset( maxOffset.X1(), 0, 0); - walberla::pe::Vec3 minX2_Offset( 0, minOffset.X2(), 0); - walberla::pe::Vec3 maxX2_Offset( 0, maxOffset.X2(), 0); - walberla::pe::Vec3 minX3_Offset( 0, 0, minOffset.X3()); - walberla::pe::Vec3 maxX3_Offset( 0, 0, maxOffset.X3()); + walberla::pe::Vec3 minX1_Offset(minOffset.X1(), 0, 0); + walberla::pe::Vec3 maxX1_Offset(maxOffset.X1(), 0, 0); + walberla::pe::Vec3 minX2_Offset(0, minOffset.X2(), 0); + walberla::pe::Vec3 maxX2_Offset(0, maxOffset.X2(), 0); + walberla::pe::Vec3 minX3_Offset(0, 0, minOffset.X3()); + walberla::pe::Vec3 maxX3_Offset(0, 0, maxOffset.X3()); walberla::pe::Vec3 minCorner = simulationDomain.minCorner(); walberla::pe::Vec3 maxCorner = simulationDomain.maxCorner(); - createPlane(*globalBodyStorage, 0, walberla::pe::Vec3( 1, 0, 0), minCorner + minX1_Offset, material); + createPlane(*globalBodyStorage, 0, walberla::pe::Vec3(1, 0, 0), minCorner + minX1_Offset, material); createPlane(*globalBodyStorage, 0, walberla::pe::Vec3(-1, 0, 0), maxCorner + maxX1_Offset, material); - createPlane(*globalBodyStorage, 0, walberla::pe::Vec3( 0, 1, 0), minCorner + minX2_Offset, material); - createPlane(*globalBodyStorage, 0, walberla::pe::Vec3( 0,-1, 0), maxCorner + maxX2_Offset, material); - createPlane(*globalBodyStorage, 0, walberla::pe::Vec3( 0, 0, 1), minCorner + minX3_Offset, material); - createPlane(*globalBodyStorage, 0, walberla::pe::Vec3( 0, 0,-1), maxCorner + maxX3_Offset, material); + createPlane(*globalBodyStorage, 0, walberla::pe::Vec3(0, 1, 0), minCorner + minX2_Offset, material); + createPlane(*globalBodyStorage, 0, walberla::pe::Vec3(0, -1, 0), maxCorner + maxX2_Offset, material); + createPlane(*globalBodyStorage, 0, walberla::pe::Vec3(0, 0, 1), minCorner + minX3_Offset, material); + createPlane(*globalBodyStorage, 0, walberla::pe::Vec3(0, 0, -1), maxCorner + maxX3_Offset, material); } -std::shared_ptr< walberla::blockforest::BlockForest > PePhysicsEngineSolverAdapter::getForest() -{ - return forest; -} +std::shared_ptr<walberla::blockforest::BlockForest> PePhysicsEngineSolverAdapter::getForest() { return forest; } -void PePhysicsEngineSolverAdapter::saveToFile(const std::string & path) +void PePhysicsEngineSolverAdapter::saveToFile(const std::string &path) { - forest->saveToFile(path+"SerializeDeserialize.sbf"); - forest->saveBlockData("SerializeDeserialize.dump", *storageId.get()); + forest->saveToFile(path + "SerializeDeserialize.sbf"); + forest->saveBlockData("SerializeDeserialize.dump", *storageId.get()); } -void PePhysicsEngineSolverAdapter::loadFromFile(const std::string & path) +void PePhysicsEngineSolverAdapter::loadFromFile(const std::string &path) { - //forest = std::make_shared< walberla::blockforest::BlockForest >( walberla::uint_c( walberla::MPIManager::instance()->rank() ), path+"SerializeDeserialize.sbf", true, false ); - std::string file = path+"SerializeDeserialize.sbf"; - forest = std::shared_ptr < walberla::blockforest::BlockForest > (new walberla::blockforest::BlockForest( walberla::uint_c( walberla::MPIManager::instance()->rank() ), file.c_str(), true, false )); - storageId = std::make_shared< walberla::domain_decomposition::BlockDataID >(forest->loadBlockData(path+"SerializeDeserialize.dump", walberla::pe::createStorageDataHandling<BodyTypeTuple>(), "Storage")); - - this->initalPeIntegrator(); - - auto ccdID = forest->addBlockData(walberla::pe::ccd::createHashGridsDataHandling(globalBodyStorage, *storageId), "CCD"); - auto fcdID = forest->addBlockData(walberla::pe::fcd::createGenericFCDDataHandling<BodyTypeTuple, walberla::pe::fcd::AnalyticCollideFunctor>(), "FCD"); - - cr = std::make_shared<walberla::pe::cr::HardContactSemiImplicitTimesteppingSolvers>(globalBodyStorage, forest, *storageId, ccdID, fcdID); - cr->setMaxIterations(peParameter->maxPeIterations); - cr->setRelaxationModel(walberla::pe::cr::HardContactSemiImplicitTimesteppingSolvers::ApproximateInelasticCoulombContactByDecoupling); - cr->setRelaxationParameter(walberla::real_t(peParameter->relaxationParameter)); - cr->setGlobalLinearAcceleration(PeConverter::convert(peParameter->globalLinearAcceleration)); - - this->executePeBodyTypeTuple(); - this->initialPeChannel(); - - for (auto blockIt = forest->begin(); blockIt != forest->end(); ++blockIt) - { - walberla::pe::ccd::ICCD* ccd = blockIt->getData< walberla::pe::ccd::ICCD >(ccdID); - ccd->reloadBodies(); - } -} + // forest = std::make_shared< walberla::blockforest::BlockForest >( walberla::uint_c( + // walberla::MPIManager::instance()->rank() ), path+"SerializeDeserialize.sbf", true, false ); + std::string file = path + "SerializeDeserialize.sbf"; + forest = std::shared_ptr<walberla::blockforest::BlockForest>(new walberla::blockforest::BlockForest( + walberla::uint_c(walberla::MPIManager::instance()->rank()), file.c_str(), true, false)); + storageId = std::make_shared<walberla::domain_decomposition::BlockDataID>(forest->loadBlockData( + path + "SerializeDeserialize.dump", walberla::pe::createStorageDataHandling<BodyTypeTuple>(), "Storage")); -std::shared_ptr<walberla::blockforest::BlockForest> PePhysicsEngineSolverAdapter::getBlockForest() -{ - return forest; + this->initalPeIntegrator(); + + auto ccdID = + forest->addBlockData(walberla::pe::ccd::createHashGridsDataHandling(globalBodyStorage, *storageId), "CCD"); + auto fcdID = forest->addBlockData( + walberla::pe::fcd::createGenericFCDDataHandling<BodyTypeTuple, walberla::pe::fcd::AnalyticCollideFunctor>(), + "FCD"); + + cr = std::make_shared<walberla::pe::cr::HardContactSemiImplicitTimesteppingSolvers>(globalBodyStorage, forest, + *storageId, ccdID, fcdID); + cr->setMaxIterations(peParameter->maxPeIterations); + cr->setRelaxationModel( + walberla::pe::cr::HardContactSemiImplicitTimesteppingSolvers::ApproximateInelasticCoulombContactByDecoupling); + cr->setRelaxationParameter(walberla::real_t(peParameter->relaxationParameter)); + cr->setGlobalLinearAcceleration(PeConverter::convert(peParameter->globalLinearAcceleration)); + + this->executePeBodyTypeTuple(); + this->initialPeChannel(); + + for (auto blockIt = forest->begin(); blockIt != forest->end(); ++blockIt) { + walberla::pe::ccd::ICCD *ccd = blockIt->getData<walberla::pe::ccd::ICCD>(ccdID); + ccd->reloadBodies(); + } } +std::shared_ptr<walberla::blockforest::BlockForest> PePhysicsEngineSolverAdapter::getBlockForest() { return forest; } + std::shared_ptr<walberla::domain_decomposition::BlockDataID> PePhysicsEngineSolverAdapter::getStorageId() { - return storageId; + return storageId; } std::shared_ptr<walberla::pe::BodyStorage> PePhysicsEngineSolverAdapter::getGlobalBodyStorage() { - return globalBodyStorage; + return globalBodyStorage; } -void PePhysicsEngineSolverAdapter::createObstacle(const Vector3D & center, const Vector3D & lengths) +void PePhysicsEngineSolverAdapter::createObstacle(const Vector3D ¢er, const Vector3D &lengths) { - const walberla::pe::MaterialID material = peParameter->planes->getPeMaterial(); - bool global = true; - bool communicating = false; - bool infiniteMass = true; + const walberla::pe::MaterialID material = peParameter->planes->getPeMaterial(); + bool global = true; + bool communicating = false; + bool infiniteMass = true; - walberla::pe::createBox(*globalBodyStorage, *forest, *storageId, 0, PeConverter::convert(center), PeConverter::convert(lengths), material, global, communicating, infiniteMass); + walberla::pe::createBox(*globalBodyStorage, *forest, *storageId, 0, PeConverter::convert(center), + PeConverter::convert(lengths), material, global, communicating, infiniteMass); } diff --git a/src/cpu/DemCoupling/physicsEngineAdapter/pe/PePhysicsEngineSolverAdapter.h b/src/cpu/DemCoupling/physicsEngineAdapter/pe/PePhysicsEngineSolverAdapter.h index b1274ce3a4a4cd6d53c37593d53532a9eb0ee5b3..5b2ef94b8a59b5073aebc7eb999db6e9eb860e3d 100644 --- a/src/cpu/DemCoupling/physicsEngineAdapter/pe/PePhysicsEngineSolverAdapter.h +++ b/src/cpu/DemCoupling/physicsEngineAdapter/pe/PePhysicsEngineSolverAdapter.h @@ -1,19 +1,18 @@ /* -* Author: S. Peters -* mail: peters@irmb.tu-bs.de -*/ + * Author: S. Peters + * mail: peters@irmb.tu-bs.de + */ #ifndef PE_PHYSICS_ENGINE_SOLVER_ADAPTER_H #define PE_PHYSICS_ENGINE_SOLVER_ADAPTER_H #include <memory> #include <shared_mutex> -#include <pe/basic.h> #include "UbTuple.h" +#include <pe/basic.h> -#include "PhysicsEngineSolverAdapter.h" #include "PePhysicsEngineSolverAdapter.h" - +#include "PhysicsEngineSolverAdapter.h" class PePhysicsEngineMaterialAdapter; class PhysicsEngineGeometryAdapter; @@ -22,29 +21,33 @@ class PeLoadBalancerAdapter; namespace walberla { - namespace domain_decomposition - { - class BlockDataID; - } - namespace blockforest - { - class BlockForest; - } - namespace pe - { - class BodyStorage; - class RigidBody; - namespace cr - { - class HardContactSemiImplicitTimesteppingSolvers; - } - } +namespace domain_decomposition +{ +class BlockDataID; } - -struct PeParameter +namespace blockforest +{ +class BlockForest; +} +namespace pe { - PeParameter(double relaxationParameter, int maxPeIterations, Vector3D globalLinearAcceleration, std::shared_ptr<PePhysicsEngineMaterialAdapter> planes, std::array<double, 6> simulationDomain, UbTupleInt3 numberOfBlocks, UbTupleBool3 isPeriodic, Vector3D minOffset, Vector3D maxOffset) - : relaxationParameter(relaxationParameter), maxPeIterations(maxPeIterations), globalLinearAcceleration(globalLinearAcceleration), simulationDomain(simulationDomain), numberOfBlocks(numberOfBlocks), isPeriodic(isPeriodic), planes(planes), minOffset(minOffset), maxOffset(maxOffset) +class BodyStorage; +class RigidBody; +namespace cr +{ +class HardContactSemiImplicitTimesteppingSolvers; +} +} // namespace pe +} // namespace walberla + +struct PeParameter { + PeParameter(double relaxationParameter, int maxPeIterations, Vector3D globalLinearAcceleration, + std::shared_ptr<PePhysicsEngineMaterialAdapter> planes, std::array<double, 6> simulationDomain, + UbTupleInt3 numberOfBlocks, UbTupleBool3 isPeriodic, Vector3D minOffset, Vector3D maxOffset) + : relaxationParameter(relaxationParameter), maxPeIterations(maxPeIterations), + globalLinearAcceleration(globalLinearAcceleration), simulationDomain(simulationDomain), + numberOfBlocks(numberOfBlocks), isPeriodic(isPeriodic), planes(planes), minOffset(minOffset), + maxOffset(maxOffset) { } @@ -60,24 +63,26 @@ struct PeParameter Vector3D minOffset; Vector3D maxOffset; - }; class PePhysicsEngineSolverAdapter : public PhysicsEngineSolverAdapter { public: - PePhysicsEngineSolverAdapter(std::shared_ptr<PeParameter> peParameter, std::shared_ptr<PeLoadBalancerAdapter> loadBalancer); + PePhysicsEngineSolverAdapter(std::shared_ptr<PeParameter> peParameter, + std::shared_ptr<PeLoadBalancerAdapter> loadBalancer); virtual ~PePhysicsEngineSolverAdapter() {} - std::shared_ptr<PhysicsEngineGeometryAdapter> createPhysicsEngineGeometryAdapter(int id, const Vector3D& position, double radius, std::shared_ptr<PhysicsEngineMaterialAdapter> material) const override; + std::shared_ptr<PhysicsEngineGeometryAdapter> + createPhysicsEngineGeometryAdapter(int id, const Vector3D &position, double radius, + std::shared_ptr<PhysicsEngineMaterialAdapter> material) const override; void runTimestep(double step) override; - std::shared_ptr< walberla::blockforest::BlockForest > getForest(); - void saveToFile(const std::string& path); - void loadFromFile(const std::string& path); + std::shared_ptr<walberla::blockforest::BlockForest> getForest(); + void saveToFile(const std::string &path); + void loadFromFile(const std::string &path); std::shared_ptr<walberla::blockforest::BlockForest> getBlockForest(); std::shared_ptr<walberla::domain_decomposition::BlockDataID> getStorageId(); std::shared_ptr<walberla::pe::BodyStorage> getGlobalBodyStorage(); - void createObstacle(const Vector3D& center, const Vector3D& lengths); + void createObstacle(const Vector3D ¢er, const Vector3D &lengths); private: void initalizePeEnvironment(); @@ -94,10 +99,9 @@ private: std::shared_ptr<PeLoadBalancerAdapter> loadBalancer; std::shared_ptr<walberla::pe::BodyStorage> globalBodyStorage; - std::shared_ptr< walberla::blockforest::BlockForest > forest; + std::shared_ptr<walberla::blockforest::BlockForest> forest; std::shared_ptr<walberla::domain_decomposition::BlockDataID> storageId; std::shared_ptr<walberla::pe::cr::HardContactSemiImplicitTimesteppingSolvers> cr; }; #endif - diff --git a/src/cpu/DemCoupling/reconstructor/EquilibriumReconstructor.cpp b/src/cpu/DemCoupling/reconstructor/EquilibriumReconstructor.cpp index ad4db58f174d24ecf456682bb7ed4b878afa410f..c5486db0e23d6df29a04e724471bac74c01ceec8 100644 --- a/src/cpu/DemCoupling/reconstructor/EquilibriumReconstructor.cpp +++ b/src/cpu/DemCoupling/reconstructor/EquilibriumReconstructor.cpp @@ -1,15 +1,17 @@ #include "EquilibriumReconstructor.h" -#include "ILBMKernel.h" +#include "BCArray3D.h" +#include "BCProcessor.h" #include "D3Q27System.h" #include "DataSet3D.h" -#include "BCProcessor.h" -#include "BCArray3D.h" +#include "ILBMKernel.h" #include "PhysicsEngineGeometryAdapter.h" -void EquilibriumReconstructor::reconstructNode(const int& x1, const int& x2, const int& x3, - const Vector3D& worldCoordinates, std::shared_ptr<PhysicsEngineGeometryAdapter> physicsEngineGeometry, std::shared_ptr<ILBMKernel> kernel) const +void EquilibriumReconstructor::reconstructNode(const int &x1, const int &x2, const int &x3, + const Vector3D &worldCoordinates, + std::shared_ptr<PhysicsEngineGeometryAdapter> physicsEngineGeometry, + std::shared_ptr<ILBMKernel> kernel) const { const double averageDensity = this->getLocalAverageDensity(x1, x2, x3, kernel); LBMReal feq[27]; @@ -20,16 +22,15 @@ void EquilibriumReconstructor::reconstructNode(const int& x1, const int& x2, con else D3Q27System::calcIncompFeq(feq, averageDensity, boundaryVelocity[0], boundaryVelocity[1], boundaryVelocity[2]); - SPtr<DistributionArray3D> distributions = kernel->getDataSet()->getFdistributions(); - //distributions->setDistribution(feq, x1, x2, x3); + // distributions->setDistribution(feq, x1, x2, x3); distributions->setDistributionInv(feq, x1, x2, x3); } - -double EquilibriumReconstructor::getLocalAverageDensity(const int &x1, const int &x2, const int &x3, std::shared_ptr<ILBMKernel> kernel) const +double EquilibriumReconstructor::getLocalAverageDensity(const int &x1, const int &x2, const int &x3, + std::shared_ptr<ILBMKernel> kernel) const { - int nAverage = 0; + int nAverage = 0; double averageDensity = 0.0; SPtr<BCArray3D> bcArray = kernel->getBCProcessor()->getBCArray(); @@ -38,14 +39,12 @@ double EquilibriumReconstructor::getLocalAverageDensity(const int &x1, const int SPtr<DistributionArray3D> distributions = kernel->getDataSet()->getFdistributions(); int neighborX1, neighborX2, neighborX3; - for (int fDir = D3Q27System::FSTARTDIR; fDir <= D3Q27System::FENDDIR; fDir++) - { + for (int fDir = D3Q27System::FSTARTDIR; fDir <= D3Q27System::FENDDIR; fDir++) { neighborX1 = x1 + D3Q27System::DX1[fDir]; neighborX2 = x2 + D3Q27System::DX2[fDir]; neighborX3 = x3 + D3Q27System::DX3[fDir]; - if (bcArray->isFluid(neighborX1, neighborX2, neighborX3)) - { + if (bcArray->isFluid(neighborX1, neighborX2, neighborX3)) { distributions->getDistribution(f, neighborX1, neighborX2, neighborX3); averageDensity += D3Q27System::getDensity(f); ++nAverage; @@ -53,4 +52,3 @@ double EquilibriumReconstructor::getLocalAverageDensity(const int &x1, const int } return (nAverage > 0) ? averageDensity / nAverage : 0.0; } - diff --git a/src/cpu/DemCoupling/reconstructor/EquilibriumReconstructor.h b/src/cpu/DemCoupling/reconstructor/EquilibriumReconstructor.h index e75297ddb4844ce57c437e98538d3b3ff243e83b..4a5c0071922645f66baeb6dcf8577f7003ca9078 100644 --- a/src/cpu/DemCoupling/reconstructor/EquilibriumReconstructor.h +++ b/src/cpu/DemCoupling/reconstructor/EquilibriumReconstructor.h @@ -1,7 +1,7 @@ /* -* Author: S. Peters -* mail: peters@irmb.tu-bs.de -*/ + * Author: S. Peters + * mail: peters@irmb.tu-bs.de + */ #ifndef EQUILIBRIUM_RECONSTRUCTOR_H #define EQUILIBRIUM_RECONSTRUCTOR_H @@ -17,13 +17,13 @@ class EquilibriumReconstructor : public Reconstructor public: virtual ~EquilibriumReconstructor() {} - void reconstructNode(const int &x1, const int &x2, const int &x3, const Vector3D& worldCoordinates, std::shared_ptr<PhysicsEngineGeometryAdapter> physicsEngineGeometry, std::shared_ptr<ILBMKernel> kernel) const override; + void reconstructNode(const int &x1, const int &x2, const int &x3, const Vector3D &worldCoordinates, + std::shared_ptr<PhysicsEngineGeometryAdapter> physicsEngineGeometry, + std::shared_ptr<ILBMKernel> kernel) const override; private: - double getLocalAverageDensity(const int &x1, const int &x2, const int &x3, std::shared_ptr<ILBMKernel> kernel) const; + double getLocalAverageDensity(const int &x1, const int &x2, const int &x3, + std::shared_ptr<ILBMKernel> kernel) const; }; - - #endif - diff --git a/src/cpu/DemCoupling/reconstructor/ExtrapolationReconstructor.cpp b/src/cpu/DemCoupling/reconstructor/ExtrapolationReconstructor.cpp index 72cc555a6dfaeb80e05d872090b771d7c61041e2..8bd915b6c130fd8a1b70cf9e54cbfdfc60b6efcc 100644 --- a/src/cpu/DemCoupling/reconstructor/ExtrapolationReconstructor.cpp +++ b/src/cpu/DemCoupling/reconstructor/ExtrapolationReconstructor.cpp @@ -1,82 +1,89 @@ #include "ExtrapolationReconstructor.h" -#include "ILBMKernel.h" +#include "BCArray3D.h" +#include "BCProcessor.h" #include "D3Q27System.h" #include "DataSet3D.h" -#include "BCProcessor.h" -#include "BCArray3D.h" +#include "ILBMKernel.h" -#include "PhysicsEngineGeometryAdapter.h" #include "DistributionArray3D.h" +#include "PhysicsEngineGeometryAdapter.h" void ExtrapolationReconstructor::setAlternativeReconstructor(std::shared_ptr<Reconstructor> alternativeReconstructor) { this->alternativeReconstructor = alternativeReconstructor; } - -ExtrapolationReconstructor::ExtrapolationReconstructor(std::shared_ptr<Reconstructor> alternativeReconstructor) : alternativeReconstructor(alternativeReconstructor) +ExtrapolationReconstructor::ExtrapolationReconstructor(std::shared_ptr<Reconstructor> alternativeReconstructor) + : alternativeReconstructor(alternativeReconstructor) { } -void ExtrapolationReconstructor::reconstructNode(const int& x1, const int& x2, const int& x3, - const Vector3D& worldCoordinates, std::shared_ptr<PhysicsEngineGeometryAdapter> physicsEngineGeometry, std::shared_ptr<ILBMKernel> kernel) const +void ExtrapolationReconstructor::reconstructNode(const int &x1, const int &x2, const int &x3, + const Vector3D &worldCoordinates, + std::shared_ptr<PhysicsEngineGeometryAdapter> physicsEngineGeometry, + std::shared_ptr<ILBMKernel> kernel) const { const UbTupleInt3 extrapolationDirection = getSphereDirection(worldCoordinates, physicsEngineGeometry); const int numberOfCellsForExtrapolation = getNumberOfExtrapolationCells(x1, x2, x3, extrapolationDirection, kernel); - //if (numberOfCellsForExtrapolation < 2) - alternativeReconstructor->reconstructNode(x1, x2, x3, worldCoordinates, physicsEngineGeometry, kernel); - //else + // if (numberOfCellsForExtrapolation < 2) + alternativeReconstructor->reconstructNode(x1, x2, x3, worldCoordinates, physicsEngineGeometry, kernel); + // else //{ - // //UBLOG(logINFO, "point (x,y,z) " << val<1>(worldCoordinates) << ", " << val<2>(worldCoordinates) << ", " << val<3>(worldCoordinates)); - // //UBLOG(logINFO, "extradir (x,y,z) " << val<1>(extrapolationDirection) << ", " << val<2>(extrapolationDirection) << ", " << val<3>(extrapolationDirection)); + // //UBLOG(logINFO, "point (x,y,z) " << val<1>(worldCoordinates) << ", " << val<2>(worldCoordinates) << ", " << + // val<3>(worldCoordinates)); + // //UBLOG(logINFO, "extradir (x,y,z) " << val<1>(extrapolationDirection) << ", " << + // val<2>(extrapolationDirection) << ", " << val<3>(extrapolationDirection)); // //UBLOG(logINFO, "numberOfCellsForExtrapolation: " << numberOfCellsForExtrapolation ); // this->extrapolatePdFs(x1, x2, x3, extrapolationDirection, numberOfCellsForExtrapolation, kernel); //} - } -UbTupleInt3 ExtrapolationReconstructor::getSphereDirection(const Vector3D& worldCoordinates, std::shared_ptr<PhysicsEngineGeometryAdapter> physicsEngineGeometry) const +UbTupleInt3 ExtrapolationReconstructor::getSphereDirection( + const Vector3D &worldCoordinates, std::shared_ptr<PhysicsEngineGeometryAdapter> physicsEngineGeometry) const { const Vector3D spherePosition = physicsEngineGeometry->getPosition(); - const Vector3D bodyNormal = worldCoordinates - spherePosition; + const Vector3D bodyNormal = worldCoordinates - spherePosition; return this->getCorrespondingLatticeDirection(bodyNormal); } -UbTupleInt3 ExtrapolationReconstructor::getCorrespondingLatticeDirection(const Vector3D& direction) const +UbTupleInt3 ExtrapolationReconstructor::getCorrespondingLatticeDirection(const Vector3D &direction) const { int correspondingDirection = 0; - double innerProduct = 0.0; - for (int fDir = D3Q27System::FSTARTDIR; fDir <= D3Q27System::FENDDIR; fDir++) - { + double innerProduct = 0.0; + for (int fDir = D3Q27System::FSTARTDIR; fDir <= D3Q27System::FENDDIR; fDir++) { // compute inner product <dir,c_i> - const double temporaryInnerProduct = direction[0] * D3Q27System::cNorm[0][fDir] + direction[1] * D3Q27System::cNorm[1][fDir] + direction[2] * D3Q27System::cNorm[2][fDir]; - if (temporaryInnerProduct > innerProduct) - { - innerProduct = temporaryInnerProduct; + const double temporaryInnerProduct = direction[0] * D3Q27System::cNorm[0][fDir] + + direction[1] * D3Q27System::cNorm[1][fDir] + + direction[2] * D3Q27System::cNorm[2][fDir]; + if (temporaryInnerProduct > innerProduct) { + innerProduct = temporaryInnerProduct; correspondingDirection = fDir; } } - return UbTupleInt3(D3Q27System::DX1[correspondingDirection], D3Q27System::DX2[correspondingDirection], D3Q27System::DX3[correspondingDirection]); + return UbTupleInt3(D3Q27System::DX1[correspondingDirection], D3Q27System::DX2[correspondingDirection], + D3Q27System::DX3[correspondingDirection]); } -int ExtrapolationReconstructor::getNumberOfExtrapolationCells(const int x1, const int x2, const int x3, const UbTupleInt3& extrapolationDirection, std::shared_ptr<ILBMKernel> kernel) const +int ExtrapolationReconstructor::getNumberOfExtrapolationCells(const int x1, const int x2, const int x3, + const UbTupleInt3 &extrapolationDirection, + std::shared_ptr<ILBMKernel> kernel) const { if (extrapolationDirection == UbTupleInt3(0, 0, 0)) return 0; const int desiredCellsInExtrapolationDirection = 3; - - for (int numCells = 1; numCells <= desiredCellsInExtrapolationDirection; ++numCells) - { - UbTupleInt3 neighbor(x1 + numCells * val<1>(extrapolationDirection), x2 + numCells * val<2>(extrapolationDirection), x3 + numCells * val<3>(extrapolationDirection)); - if(!kernel->isInsideOfDomain(val<1>(neighbor), val<2>(neighbor), val<3>(neighbor))) - return numCells - 1; + for (int numCells = 1; numCells <= desiredCellsInExtrapolationDirection; ++numCells) { + UbTupleInt3 neighbor(x1 + numCells * val<1>(extrapolationDirection), + x2 + numCells * val<2>(extrapolationDirection), + x3 + numCells * val<3>(extrapolationDirection)); + if (!kernel->isInsideOfDomain(val<1>(neighbor), val<2>(neighbor), val<3>(neighbor))) + return numCells - 1; if (!kernel->getBCProcessor()->getBCArray()->isFluid(val<1>(neighbor), val<2>(neighbor), val<3>(neighbor))) return numCells - 1; @@ -84,9 +91,10 @@ int ExtrapolationReconstructor::getNumberOfExtrapolationCells(const int x1, cons return desiredCellsInExtrapolationDirection; } - void ExtrapolationReconstructor::extrapolatePdFs(const int x1, const int x2, const int x3, - const UbTupleInt3& extrapolationDirection, int numberOfCellsForExtrapolation, std::shared_ptr<ILBMKernel> kernel) const + const UbTupleInt3 &extrapolationDirection, + int numberOfCellsForExtrapolation, + std::shared_ptr<ILBMKernel> kernel) const { SPtr<DistributionArray3D> distributions = kernel->getDataSet()->getFdistributions(); @@ -109,9 +117,8 @@ void ExtrapolationReconstructor::extrapolatePdFs(const int x1, const int x2, con for (int fDir = D3Q27System::FSTARTDIR; fDir <= D3Q27System::FENDDIR; fDir++) pdf[fDir] = 3 * pdfNeighbor1[fDir] - 3 * pdfNeighbor2[fDir] + pdfNeighbor3[fDir]; - } - else // numberOfCellsForExtrapolation == 2 // linear normal extrapolation - { + } else // numberOfCellsForExtrapolation == 2 // linear normal extrapolation + { for (int fDir = D3Q27System::FSTARTDIR; fDir <= D3Q27System::FENDDIR; fDir++) pdf[fDir] = 2 * pdfNeighbor1[fDir] - pdfNeighbor2[fDir]; } diff --git a/src/cpu/DemCoupling/reconstructor/ExtrapolationReconstructor.h b/src/cpu/DemCoupling/reconstructor/ExtrapolationReconstructor.h index ec60da39e842b3a0498bcd0dccc77a176d2af0a7..2844fdf2490a43e6db31ea9bf32dbcdea67d6f34 100644 --- a/src/cpu/DemCoupling/reconstructor/ExtrapolationReconstructor.h +++ b/src/cpu/DemCoupling/reconstructor/ExtrapolationReconstructor.h @@ -1,7 +1,7 @@ /* -* Author: S. Peters -* mail: peters@irmb.tu-bs.de -*/ + * Author: S. Peters + * mail: peters@irmb.tu-bs.de + */ #ifndef EXTRAPOLATION_RECONSTRUCTOR_H #define EXTRAPOLATION_RECONSTRUCTOR_H @@ -20,23 +20,22 @@ public: ExtrapolationReconstructor(std::shared_ptr<Reconstructor> alternativeReconstructor); virtual ~ExtrapolationReconstructor() {} - - void reconstructNode(const int &x1, const int &x2, const int &x3, const Vector3D& worldCoordinates, std::shared_ptr<PhysicsEngineGeometryAdapter> physicsEngineGeometry, std::shared_ptr<ILBMKernel> kernel) const override; + void reconstructNode(const int &x1, const int &x2, const int &x3, const Vector3D &worldCoordinates, + std::shared_ptr<PhysicsEngineGeometryAdapter> physicsEngineGeometry, + std::shared_ptr<ILBMKernel> kernel) const override; void setAlternativeReconstructor(std::shared_ptr<Reconstructor> alternativeReconstructor); private: - int getNumberOfExtrapolationCells(const int x1, const int x2, const int x3, const UbTupleInt3& ubTuple, std::shared_ptr<ILBMKernel> kernel) const; - UbTupleInt3 getSphereDirection(const Vector3D& worldCoordinates, std::shared_ptr<PhysicsEngineGeometryAdapter> physicsEngineGeometry) const; - UbTupleInt3 getCorrespondingLatticeDirection(const Vector3D& direction) const; - void extrapolatePdFs(const int x1, const int x2, const int x3, const UbTupleInt3& ubTuple, int numberOfCellsForExtrapolation, std::shared_ptr<ILBMKernel> kernel) const; - + int getNumberOfExtrapolationCells(const int x1, const int x2, const int x3, const UbTupleInt3 &ubTuple, + std::shared_ptr<ILBMKernel> kernel) const; + UbTupleInt3 getSphereDirection(const Vector3D &worldCoordinates, + std::shared_ptr<PhysicsEngineGeometryAdapter> physicsEngineGeometry) const; + UbTupleInt3 getCorrespondingLatticeDirection(const Vector3D &direction) const; + void extrapolatePdFs(const int x1, const int x2, const int x3, const UbTupleInt3 &ubTuple, + int numberOfCellsForExtrapolation, std::shared_ptr<ILBMKernel> kernel) const; std::shared_ptr<Reconstructor> alternativeReconstructor; - }; - - #endif - diff --git a/src/cpu/DemCoupling/reconstructor/LBMReconstructor.cpp b/src/cpu/DemCoupling/reconstructor/LBMReconstructor.cpp index 1cef0c2f023b2fd2c8d07a8a280aa65b82187211..c6dfdc6dfbe064918fc50faf3222ed14d2b3a8d3 100644 --- a/src/cpu/DemCoupling/reconstructor/LBMReconstructor.cpp +++ b/src/cpu/DemCoupling/reconstructor/LBMReconstructor.cpp @@ -1,10 +1,10 @@ #include "LBMReconstructor.h" -#include "ILBMKernel.h" +#include "BCArray3D.h" +#include "BCProcessor.h" #include "D3Q27System.h" #include "DataSet3D.h" -#include "BCProcessor.h" -#include "BCArray3D.h" +#include "ILBMKernel.h" #include "PhysicsEngineGeometryAdapter.h" @@ -12,138 +12,122 @@ using namespace D3Q27System; LBMReconstructor::LBMReconstructor(bool compressible) { - if (compressible) - { - calcMacrosFct = &D3Q27System::calcCompMacroscopicValues; - } - else - { - calcMacrosFct = &D3Q27System::calcIncompMacroscopicValues; - } + if (compressible) { + calcMacrosFct = &D3Q27System::calcCompMacroscopicValues; + } else { + calcMacrosFct = &D3Q27System::calcIncompMacroscopicValues; + } } -void LBMReconstructor::reconstructNode(const int& x1, const int& x2, const int& x3, - const Vector3D& worldCoordinates, std::shared_ptr<PhysicsEngineGeometryAdapter> physicsEngineGeometry, std::shared_ptr<ILBMKernel> kernel) const +void LBMReconstructor::reconstructNode(const int &x1, const int &x2, const int &x3, const Vector3D &worldCoordinates, + std::shared_ptr<PhysicsEngineGeometryAdapter> physicsEngineGeometry, + std::shared_ptr<ILBMKernel> kernel) const { - LBMReal pdf[D3Q27System::ENDF + 1]; - - LBMReal rho, vx1, vx2, vx3; - calcMacrosFct(pdf, rho, vx1, vx2, vx3); - - LBMReal rho_dif = 1; + LBMReal pdf[D3Q27System::ENDF + 1]; - while (rho_dif > 1e-5) - { - for (int fDir = D3Q27System::FSTARTDIR; fDir <= D3Q27System::FENDDIR; fDir++) - { + LBMReal rho, vx1, vx2, vx3; + calcMacrosFct(pdf, rho, vx1, vx2, vx3); - UbTupleInt3 neighbor(x1 + D3Q27System::DX1[fDir], x2 + D3Q27System::DX2[fDir], x3 + D3Q27System::DX3[fDir]); - - if (!kernel->getBCProcessor()->getBCArray()->isFluid(val<1>(neighbor), val<2>(neighbor), val<3>(neighbor))) - { - LBMReal pdfNeighbor[D3Q27System::ENDF + 1]; - SPtr<DistributionArray3D> distributions = kernel->getDataSet()->getFdistributions(); - const int invDir = D3Q27System::INVDIR[fDir]; - distributions->getDistributionForDirection(pdfNeighbor[invDir], val<1>(neighbor), val<2>(neighbor), val<3>(neighbor)); - distributions->setDistributionInvForDirection(pdf[invDir], x1, x2, x3, invDir); - } - - - } - } - - - - LBMReal collFactor = kernel->getCollisionFactor(); - collide(pdf, collFactor); + LBMReal rho_dif = 1; + while (rho_dif > 1e-5) { + for (int fDir = D3Q27System::FSTARTDIR; fDir <= D3Q27System::FENDDIR; fDir++) { + UbTupleInt3 neighbor(x1 + D3Q27System::DX1[fDir], x2 + D3Q27System::DX2[fDir], x3 + D3Q27System::DX3[fDir]); + if (!kernel->getBCProcessor()->getBCArray()->isFluid(val<1>(neighbor), val<2>(neighbor), + val<3>(neighbor))) { + LBMReal pdfNeighbor[D3Q27System::ENDF + 1]; + SPtr<DistributionArray3D> distributions = kernel->getDataSet()->getFdistributions(); + const int invDir = D3Q27System::INVDIR[fDir]; + distributions->getDistributionForDirection(pdfNeighbor[invDir], val<1>(neighbor), val<2>(neighbor), + val<3>(neighbor)); + distributions->setDistributionInvForDirection(pdf[invDir], x1, x2, x3, invDir); + } + } + } + LBMReal collFactor = kernel->getCollisionFactor(); + collide(pdf, collFactor); } - -void LBMReconstructor::collide(LBMReal* f, LBMReal collFactor) +void LBMReconstructor::collide(LBMReal *f, LBMReal collFactor) { - LBMReal drho, vx1, vx2, vx3; - LBMReal feq[D3Q27System::ENDF+1]; - - - drho = ((f[TNE]+f[BSW])+(f[TSE]+f[BNW]))+((f[BSE]+f[TNW])+(f[TSW]+f[BNE])) - +(((f[NE]+f[SW])+(f[SE]+f[NW]))+((f[TE]+f[BW])+(f[BE]+f[TW])) - +((f[BN]+f[TS])+(f[TN]+f[BS])))+((f[E]+f[W])+(f[N]+f[S]) - +(f[T]+f[B]))+f[ZERO]; - - vx1 = ((((f[TNE]-f[BSW])+(f[TSE]-f[BNW]))+((f[BSE]-f[TNW])+(f[BNE]-f[TSW])))+ - (((f[BE]-f[TW])+(f[TE]-f[BW]))+((f[SE]-f[NW])+(f[NE]-f[SW])))+ - (f[E]-f[W])); - - vx2 = ((((f[TNE]-f[BSW])+(f[BNW]-f[TSE]))+((f[TNW]-f[BSE])+(f[BNE]-f[TSW])))+ - (((f[BN]-f[TS])+(f[TN]-f[BS]))+((f[NW]-f[SE])+(f[NE]-f[SW])))+ - (f[N]-f[S])); - - vx3 = ((((f[TNE]-f[BSW])+(f[TSE]-f[BNW]))+((f[TNW]-f[BSE])+(f[TSW]-f[BNE])))+ - (((f[TS]-f[BN])+(f[TN]-f[BS]))+((f[TW]-f[BE])+(f[TE]-f[BW])))+ - (f[T]-f[B])); - - LBMReal cu_sq = 1.5*(vx1*vx1+vx2*vx2+vx3*vx3); - - feq[ZERO] = c8o27*(drho-cu_sq); - feq[E] = c2o27*(drho+3.0*(vx1)+c9o2*(vx1)*(vx1)-cu_sq); - feq[W] = c2o27*(drho+3.0*(-vx1)+c9o2*(-vx1)*(-vx1)-cu_sq); - feq[N] = c2o27*(drho+3.0*(vx2)+c9o2*(vx2)*(vx2)-cu_sq); - feq[S] = c2o27*(drho+3.0*(-vx2)+c9o2*(-vx2)*(-vx2)-cu_sq); - feq[T] = c2o27*(drho+3.0*(vx3)+c9o2*(vx3)*(vx3)-cu_sq); - feq[B] = c2o27*(drho+3.0*(-vx3)+c9o2*(-vx3)*(-vx3)-cu_sq); - feq[NE] = c1o54*(drho+3.0*(vx1+vx2)+c9o2*(vx1+vx2)*(vx1+vx2)-cu_sq); - feq[SW] = c1o54*(drho+3.0*(-vx1-vx2)+c9o2*(-vx1-vx2)*(-vx1-vx2)-cu_sq); - feq[SE] = c1o54*(drho+3.0*(vx1-vx2)+c9o2*(vx1-vx2)*(vx1-vx2)-cu_sq); - feq[NW] = c1o54*(drho+3.0*(-vx1+vx2)+c9o2*(-vx1+vx2)*(-vx1+vx2)-cu_sq); - feq[TE] = c1o54*(drho+3.0*(vx1+vx3)+c9o2*(vx1+vx3)*(vx1+vx3)-cu_sq); - feq[BW] = c1o54*(drho+3.0*(-vx1-vx3)+c9o2*(-vx1-vx3)*(-vx1-vx3)-cu_sq); - feq[BE] = c1o54*(drho+3.0*(vx1-vx3)+c9o2*(vx1-vx3)*(vx1-vx3)-cu_sq); - feq[TW] = c1o54*(drho+3.0*(-vx1+vx3)+c9o2*(-vx1+vx3)*(-vx1+vx3)-cu_sq); - feq[TN] = c1o54*(drho+3.0*(vx2+vx3)+c9o2*(vx2+vx3)*(vx2+vx3)-cu_sq); - feq[BS] = c1o54*(drho+3.0*(-vx2-vx3)+c9o2*(-vx2-vx3)*(-vx2-vx3)-cu_sq); - feq[BN] = c1o54*(drho+3.0*(vx2-vx3)+c9o2*(vx2-vx3)*(vx2-vx3)-cu_sq); - feq[TS] = c1o54*(drho+3.0*(-vx2+vx3)+c9o2*(-vx2+vx3)*(-vx2+vx3)-cu_sq); - feq[TNE] = c1o216*(drho+3.0*(vx1+vx2+vx3)+c9o2*(vx1+vx2+vx3)*(vx1+vx2+vx3)-cu_sq); - feq[BSW] = c1o216*(drho+3.0*(-vx1-vx2-vx3)+c9o2*(-vx1-vx2-vx3)*(-vx1-vx2-vx3)-cu_sq); - feq[BNE] = c1o216*(drho+3.0*(vx1+vx2-vx3)+c9o2*(vx1+vx2-vx3)*(vx1+vx2-vx3)-cu_sq); - feq[TSW] = c1o216*(drho+3.0*(-vx1-vx2+vx3)+c9o2*(-vx1-vx2+vx3)*(-vx1-vx2+vx3)-cu_sq); - feq[TSE] = c1o216*(drho+3.0*(vx1-vx2+vx3)+c9o2*(vx1-vx2+vx3)*(vx1-vx2+vx3)-cu_sq); - feq[BNW] = c1o216*(drho+3.0*(-vx1+vx2-vx3)+c9o2*(-vx1+vx2-vx3)*(-vx1+vx2-vx3)-cu_sq); - feq[BSE] = c1o216*(drho+3.0*(vx1-vx2-vx3)+c9o2*(vx1-vx2-vx3)*(vx1-vx2-vx3)-cu_sq); - feq[TNW] = c1o216*(drho+3.0*(-vx1+vx2+vx3)+c9o2*(-vx1+vx2+vx3)*(-vx1+vx2+vx3)-cu_sq); - - //Relaxation - f[ZERO] += (feq[ZERO]-f[ZERO])*collFactor; - f[E] += (feq[E]-f[E])*collFactor; - f[W] += (feq[W]-f[W])*collFactor; - f[N] += (feq[N]-f[N])*collFactor; - f[S] += (feq[S]-f[S])*collFactor; - f[T] += (feq[T]-f[T])*collFactor; - f[B] += (feq[B]-f[B])*collFactor; - f[NE] += (feq[NE]-f[NE])*collFactor; - f[SW] += (feq[SW]-f[SW])*collFactor; - f[SE] += (feq[SE]-f[SE])*collFactor; - f[NW] += (feq[NW]-f[NW])*collFactor; - f[TE] += (feq[TE]-f[TE])*collFactor; - f[BW] += (feq[BW]-f[BW])*collFactor; - f[BE] += (feq[BE]-f[BE])*collFactor; - f[TW] += (feq[TW]-f[TW])*collFactor; - f[TN] += (feq[TN]-f[TN])*collFactor; - f[BS] += (feq[BS]-f[BS])*collFactor; - f[BN] += (feq[BN]-f[BN])*collFactor; - f[TS] += (feq[TS]-f[TS])*collFactor; - - f[TNE] += (feq[TNE]-f[TNE])*collFactor; - f[BSW] += (feq[BSW]-f[BSW])*collFactor; - f[BNE] += (feq[BNE]-f[BNE])*collFactor; - f[TSW] += (feq[TSW]-f[TSW])*collFactor; - f[TSE] += (feq[TSE]-f[TSE])*collFactor; - f[BNW] += (feq[BNW]-f[BNW])*collFactor; - f[BSE] += (feq[BSE]-f[BSE])*collFactor; - f[TNW] += (feq[TNW]-f[TNW])*collFactor; + LBMReal drho, vx1, vx2, vx3; + LBMReal feq[D3Q27System::ENDF + 1]; + + drho = ((f[TNE] + f[BSW]) + (f[TSE] + f[BNW])) + ((f[BSE] + f[TNW]) + (f[TSW] + f[BNE])) + + (((f[NE] + f[SW]) + (f[SE] + f[NW])) + ((f[TE] + f[BW]) + (f[BE] + f[TW])) + + ((f[BN] + f[TS]) + (f[TN] + f[BS]))) + + ((f[E] + f[W]) + (f[N] + f[S]) + (f[T] + f[B])) + f[ZERO]; + + vx1 = ((((f[TNE] - f[BSW]) + (f[TSE] - f[BNW])) + ((f[BSE] - f[TNW]) + (f[BNE] - f[TSW]))) + + (((f[BE] - f[TW]) + (f[TE] - f[BW])) + ((f[SE] - f[NW]) + (f[NE] - f[SW]))) + (f[E] - f[W])); + + vx2 = ((((f[TNE] - f[BSW]) + (f[BNW] - f[TSE])) + ((f[TNW] - f[BSE]) + (f[BNE] - f[TSW]))) + + (((f[BN] - f[TS]) + (f[TN] - f[BS])) + ((f[NW] - f[SE]) + (f[NE] - f[SW]))) + (f[N] - f[S])); + + vx3 = ((((f[TNE] - f[BSW]) + (f[TSE] - f[BNW])) + ((f[TNW] - f[BSE]) + (f[TSW] - f[BNE]))) + + (((f[TS] - f[BN]) + (f[TN] - f[BS])) + ((f[TW] - f[BE]) + (f[TE] - f[BW]))) + (f[T] - f[B])); + + LBMReal cu_sq = 1.5 * (vx1 * vx1 + vx2 * vx2 + vx3 * vx3); + + feq[ZERO] = c8o27 * (drho - cu_sq); + feq[E] = c2o27 * (drho + 3.0 * (vx1) + c9o2 * (vx1) * (vx1)-cu_sq); + feq[W] = c2o27 * (drho + 3.0 * (-vx1) + c9o2 * (-vx1) * (-vx1) - cu_sq); + feq[N] = c2o27 * (drho + 3.0 * (vx2) + c9o2 * (vx2) * (vx2)-cu_sq); + feq[S] = c2o27 * (drho + 3.0 * (-vx2) + c9o2 * (-vx2) * (-vx2) - cu_sq); + feq[T] = c2o27 * (drho + 3.0 * (vx3) + c9o2 * (vx3) * (vx3)-cu_sq); + feq[B] = c2o27 * (drho + 3.0 * (-vx3) + c9o2 * (-vx3) * (-vx3) - cu_sq); + feq[NE] = c1o54 * (drho + 3.0 * (vx1 + vx2) + c9o2 * (vx1 + vx2) * (vx1 + vx2) - cu_sq); + feq[SW] = c1o54 * (drho + 3.0 * (-vx1 - vx2) + c9o2 * (-vx1 - vx2) * (-vx1 - vx2) - cu_sq); + feq[SE] = c1o54 * (drho + 3.0 * (vx1 - vx2) + c9o2 * (vx1 - vx2) * (vx1 - vx2) - cu_sq); + feq[NW] = c1o54 * (drho + 3.0 * (-vx1 + vx2) + c9o2 * (-vx1 + vx2) * (-vx1 + vx2) - cu_sq); + feq[TE] = c1o54 * (drho + 3.0 * (vx1 + vx3) + c9o2 * (vx1 + vx3) * (vx1 + vx3) - cu_sq); + feq[BW] = c1o54 * (drho + 3.0 * (-vx1 - vx3) + c9o2 * (-vx1 - vx3) * (-vx1 - vx3) - cu_sq); + feq[BE] = c1o54 * (drho + 3.0 * (vx1 - vx3) + c9o2 * (vx1 - vx3) * (vx1 - vx3) - cu_sq); + feq[TW] = c1o54 * (drho + 3.0 * (-vx1 + vx3) + c9o2 * (-vx1 + vx3) * (-vx1 + vx3) - cu_sq); + feq[TN] = c1o54 * (drho + 3.0 * (vx2 + vx3) + c9o2 * (vx2 + vx3) * (vx2 + vx3) - cu_sq); + feq[BS] = c1o54 * (drho + 3.0 * (-vx2 - vx3) + c9o2 * (-vx2 - vx3) * (-vx2 - vx3) - cu_sq); + feq[BN] = c1o54 * (drho + 3.0 * (vx2 - vx3) + c9o2 * (vx2 - vx3) * (vx2 - vx3) - cu_sq); + feq[TS] = c1o54 * (drho + 3.0 * (-vx2 + vx3) + c9o2 * (-vx2 + vx3) * (-vx2 + vx3) - cu_sq); + feq[TNE] = c1o216 * (drho + 3.0 * (vx1 + vx2 + vx3) + c9o2 * (vx1 + vx2 + vx3) * (vx1 + vx2 + vx3) - cu_sq); + feq[BSW] = c1o216 * (drho + 3.0 * (-vx1 - vx2 - vx3) + c9o2 * (-vx1 - vx2 - vx3) * (-vx1 - vx2 - vx3) - cu_sq); + feq[BNE] = c1o216 * (drho + 3.0 * (vx1 + vx2 - vx3) + c9o2 * (vx1 + vx2 - vx3) * (vx1 + vx2 - vx3) - cu_sq); + feq[TSW] = c1o216 * (drho + 3.0 * (-vx1 - vx2 + vx3) + c9o2 * (-vx1 - vx2 + vx3) * (-vx1 - vx2 + vx3) - cu_sq); + feq[TSE] = c1o216 * (drho + 3.0 * (vx1 - vx2 + vx3) + c9o2 * (vx1 - vx2 + vx3) * (vx1 - vx2 + vx3) - cu_sq); + feq[BNW] = c1o216 * (drho + 3.0 * (-vx1 + vx2 - vx3) + c9o2 * (-vx1 + vx2 - vx3) * (-vx1 + vx2 - vx3) - cu_sq); + feq[BSE] = c1o216 * (drho + 3.0 * (vx1 - vx2 - vx3) + c9o2 * (vx1 - vx2 - vx3) * (vx1 - vx2 - vx3) - cu_sq); + feq[TNW] = c1o216 * (drho + 3.0 * (-vx1 + vx2 + vx3) + c9o2 * (-vx1 + vx2 + vx3) * (-vx1 + vx2 + vx3) - cu_sq); + + // Relaxation + f[ZERO] += (feq[ZERO] - f[ZERO]) * collFactor; + f[E] += (feq[E] - f[E]) * collFactor; + f[W] += (feq[W] - f[W]) * collFactor; + f[N] += (feq[N] - f[N]) * collFactor; + f[S] += (feq[S] - f[S]) * collFactor; + f[T] += (feq[T] - f[T]) * collFactor; + f[B] += (feq[B] - f[B]) * collFactor; + f[NE] += (feq[NE] - f[NE]) * collFactor; + f[SW] += (feq[SW] - f[SW]) * collFactor; + f[SE] += (feq[SE] - f[SE]) * collFactor; + f[NW] += (feq[NW] - f[NW]) * collFactor; + f[TE] += (feq[TE] - f[TE]) * collFactor; + f[BW] += (feq[BW] - f[BW]) * collFactor; + f[BE] += (feq[BE] - f[BE]) * collFactor; + f[TW] += (feq[TW] - f[TW]) * collFactor; + f[TN] += (feq[TN] - f[TN]) * collFactor; + f[BS] += (feq[BS] - f[BS]) * collFactor; + f[BN] += (feq[BN] - f[BN]) * collFactor; + f[TS] += (feq[TS] - f[TS]) * collFactor; + + f[TNE] += (feq[TNE] - f[TNE]) * collFactor; + f[BSW] += (feq[BSW] - f[BSW]) * collFactor; + f[BNE] += (feq[BNE] - f[BNE]) * collFactor; + f[TSW] += (feq[TSW] - f[TSW]) * collFactor; + f[TSE] += (feq[TSE] - f[TSE]) * collFactor; + f[BNW] += (feq[BNW] - f[BNW]) * collFactor; + f[BSE] += (feq[BSE] - f[BSE]) * collFactor; + f[TNW] += (feq[TNW] - f[TNW]) * collFactor; } \ No newline at end of file diff --git a/src/cpu/DemCoupling/reconstructor/LBMReconstructor.h b/src/cpu/DemCoupling/reconstructor/LBMReconstructor.h index 0ba24f89894d20b0b738fedb022fb8f34eb557d5..173f008a30bc9f1edf4b79eecce87fc0941d9f62 100644 --- a/src/cpu/DemCoupling/reconstructor/LBMReconstructor.h +++ b/src/cpu/DemCoupling/reconstructor/LBMReconstructor.h @@ -1,7 +1,7 @@ /* -* Author: S. Peters -* mail: peters@irmb.tu-bs.de -*/ + * Author: S. Peters + * mail: peters@irmb.tu-bs.de + */ #ifndef LBM_RECONSTRUCTOR_H #define LBM_RECONSTRUCTOR_H @@ -14,24 +14,22 @@ class ILBMKernel; class PhysicsEngineGeometryAdapter; - class LBMReconstructor : public Reconstructor { public: LBMReconstructor(bool compressible); virtual ~LBMReconstructor() {} - - void reconstructNode(const int &x1, const int &x2, const int &x3, const Vector3D& worldCoordinates, std::shared_ptr<PhysicsEngineGeometryAdapter> physicsEngineGeometry, std::shared_ptr<ILBMKernel> kernel) const override; -private: - static void collide(LBMReal* f, LBMReal collFactor); + void reconstructNode(const int &x1, const int &x2, const int &x3, const Vector3D &worldCoordinates, + std::shared_ptr<PhysicsEngineGeometryAdapter> physicsEngineGeometry, + std::shared_ptr<ILBMKernel> kernel) const override; - typedef void(*CalcMacrosFct)(const LBMReal* const& /*f[27]*/, LBMReal& /*rho*/, LBMReal& /*vx1*/, LBMReal& /*vx2*/, LBMReal& /*vx3*/); - CalcMacrosFct calcMacrosFct; +private: + static void collide(LBMReal *f, LBMReal collFactor); + typedef void (*CalcMacrosFct)(const LBMReal *const & /*f[27]*/, LBMReal & /*rho*/, LBMReal & /*vx1*/, + LBMReal & /*vx2*/, LBMReal & /*vx3*/); + CalcMacrosFct calcMacrosFct; }; - - #endif - diff --git a/src/cpu/DemCoupling/reconstructor/Reconstructor.h b/src/cpu/DemCoupling/reconstructor/Reconstructor.h index cbcb49ba23b4483bbca5d2c778d682fa1046dca1..15355d515dc332521583955f225c3e8758bb5fb7 100644 --- a/src/cpu/DemCoupling/reconstructor/Reconstructor.h +++ b/src/cpu/DemCoupling/reconstructor/Reconstructor.h @@ -1,7 +1,7 @@ /* -* Author: S. Peters -* mail: peters@irmb.tu-bs.de -*/ + * Author: S. Peters + * mail: peters@irmb.tu-bs.de + */ #ifndef RECONSTRCUTOR_H #define RECONSTRCUTOR_H @@ -17,11 +17,9 @@ class Reconstructor public: virtual ~Reconstructor() {} - virtual void reconstructNode(const int &x1, const int &x2, const int &x3, const Vector3D& worldCoordinates, SPtr<PhysicsEngineGeometryAdapter> physicsEngineGeometry, std::shared_ptr<ILBMKernel> kernel) const = 0; - + virtual void reconstructNode(const int &x1, const int &x2, const int &x3, const Vector3D &worldCoordinates, + SPtr<PhysicsEngineGeometryAdapter> physicsEngineGeometry, + std::shared_ptr<ILBMKernel> kernel) const = 0; }; - - #endif - diff --git a/src/cpu/DemCoupling/reconstructor/VelocityBcReconstructor.cpp b/src/cpu/DemCoupling/reconstructor/VelocityBcReconstructor.cpp index 1b928273074e1faad2deae4fe7e19c85e7d39e05..c48586ca4ed170d7129990590a7e7ec32154c5f7 100644 --- a/src/cpu/DemCoupling/reconstructor/VelocityBcReconstructor.cpp +++ b/src/cpu/DemCoupling/reconstructor/VelocityBcReconstructor.cpp @@ -2,23 +2,25 @@ #include <exception> -#include "ILBMKernel.h" -#include "D3Q27System.h" #include "BCArray3D.h" -#include "EsoTwist3D.h" #include "BCProcessor.h" +#include "D3Q27System.h" #include "DataSet3D.h" +#include "EsoTwist3D.h" +#include "ILBMKernel.h" #include "PhysicsEngineGeometryAdapter.h" -void VelocityBcReconstructor::reconstructNode(const int& x1, const int& x2, const int& x3, - const Vector3D& worldCoordinates, std::shared_ptr<PhysicsEngineGeometryAdapter> physicsEngineGeometry, std::shared_ptr<ILBMKernel> kernel) const +void VelocityBcReconstructor::reconstructNode(const int &x1, const int &x2, const int &x3, + const Vector3D &worldCoordinates, + std::shared_ptr<PhysicsEngineGeometryAdapter> physicsEngineGeometry, + std::shared_ptr<ILBMKernel> kernel) const { if (kernel->getCompressible()) throw std::runtime_error("not implemented yet!"); const Vector3D boundaryVelocity = physicsEngineGeometry->getVelocityAtPosition(worldCoordinates); - //TODO: move to D3Q27 system + // TODO: move to D3Q27 system LBMReal wijk[D3Q27System::ENDF + 1]; D3Q27System::calcIncompFeq(wijk, 1, 0, 0, 0); @@ -47,31 +49,27 @@ void VelocityBcReconstructor::reconstructNode(const int& x1, const int& x2, cons double sumRho = 0, sumWijk = 0; double collFactor = kernel->getCollisionFactor(); - for (int fDir = D3Q27System::FSTARTDIR; fDir <= D3Q27System::FENDDIR; fDir++) - { + for (int fDir = D3Q27System::FSTARTDIR; fDir <= D3Q27System::FENDDIR; fDir++) { neighborX1 = x1 + D3Q27System::DX1[fDir]; neighborX2 = x2 + D3Q27System::DX2[fDir]; neighborX3 = x3 + D3Q27System::DX3[fDir]; - if (bcArray->isFluid(neighborX1, neighborX2, neighborX3)) - { + if (bcArray->isFluid(neighborX1, neighborX2, neighborX3)) { int invDir = D3Q27System::INVDIR[fDir]; neighborX1Inv = x1 + D3Q27System::DX1[invDir]; neighborX2Inv = x2 + D3Q27System::DX2[invDir]; neighborX3Inv = x3 + D3Q27System::DX3[invDir]; - if (!bcArray->isFluid(neighborX1Inv, neighborX2Inv, neighborX3Inv)) - { + if (!bcArray->isFluid(neighborX1Inv, neighborX2Inv, neighborX3Inv)) { double velocity = bc->getBoundaryVelocity(invDir); - fpre[fDir] = fpre[invDir] - velocity; + fpre[fDir] = fpre[invDir] - velocity; double Omega = fpost[fDir] - fpre[fDir]; sumRho += Omega / collFactor + fpre[fDir] - feqNullRho[fDir]; sumWijk += wijk[fDir]; } - } } @@ -79,24 +77,20 @@ void VelocityBcReconstructor::reconstructNode(const int& x1, const int& x2, cons if (sumWijk > 0.0) rho = sumRho / sumWijk; - for (int fDir = D3Q27System::FSTARTDIR; fDir <= D3Q27System::FENDDIR; fDir++) - { + for (int fDir = D3Q27System::FSTARTDIR; fDir <= D3Q27System::FENDDIR; fDir++) { neighborX1 = x1 + D3Q27System::DX1[fDir]; neighborX2 = x2 + D3Q27System::DX2[fDir]; neighborX3 = x3 + D3Q27System::DX3[fDir]; - if (!bcArray->isFluid(neighborX1, neighborX2, neighborX3)) - { - int invDir = D3Q27System::INVDIR[fDir]; + if (!bcArray->isFluid(neighborX1, neighborX2, neighborX3)) { + int invDir = D3Q27System::INVDIR[fDir]; neighborX1Inv = x1 + D3Q27System::DX1[invDir]; neighborX2Inv = x2 + D3Q27System::DX2[invDir]; neighborX3Inv = x3 + D3Q27System::DX3[invDir]; - if (!bcArray->isFluid(neighborX1Inv, neighborX2Inv, neighborX3Inv)) - { - fpre[fDir] = D3Q27System::getIncompFeqForDirection(fDir, rho, bc->getBoundaryVelocityX1(), bc->getBoundaryVelocityX2(), bc->getBoundaryVelocityX3()); + if (!bcArray->isFluid(neighborX1Inv, neighborX2Inv, neighborX3Inv)) { + fpre[fDir] = D3Q27System::getIncompFeqForDirection( + fDir, rho, bc->getBoundaryVelocityX1(), bc->getBoundaryVelocityX2(), bc->getBoundaryVelocityX3()); } - } } - } diff --git a/src/cpu/DemCoupling/reconstructor/VelocityBcReconstructor.h b/src/cpu/DemCoupling/reconstructor/VelocityBcReconstructor.h index 8be5bcb65d20fd1bfeb37ea333ec03223fefa51b..9f5b3f0b67be91edbcfcdadbc8f5c637a87827dc 100644 --- a/src/cpu/DemCoupling/reconstructor/VelocityBcReconstructor.h +++ b/src/cpu/DemCoupling/reconstructor/VelocityBcReconstructor.h @@ -1,7 +1,7 @@ /* -* Author: S. Peters -* mail: peters@irmb.tu-bs.de -*/ + * Author: S. Peters + * mail: peters@irmb.tu-bs.de + */ #ifndef VELOCITY_BC_RECONSTRUCTOR_H #define VELOCITY_BC_RECONSTRUCTOR_H @@ -17,11 +17,9 @@ class VelocityBcReconstructor : public Reconstructor public: virtual ~VelocityBcReconstructor() {} - void reconstructNode(const int &x1, const int &x2, const int &x3, const Vector3D& worldCoordinates, std::shared_ptr<PhysicsEngineGeometryAdapter> physicsEngineGeometry, std::shared_ptr<ILBMKernel> kernel) const override; - + void reconstructNode(const int &x1, const int &x2, const int &x3, const Vector3D &worldCoordinates, + std::shared_ptr<PhysicsEngineGeometryAdapter> physicsEngineGeometry, + std::shared_ptr<ILBMKernel> kernel) const override; }; - - #endif - diff --git a/src/cpu/VirtualFluids.h b/src/cpu/VirtualFluids.h index faae5c778c5e39ca5782c722cf096d0a92df94ae..576687d6957b70d2b52e9b8be89096c6ab336a4b 100644 --- a/src/cpu/VirtualFluids.h +++ b/src/cpu/VirtualFluids.h @@ -34,7 +34,7 @@ #ifndef VirtualFluids_h__ #define VirtualFluids_h__ -//VirtualFluids header files +// VirtualFluids header files #ifdef _OPENMP #include <omp.h> @@ -42,19 +42,6 @@ #include <basics/PointerDefinitions.h> -#include <muParser.h> -#include <muParserBase.h> -#include <muParserBytecode.h> -#include <muParserCallback.h> -#include <muParserDef.h> -#include <muParserDLL.h> -#include <muParserError.h> -#include <muParserFixes.h> -#include <muParserInt.h> -#include <muParserTemplateMagic.h> -#include <muParserTest.h> -#include <muParserToken.h> -#include <muParserTokenReader.h> #include <basics/container/CbArray2D.h> #include <basics/container/CbArray3D.h> #include <basics/container/CbArray4D.h> @@ -100,43 +87,54 @@ #include <basics/writer/WbWriterVtkXmlASCII.h> #include <basics/writer/WbWriterVtkXmlBinary.h> #include <basics/writer/WbWriterX3D.h> +#include <muParser.h> +#include <muParserBase.h> +#include <muParserBytecode.h> +#include <muParserCallback.h> +#include <muParserDLL.h> +#include <muParserDef.h> +#include <muParserError.h> +#include <muParserFixes.h> +#include <muParserInt.h> +#include <muParserTemplateMagic.h> +#include <muParserTest.h> +#include <muParserToken.h> +#include <muParserTokenReader.h> -#include <BoundaryConditions/BCArray3D.h> -#include <BoundaryConditions/BCProcessor.h> +#include <BoundaryConditions/BCAdapter.h> #include <BoundaryConditions/BCAlgorithm.h> +#include <BoundaryConditions/BCArray3D.h> #include <BoundaryConditions/BCFunction.h> +#include <BoundaryConditions/BCProcessor.h> #include <BoundaryConditions/BoundaryConditions.h> -#include <BoundaryConditions/BCAdapter.h> #include <BoundaryConditions/DensityBCAdapter.h> -#include <BoundaryConditions/BCProcessor.h> -#include <BoundaryConditions/ThinWallBCProcessor.h> +#include <BoundaryConditions/EqDensityBCAlgorithm.h> +#include <BoundaryConditions/HighViscosityNoSlipBCAlgorithm.h> #include <BoundaryConditions/NoSlipBCAdapter.h> +#include <BoundaryConditions/NoSlipBCAlgorithm.h> +#include <BoundaryConditions/NonEqDensityBCAlgorithm.h> +#include <BoundaryConditions/NonReflectingOutflowBCAlgorithm.h> #include <BoundaryConditions/SlipBCAdapter.h> +#include <BoundaryConditions/SlipBCAlgorithm.h> +#include <BoundaryConditions/ThinWallBCProcessor.h> +#include <BoundaryConditions/ThinWallNoSlipBCAlgorithm.h> #include <BoundaryConditions/VelocityBCAdapter.h> -#include <BoundaryConditions/BCAlgorithm.h> #include <BoundaryConditions/VelocityBCAlgorithm.h> -#include <BoundaryConditions/NonEqDensityBCAlgorithm.h> -#include <BoundaryConditions/EqDensityBCAlgorithm.h> -#include <BoundaryConditions/NoSlipBCAlgorithm.h> -#include <BoundaryConditions/ThinWallNoSlipBCAlgorithm.h> -#include <BoundaryConditions/HighViscosityNoSlipBCAlgorithm.h> -#include <BoundaryConditions/SlipBCAlgorithm.h> -#include <BoundaryConditions/NonReflectingOutflowBCAlgorithm.h> #include <BoundaryConditions/VelocityWithDensityBCAlgorithm.h> #include <Connectors/Block3DConnector.h> +#include <Connectors/Block3DConnectorFactory.h> +#include <Connectors/CoarseToFineBlock3DConnector.h> +#include <Connectors/CoarseToFineNodeSetBlock3DConnector.h> +#include <Connectors/ConnectorFactory.h> #include <Connectors/D3Q27ETCFOffVectorConnector.h> #include <Connectors/D3Q27ETFCOffVectorConnector.h> #include <Connectors/D3Q27ETFullDirectConnector.h> #include <Connectors/D3Q27ETFullVectorConnector.h> -#include <Connectors/LocalBlock3DConnector.h> -#include <Connectors/RemoteBlock3DConnector.h> -#include <Connectors/CoarseToFineBlock3DConnector.h> -#include <Connectors/CoarseToFineNodeSetBlock3DConnector.h> #include <Connectors/FineToCoarseBlock3DConnector.h> #include <Connectors/FineToCoarseNodeSetBlock3DConnector.h> -#include <Connectors/ConnectorFactory.h> -#include <Connectors/Block3DConnectorFactory.h> +#include <Connectors/LocalBlock3DConnector.h> +#include <Connectors/RemoteBlock3DConnector.h> #include <Data/D3Q27EsoTwist3DSplittedVector.h> #include <Data/D3Q27EsoTwist3DSplittedVectorEx.h> @@ -146,9 +144,9 @@ #include <Data/EsoTwistD3Q27System.h> #include <Data/VoidData3D.h> +#include <Grid/BasicCalculator.h> #include <Grid/Block3D.h> #include <Grid/Calculator.h> -#include <Grid/BasicCalculator.h> #include <Grid/Grid3D.h> #include <Grid/Grid3DSystem.h> @@ -157,59 +155,58 @@ #include <Interactors/Interactor3D.h> #include <Interactors/InteractorsHelper.h> -#include <CoProcessors/WriteBlocksCoProcessor.h> #include <CoProcessors/AdjustForcingCoProcessor.h> #include <CoProcessors/CalculateForcesCoProcessor.h> -#include <CoProcessors/WriteMacroscopicQuantitiesCoProcessor.h> -#include <CoProcessors/WriteMQFromSelectionCoProcessor.h> +#include <CoProcessors/WriteBlocksCoProcessor.h> #include <CoProcessors/WriteBoundaryConditionsCoProcessor.h> +#include <CoProcessors/WriteMQFromSelectionCoProcessor.h> +#include <CoProcessors/WriteMacroscopicQuantitiesCoProcessor.h> //#include <CoProcessors/PathLineCoProcessor.h> //#include <CoProcessors/PathLineCoProcessorMcpart.h> -#include <CoProcessors/PressureDifferenceCoProcessor.h> #include <CoProcessors/EmergencyExitCoProcessor.h> #include <CoProcessors/NUPSCounterCoProcessor.h> +#include <CoProcessors/PressureDifferenceCoProcessor.h> //#include <CoProcessors/Particles.h> -#include <CoProcessors/CoProcessor.h> -#include <CoProcessors/TurbulenceIntensityCoProcessor.h> #include <CoProcessors/AverageValuesCoProcessor.h> +#include <CoProcessors/CoProcessor.h> #include <CoProcessors/DecreaseViscosityCoProcessor.h> -#include <CoProcessors/TimeseriesCoProcessor.h> -#include <CoProcessors/ShearStressCoProcessor.h> -#include <CoProcessors/QCriterionCoProcessor.h> #include <CoProcessors/InSituVTKCoProcessor.h> +#include <CoProcessors/QCriterionCoProcessor.h> +#include <CoProcessors/ShearStressCoProcessor.h> +#include <CoProcessors/TimeseriesCoProcessor.h> +#include <CoProcessors/TurbulenceIntensityCoProcessor.h> //#include <CoProcessors/MeanValuesCoProcessor.h> -#include <CoProcessors/TimeAveragedValuesCoProcessor.h> #include <CoProcessors/InSituCatalystCoProcessor.h> -#include <CoProcessors/MPIIORestartCoProcessor.h> -#include <CoProcessors/MPIIOMigrationCoProcessor.h> -#include <CoProcessors/MPIIOMigrationBECoProcessor.h> -#include <CoProcessors/PressureCoefficientCoProcessor.h> #include <CoProcessors/LineTimeSeriesCoProcessor.h> +#include <CoProcessors/MPIIOMigrationBECoProcessor.h> +#include <CoProcessors/MPIIOMigrationCoProcessor.h> +#include <CoProcessors/MPIIORestartCoProcessor.h> #include <CoProcessors/MicrophoneArrayCoProcessor.h> +#include <CoProcessors/PressureCoefficientCoProcessor.h> +#include <CoProcessors/TimeAveragedValuesCoProcessor.h> #include <IntegrateValuesHelper.h> //#include <LBM/D3Q27CompactInterpolationProcessor.h> -#include <LBM/IncompressibleOffsetInterpolationProcessor.h> #include <LBM/CompressibleOffsetInterpolationProcessor.h> #include <LBM/CompressibleOffsetMomentsInterpolationProcessor.h> #include <LBM/CompressibleOffsetSquarePressureInterpolationProcessor.h> +#include <LBM/IncompressibleOffsetInterpolationProcessor.h> #include <LBM/InterpolationHelper.h> #include <LBM/InterpolationProcessor.h> //#include <LBM/D3Q27OffsetInterpolationProcessor.h> +#include <IncompressibleCumulantWithSpongeLayerLBMKernel.h> +#include <LBM/CompressibleCumulant4thOrderViscosityLBMKernel.h> +#include <LBM/CompressibleCumulantLBMKernel.h> #include <LBM/D3Q27System.h> #include <LBM/ICell.h> -#include <LBM/InterpolationProcessor.h> -#include <LBM/LBMKernel.h> -#include <IncompressibleCumulantWithSpongeLayerLBMKernel.h> -#include <LBM/LBMKernel.h> #include <LBM/IncompressibleCumulantLBMKernel.h> -#include <LBM/CompressibleCumulantLBMKernel.h> -#include <LBM/CompressibleCumulant4thOrderViscosityLBMKernel.h> #include <LBM/InitDensityLBMKernel.h> -#include <LBM/VoidLBMKernel.h> +#include <LBM/InterpolationProcessor.h> +#include <LBM/LBMKernel.h> +#include <LBM/LBMKernelETD3Q27BGK.h> #include <LBM/LBMSystem.h> #include <LBM/LBMUnitConverter.h> -#include <LBM/LBMKernelETD3Q27BGK.h> +#include <LBM/VoidLBMKernel.h> #include <geometry3d/CoordinateTransformation3D.h> #include <geometry3d/GbCuboid3D.h> @@ -225,9 +222,9 @@ #include <geometry3d/GbQuadFaceMesh3D.h> #include <geometry3d/GbSphere3D.h> #include <geometry3d/GbSystem3D.h> +#include <geometry3d/GbTriFaceMesh3D.h> #include <geometry3d/GbTriangle3D.h> #include <geometry3d/GbTriangularMesh3D.h> -#include <geometry3d/GbTriFaceMesh3D.h> #include <geometry3d/GbVector3D.h> #include <geometry3d/GbVoxelMatrix3D.h> #include <geometry3d/KdTree/KdNode.h> @@ -244,29 +241,35 @@ #include <geometry3d/KdTree/splitalgorithms/KdSpatiallMedianSplit.h> #include <geometry3d/KdTree/splitalgorithms/KdSplitAlgorithm.h> +#include <Parallel/BlocksDistributor.h> #include <Parallel/Communicator.h> -#include <Parallel/MetisPartitioner.h> #include <Parallel/MPICommunicator.h> +#include <Parallel/MetisPartitioner.h> #include <Parallel/NullCommunicator.h> #include <Parallel/PriorityQueueDecompositor.h> #include <Parallel/SimpleGeometricPartitioner.h> #include <Parallel/ZoltanPartitioner.h> -#include <Parallel/BlocksDistributor.h> +#include <Utilities/ChangeRandomQs.hpp> +#include <Utilities/CheckpointConverter.h> +#include <Utilities/ConfigurationFile.hpp> #include <Utilities/MathUtil.hpp> #include <Utilities/MemoryUtil.h> -#include <Utilities/ConfigurationFile.hpp> #include <Utilities/VoxelMatrixUtil.hpp> -#include <Utilities/ChangeRandomQs.hpp> -#include <Utilities/CheckpointConverter.h> +#include <CheckRatioBlockVisitor.h> +#include <InitDistributionsFromFileBlockVisitor.h> +#include <InitDistributionsWithInterpolationGridVisitor.h> +#include <SpongeLayerBlockVisitor.h> #include <Visitors/Block3DVisitor.h> +#include <Visitors/BoundaryConditionsBlockVisitor.h> +#include <Visitors/ChangeBoundaryDensityBlockVisitor.h> +#include <Visitors/CoarsenCrossAndInsideGbObjectBlockVisitor.h> +#include <Visitors/ConnectorBlockVisitor.h> #include <Visitors/CreateTransmittersHelper.h> -#include <Visitors/InitDistributionsBlockVisitor.h> -#include <Visitors/SetConnectorsBlockVisitor.h> -#include <Visitors/SetUndefinedNodesBlockVisitor.h> #include <Visitors/GenBlocksGridVisitor.h> #include <Visitors/Grid3DVisitor.h> +#include <Visitors/InitDistributionsBlockVisitor.h> #include <Visitors/MetisPartitioningGridVisitor.h> #include <Visitors/OverlapBlockVisitor.h> #include <Visitors/PQueuePartitioningGridVisitor.h> @@ -274,26 +277,19 @@ #include <Visitors/RatioSmoothBlockVisitor.h> #include <Visitors/RefineCrossAndInsideGbObjectBlockVisitor.h> #include <Visitors/RefineInterGbObjectsVisitor.h> -#include <Visitors/CoarsenCrossAndInsideGbObjectBlockVisitor.h> +#include <Visitors/RenumberBlockVisitor.h> +#include <Visitors/SetBcBlocksBlockVisitor.h> +#include <Visitors/SetConnectorsBlockVisitor.h> +#include <Visitors/SetForcingBlockVisitor.h> #include <Visitors/SetInterpolationDirsBlockVisitor.h> #include <Visitors/SetKernelBlockVisitor.h> -#include <Visitors/SetForcingBlockVisitor.h> -#include <Visitors/SetSpongeLayerBlockVisitor.h> #include <Visitors/SetSolidBlocksBlockVisitor.h> -#include <Visitors/SetBcBlocksBlockVisitor.h> -#include <Visitors/RenumberBlockVisitor.h> -#include <Visitors/ConnectorBlockVisitor.h> +#include <Visitors/SetSpongeLayerBlockVisitor.h> +#include <Visitors/SetUndefinedNodesBlockVisitor.h> #include <Visitors/ViscosityBlockVisitor.h> -#include <Visitors/BoundaryConditionsBlockVisitor.h> -#include <Visitors/BoundaryConditionsBlockVisitor.h> -#include <Visitors/ChangeBoundaryDensityBlockVisitor.h> -#include <InitDistributionsFromFileBlockVisitor.h> -#include <InitDistributionsWithInterpolationGridVisitor.h> -#include <CheckRatioBlockVisitor.h> -#include <SpongeLayerBlockVisitor.h> #include <ZoltanPartitioningGridVisitor.h> -#include <Visitors/RefineCrossAndInsideGbObjectHelper.h> #include <RefineAroundGbObjectHelper.h> +#include <Visitors/RefineCrossAndInsideGbObjectHelper.h> #endif // VirtualFluids_h__ diff --git a/src/cpu/VirtualFluidsCore/BoundaryConditions/BCAdapter.h b/src/cpu/VirtualFluidsCore/BoundaryConditions/BCAdapter.h index b4f08b2002670e8076f6bd19fb1577404f5af0f5..d66dd3bc64caac711c61f75ed92d7065baaa2699 100644 --- a/src/cpu/VirtualFluidsCore/BoundaryConditions/BCAdapter.h +++ b/src/cpu/VirtualFluidsCore/BoundaryConditions/BCAdapter.h @@ -1,28 +1,28 @@ //======================================================================================= -// ____ ____ __ ______ __________ __ __ __ __ -// \ \ | | | | | _ \ |___ ___| | | | | / \ | | -// \ \ | | | | | |_) | | | | | | | / \ | | -// \ \ | | | | | _ / | | | | | | / /\ \ | | -// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ -// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| -// \ \ | | ________________________________________________________________ -// \ \ | | | ______________________________________________________________| -// \ \| | | | __ __ __ __ ______ _______ -// \ | | |_____ | | | | | | | | | _ \ / _____) -// \ | | _____| | | | | | | | | | | \ \ \_______ +// ____ ____ __ ______ __________ __ __ __ __ +// \ \ | | | | | _ \ |___ ___| | | | | / \ | | +// \ \ | | | | | |_) | | | | | | | / \ | | +// \ \ | | | | | _ / | | | | | | / /\ \ | | +// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ +// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| +// \ \ | | ________________________________________________________________ +// \ \ | | | ______________________________________________________________| +// \ \| | | | __ __ __ __ ______ _______ +// \ | | |_____ | | | | | | | | | _ \ / _____) +// \ | | _____| | | | | | | | | | | \ \ \_______ // \ | | | | |_____ | \_/ | | | | |_/ / _____ | -// \ _____| |__| |________| \_______/ |__| |______/ (_______/ +// \ _____| |__| |________| \_______/ |__| |______/ (_______/ // -// This file is part of VirtualFluids. VirtualFluids is free software: you can +// This file is part of VirtualFluids. VirtualFluids is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of +// License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. -// -// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// +// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License along // with VirtualFluids (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>. // @@ -35,8 +35,8 @@ #include <PointerDefinitions.h> -#include "BoundaryConditions.h" #include "BCAlgorithm.h" +#include "BoundaryConditions.h" class D3Q27Interactor; @@ -45,42 +45,45 @@ class D3Q27Interactor; class BCAdapter { public: - BCAdapter() = default; + BCAdapter() = default; - //! \param secondaryBcOption additional option of boundary conditions - BCAdapter(const short& secondaryBcOption) - : secondaryBcOption(secondaryBcOption) - { - } - virtual ~BCAdapter() = default; + //! \param secondaryBcOption additional option of boundary conditions + BCAdapter(const short &secondaryBcOption) : secondaryBcOption(secondaryBcOption) {} + virtual ~BCAdapter() = default; - //methods - bool isTimeDependent() { return((this->type & TIMEDEPENDENT) == TIMEDEPENDENT); } + // methods + bool isTimeDependent() { return ((this->type & TIMEDEPENDENT) == TIMEDEPENDENT); } - virtual short getSecondaryBcOption() { return this->secondaryBcOption; } - virtual void setSecondaryBcOption(const short& val) { this->secondaryBcOption=val; } + virtual short getSecondaryBcOption() { return this->secondaryBcOption; } + virtual void setSecondaryBcOption(const short &val) { this->secondaryBcOption = val; } - virtual void init(const D3Q27Interactor* const& interactor, const double& time=0) = 0; - virtual void update(const D3Q27Interactor* const& interactor, const double& time=0) = 0; + virtual void init(const D3Q27Interactor *const &interactor, const double &time = 0) = 0; + virtual void update(const D3Q27Interactor *const &interactor, const double &time = 0) = 0; - virtual void adaptBC( const D3Q27Interactor& interactor, SPtr<BoundaryConditions> bc, const double& worldX1, const double& worldX2, const double& worldX3, const double& time=0 ) = 0; - virtual void adaptBCForDirection( const D3Q27Interactor& interactor, SPtr<BoundaryConditions> bc, const double& worldX1, const double& worldX2, const double& worldX3, const double& q, const int& fdirection, const double& time=0 ) = 0; + virtual void adaptBC(const D3Q27Interactor &interactor, SPtr<BoundaryConditions> bc, const double &worldX1, + const double &worldX2, const double &worldX3, const double &time = 0) = 0; + virtual void adaptBCForDirection(const D3Q27Interactor &interactor, SPtr<BoundaryConditions> bc, + const double &worldX1, const double &worldX2, const double &worldX3, + const double &q, const int &fdirection, const double &time = 0) = 0; - void setBcAlgorithm(SPtr<BCAlgorithm> alg) {algorithmType = alg->getType(); algorithm = alg;} - SPtr<BCAlgorithm> getAlgorithm() {return algorithm;} - char getBcAlgorithmType() {return algorithmType;} + void setBcAlgorithm(SPtr<BCAlgorithm> alg) + { + algorithmType = alg->getType(); + algorithm = alg; + } + SPtr<BCAlgorithm> getAlgorithm() { return algorithm; } + char getBcAlgorithmType() { return algorithmType; } protected: - short secondaryBcOption{0}; + short secondaryBcOption{ 0 }; - char type{0}; + char type{ 0 }; - SPtr<BCAlgorithm> algorithm; - char algorithmType{-1}; + SPtr<BCAlgorithm> algorithm; + char algorithmType{ -1 }; - static const char TIMEDEPENDENT = 1<<0;//'1'; - static const char TIMEPERIODIC = 1<<1;//'2'; + static const char TIMEDEPENDENT = 1 << 0; //'1'; + static const char TIMEPERIODIC = 1 << 1; //'2'; }; - -#endif //D3Q27BOUNDARYCONDITIONADAPTER_H +#endif // D3Q27BOUNDARYCONDITIONADAPTER_H diff --git a/src/cpu/VirtualFluidsCore/BoundaryConditions/BCAlgorithm.cpp b/src/cpu/VirtualFluidsCore/BoundaryConditions/BCAlgorithm.cpp index ffc8679ac08323fb4f1b0cde851dd04e352c4130..61b427e323dce214240f439eb0ff45c62029e05f 100644 --- a/src/cpu/VirtualFluidsCore/BoundaryConditions/BCAlgorithm.cpp +++ b/src/cpu/VirtualFluidsCore/BoundaryConditions/BCAlgorithm.cpp @@ -1,28 +1,28 @@ //======================================================================================= -// ____ ____ __ ______ __________ __ __ __ __ -// \ \ | | | | | _ \ |___ ___| | | | | / \ | | -// \ \ | | | | | |_) | | | | | | | / \ | | -// \ \ | | | | | _ / | | | | | | / /\ \ | | -// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ -// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| -// \ \ | | ________________________________________________________________ -// \ \ | | | ______________________________________________________________| -// \ \| | | | __ __ __ __ ______ _______ -// \ | | |_____ | | | | | | | | | _ \ / _____) -// \ | | _____| | | | | | | | | | | \ \ \_______ +// ____ ____ __ ______ __________ __ __ __ __ +// \ \ | | | | | _ \ |___ ___| | | | | / \ | | +// \ \ | | | | | |_) | | | | | | | / \ | | +// \ \ | | | | | _ / | | | | | | / /\ \ | | +// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ +// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| +// \ \ | | ________________________________________________________________ +// \ \ | | | ______________________________________________________________| +// \ \| | | | __ __ __ __ ______ _______ +// \ | | |_____ | | | | | | | | | _ \ / _____) +// \ | | _____| | | | | | | | | | | \ \ \_______ // \ | | | | |_____ | \_/ | | | | |_/ / _____ | -// \ _____| |__| |________| \_______/ |__| |______/ (_______/ +// \ _____| |__| |________| \_______/ |__| |______/ (_______/ // -// This file is part of VirtualFluids. VirtualFluids is free software: you can +// This file is part of VirtualFluids. VirtualFluids is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of +// License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. -// -// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// +// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License along // with VirtualFluids (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>. // @@ -33,10 +33,9 @@ #include "BCAlgorithm.h" +#include "BCArray3D.h" #include "BoundaryConditions.h" #include "EsoTwist3D.h" -#include "BCArray3D.h" - ////////////////////////////////////////////////////////////////////////// void BCAlgorithm::setNodeIndex(int x1, int x2, int x3) @@ -46,54 +45,32 @@ void BCAlgorithm::setNodeIndex(int x1, int x2, int x3) this->x3 = x3; } ////////////////////////////////////////////////////////////////////////// -void BCAlgorithm::setBcPointer(SPtr<BoundaryConditions> bcPtr) -{ - this->bcPtr = bcPtr; -} +void BCAlgorithm::setBcPointer(SPtr<BoundaryConditions> bcPtr) { this->bcPtr = bcPtr; } ////////////////////////////////////////////////////////////////////////// void BCAlgorithm::setCompressible(bool c) { - compressible = c; + compressible = c; - if (this->compressible) - { - calcFeqsForDirFct = &D3Q27System::getCompFeqForDirection; - calcMacrosFct = &D3Q27System::calcCompMacroscopicValues; - calcFeqFct = &D3Q27System::calcCompFeq; - compressibleFactor = 1.0; - } - else - { - calcFeqsForDirFct = &D3Q27System::getIncompFeqForDirection; - calcMacrosFct = &D3Q27System::calcIncompMacroscopicValues; - calcFeqFct = &D3Q27System::calcIncompFeq; - compressibleFactor = 0.0; - } + if (this->compressible) { + calcFeqsForDirFct = &D3Q27System::getCompFeqForDirection; + calcMacrosFct = &D3Q27System::calcCompMacroscopicValues; + calcFeqFct = &D3Q27System::calcCompFeq; + compressibleFactor = 1.0; + } else { + calcFeqsForDirFct = &D3Q27System::getIncompFeqForDirection; + calcMacrosFct = &D3Q27System::calcIncompMacroscopicValues; + calcFeqFct = &D3Q27System::calcIncompFeq; + compressibleFactor = 0.0; + } } ////////////////////////////////////////////////////////////////////////// -void BCAlgorithm::setCollFactor(LBMReal cf) -{ - collFactor = cf; -} +void BCAlgorithm::setCollFactor(LBMReal cf) { collFactor = cf; } ////////////////////////////////////////////////////////////////////////// -char BCAlgorithm::getType() -{ - return type; -} +char BCAlgorithm::getType() { return type; } ////////////////////////////////////////////////////////////////////////// -bool BCAlgorithm::isPreCollision() -{ - return preCollision; -} +bool BCAlgorithm::isPreCollision() { return preCollision; } ////////////////////////////////////////////////////////////////////////// -SPtr<BCArray3D> BCAlgorithm::getBcArray() -{ - return bcArray; -} +SPtr<BCArray3D> BCAlgorithm::getBcArray() { return bcArray; } ////////////////////////////////////////////////////////////////////////// -void BCAlgorithm::setBcArray(SPtr<BCArray3D> bcarray) -{ - bcArray = bcarray; -} - +void BCAlgorithm::setBcArray(SPtr<BCArray3D> bcarray) { bcArray = bcarray; } diff --git a/src/cpu/VirtualFluidsCore/BoundaryConditions/BCAlgorithm.h b/src/cpu/VirtualFluidsCore/BoundaryConditions/BCAlgorithm.h index 0b4110fe9147f8e081096e2cded21a0c0953cd53..7cef8205ce13d89802c9bbd7eebb5d6eb3759b3f 100644 --- a/src/cpu/VirtualFluidsCore/BoundaryConditions/BCAlgorithm.h +++ b/src/cpu/VirtualFluidsCore/BoundaryConditions/BCAlgorithm.h @@ -1,28 +1,28 @@ //======================================================================================= -// ____ ____ __ ______ __________ __ __ __ __ -// \ \ | | | | | _ \ |___ ___| | | | | / \ | | -// \ \ | | | | | |_) | | | | | | | / \ | | -// \ \ | | | | | _ / | | | | | | / /\ \ | | -// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ -// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| -// \ \ | | ________________________________________________________________ -// \ \ | | | ______________________________________________________________| -// \ \| | | | __ __ __ __ ______ _______ -// \ | | |_____ | | | | | | | | | _ \ / _____) -// \ | | _____| | | | | | | | | | | \ \ \_______ +// ____ ____ __ ______ __________ __ __ __ __ +// \ \ | | | | | _ \ |___ ___| | | | | / \ | | +// \ \ | | | | | |_) | | | | | | | / \ | | +// \ \ | | | | | _ / | | | | | | / /\ \ | | +// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ +// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| +// \ \ | | ________________________________________________________________ +// \ \ | | | ______________________________________________________________| +// \ \| | | | __ __ __ __ ______ _______ +// \ | | |_____ | | | | | | | | | _ \ / _____) +// \ | | _____| | | | | | | | | | | \ \ \_______ // \ | | | | |_____ | \_/ | | | | |_/ / _____ | -// \ _____| |__| |________| \_______/ |__| |______/ (_______/ +// \ _____| |__| |________| \_______/ |__| |______/ (_______/ // -// This file is part of VirtualFluids. VirtualFluids is free software: you can +// This file is part of VirtualFluids. VirtualFluids is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of +// License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. -// -// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// +// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License along // with VirtualFluids (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>. // @@ -47,54 +47,54 @@ class BoundaryConditions; class BCAlgorithm { public: - static const char VelocityBCAlgorithm = 0; - static const char EqDensityBCAlgorithm = 1; - static const char NonEqDensityBCAlgorithm = 2; - static const char NoSlipBCAlgorithm = 3; - static const char SlipBCAlgorithm = 4; - static const char HighViscosityNoSlipBCAlgorithm = 5; - static const char ThinWallNoSlipBCAlgorithm = 6; - static const char VelocityWithDensityBCAlgorithm = 7; - static const char NonReflectingOutflowBCAlgorithm = 8; + static const char VelocityBCAlgorithm = 0; + static const char EqDensityBCAlgorithm = 1; + static const char NonEqDensityBCAlgorithm = 2; + static const char NoSlipBCAlgorithm = 3; + static const char SlipBCAlgorithm = 4; + static const char HighViscosityNoSlipBCAlgorithm = 5; + static const char ThinWallNoSlipBCAlgorithm = 6; + static const char VelocityWithDensityBCAlgorithm = 7; + static const char NonReflectingOutflowBCAlgorithm = 8; public: - BCAlgorithm() = default; - virtual ~BCAlgorithm() = default; - - virtual void addDistributions(SPtr<DistributionArray3D> distributions) = 0; - void setNodeIndex(int x1, int x2, int x3); - void setBcPointer(SPtr<BoundaryConditions> bcPtr); - void setCompressible(bool c); - void setCollFactor(LBMReal cf); - char getType(); - bool isPreCollision(); - virtual SPtr<BCAlgorithm> clone() = 0; - SPtr<BCArray3D> getBcArray(); - void setBcArray(SPtr<BCArray3D> bcarray); - virtual void applyBC() = 0; + BCAlgorithm() = default; + virtual ~BCAlgorithm() = default; + + virtual void addDistributions(SPtr<DistributionArray3D> distributions) = 0; + void setNodeIndex(int x1, int x2, int x3); + void setBcPointer(SPtr<BoundaryConditions> bcPtr); + void setCompressible(bool c); + void setCollFactor(LBMReal cf); + char getType(); + bool isPreCollision(); + virtual SPtr<BCAlgorithm> clone() = 0; + SPtr<BCArray3D> getBcArray(); + void setBcArray(SPtr<BCArray3D> bcarray); + virtual void applyBC() = 0; protected: - bool compressible{false}; - char type; - bool preCollision; + bool compressible{ false }; + char type; + bool preCollision; - SPtr<BoundaryConditions> bcPtr; - SPtr<DistributionArray3D> distributions; - SPtr<BCArray3D> bcArray; + SPtr<BoundaryConditions> bcPtr; + SPtr<DistributionArray3D> distributions; + SPtr<BCArray3D> bcArray; - LBMReal collFactor; - int x1, x2, x3; + LBMReal collFactor; + int x1, x2, x3; - LBMReal compressibleFactor; + LBMReal compressibleFactor; - using CalcMacrosFct = void (*)(const LBMReal *const &, LBMReal &, LBMReal &, LBMReal &, LBMReal &); - using CalcFeqForDirFct = LBMReal (*)(const int &, const LBMReal &, const LBMReal &, const LBMReal &, const LBMReal &); + using CalcMacrosFct = void (*)(const LBMReal *const &, LBMReal &, LBMReal &, LBMReal &, LBMReal &); + using CalcFeqForDirFct = LBMReal (*)(const int &, const LBMReal &, const LBMReal &, const LBMReal &, + const LBMReal &); using CalcFeqFct = void (*)(LBMReal *const &, const LBMReal &, const LBMReal &, const LBMReal &, const LBMReal &); - - CalcFeqForDirFct calcFeqsForDirFct ; - CalcMacrosFct calcMacrosFct; - CalcFeqFct calcFeqFct; -}; + CalcFeqForDirFct calcFeqsForDirFct; + CalcMacrosFct calcMacrosFct; + CalcFeqFct calcFeqFct; +}; -#endif +#endif diff --git a/src/cpu/VirtualFluidsCore/BoundaryConditions/BCArray3D.cpp b/src/cpu/VirtualFluidsCore/BoundaryConditions/BCArray3D.cpp index 913967fabf3795223389498886732999de55adaf..87606eecf03943259dfec89a805336d2a3190bfa 100644 --- a/src/cpu/VirtualFluidsCore/BoundaryConditions/BCArray3D.cpp +++ b/src/cpu/VirtualFluidsCore/BoundaryConditions/BCArray3D.cpp @@ -1,28 +1,28 @@ //======================================================================================= -// ____ ____ __ ______ __________ __ __ __ __ -// \ \ | | | | | _ \ |___ ___| | | | | / \ | | -// \ \ | | | | | |_) | | | | | | | / \ | | -// \ \ | | | | | _ / | | | | | | / /\ \ | | -// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ -// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| -// \ \ | | ________________________________________________________________ -// \ \ | | | ______________________________________________________________| -// \ \| | | | __ __ __ __ ______ _______ -// \ | | |_____ | | | | | | | | | _ \ / _____) -// \ | | _____| | | | | | | | | | | \ \ \_______ +// ____ ____ __ ______ __________ __ __ __ __ +// \ \ | | | | | _ \ |___ ___| | | | | / \ | | +// \ \ | | | | | |_) | | | | | | | / \ | | +// \ \ | | | | | _ / | | | | | | / /\ \ | | +// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ +// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| +// \ \ | | ________________________________________________________________ +// \ \ | | | ______________________________________________________________| +// \ \| | | | __ __ __ __ ______ _______ +// \ | | |_____ | | | | | | | | | _ \ / _____) +// \ | | _____| | | | | | | | | | | \ \ \_______ // \ | | | | |_____ | \_/ | | | | |_/ / _____ | -// \ _____| |__| |________| \_______/ |__| |______/ (_______/ +// \ _____| |__| |________| \_______/ |__| |______/ (_______/ // -// This file is part of VirtualFluids. VirtualFluids is free software: you can +// This file is part of VirtualFluids. VirtualFluids is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of +// License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. -// -// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// +// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License along // with VirtualFluids (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>. // @@ -33,204 +33,206 @@ #include "BCArray3D.h" -const int BCArray3D::SOLID = -1; -const int BCArray3D::FLUID = -2; +const int BCArray3D::SOLID = -1; +const int BCArray3D::FLUID = -2; const int BCArray3D::INTERFACECF = -3; const int BCArray3D::INTERFACEFC = -4; -const int BCArray3D::UNDEFINED = -5; +const int BCArray3D::UNDEFINED = -5; ////////////////////////////////////////////////////////////////////////// BCArray3D::BCArray3D() = default; ////////////////////////////////////////////////////////////////////////// BCArray3D::BCArray3D(std::size_t nx1, std::size_t nx2, std::size_t nx3) { - bcindexmatrix.resize(nx1, nx2, nx3, UNDEFINED); + bcindexmatrix.resize(nx1, nx2, nx3, UNDEFINED); } ////////////////////////////////////////////////////////////////////////// BCArray3D::BCArray3D(std::size_t nx1, std::size_t nx2, std::size_t nx3, int val) { - bcindexmatrix.resize(nx1, nx2, nx3, val); + bcindexmatrix.resize(nx1, nx2, nx3, val); } ////////////////////////////////////////////////////////////////////////// BCArray3D::~BCArray3D() = default; ////////////////////////////////////////////////////////////////////////// -void BCArray3D::resize(std::size_t nx1, std::size_t nx2, std::size_t nx3) -{ - bcindexmatrix.resize(nx1, nx2, nx3); -} +void BCArray3D::resize(std::size_t nx1, std::size_t nx2, std::size_t nx3) { bcindexmatrix.resize(nx1, nx2, nx3); } ////////////////////////////////////////////////////////////////////////// void BCArray3D::resize(std::size_t nx1, std::size_t nx2, std::size_t nx3, int val) { - bcindexmatrix.resize(nx1, nx2, nx3, val); + bcindexmatrix.resize(nx1, nx2, nx3, val); } ////////////////////////////////////////////////////////////////////////// -bool BCArray3D::validIndices(std::size_t x1, std::size_t x2, std::size_t x3) const +bool BCArray3D::validIndices(std::size_t x1, std::size_t x2, std::size_t x3) const { - if (x1 < 0 || x1 >= this->bcindexmatrix.getNX1()) return false; - if (x2 < 0 || x2 >= this->bcindexmatrix.getNX2()) return false; - if (x3 < 0 || x3 >= this->bcindexmatrix.getNX3()) return false; - return true; + if (x1 < 0 || x1 >= this->bcindexmatrix.getNX1()) + return false; + if (x2 < 0 || x2 >= this->bcindexmatrix.getNX2()) + return false; + if (x3 < 0 || x3 >= this->bcindexmatrix.getNX3()) + return false; + return true; } ////////////////////////////////////////////////////////////////////////// -void BCArray3D::setBC(std::size_t x1, std::size_t x2, std::size_t x3, SPtr<BoundaryConditions> const& bc) +void BCArray3D::setBC(std::size_t x1, std::size_t x2, std::size_t x3, SPtr<BoundaryConditions> const &bc) { - if (this->hasBC(x1, x2, x3)) - { - if (this->getBC(x1, x2, x3) == bc) return; - else this->deleteBC(x1, x2, x3); - } + if (this->hasBC(x1, x2, x3)) { + if (this->getBC(x1, x2, x3) == bc) + return; + else + this->deleteBC(x1, x2, x3); + } - //if no vacant BCs available - if (indexContainer.empty()) - { - bcvector.push_back(bc); - bcindexmatrix(x1, x2, x3) = (int)bcvector.size() - 1; - } - else - { - int index = indexContainer.back(); - bcindexmatrix(x1, x2, x3) = index; - bcvector[index] = bc; - indexContainer.pop_back(); - } + // if no vacant BCs available + if (indexContainer.empty()) { + bcvector.push_back(bc); + bcindexmatrix(x1, x2, x3) = (int)bcvector.size() - 1; + } else { + int index = indexContainer.back(); + bcindexmatrix(x1, x2, x3) = index; + bcvector[index] = bc; + indexContainer.pop_back(); + } } ////////////////////////////////////////////////////////////////////////// void BCArray3D::setSolid(std::size_t x1, std::size_t x2, std::size_t x3) { - if (this->hasBC(x1, x2, x3)) this->deleteBC(x1, x2, x3); - bcindexmatrix(x1, x2, x3) = SOLID; + if (this->hasBC(x1, x2, x3)) + this->deleteBC(x1, x2, x3); + bcindexmatrix(x1, x2, x3) = SOLID; } ////////////////////////////////////////////////////////////////////////// void BCArray3D::setFluid(std::size_t x1, std::size_t x2, std::size_t x3) { - if (this->hasBC(x1, x2, x3)) this->deleteBC(x1, x2, x3); - bcindexmatrix(x1, x2, x3) = FLUID; + if (this->hasBC(x1, x2, x3)) + this->deleteBC(x1, x2, x3); + bcindexmatrix(x1, x2, x3) = FLUID; } ////////////////////////////////////////////////////////////////////////// void BCArray3D::setUndefined(std::size_t x1, std::size_t x2, std::size_t x3) { - if (this->hasBC(x1, x2, x3)) this->deleteBC(x1, x2, x3); - bcindexmatrix(x1, x2, x3) = UNDEFINED; + if (this->hasBC(x1, x2, x3)) + this->deleteBC(x1, x2, x3); + bcindexmatrix(x1, x2, x3) = UNDEFINED; } ////////////////////////////////////////////////////////////////////////// std::size_t BCArray3D::getNumberOfSolidEntries() const { - const std::vector<int>& data = bcindexmatrix.getDataVector(); - std::size_t counter = 0; - for (std::size_t i = 0; i < data.size(); i++) - if (data[i] == SOLID) counter++; - return counter; + const std::vector<int> &data = bcindexmatrix.getDataVector(); + std::size_t counter = 0; + for (std::size_t i = 0; i < data.size(); i++) + if (data[i] == SOLID) + counter++; + return counter; } ////////////////////////////////////////////////////////////////////////// std::size_t BCArray3D::getNumberOfFluidEntries() const { - const std::vector<int>& data = bcindexmatrix.getDataVector(); - std::size_t counter = 0; - for (std::size_t i = 0; i < data.size(); i++) - { - int tmp = data[i]; - if (tmp == FLUID || tmp >= 0) counter++; - } - return counter; + const std::vector<int> &data = bcindexmatrix.getDataVector(); + std::size_t counter = 0; + for (std::size_t i = 0; i < data.size(); i++) { + int tmp = data[i]; + if (tmp == FLUID || tmp >= 0) + counter++; + } + return counter; } ////////////////////////////////////////////////////////////////////////// std::size_t BCArray3D::getNumberOfFluidWithoutBCEntries() const { - const std::vector<int>& data = bcindexmatrix.getDataVector(); - std::size_t counter = 0; - for (std::size_t i = 0; i < data.size(); i++) - if (data[i] == FLUID) counter++; - return counter; + const std::vector<int> &data = bcindexmatrix.getDataVector(); + std::size_t counter = 0; + for (std::size_t i = 0; i < data.size(); i++) + if (data[i] == FLUID) + counter++; + return counter; } ////////////////////////////////////////////////////////////////////////// std::size_t BCArray3D::getNumberOfBCEntries() const { - const std::vector<int>& data = bcindexmatrix.getDataVector(); - std::size_t counter = 0; - for (std::size_t i = 0; i < data.size(); i++) - if (data[i] >= 0) counter++; - return counter; + const std::vector<int> &data = bcindexmatrix.getDataVector(); + std::size_t counter = 0; + for (std::size_t i = 0; i < data.size(); i++) + if (data[i] >= 0) + counter++; + return counter; } ////////////////////////////////////////////////////////////////////////// std::size_t BCArray3D::getNumberOfUndefinedEntries() const { - const std::vector<int>& data = bcindexmatrix.getDataVector(); - std::size_t counter = 0; - for (std::size_t i = 0; i < data.size(); i++) - if (data[i] == UNDEFINED) counter++; - return counter; + const std::vector<int> &data = bcindexmatrix.getDataVector(); + std::size_t counter = 0; + for (std::size_t i = 0; i < data.size(); i++) + if (data[i] == UNDEFINED) + counter++; + return counter; } ////////////////////////////////////////////////////////////////////////// -std::size_t BCArray3D::getBCVectorSize() const -{ - return this->bcvector.size(); -} +std::size_t BCArray3D::getBCVectorSize() const { return this->bcvector.size(); } ////////////////////////////////////////////////////////////////////////// std::string BCArray3D::toString() const { - std::size_t solidCounter = 0; - std::size_t fluidCounter = 0; - std::size_t bcCounter = 0; - std::size_t undefCounter = 0; + std::size_t solidCounter = 0; + std::size_t fluidCounter = 0; + std::size_t bcCounter = 0; + std::size_t undefCounter = 0; - for (size_t x1 = 0; x1 < bcindexmatrix.getNX1(); x1++) - { - for (size_t x2 = 0; x2 < bcindexmatrix.getNX2(); x2++) - { - for (size_t x3 = 0; x3 < bcindexmatrix.getNX3(); x3++) - { - if (bcindexmatrix(x1, x2, x3) >= 0) bcCounter++; - else if (bcindexmatrix(x1, x2, x3) == FLUID) fluidCounter++; - else if (bcindexmatrix(x1, x2, x3) == SOLID) solidCounter++; - else if (bcindexmatrix(x1, x2, x3) == UNDEFINED) undefCounter++; - else throw UbException(UB_EXARGS, "invalid matrixEntry"); - } - } - } + for (size_t x1 = 0; x1 < bcindexmatrix.getNX1(); x1++) { + for (size_t x2 = 0; x2 < bcindexmatrix.getNX2(); x2++) { + for (size_t x3 = 0; x3 < bcindexmatrix.getNX3(); x3++) { + if (bcindexmatrix(x1, x2, x3) >= 0) + bcCounter++; + else if (bcindexmatrix(x1, x2, x3) == FLUID) + fluidCounter++; + else if (bcindexmatrix(x1, x2, x3) == SOLID) + solidCounter++; + else if (bcindexmatrix(x1, x2, x3) == UNDEFINED) + undefCounter++; + else + throw UbException(UB_EXARGS, "invalid matrixEntry"); + } + } + } - std::size_t unrefEntriesInBcVector = 0; - for (std::size_t i = 0; i < bcvector.size(); i++) if (!bcvector[i]) unrefEntriesInBcVector++; + std::size_t unrefEntriesInBcVector = 0; + for (std::size_t i = 0; i < bcvector.size(); i++) + if (!bcvector[i]) + unrefEntriesInBcVector++; - std::stringstream text; - text << "BCArray<" << typeid(SPtr<BoundaryConditions>).name() << "," << typeid(int).name() << ">"; - text << "[ entries: " << bcindexmatrix.getNX1() << "x" << bcindexmatrix.getNX2(); - text << "x" << bcindexmatrix.getNX3() << "="; - text << bcindexmatrix.getNX1()*bcindexmatrix.getNX2()*bcindexmatrix.getNX3() << " ]:\n"; - text << " - #fluid entries : " << fluidCounter << std::endl; - text << " - #bc entries : " << bcCounter << std::endl; - text << " - #solid entries : " << solidCounter << std::endl; - text << " - #undef entries : " << undefCounter << std::endl; - text << " - bcvector-entries : " << bcvector.size() << " (empty ones: " << unrefEntriesInBcVector << ")\n"; - text << " - indexContainer-entries: " << indexContainer.size() << std::endl; + std::stringstream text; + text << "BCArray<" << typeid(SPtr<BoundaryConditions>).name() << "," << typeid(int).name() << ">"; + text << "[ entries: " << bcindexmatrix.getNX1() << "x" << bcindexmatrix.getNX2(); + text << "x" << bcindexmatrix.getNX3() << "="; + text << bcindexmatrix.getNX1() * bcindexmatrix.getNX2() * bcindexmatrix.getNX3() << " ]:\n"; + text << " - #fluid entries : " << fluidCounter << std::endl; + text << " - #bc entries : " << bcCounter << std::endl; + text << " - #solid entries : " << solidCounter << std::endl; + text << " - #undef entries : " << undefCounter << std::endl; + text << " - bcvector-entries : " << bcvector.size() << " (empty ones: " << unrefEntriesInBcVector << ")\n"; + text << " - indexContainer-entries: " << indexContainer.size() << std::endl; - return text.str(); + return text.str(); } ////////////////////////////////////////////////////////////////////////// -std::vector< int >& BCArray3D::getBcindexmatrixDataVector() -{ - return bcindexmatrix.getDataVector(); -} - +std::vector<int> &BCArray3D::getBcindexmatrixDataVector() { return bcindexmatrix.getDataVector(); } ////////////////////////////////////////////////////////////////////////// void BCArray3D::deleteBCAndSetType(std::size_t x1, std::size_t x2, std::size_t x3, int type) - { - this->deleteBC(x1, x2, x3); +{ + this->deleteBC(x1, x2, x3); - //Assign matrix to new type - bcindexmatrix(x1, x2, x3) = type; - } + // Assign matrix to new type + bcindexmatrix(x1, x2, x3) = type; +} ////////////////////////////////////////////////////////////////////////// void BCArray3D::deleteBC(std::size_t x1, std::size_t x2, std::size_t x3) - { - //check if BC exists at all - int index = bcindexmatrix(x1, x2, x3); - if (index < 0) return; +{ + // check if BC exists at all + int index = bcindexmatrix(x1, x2, x3); + if (index < 0) + return; - //slide the released index into the index container - indexContainer.push_back(index); + // slide the released index into the index container + indexContainer.push_back(index); - //"delete" element - bcvector[index] = SPtr<BoundaryConditions>(); - } - \ No newline at end of file + //"delete" element + bcvector[index] = SPtr<BoundaryConditions>(); +} diff --git a/src/cpu/VirtualFluidsCore/BoundaryConditions/BCArray3D.h b/src/cpu/VirtualFluidsCore/BoundaryConditions/BCArray3D.h index a189737f0e75be576253883bd25186e33c6c79f6..835e5b1c95454a9fbe8186d6942c3936a5e0e2cc 100644 --- a/src/cpu/VirtualFluidsCore/BoundaryConditions/BCArray3D.h +++ b/src/cpu/VirtualFluidsCore/BoundaryConditions/BCArray3D.h @@ -1,28 +1,28 @@ //======================================================================================= -// ____ ____ __ ______ __________ __ __ __ __ -// \ \ | | | | | _ \ |___ ___| | | | | / \ | | -// \ \ | | | | | |_) | | | | | | | / \ | | -// \ \ | | | | | _ / | | | | | | / /\ \ | | -// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ -// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| -// \ \ | | ________________________________________________________________ -// \ \ | | | ______________________________________________________________| -// \ \| | | | __ __ __ __ ______ _______ -// \ | | |_____ | | | | | | | | | _ \ / _____) -// \ | | _____| | | | | | | | | | | \ \ \_______ +// ____ ____ __ ______ __________ __ __ __ __ +// \ \ | | | | | _ \ |___ ___| | | | | / \ | | +// \ \ | | | | | |_) | | | | | | | / \ | | +// \ \ | | | | | _ / | | | | | | / /\ \ | | +// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ +// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| +// \ \ | | ________________________________________________________________ +// \ \ | | | ______________________________________________________________| +// \ \| | | | __ __ __ __ ______ _______ +// \ | | |_____ | | | | | | | | | _ \ / _____) +// \ | | _____| | | | | | | | | | | \ \ \_______ // \ | | | | |_____ | \_/ | | | | |_/ / _____ | -// \ _____| |__| |________| \_______/ |__| |______/ (_______/ +// \ _____| |__| |________| \_______/ |__| |______/ (_______/ // -// This file is part of VirtualFluids. VirtualFluids is free software: you can +// This file is part of VirtualFluids. VirtualFluids is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of +// License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. -// -// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// +// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License along // with VirtualFluids (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>. // @@ -41,108 +41,107 @@ #include <PointerDefinitions.h> -//! A class implements array to store boundary conditions flags +//! A class implements array to store boundary conditions flags class BCArray3D { public: - ////////////////////////////////////////////////////////////////////////// - BCArray3D(); - ////////////////////////////////////////////////////////////////////////// - BCArray3D(std::size_t nx1, std::size_t nx2, std::size_t nx3); - ////////////////////////////////////////////////////////////////////////// - BCArray3D(std::size_t nx1, std::size_t nx2, std::size_t nx3, int val); - ////////////////////////////////////////////////////////////////////////// - virtual ~BCArray3D(); - ////////////////////////////////////////////////////////////////////////// - inline std::size_t getNX1() const; - ////////////////////////////////////////////////////////////////////////// - inline std::size_t getNX2() const; - ////////////////////////////////////////////////////////////////////////// - inline std::size_t getNX3() const; - ////////////////////////////////////////////////////////////////////////// - void resize(std::size_t nx1, std::size_t nx2, std::size_t nx3); - ////////////////////////////////////////////////////////////////////////// - void resize(std::size_t nx1, std::size_t nx2, std::size_t nx3, int val); - ////////////////////////////////////////////////////////////////////////// - bool validIndices(std::size_t x1, std::size_t x2, std::size_t x3) const; - ////////////////////////////////////////////////////////////////////////// - inline bool hasBC(std::size_t x1, std::size_t x2, std::size_t x3) const; - ////////////////////////////////////////////////////////////////////////// - void setBC(std::size_t x1, std::size_t x2, std::size_t x3, SPtr<BoundaryConditions> const& bc); - ////////////////////////////////////////////////////////////////////////// - inline int getBCVectorIndex(std::size_t x1, std::size_t x2, std::size_t x3) const; - ////////////////////////////////////////////////////////////////////////// - inline const SPtr<BoundaryConditions> getBC(std::size_t x1, std::size_t x2, std::size_t x3) const; - ////////////////////////////////////////////////////////////////////////// - inline SPtr<BoundaryConditions> getBC(std::size_t x1, std::size_t x2, std::size_t x3); - ////////////////////////////////////////////////////////////////////////// - void setSolid(std::size_t x1, std::size_t x2, std::size_t x3); - ////////////////////////////////////////////////////////////////////////// - inline bool isSolid(std::size_t x1, std::size_t x2, std::size_t x3) const; - ////////////////////////////////////////////////////////////////////////// - void setFluid(std::size_t x1, std::size_t x2, std::size_t x3); - ////////////////////////////////////////////////////////////////////////// - //true : FLUID or BC - //false: UNDEFINED or SOLID - inline bool isFluid(std::size_t x1, std::size_t x2, std::size_t x3) const; - ////////////////////////////////////////////////////////////////////////// - inline bool isFluidWithoutBC(std::size_t x1, std::size_t x2, std::size_t x3) const; - ////////////////////////////////////////////////////////////////////////// - inline bool isUndefined(std::size_t x1, std::size_t x2, std::size_t x3) const; - ////////////////////////////////////////////////////////////////////////// - void setUndefined(std::size_t x1, std::size_t x2, std::size_t x3); - ////////////////////////////////////////////////////////////////////////// - inline bool isInterfaceCF(std::size_t x1, std::size_t x2, std::size_t x3) const; - ////////////////////////////////////////////////////////////////////////// - void setInterfaceCF(std::size_t x1, std::size_t x2, std::size_t x3); - ////////////////////////////////////////////////////////////////////////// - inline bool isInterfaceFC(std::size_t x1, std::size_t x2, std::size_t x3) const; - ////////////////////////////////////////////////////////////////////////// - void setInterfaceFC(std::size_t x1, std::size_t x2, std::size_t x3); - ////////////////////////////////////////////////////////////////////////// - std::size_t getNumberOfSolidEntries() const; - ////////////////////////////////////////////////////////////////////////// - std::size_t getNumberOfFluidEntries() const; - ////////////////////////////////////////////////////////////////////////// - std::size_t getNumberOfFluidWithoutBCEntries() const; - ////////////////////////////////////////////////////////////////////////// - std::size_t getNumberOfBCEntries() const; - ////////////////////////////////////////////////////////////////////////// - std::size_t getNumberOfUndefinedEntries() const; - ////////////////////////////////////////////////////////////////////////// - std::size_t getBCVectorSize() const; - ////////////////////////////////////////////////////////////////////////// - std::string toString() const; - ////////////////////////////////////////////////////////////////////////// - std::vector< int >& getBcindexmatrixDataVector(); - ////////////////////////////////////////////////////////////////////////// - bool isInsideOfDomain(const int &x1, const int &x2, const int &x3, const int& ghostLayerWidth) const; + ////////////////////////////////////////////////////////////////////////// + BCArray3D(); + ////////////////////////////////////////////////////////////////////////// + BCArray3D(std::size_t nx1, std::size_t nx2, std::size_t nx3); + ////////////////////////////////////////////////////////////////////////// + BCArray3D(std::size_t nx1, std::size_t nx2, std::size_t nx3, int val); + ////////////////////////////////////////////////////////////////////////// + virtual ~BCArray3D(); + ////////////////////////////////////////////////////////////////////////// + inline std::size_t getNX1() const; + ////////////////////////////////////////////////////////////////////////// + inline std::size_t getNX2() const; + ////////////////////////////////////////////////////////////////////////// + inline std::size_t getNX3() const; + ////////////////////////////////////////////////////////////////////////// + void resize(std::size_t nx1, std::size_t nx2, std::size_t nx3); + ////////////////////////////////////////////////////////////////////////// + void resize(std::size_t nx1, std::size_t nx2, std::size_t nx3, int val); + ////////////////////////////////////////////////////////////////////////// + bool validIndices(std::size_t x1, std::size_t x2, std::size_t x3) const; + ////////////////////////////////////////////////////////////////////////// + inline bool hasBC(std::size_t x1, std::size_t x2, std::size_t x3) const; + ////////////////////////////////////////////////////////////////////////// + void setBC(std::size_t x1, std::size_t x2, std::size_t x3, SPtr<BoundaryConditions> const &bc); + ////////////////////////////////////////////////////////////////////////// + inline int getBCVectorIndex(std::size_t x1, std::size_t x2, std::size_t x3) const; + ////////////////////////////////////////////////////////////////////////// + inline const SPtr<BoundaryConditions> getBC(std::size_t x1, std::size_t x2, std::size_t x3) const; + ////////////////////////////////////////////////////////////////////////// + inline SPtr<BoundaryConditions> getBC(std::size_t x1, std::size_t x2, std::size_t x3); + ////////////////////////////////////////////////////////////////////////// + void setSolid(std::size_t x1, std::size_t x2, std::size_t x3); + ////////////////////////////////////////////////////////////////////////// + inline bool isSolid(std::size_t x1, std::size_t x2, std::size_t x3) const; + ////////////////////////////////////////////////////////////////////////// + void setFluid(std::size_t x1, std::size_t x2, std::size_t x3); + ////////////////////////////////////////////////////////////////////////// + // true : FLUID or BC + // false: UNDEFINED or SOLID + inline bool isFluid(std::size_t x1, std::size_t x2, std::size_t x3) const; + ////////////////////////////////////////////////////////////////////////// + inline bool isFluidWithoutBC(std::size_t x1, std::size_t x2, std::size_t x3) const; + ////////////////////////////////////////////////////////////////////////// + inline bool isUndefined(std::size_t x1, std::size_t x2, std::size_t x3) const; + ////////////////////////////////////////////////////////////////////////// + void setUndefined(std::size_t x1, std::size_t x2, std::size_t x3); + ////////////////////////////////////////////////////////////////////////// + inline bool isInterfaceCF(std::size_t x1, std::size_t x2, std::size_t x3) const; + ////////////////////////////////////////////////////////////////////////// + void setInterfaceCF(std::size_t x1, std::size_t x2, std::size_t x3); + ////////////////////////////////////////////////////////////////////////// + inline bool isInterfaceFC(std::size_t x1, std::size_t x2, std::size_t x3) const; + ////////////////////////////////////////////////////////////////////////// + void setInterfaceFC(std::size_t x1, std::size_t x2, std::size_t x3); + ////////////////////////////////////////////////////////////////////////// + std::size_t getNumberOfSolidEntries() const; + ////////////////////////////////////////////////////////////////////////// + std::size_t getNumberOfFluidEntries() const; + ////////////////////////////////////////////////////////////////////////// + std::size_t getNumberOfFluidWithoutBCEntries() const; + ////////////////////////////////////////////////////////////////////////// + std::size_t getNumberOfBCEntries() const; + ////////////////////////////////////////////////////////////////////////// + std::size_t getNumberOfUndefinedEntries() const; + ////////////////////////////////////////////////////////////////////////// + std::size_t getBCVectorSize() const; + ////////////////////////////////////////////////////////////////////////// + std::string toString() const; + ////////////////////////////////////////////////////////////////////////// + std::vector<int> &getBcindexmatrixDataVector(); + ////////////////////////////////////////////////////////////////////////// + bool isInsideOfDomain(const int &x1, const int &x2, const int &x3, const int &ghostLayerWidth) const; - static const int SOLID; - static const int FLUID; - static const int INTERFACECF; - static const int INTERFACEFC; - static const int UNDEFINED; + static const int SOLID; + static const int FLUID; + static const int INTERFACECF; + static const int INTERFACEFC; + static const int UNDEFINED; private: - ////////////////////////////////////////////////////////////////////////// - void deleteBCAndSetType(std::size_t x1, std::size_t x2, std::size_t x3, int type); - ////////////////////////////////////////////////////////////////////////// - void deleteBC(std::size_t x1, std::size_t x2, std::size_t x3); + ////////////////////////////////////////////////////////////////////////// + void deleteBCAndSetType(std::size_t x1, std::size_t x2, std::size_t x3, int type); + ////////////////////////////////////////////////////////////////////////// + void deleteBC(std::size_t x1, std::size_t x2, std::size_t x3); - friend class MPIIORestartCoProcessor; - friend class MPIIOMigrationCoProcessor; - friend class MPIIOMigrationBECoProcessor; + friend class MPIIORestartCoProcessor; + friend class MPIIOMigrationCoProcessor; + friend class MPIIOMigrationBECoProcessor; protected: - ////////////////////////////////////////////////////////////////////////// - //-1 solid // -2 fluid -... - CbArray3D<int, IndexerX3X2X1> bcindexmatrix; - std::vector<SPtr<BoundaryConditions>> bcvector; - std::vector<int> indexContainer; + ////////////////////////////////////////////////////////////////////////// + //-1 solid // -2 fluid -... + CbArray3D<int, IndexerX3X2X1> bcindexmatrix; + std::vector<SPtr<BoundaryConditions>> bcvector; + std::vector<int> indexContainer; }; - ////////////////////////////////////////////////////////////////////////// inline std::size_t BCArray3D::getNX1() const { return bcindexmatrix.getNX1(); } ////////////////////////////////////////////////////////////////////////// @@ -150,66 +149,68 @@ inline std::size_t BCArray3D::getNX2() const { return bcindexmatrix.getNX2(); } ////////////////////////////////////////////////////////////////////////// inline std::size_t BCArray3D::getNX3() const { return bcindexmatrix.getNX3(); } ////////////////////////////////////////////////////////////////////////// -inline bool BCArray3D::hasBC(std::size_t x1, std::size_t x2, std::size_t x3) const +inline bool BCArray3D::hasBC(std::size_t x1, std::size_t x2, std::size_t x3) const { - return bcindexmatrix(x1, x2, x3) >= 0; + return bcindexmatrix(x1, x2, x3) >= 0; } ////////////////////////////////////////////////////////////////////////// inline int BCArray3D::getBCVectorIndex(std::size_t x1, std::size_t x2, std::size_t x3) const { - return bcindexmatrix(x1, x2, x3); + return bcindexmatrix(x1, x2, x3); } ////////////////////////////////////////////////////////////////////////// -inline const SPtr<BoundaryConditions> BCArray3D::getBC(std::size_t x1, std::size_t x2, std::size_t x3) const +inline const SPtr<BoundaryConditions> BCArray3D::getBC(std::size_t x1, std::size_t x2, std::size_t x3) const { - int index = bcindexmatrix(x1, x2, x3); - if (index < 0) return SPtr<BoundaryConditions>(); //=> NULL Pointer + int index = bcindexmatrix(x1, x2, x3); + if (index < 0) + return SPtr<BoundaryConditions>(); //=> NULL Pointer - return bcvector[index]; + return bcvector[index]; } ////////////////////////////////////////////////////////////////////////// inline SPtr<BoundaryConditions> BCArray3D::getBC(std::size_t x1, std::size_t x2, std::size_t x3) { - int index = bcindexmatrix(x1, x2, x3); - if (index < 0) return SPtr<BoundaryConditions>(); //=> NULL Pointer + int index = bcindexmatrix(x1, x2, x3); + if (index < 0) + return SPtr<BoundaryConditions>(); //=> NULL Pointer - return bcvector[index]; + return bcvector[index]; } ////////////////////////////////////////////////////////////////////////// inline bool BCArray3D::isSolid(std::size_t x1, std::size_t x2, std::size_t x3) const { - return bcindexmatrix(x1, x2, x3) == SOLID; + return bcindexmatrix(x1, x2, x3) == SOLID; } ////////////////////////////////////////////////////////////////////////// -//true : FLUID or BC -//false: UNDEFINED or SOLID +// true : FLUID or BC +// false: UNDEFINED or SOLID inline bool BCArray3D::isFluid(std::size_t x1, std::size_t x2, std::size_t x3) const { - int tmp = bcindexmatrix(x1, x2, x3); - return (tmp == FLUID || tmp >= 0); + int tmp = bcindexmatrix(x1, x2, x3); + return (tmp == FLUID || tmp >= 0); } ////////////////////////////////////////////////////////////////////////// inline bool BCArray3D::isFluidWithoutBC(std::size_t x1, std::size_t x2, std::size_t x3) const { - return bcindexmatrix(x1, x2, x3) == FLUID; + return bcindexmatrix(x1, x2, x3) == FLUID; } ////////////////////////////////////////////////////////////////////////// inline bool BCArray3D::isUndefined(std::size_t x1, std::size_t x2, std::size_t x3) const { - return bcindexmatrix(x1, x2, x3) == UNDEFINED; + return bcindexmatrix(x1, x2, x3) == UNDEFINED; } ////////////////////////////////////////////////////////////////////////// inline bool BCArray3D::isInterfaceCF(std::size_t x1, std::size_t x2, std::size_t x3) const { - return bcindexmatrix(x1, x2, x3) == INTERFACECF; + return bcindexmatrix(x1, x2, x3) == INTERFACECF; } ////////////////////////////////////////////////////////////////////////// inline bool BCArray3D::isInterfaceFC(std::size_t x1, std::size_t x2, std::size_t x3) const { - return bcindexmatrix(x1, x2, x3) == INTERFACEFC; + return bcindexmatrix(x1, x2, x3) == INTERFACEFC; } ////////////////////////////////////////////////////////////////////////// -inline bool BCArray3D::isInsideOfDomain(const int& x1, const int& x2, const int& x3, const int& ghostLayerWidth) const +inline bool BCArray3D::isInsideOfDomain(const int &x1, const int &x2, const int &x3, const int &ghostLayerWidth) const { const int minX1 = ghostLayerWidth; const int maxX1 = (int)this->getNX1() - 1 - ghostLayerWidth; @@ -221,4 +222,4 @@ inline bool BCArray3D::isInsideOfDomain(const int& x1, const int& x2, const int& return (!(x1 < minX1 || x1 > maxX1 || x2 < minX2 || x2 > maxX2 || x3 < minX3 || x3 > maxX3)); } -#endif +#endif diff --git a/src/cpu/VirtualFluidsCore/BoundaryConditions/BCFunction.cpp b/src/cpu/VirtualFluidsCore/BoundaryConditions/BCFunction.cpp index 34c536c8ea588c7e42c208a1f4bfdec2ce98c67a..781958f858e54a348358ec11014ef1012779ebc9 100644 --- a/src/cpu/VirtualFluidsCore/BoundaryConditions/BCFunction.cpp +++ b/src/cpu/VirtualFluidsCore/BoundaryConditions/BCFunction.cpp @@ -1,28 +1,28 @@ //======================================================================================= -// ____ ____ __ ______ __________ __ __ __ __ -// \ \ | | | | | _ \ |___ ___| | | | | / \ | | -// \ \ | | | | | |_) | | | | | | | / \ | | -// \ \ | | | | | _ / | | | | | | / /\ \ | | -// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ -// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| -// \ \ | | ________________________________________________________________ -// \ \ | | | ______________________________________________________________| -// \ \| | | | __ __ __ __ ______ _______ -// \ | | |_____ | | | | | | | | | _ \ / _____) -// \ | | _____| | | | | | | | | | | \ \ \_______ +// ____ ____ __ ______ __________ __ __ __ __ +// \ \ | | | | | _ \ |___ ___| | | | | / \ | | +// \ \ | | | | | |_) | | | | | | | / \ | | +// \ \ | | | | | _ / | | | | | | / /\ \ | | +// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ +// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| +// \ \ | | ________________________________________________________________ +// \ \ | | | ______________________________________________________________| +// \ \| | | | __ __ __ __ ______ _______ +// \ | | |_____ | | | | | | | | | _ \ / _____) +// \ | | _____| | | | | | | | | | | \ \ \_______ // \ | | | | |_____ | \_/ | | | | |_/ / _____ | -// \ _____| |__| |________| \_______/ |__| |______/ (_______/ +// \ _____| |__| |________| \_______/ |__| |______/ (_______/ // -// This file is part of VirtualFluids. VirtualFluids is free software: you can +// This file is part of VirtualFluids. VirtualFluids is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of +// License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. -// -// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// +// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License along // with VirtualFluids (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>. // @@ -35,4 +35,3 @@ const double BCFunction::INFTIMEDEPENDENT = -1.0; const double BCFunction::INFCONST = -10.0; - diff --git a/src/cpu/VirtualFluidsCore/BoundaryConditions/BCFunction.h b/src/cpu/VirtualFluidsCore/BoundaryConditions/BCFunction.h index 96102f82a3a9c426b9ad669058b5b8ec75058032..cf1a5a578af00fd4e326f72ac922f2f4d018667f 100644 --- a/src/cpu/VirtualFluidsCore/BoundaryConditions/BCFunction.h +++ b/src/cpu/VirtualFluidsCore/BoundaryConditions/BCFunction.h @@ -1,28 +1,28 @@ //======================================================================================= -// ____ ____ __ ______ __________ __ __ __ __ -// \ \ | | | | | _ \ |___ ___| | | | | / \ | | -// \ \ | | | | | |_) | | | | | | | / \ | | -// \ \ | | | | | _ / | | | | | | / /\ \ | | -// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ -// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| -// \ \ | | ________________________________________________________________ -// \ \ | | | ______________________________________________________________| -// \ \| | | | __ __ __ __ ______ _______ -// \ | | |_____ | | | | | | | | | _ \ / _____) -// \ | | _____| | | | | | | | | | | \ \ \_______ +// ____ ____ __ ______ __________ __ __ __ __ +// \ \ | | | | | _ \ |___ ___| | | | | / \ | | +// \ \ | | | | | |_) | | | | | | | / \ | | +// \ \ | | | | | _ / | | | | | | / /\ \ | | +// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ +// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| +// \ \ | | ________________________________________________________________ +// \ \ | | | ______________________________________________________________| +// \ \| | | | __ __ __ __ ______ _______ +// \ | | |_____ | | | | | | | | | _ \ / _____) +// \ | | _____| | | | | | | | | | | \ \ \_______ // \ | | | | |_____ | \_/ | | | | |_/ / _____ | -// \ _____| |__| |________| \_______/ |__| |______/ (_______/ +// \ _____| |__| |________| \_______/ |__| |______/ (_______/ // -// This file is part of VirtualFluids. VirtualFluids is free software: you can +// This file is part of VirtualFluids. VirtualFluids is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of +// License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. -// -// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// +// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License along // with VirtualFluids (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>. // @@ -38,76 +38,81 @@ #include <muParser.h> -//! A class implements function parcer for boundary conditions +//! A class implements function parcer for boundary conditions class BCFunction { public: - static const double INFTIMEDEPENDENT; - static const double INFCONST; + static const double INFTIMEDEPENDENT; + static const double INFCONST; public: - BCFunction() - : starttime(-Ub::inf ), endtime(-Ub::inf ) - { - - } - BCFunction( const mu::Parser& function, const double& starttime, const double& endtime ) - : function(function), starttime(starttime), endtime(endtime) - { + BCFunction() : starttime(-Ub::inf), endtime(-Ub::inf) {} + BCFunction(const mu::Parser &function, const double &starttime, const double &endtime) + : function(function), starttime(starttime), endtime(endtime) + { + } + BCFunction(const std::string &functionstring, const double &starttime, const double &endtime) + : starttime(starttime), endtime(endtime) + { + this->setFunction(functionstring); + } + BCFunction(const double &velocity, const double &starttime, const double &endtime) + : starttime(starttime), endtime(endtime) + { + this->setFunction(velocity); + } - } - BCFunction( const std::string& functionstring, const double& starttime, const double& endtime ) - : starttime(starttime), endtime(endtime) - { - this->setFunction(functionstring); - } - BCFunction( const double& velocity, const double& starttime, const double& endtime ) - : starttime(starttime), endtime(endtime) - { - this->setFunction(velocity); - } + void setFunction(const mu::Parser &function) { this->function = function; } + void setFunction(const std::string &functionstring) { this->function.SetExpr(functionstring); } + void setFunction(const double &constVelocity) + { + std::stringstream dummy; + dummy << constVelocity; + function.SetExpr(dummy.str()); + } + void setStartTime(const double &starttime) { this->starttime = starttime; } + void setEndTime(const double &endtime) { this->endtime = endtime; } - void setFunction(const mu::Parser& function) { this->function = function; } - void setFunction(const std::string& functionstring) { this->function.SetExpr(functionstring); } - void setFunction(const double& constVelocity) { std::stringstream dummy; dummy<<constVelocity; function.SetExpr(dummy.str()); } - void setStartTime(const double& starttime) {this->starttime = starttime; } - void setEndTime(const double& endtime) {this->endtime = endtime; } + mu::Parser &getFunction() { return function; } + const mu::Parser &getFunction() const { return function; } + const double &getStartTime() const { return starttime; } + const double &getEndTime() const { return endtime; } - mu::Parser& getFunction() { return function; } - const mu::Parser& getFunction() const { return function; } - const double& getStartTime() const { return starttime; } - const double& getEndTime() const { return endtime; } - - std::string toString() const - { - std::stringstream info; - if (starttime==INFTIMEDEPENDENT) info<<"start=inf. timedep., "; - else if(starttime==INFCONST ) info<<"start=inf. const., "; - else info<<"start="<<starttime<<", "; - if (endtime==INFTIMEDEPENDENT) info<<"end=inf. timedep."<<std::endl; - else if(endtime==INFCONST ) info<<"end=inf. const."<<std::endl; - else info<<"end="<<endtime<<std::endl; - info<<"expr="<<function.GetExpr()<<std::endl; - info<<"with constants: "; - mu::valmap_type cmap = function.GetConst(); - for(mu::valmap_type::const_iterator item = cmap.begin(); item!=cmap.end(); ++item) - info<<item->first<<"="<<item->second<<", "; - return info.str(); - } - /*==========================================================*/ - friend inline std::ostream& operator << (std::ostream& os, const BCFunction& bc) - { - os<<bc.toString(); - return os; - } + std::string toString() const + { + std::stringstream info; + if (starttime == INFTIMEDEPENDENT) + info << "start=inf. timedep., "; + else if (starttime == INFCONST) + info << "start=inf. const., "; + else + info << "start=" << starttime << ", "; + if (endtime == INFTIMEDEPENDENT) + info << "end=inf. timedep." << std::endl; + else if (endtime == INFCONST) + info << "end=inf. const." << std::endl; + else + info << "end=" << endtime << std::endl; + info << "expr=" << function.GetExpr() << std::endl; + info << "with constants: "; + mu::valmap_type cmap = function.GetConst(); + for (mu::valmap_type::const_iterator item = cmap.begin(); item != cmap.end(); ++item) + info << item->first << "=" << item->second << ", "; + return info.str(); + } + /*==========================================================*/ + friend inline std::ostream &operator<<(std::ostream &os, const BCFunction &bc) + { + os << bc.toString(); + return os; + } protected: - mu::Parser function; - double starttime; - double endtime; + mu::Parser function; + double starttime; + double endtime; private: - }; -#endif //D3Q27BCFUNCTION_H +#endif // D3Q27BCFUNCTION_H diff --git a/src/cpu/VirtualFluidsCore/BoundaryConditions/BCProcessor.cpp b/src/cpu/VirtualFluidsCore/BoundaryConditions/BCProcessor.cpp index 020f4d60d091c4cb26beb7556b51f9edf94cc904..de647a842d1ffcdb08d39988befe1ed19ebc5842 100644 --- a/src/cpu/VirtualFluidsCore/BoundaryConditions/BCProcessor.cpp +++ b/src/cpu/VirtualFluidsCore/BoundaryConditions/BCProcessor.cpp @@ -1,28 +1,28 @@ //======================================================================================= -// ____ ____ __ ______ __________ __ __ __ __ -// \ \ | | | | | _ \ |___ ___| | | | | / \ | | -// \ \ | | | | | |_) | | | | | | | / \ | | -// \ \ | | | | | _ / | | | | | | / /\ \ | | -// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ -// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| -// \ \ | | ________________________________________________________________ -// \ \ | | | ______________________________________________________________| -// \ \| | | | __ __ __ __ ______ _______ -// \ | | |_____ | | | | | | | | | _ \ / _____) -// \ | | _____| | | | | | | | | | | \ \ \_______ +// ____ ____ __ ______ __________ __ __ __ __ +// \ \ | | | | | _ \ |___ ___| | | | | / \ | | +// \ \ | | | | | |_) | | | | | | | / \ | | +// \ \ | | | | | _ / | | | | | | / /\ \ | | +// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ +// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| +// \ \ | | ________________________________________________________________ +// \ \ | | | ______________________________________________________________| +// \ \| | | | __ __ __ __ ______ _______ +// \ | | |_____ | | | | | | | | | _ \ / _____) +// \ | | _____| | | | | | | | | | | \ \ \_______ // \ | | | | |_____ | \_/ | | | | |_/ / _____ | -// \ _____| |__| |________| \_______/ |__| |______/ (_______/ +// \ _____| |__| |________| \_______/ |__| |______/ (_______/ // -// This file is part of VirtualFluids. VirtualFluids is free software: you can +// This file is part of VirtualFluids. VirtualFluids is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of +// License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. -// -// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// +// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License along // with VirtualFluids (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>. // @@ -32,56 +32,47 @@ //======================================================================================= #include "BCProcessor.h" +#include "BCAlgorithm.h" +#include "BCArray3D.h" #include "D3Q27EsoTwist3DSplittedVector.h" #include "DataSet3D.h" #include "ILBMKernel.h" -#include "BCArray3D.h" -#include "BCAlgorithm.h" -BCProcessor::BCProcessor() -= default; +BCProcessor::BCProcessor() = default; ////////////////////////////////////////////////////////////////////////// BCProcessor::BCProcessor(SPtr<ILBMKernel> kernel) { - SPtr<DistributionArray3D> distributions = std::dynamic_pointer_cast<EsoTwist3D>(kernel->getDataSet()->getFdistributions()); - bcArray = std::make_shared<BCArray3D>(distributions->getNX1(), distributions->getNX2(), distributions->getNX3(), BCArray3D::FLUID); + SPtr<DistributionArray3D> distributions = + std::dynamic_pointer_cast<EsoTwist3D>(kernel->getDataSet()->getFdistributions()); + bcArray = std::make_shared<BCArray3D>(distributions->getNX1(), distributions->getNX2(), distributions->getNX3(), + BCArray3D::FLUID); } ////////////////////////////////////////////////////////////////////////// -BCProcessor::~BCProcessor() -= default; +BCProcessor::~BCProcessor() = default; ////////////////////////////////////////////////////////////////////////// SPtr<BCProcessor> BCProcessor::clone(SPtr<ILBMKernel> kernel) { - SPtr<BCProcessor> bcProcessor(new BCProcessor(kernel)); - return bcProcessor; + SPtr<BCProcessor> bcProcessor(new BCProcessor(kernel)); + return bcProcessor; } ////////////////////////////////////////////////////////////////////////// -SPtr<BCArray3D> BCProcessor::getBCArray() -{ - return bcArray; -} +SPtr<BCArray3D> BCProcessor::getBCArray() { return bcArray; } ////////////////////////////////////////////////////////////////////////// -void BCProcessor::setBCArray(SPtr<BCArray3D> bcarray) -{ - bcArray = bcarray; -} +void BCProcessor::setBCArray(SPtr<BCArray3D> bcarray) { bcArray = bcarray; } ////////////////////////////////////////////////////////////////////////// void BCProcessor::addBC(SPtr<BCAlgorithm> bc) { - if (bc->isPreCollision()) - { - preBC.push_back(bc); - } - else - { - postBC.push_back(bc); - } + if (bc->isPreCollision()) { + preBC.push_back(bc); + } else { + postBC.push_back(bc); + } } ////////////////////////////////////////////////////////////////////////// void BCProcessor::applyPreCollisionBC() { - for(SPtr<BCAlgorithm> bc : preBC) - bc->applyBC(); + for (SPtr<BCAlgorithm> bc : preBC) + bc->applyBC(); } ////////////////////////////////////////////////////////////////////////// void BCProcessor::applyPostCollisionBC() @@ -92,7 +83,6 @@ void BCProcessor::applyPostCollisionBC() ////////////////////////////////////////////////////////////////////////// void BCProcessor::clearBC() { - preBC.clear(); - postBC.clear(); + preBC.clear(); + postBC.clear(); } - diff --git a/src/cpu/VirtualFluidsCore/BoundaryConditions/BCProcessor.h b/src/cpu/VirtualFluidsCore/BoundaryConditions/BCProcessor.h index 4c3f66ac2365bed782f3622c28694382da8d4bc0..266307305db6febd885d6e90a8385714947221ff 100644 --- a/src/cpu/VirtualFluidsCore/BoundaryConditions/BCProcessor.h +++ b/src/cpu/VirtualFluidsCore/BoundaryConditions/BCProcessor.h @@ -1,28 +1,28 @@ //======================================================================================= -// ____ ____ __ ______ __________ __ __ __ __ -// \ \ | | | | | _ \ |___ ___| | | | | / \ | | -// \ \ | | | | | |_) | | | | | | | / \ | | -// \ \ | | | | | _ / | | | | | | / /\ \ | | -// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ -// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| -// \ \ | | ________________________________________________________________ -// \ \ | | | ______________________________________________________________| -// \ \| | | | __ __ __ __ ______ _______ -// \ | | |_____ | | | | | | | | | _ \ / _____) -// \ | | _____| | | | | | | | | | | \ \ \_______ +// ____ ____ __ ______ __________ __ __ __ __ +// \ \ | | | | | _ \ |___ ___| | | | | / \ | | +// \ \ | | | | | |_) | | | | | | | / \ | | +// \ \ | | | | | _ / | | | | | | / /\ \ | | +// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ +// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| +// \ \ | | ________________________________________________________________ +// \ \ | | | ______________________________________________________________| +// \ \| | | | __ __ __ __ ______ _______ +// \ | | |_____ | | | | | | | | | _ \ / _____) +// \ | | _____| | | | | | | | | | | \ \ \_______ // \ | | | | |_____ | \_/ | | | | |_/ / _____ | -// \ _____| |__| |________| \_______/ |__| |______/ (_______/ +// \ _____| |__| |________| \_______/ |__| |______/ (_______/ // -// This file is part of VirtualFluids. VirtualFluids is free software: you can +// This file is part of VirtualFluids. VirtualFluids is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of +// License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. -// -// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// +// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License along // with VirtualFluids (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>. // @@ -41,28 +41,28 @@ class BCArray3D; class BCAlgorithm; class ILBMKernel; -//! A class provides an interface for boundary conditions in the calculation loop. +//! A class provides an interface for boundary conditions in the calculation loop. class BCProcessor { public: - BCProcessor(); - BCProcessor(SPtr<ILBMKernel> kernel); - virtual ~BCProcessor(); - virtual SPtr<BCArray3D> getBCArray(); - virtual void setBCArray(SPtr<BCArray3D> bcarray); - virtual SPtr<BCProcessor> clone(SPtr<ILBMKernel> kernel); + BCProcessor(); + BCProcessor(SPtr<ILBMKernel> kernel); + virtual ~BCProcessor(); + virtual SPtr<BCArray3D> getBCArray(); + virtual void setBCArray(SPtr<BCArray3D> bcarray); + virtual SPtr<BCProcessor> clone(SPtr<ILBMKernel> kernel); + + void addBC(SPtr<BCAlgorithm> bc); + void applyPreCollisionBC(); + void applyPostCollisionBC(); + void clearBC(); - void addBC(SPtr<BCAlgorithm> bc); - void applyPreCollisionBC(); - void applyPostCollisionBC(); - void clearBC(); protected: - std::vector<SPtr<BCAlgorithm> > preBC; - std::vector<SPtr<BCAlgorithm> > postBC; - SPtr<BCArray3D> bcArray; + std::vector<SPtr<BCAlgorithm>> preBC; + std::vector<SPtr<BCAlgorithm>> postBC; + SPtr<BCArray3D> bcArray; private: - }; #endif diff --git a/src/cpu/VirtualFluidsCore/BoundaryConditions/BoundaryConditions.cpp b/src/cpu/VirtualFluidsCore/BoundaryConditions/BoundaryConditions.cpp index 23ffad85e6cf0454e6f1927f22ee3ad94828d23f..d66094dcc2277e297f03da91fe885f7e569d3aa2 100644 --- a/src/cpu/VirtualFluidsCore/BoundaryConditions/BoundaryConditions.cpp +++ b/src/cpu/VirtualFluidsCore/BoundaryConditions/BoundaryConditions.cpp @@ -1,28 +1,28 @@ //======================================================================================= -// ____ ____ __ ______ __________ __ __ __ __ -// \ \ | | | | | _ \ |___ ___| | | | | / \ | | -// \ \ | | | | | |_) | | | | | | | / \ | | -// \ \ | | | | | _ / | | | | | | / /\ \ | | -// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ -// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| -// \ \ | | ________________________________________________________________ -// \ \ | | | ______________________________________________________________| -// \ \| | | | __ __ __ __ ______ _______ -// \ | | |_____ | | | | | | | | | _ \ / _____) -// \ | | _____| | | | | | | | | | | \ \ \_______ +// ____ ____ __ ______ __________ __ __ __ __ +// \ \ | | | | | _ \ |___ ___| | | | | / \ | | +// \ \ | | | | | |_) | | | | | | | / \ | | +// \ \ | | | | | _ / | | | | | | / /\ \ | | +// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ +// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| +// \ \ | | ________________________________________________________________ +// \ \ | | | ______________________________________________________________| +// \ \| | | | __ __ __ __ ______ _______ +// \ | | |_____ | | | | | | | | | _ \ / _____) +// \ | | _____| | | | | | | | | | | \ \ \_______ // \ | | | | |_____ | \_/ | | | | |_/ / _____ | -// \ _____| |__| |________| \_______/ |__| |______/ (_______/ +// \ _____| |__| |________| \_______/ |__| |______/ (_______/ // -// This file is part of VirtualFluids. VirtualFluids is free software: you can +// This file is part of VirtualFluids. VirtualFluids is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of +// License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. -// -// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// +// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License along // with VirtualFluids (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>. // @@ -33,5 +33,4 @@ #include "BoundaryConditions.h" -const long long BoundaryConditions::maxOptionVal = ( 1<<optionDigits ) - 1; //2^3-1 -> 7 - +const long long BoundaryConditions::maxOptionVal = (1 << optionDigits) - 1; // 2^3-1 -> 7 diff --git a/src/cpu/VirtualFluidsCore/BoundaryConditions/BoundaryConditions.h b/src/cpu/VirtualFluidsCore/BoundaryConditions/BoundaryConditions.h index 1f740776ea4ef75d49e825c73f354357464145a7..886d1ee2d6f44402ba39255bce3ad16425ce437e 100644 --- a/src/cpu/VirtualFluidsCore/BoundaryConditions/BoundaryConditions.h +++ b/src/cpu/VirtualFluidsCore/BoundaryConditions/BoundaryConditions.h @@ -1,28 +1,28 @@ //======================================================================================= -// ____ ____ __ ______ __________ __ __ __ __ -// \ \ | | | | | _ \ |___ ___| | | | | / \ | | -// \ \ | | | | | |_) | | | | | | | / \ | | -// \ \ | | | | | _ / | | | | | | / /\ \ | | -// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ -// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| -// \ \ | | ________________________________________________________________ -// \ \ | | | ______________________________________________________________| -// \ \| | | | __ __ __ __ ______ _______ -// \ | | |_____ | | | | | | | | | _ \ / _____) -// \ | | _____| | | | | | | | | | | \ \ \_______ +// ____ ____ __ ______ __________ __ __ __ __ +// \ \ | | | | | _ \ |___ ___| | | | | / \ | | +// \ \ | | | | | |_) | | | | | | | / \ | | +// \ \ | | | | | _ / | | | | | | / /\ \ | | +// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ +// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| +// \ \ | | ________________________________________________________________ +// \ \ | | | ______________________________________________________________| +// \ \| | | | __ __ __ __ ______ _______ +// \ | | |_____ | | | | | | | | | _ \ / _____) +// \ | | _____| | | | | | | | | | | \ \ \_______ // \ | | | | |_____ | \_/ | | | | |_/ / _____ | -// \ _____| |__| |________| \_______/ |__| |______/ (_______/ +// \ _____| |__| |________| \_______/ |__| |______/ (_______/ // -// This file is part of VirtualFluids. VirtualFluids is free software: you can +// This file is part of VirtualFluids. VirtualFluids is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of +// License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. -// -// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// +// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License along // with VirtualFluids (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>. // @@ -33,240 +33,336 @@ #ifndef BoundaryConditions_H #define BoundaryConditions_H -#include <vector> #include <string> +#include <vector> -#include "Vector3D.h" -#include "UbException.h" +#include "D3Q27System.h" +#include "UbException.h" #include "UbSystem.h" #include "UbTuple.h" -#include "D3Q27System.h" +#include "Vector3D.h" #include <PointerDefinitions.h> //! Difenition of baundary conditions in grid generation -class BoundaryConditions +class BoundaryConditions { public: - BoundaryConditions() - - { - UB_STATIC_ASSERT( sizeof(long long) >= 8); - UB_STATIC_ASSERT( (sizeof(long long)*8) >= (D3Q27System::FENDDIR+1)*BoundaryConditions::optionDigits ); + BoundaryConditions() + + { + UB_STATIC_ASSERT(sizeof(long long) >= 8); + UB_STATIC_ASSERT((sizeof(long long) * 8) >= (D3Q27System::FENDDIR + 1) * BoundaryConditions::optionDigits); + + for (int fdir = D3Q27System::FSTARTDIR; fdir <= D3Q27System::FENDDIR; fdir++) + q[fdir] = -999.; + } + virtual ~BoundaryConditions() = default; - for(int fdir=D3Q27System::FSTARTDIR; fdir<=D3Q27System::FENDDIR; fdir++) - q[fdir] = -999.; - } - virtual ~BoundaryConditions() = default; + virtual bool isEmpty() + { + return (noslipBoundaryFlags & slipBoundaryFlags & velocityBoundaryFlags & densityBoundaryFlags) == 0; + } + virtual bool hasBoundaryCondition() + { + return (hasNoSlipBoundary() || hasSlipBoundary() || hasDensityBoundary() || hasVelocityBoundary() || + hasWallModelBoundary()); + } - virtual bool isEmpty() { return (noslipBoundaryFlags&slipBoundaryFlags&velocityBoundaryFlags&densityBoundaryFlags)==0;} - virtual bool hasBoundaryCondition() - { - return ( hasNoSlipBoundary() || hasSlipBoundary() - || hasDensityBoundary() || hasVelocityBoundary() || hasWallModelBoundary() ); - } + virtual bool hasBoundaryConditionFlag(const int &direction) + { + assert(direction >= D3Q27System::FSTARTDIR && direction <= D3Q27System::FENDDIR); - virtual bool hasBoundaryConditionFlag(const int& direction) - { - assert( direction >= D3Q27System::FSTARTDIR && direction <= D3Q27System::FENDDIR ); + return (hasNoSlipBoundaryFlag(direction) || hasSlipBoundaryFlag(direction) || + hasDensityBoundaryFlag(direction) || hasVelocityBoundaryFlag(direction) || + hasWallModelBoundaryFlag(direction)); + } - return ( hasNoSlipBoundaryFlag(direction) || hasSlipBoundaryFlag(direction) - || hasDensityBoundaryFlag(direction) || hasVelocityBoundaryFlag(direction) || hasWallModelBoundaryFlag(direction)); - } protected: - void setFlagBits(long long& flag, const int& direction, const short& secOpt) - { - if( (secOpt+1)>maxOptionVal ) - throw UbException(UB_EXARGS,"error: option > "+UbSystem::toString(maxOptionVal-1)); - - //all digits at the respective positions to "0" - flag &= ~( maxOptionVal<<(direction*optionDigits) ); - //set all digits according to the flag at the respective positions - flag |= ((long long)(secOpt+1)<<(direction*optionDigits)); - } + void setFlagBits(long long &flag, const int &direction, const short &secOpt) + { + if ((secOpt + 1) > maxOptionVal) + throw UbException(UB_EXARGS, "error: option > " + UbSystem::toString(maxOptionVal - 1)); + + // all digits at the respective positions to "0" + flag &= ~(maxOptionVal << (direction * optionDigits)); + // set all digits according to the flag at the respective positions + flag |= ((long long)(secOpt + 1) << (direction * optionDigits)); + } + public: - /*===================== NoSlip Boundary ==================================================*/ - void setNoSlipBoundaryFlag(const int& direction, const short& secOpt=0) { this->setFlagBits(noslipBoundaryFlags,direction,secOpt); } - void unsetNoSlipBoundaryFlag(const int& direction) { this->noslipBoundaryFlags &= ~( maxOptionVal<<(direction*optionDigits) ); } - void unsetNoSlipBoundary() { this->noslipBoundaryFlags = 0; } - long long getNoSlipBoundary() { return this->noslipBoundaryFlags; } - bool hasNoSlipBoundary() { return (noslipBoundaryFlags!=0); } - bool hasNoSlipBoundaryFlag(const int& direction) { return ( ( ( noslipBoundaryFlags>>(optionDigits*direction) ) & maxOptionVal ) != 0); } - short getNoSlipSecondaryOption(const int& direction) { return (short)( ( ( noslipBoundaryFlags>>(optionDigits*direction) ) & maxOptionVal ) - 1 ); } - /*===================== WallModel Boundary ==================================================*/ - void setWallModelBoundaryFlag(const int& direction, const short& secOpt=0) { this->setFlagBits(wallModelBoundaryFlags,direction,secOpt); } - void unsetWallModelBoundaryFlag(const int& direction) { this->wallModelBoundaryFlags &= ~( maxOptionVal<<(direction*optionDigits) ); } - void unsetWallModelBoundary() { this->wallModelBoundaryFlags = 0; } - long long getWallModelBoundary() { return this->wallModelBoundaryFlags; } - bool hasWallModelBoundary() { return (wallModelBoundaryFlags!=0); } - bool hasWallModelBoundaryFlag(const int& direction) { return ( ( ( wallModelBoundaryFlags>>(optionDigits*direction) ) & maxOptionVal ) != 0); } - short getWallModelSecondaryOption(const int& direction) { return (short)( ( ( wallModelBoundaryFlags>>(optionDigits*direction) ) & maxOptionVal ) - 1 ); } - /*===================== Slip-Solid Boundary ==================================================*/ - void setSlipBoundaryFlag(const int& direction, const short& secOpt=0) { this->setFlagBits(slipBoundaryFlags,direction,secOpt); } - void unsetSlipBoundaryFlag(const int& direction) { this->slipBoundaryFlags &= ~( maxOptionVal<<(direction*optionDigits) ); } - void unsetSlipBoundary() { this->slipBoundaryFlags = 0; } - long long getSlipBoundary() { return this->slipBoundaryFlags; } - bool hasSlipBoundary() { return (slipBoundaryFlags!=0); } - bool hasSlipBoundaryFlag(const int& direction) { return ( ( ( slipBoundaryFlags>>(optionDigits*direction) ) & maxOptionVal ) != 0); } - short getSlipSecondaryOption(const int& direction) { return (short)( ( ( slipBoundaryFlags>>(optionDigits*direction) ) & maxOptionVal ) - 1 ); } - void setNormalVector(const LBMReal& nx1,const LBMReal& nx2,const LBMReal& nx3) { this->nx1 = nx1; this->nx2 = nx2; this->nx3 = nx3;} - UbTupleDouble3 getNormalVector() { return makeUbTuple(nx1,nx2,nx3); } + /*===================== NoSlip Boundary ==================================================*/ + void setNoSlipBoundaryFlag(const int &direction, const short &secOpt = 0) + { + this->setFlagBits(noslipBoundaryFlags, direction, secOpt); + } + void unsetNoSlipBoundaryFlag(const int &direction) + { + this->noslipBoundaryFlags &= ~(maxOptionVal << (direction * optionDigits)); + } + void unsetNoSlipBoundary() { this->noslipBoundaryFlags = 0; } + long long getNoSlipBoundary() { return this->noslipBoundaryFlags; } + bool hasNoSlipBoundary() { return (noslipBoundaryFlags != 0); } + bool hasNoSlipBoundaryFlag(const int &direction) + { + return (((noslipBoundaryFlags >> (optionDigits * direction)) & maxOptionVal) != 0); + } + short getNoSlipSecondaryOption(const int &direction) + { + return (short)(((noslipBoundaryFlags >> (optionDigits * direction)) & maxOptionVal) - 1); + } + /*===================== WallModel Boundary ==================================================*/ + void setWallModelBoundaryFlag(const int &direction, const short &secOpt = 0) + { + this->setFlagBits(wallModelBoundaryFlags, direction, secOpt); + } + void unsetWallModelBoundaryFlag(const int &direction) + { + this->wallModelBoundaryFlags &= ~(maxOptionVal << (direction * optionDigits)); + } + void unsetWallModelBoundary() { this->wallModelBoundaryFlags = 0; } + long long getWallModelBoundary() { return this->wallModelBoundaryFlags; } + bool hasWallModelBoundary() { return (wallModelBoundaryFlags != 0); } + bool hasWallModelBoundaryFlag(const int &direction) + { + return (((wallModelBoundaryFlags >> (optionDigits * direction)) & maxOptionVal) != 0); + } + short getWallModelSecondaryOption(const int &direction) + { + return (short)(((wallModelBoundaryFlags >> (optionDigits * direction)) & maxOptionVal) - 1); + } + /*===================== Slip-Solid Boundary ==================================================*/ + void setSlipBoundaryFlag(const int &direction, const short &secOpt = 0) + { + this->setFlagBits(slipBoundaryFlags, direction, secOpt); + } + void unsetSlipBoundaryFlag(const int &direction) + { + this->slipBoundaryFlags &= ~(maxOptionVal << (direction * optionDigits)); + } + void unsetSlipBoundary() { this->slipBoundaryFlags = 0; } + long long getSlipBoundary() { return this->slipBoundaryFlags; } + bool hasSlipBoundary() { return (slipBoundaryFlags != 0); } + bool hasSlipBoundaryFlag(const int &direction) + { + return (((slipBoundaryFlags >> (optionDigits * direction)) & maxOptionVal) != 0); + } + short getSlipSecondaryOption(const int &direction) + { + return (short)(((slipBoundaryFlags >> (optionDigits * direction)) & maxOptionVal) - 1); + } + void setNormalVector(const LBMReal &nx1, const LBMReal &nx2, const LBMReal &nx3) + { + this->nx1 = nx1; + this->nx2 = nx2; + this->nx3 = nx3; + } + UbTupleDouble3 getNormalVector() { return makeUbTuple(nx1, nx2, nx3); } - /*============== Velocity Boundary ========================*/ - void setVelocityBoundaryFlag(const int& direction, const short& secOpt=0) { this->setFlagBits(velocityBoundaryFlags,direction,secOpt); } - void unsetVelocityBoundaryFlag(const int& direction) { this->velocityBoundaryFlags &= ~( maxOptionVal<<(direction*optionDigits) ); } - void unsetVelocityBoundary() { this->velocityBoundaryFlags = 0; } - long long getVelocityBoundary() { return this->velocityBoundaryFlags; } - bool hasVelocityBoundary() { return this->velocityBoundaryFlags!=0; } - bool hasVelocityBoundaryFlag(const int& direction) { return ( ( ( velocityBoundaryFlags>>(optionDigits*direction) ) & maxOptionVal ) != 0); } - short getVelocitySecondaryOption(const int& direction) { return (short)( ( ( velocityBoundaryFlags>>(optionDigits*direction) ) & maxOptionVal ) - 1 ); } + /*============== Velocity Boundary ========================*/ + void setVelocityBoundaryFlag(const int &direction, const short &secOpt = 0) + { + this->setFlagBits(velocityBoundaryFlags, direction, secOpt); + } + void unsetVelocityBoundaryFlag(const int &direction) + { + this->velocityBoundaryFlags &= ~(maxOptionVal << (direction * optionDigits)); + } + void unsetVelocityBoundary() { this->velocityBoundaryFlags = 0; } + long long getVelocityBoundary() { return this->velocityBoundaryFlags; } + bool hasVelocityBoundary() { return this->velocityBoundaryFlags != 0; } + bool hasVelocityBoundaryFlag(const int &direction) + { + return (((velocityBoundaryFlags >> (optionDigits * direction)) & maxOptionVal) != 0); + } + short getVelocitySecondaryOption(const int &direction) + { + return (short)(((velocityBoundaryFlags >> (optionDigits * direction)) & maxOptionVal) - 1); + } - void setBoundaryVelocity(const Vector3D& vx) + void setBoundaryVelocity(const Vector3D &vx) + { + setBoundaryVelocityX1((LBMReal)vx[0]); + setBoundaryVelocityX2((LBMReal)vx[1]); + setBoundaryVelocityX3((LBMReal)vx[2]); + } + void setBoundaryVelocityX1(const LBMReal &vx1) { this->bcVelocityX1 = vx1; } + void setBoundaryVelocityX2(const LBMReal &vx2) { this->bcVelocityX2 = vx2; } + void setBoundaryVelocityX3(const LBMReal &vx3) { this->bcVelocityX3 = vx3; } + LBMReal getBoundaryVelocityX1() { return this->bcVelocityX1; } + LBMReal getBoundaryVelocityX2() { return this->bcVelocityX2; } + LBMReal getBoundaryVelocityX3() { return this->bcVelocityX3; } + LBMReal getBoundaryVelocity(const int &direction) { - setBoundaryVelocityX1((LBMReal)vx[0]); - setBoundaryVelocityX2((LBMReal)vx[1]); - setBoundaryVelocityX3((LBMReal)vx[2]); - } - void setBoundaryVelocityX1(const LBMReal& vx1) { this->bcVelocityX1 = vx1; } - void setBoundaryVelocityX2(const LBMReal& vx2) { this->bcVelocityX2 = vx2; } - void setBoundaryVelocityX3(const LBMReal& vx3) { this->bcVelocityX3 = vx3; } - LBMReal getBoundaryVelocityX1() { return this->bcVelocityX1; } - LBMReal getBoundaryVelocityX2() { return this->bcVelocityX2; } - LBMReal getBoundaryVelocityX3() { return this->bcVelocityX3; } - LBMReal getBoundaryVelocity(const int& direction) - { - switch(direction) - { - case D3Q27System::E : return (LBMReal)( UbMath::c4o9*(+bcVelocityX1) ); //(2/cs^2)(=6)*rho_0(=1 for incompressible)*wi*u*ei with cs=1/sqrt(3) - case D3Q27System::W : return (LBMReal)( UbMath::c4o9*(-bcVelocityX1) ); - case D3Q27System::N : return (LBMReal)( UbMath::c4o9*(+bcVelocityX2) ); - case D3Q27System::S : return (LBMReal)( UbMath::c4o9*(-bcVelocityX2) ); - case D3Q27System::T : return (LBMReal)( UbMath::c4o9*(+bcVelocityX3) ); - case D3Q27System::B : return (LBMReal)( UbMath::c4o9*(-bcVelocityX3) ); - case D3Q27System::NE: return (LBMReal)( UbMath::c1o9*(+bcVelocityX1+bcVelocityX2 ) ); - case D3Q27System::SW: return (LBMReal)( UbMath::c1o9*(-bcVelocityX1-bcVelocityX2 ) ); - case D3Q27System::SE: return (LBMReal)( UbMath::c1o9*(+bcVelocityX1-bcVelocityX2 ) ); - case D3Q27System::NW: return (LBMReal)( UbMath::c1o9*(-bcVelocityX1+bcVelocityX2 ) ); - case D3Q27System::TE: return (LBMReal)( UbMath::c1o9*(+bcVelocityX1 +bcVelocityX3) ); - case D3Q27System::BW: return (LBMReal)( UbMath::c1o9*(-bcVelocityX1 -bcVelocityX3) ); - case D3Q27System::BE: return (LBMReal)( UbMath::c1o9*(+bcVelocityX1 -bcVelocityX3) ); - case D3Q27System::TW: return (LBMReal)( UbMath::c1o9*(-bcVelocityX1 +bcVelocityX3) ); - case D3Q27System::TN: return (LBMReal)( UbMath::c1o9*( +bcVelocityX2+bcVelocityX3) ); - case D3Q27System::BS: return (LBMReal)( UbMath::c1o9*( -bcVelocityX2-bcVelocityX3) ); - case D3Q27System::BN: return (LBMReal)( UbMath::c1o9*( +bcVelocityX2-bcVelocityX3) ); - case D3Q27System::TS: return (LBMReal)( UbMath::c1o9*( -bcVelocityX2+bcVelocityX3) ); - case D3Q27System::TNE: return (LBMReal)( UbMath::c1o36*(+bcVelocityX1+bcVelocityX2+bcVelocityX3) ); - case D3Q27System::BSW: return (LBMReal)( UbMath::c1o36*(-bcVelocityX1-bcVelocityX2-bcVelocityX3) ); - case D3Q27System::BNE: return (LBMReal)( UbMath::c1o36*(+bcVelocityX1+bcVelocityX2-bcVelocityX3) ); - case D3Q27System::TSW: return (LBMReal)( UbMath::c1o36*(-bcVelocityX1-bcVelocityX2+bcVelocityX3) ); - case D3Q27System::TSE: return (LBMReal)( UbMath::c1o36*(+bcVelocityX1-bcVelocityX2+bcVelocityX3) ); - case D3Q27System::BNW: return (LBMReal)( UbMath::c1o36*(-bcVelocityX1+bcVelocityX2-bcVelocityX3) ); - case D3Q27System::BSE: return (LBMReal)( UbMath::c1o36*(+bcVelocityX1-bcVelocityX2-bcVelocityX3) ); - case D3Q27System::TNW: return (LBMReal)( UbMath::c1o36*(-bcVelocityX1+bcVelocityX2+bcVelocityX3) ); - default: throw UbException(UB_EXARGS,"unknown error"); - } - } + switch (direction) { + case D3Q27System::E: + return (LBMReal)(UbMath::c4o9 * + (+bcVelocityX1)); //(2/cs^2)(=6)*rho_0(=1 for incompressible)*wi*u*ei with cs=1/sqrt(3) + case D3Q27System::W: + return (LBMReal)(UbMath::c4o9 * (-bcVelocityX1)); + case D3Q27System::N: + return (LBMReal)(UbMath::c4o9 * (+bcVelocityX2)); + case D3Q27System::S: + return (LBMReal)(UbMath::c4o9 * (-bcVelocityX2)); + case D3Q27System::T: + return (LBMReal)(UbMath::c4o9 * (+bcVelocityX3)); + case D3Q27System::B: + return (LBMReal)(UbMath::c4o9 * (-bcVelocityX3)); + case D3Q27System::NE: + return (LBMReal)(UbMath::c1o9 * (+bcVelocityX1 + bcVelocityX2)); + case D3Q27System::SW: + return (LBMReal)(UbMath::c1o9 * (-bcVelocityX1 - bcVelocityX2)); + case D3Q27System::SE: + return (LBMReal)(UbMath::c1o9 * (+bcVelocityX1 - bcVelocityX2)); + case D3Q27System::NW: + return (LBMReal)(UbMath::c1o9 * (-bcVelocityX1 + bcVelocityX2)); + case D3Q27System::TE: + return (LBMReal)(UbMath::c1o9 * (+bcVelocityX1 + bcVelocityX3)); + case D3Q27System::BW: + return (LBMReal)(UbMath::c1o9 * (-bcVelocityX1 - bcVelocityX3)); + case D3Q27System::BE: + return (LBMReal)(UbMath::c1o9 * (+bcVelocityX1 - bcVelocityX3)); + case D3Q27System::TW: + return (LBMReal)(UbMath::c1o9 * (-bcVelocityX1 + bcVelocityX3)); + case D3Q27System::TN: + return (LBMReal)(UbMath::c1o9 * (+bcVelocityX2 + bcVelocityX3)); + case D3Q27System::BS: + return (LBMReal)(UbMath::c1o9 * (-bcVelocityX2 - bcVelocityX3)); + case D3Q27System::BN: + return (LBMReal)(UbMath::c1o9 * (+bcVelocityX2 - bcVelocityX3)); + case D3Q27System::TS: + return (LBMReal)(UbMath::c1o9 * (-bcVelocityX2 + bcVelocityX3)); + case D3Q27System::TNE: + return (LBMReal)(UbMath::c1o36 * (+bcVelocityX1 + bcVelocityX2 + bcVelocityX3)); + case D3Q27System::BSW: + return (LBMReal)(UbMath::c1o36 * (-bcVelocityX1 - bcVelocityX2 - bcVelocityX3)); + case D3Q27System::BNE: + return (LBMReal)(UbMath::c1o36 * (+bcVelocityX1 + bcVelocityX2 - bcVelocityX3)); + case D3Q27System::TSW: + return (LBMReal)(UbMath::c1o36 * (-bcVelocityX1 - bcVelocityX2 + bcVelocityX3)); + case D3Q27System::TSE: + return (LBMReal)(UbMath::c1o36 * (+bcVelocityX1 - bcVelocityX2 + bcVelocityX3)); + case D3Q27System::BNW: + return (LBMReal)(UbMath::c1o36 * (-bcVelocityX1 + bcVelocityX2 - bcVelocityX3)); + case D3Q27System::BSE: + return (LBMReal)(UbMath::c1o36 * (+bcVelocityX1 - bcVelocityX2 - bcVelocityX3)); + case D3Q27System::TNW: + return (LBMReal)(UbMath::c1o36 * (-bcVelocityX1 + bcVelocityX2 + bcVelocityX3)); + default: + throw UbException(UB_EXARGS, "unknown error"); + } + } - /*============== Density Boundary ========================*/ - void setDensityBoundaryFlag(const int& direction, const short& secOpt=0) { this->setFlagBits(densityBoundaryFlags,direction,secOpt); } - void unsetDensityBoundaryFlag(const int& direction) { this->densityBoundaryFlags &= ~( maxOptionVal<<(direction*optionDigits) ); } - void unsetDensityBoundary() { this->densityBoundaryFlags = 0; } - long long getDensityBoundary() { return this->densityBoundaryFlags; } - bool hasDensityBoundary() { return (this->densityBoundaryFlags!=0); } - bool hasDensityBoundaryFlag(const int& direction) { return ( ( ( densityBoundaryFlags>>(optionDigits*direction) ) & maxOptionVal ) != 0); } - short getDensitySecondaryOption(const int& direction) { return (short)( ( ( densityBoundaryFlags>>(optionDigits*direction) ) & maxOptionVal ) - 1 ); } + /*============== Density Boundary ========================*/ + void setDensityBoundaryFlag(const int &direction, const short &secOpt = 0) + { + this->setFlagBits(densityBoundaryFlags, direction, secOpt); + } + void unsetDensityBoundaryFlag(const int &direction) + { + this->densityBoundaryFlags &= ~(maxOptionVal << (direction * optionDigits)); + } + void unsetDensityBoundary() { this->densityBoundaryFlags = 0; } + long long getDensityBoundary() { return this->densityBoundaryFlags; } + bool hasDensityBoundary() { return (this->densityBoundaryFlags != 0); } + bool hasDensityBoundaryFlag(const int &direction) + { + return (((densityBoundaryFlags >> (optionDigits * direction)) & maxOptionVal) != 0); + } + short getDensitySecondaryOption(const int &direction) + { + return (short)(((densityBoundaryFlags >> (optionDigits * direction)) & maxOptionVal) - 1); + } - void setBoundaryDensity(LBMReal density) { this->bcDensity = density; } - LBMReal getBoundaryDensity() { return this->bcDensity; } + void setBoundaryDensity(LBMReal density) { this->bcDensity = density; } + LBMReal getBoundaryDensity() { return this->bcDensity; } - //Lodi extension - void setDensityLodiDensity(const LBMReal& bcLodiDensity) { this->bcLodiDensity = bcLodiDensity; } - void setDensityLodiVelocityX1(const LBMReal& bcLodiVelocityX1) { this->bcLodiVelocityX1 = bcLodiVelocityX1; } - void setDensityLodiVelocityX2(const LBMReal& bcLodiVelocityX2) { this->bcLodiVelocityX2 = bcLodiVelocityX2; } - void setDensityLodiVelocityX3(const LBMReal& bcLodiVelocityX3) { this->bcLodiVelocityX3 = bcLodiVelocityX3; } - void setDensityLodiLength(const LBMReal& bcLodiLentgh) { this->bcLodiLentgh = bcLodiLentgh; } - LBMReal getDensityLodiDensity() const { return this->bcLodiDensity; } - LBMReal getDensityLodiVelocityX1() const { return this->bcLodiVelocityX1; } - LBMReal getDensityLodiVelocityX2() const { return this->bcLodiVelocityX2; } - LBMReal getDensityLodiVelocityX3() const { return this->bcLodiVelocityX3; } - LBMReal getDensityLodiLength() const { return this->bcLodiLentgh; } + // Lodi extension + void setDensityLodiDensity(const LBMReal &bcLodiDensity) { this->bcLodiDensity = bcLodiDensity; } + void setDensityLodiVelocityX1(const LBMReal &bcLodiVelocityX1) { this->bcLodiVelocityX1 = bcLodiVelocityX1; } + void setDensityLodiVelocityX2(const LBMReal &bcLodiVelocityX2) { this->bcLodiVelocityX2 = bcLodiVelocityX2; } + void setDensityLodiVelocityX3(const LBMReal &bcLodiVelocityX3) { this->bcLodiVelocityX3 = bcLodiVelocityX3; } + void setDensityLodiLength(const LBMReal &bcLodiLentgh) { this->bcLodiLentgh = bcLodiLentgh; } + LBMReal getDensityLodiDensity() const { return this->bcLodiDensity; } + LBMReal getDensityLodiVelocityX1() const { return this->bcLodiVelocityX1; } + LBMReal getDensityLodiVelocityX2() const { return this->bcLodiVelocityX2; } + LBMReal getDensityLodiVelocityX3() const { return this->bcLodiVelocityX3; } + LBMReal getDensityLodiLength() const { return this->bcLodiLentgh; } - LBMReal& densityLodiDensity() { return this->bcLodiDensity; } - LBMReal& densityLodiVelocityX1() { return this->bcLodiVelocityX1; } - LBMReal& densityLodiVelocityX2() { return this->bcLodiVelocityX2; } - LBMReal& densityLodiVelocityX3() { return this->bcLodiVelocityX3; } - LBMReal& densityLodiLentgh() { return this->bcLodiLentgh; } + LBMReal &densityLodiDensity() { return this->bcLodiDensity; } + LBMReal &densityLodiVelocityX1() { return this->bcLodiVelocityX1; } + LBMReal &densityLodiVelocityX2() { return this->bcLodiVelocityX2; } + LBMReal &densityLodiVelocityX3() { return this->bcLodiVelocityX3; } + LBMReal &densityLodiLentgh() { return this->bcLodiLentgh; } - const LBMReal& densityLodiDensity() const { return this->bcLodiDensity; } - const LBMReal& densityLodiVelocityX1() const { return this->bcLodiVelocityX1; } - const LBMReal& densityLodiVelocityX2() const { return this->bcLodiVelocityX2; } - const LBMReal& densityLodiVelocityX3() const { return this->bcLodiVelocityX3; } - const LBMReal& densityLodiLentgh() const { return this->bcLodiLentgh; } + const LBMReal &densityLodiDensity() const { return this->bcLodiDensity; } + const LBMReal &densityLodiVelocityX1() const { return this->bcLodiVelocityX1; } + const LBMReal &densityLodiVelocityX2() const { return this->bcLodiVelocityX2; } + const LBMReal &densityLodiVelocityX3() const { return this->bcLodiVelocityX3; } + const LBMReal &densityLodiLentgh() const { return this->bcLodiLentgh; } + /*======================= Qs =============================*/ + void setQ(const LBMReal &val, const int &direction) { q[direction] = val; } + LBMReal getQ(const int &direction) { return q[direction]; } - /*======================= Qs =============================*/ - void setQ(const LBMReal& val, const int& direction) { q[direction] = val; } - LBMReal getQ(const int& direction) { return q[direction]; } - - virtual std::vector< std::string > getBCNames() - { - std::vector< std::string > tmp; - tmp.emplace_back("NoSlipBC" ); - tmp.emplace_back("SlipBC" ); - tmp.emplace_back("VelocityBC" ); - tmp.emplace_back("DensityBC" ); - return tmp; - } - virtual std::vector< long long > getBCFlags() - { - std::vector< long long > tmp; - tmp.push_back( noslipBoundaryFlags ); - tmp.push_back( slipBoundaryFlags ); - tmp.push_back( velocityBoundaryFlags ); - tmp.push_back( densityBoundaryFlags ); - return tmp; - } + virtual std::vector<std::string> getBCNames() + { + std::vector<std::string> tmp; + tmp.emplace_back("NoSlipBC"); + tmp.emplace_back("SlipBC"); + tmp.emplace_back("VelocityBC"); + tmp.emplace_back("DensityBC"); + return tmp; + } + virtual std::vector<long long> getBCFlags() + { + std::vector<long long> tmp; + tmp.push_back(noslipBoundaryFlags); + tmp.push_back(slipBoundaryFlags); + tmp.push_back(velocityBoundaryFlags); + tmp.push_back(densityBoundaryFlags); + return tmp; + } - static bool hasFlagForDirection(const long long& flag, const int& direction) - { - return ( ( ( flag>>(optionDigits*direction) ) & maxOptionVal ) != 0); - } + static bool hasFlagForDirection(const long long &flag, const int &direction) + { + return (((flag >> (optionDigits * direction)) & maxOptionVal) != 0); + } - void setBcAlgorithmType(char alg) { algorithmType = alg; } - char getBcAlgorithmType() { return algorithmType; } + void setBcAlgorithmType(char alg) { algorithmType = alg; } + char getBcAlgorithmType() { return algorithmType; } public: - static const int optionDigits = 2; //--> 2 bits for secondary Option --> maxOptionVal = 7 - static const long long maxOptionVal;// = ( 1<<optionDigits ) - 1; //2^3-1 -> 7 + static const int optionDigits = 2; //--> 2 bits for secondary Option --> maxOptionVal = 7 + static const long long maxOptionVal; // = ( 1<<optionDigits ) - 1; //2^3-1 -> 7 protected: - LBMReal q[D3Q27System::FENDDIR+1]; - - long long noslipBoundaryFlags{0}; - long long slipBoundaryFlags{0}; - long long velocityBoundaryFlags{0}; - long long densityBoundaryFlags{0}; - long long wallModelBoundaryFlags{0}; + LBMReal q[D3Q27System::FENDDIR + 1]; - LBMReal bcVelocityX1{0.0f}; - LBMReal bcVelocityX2{0.0f}; - LBMReal bcVelocityX3{0.0f}; - LBMReal bcDensity{0.0f}; + long long noslipBoundaryFlags{ 0 }; + long long slipBoundaryFlags{ 0 }; + long long velocityBoundaryFlags{ 0 }; + long long densityBoundaryFlags{ 0 }; + long long wallModelBoundaryFlags{ 0 }; - LBMReal bcLodiDensity{0.0f}; - LBMReal bcLodiVelocityX1{0.0f}; - LBMReal bcLodiVelocityX2{0.0f}; - LBMReal bcLodiVelocityX3{0.0f}; - LBMReal bcLodiLentgh{0.0f}; + LBMReal bcVelocityX1{ 0.0f }; + LBMReal bcVelocityX2{ 0.0f }; + LBMReal bcVelocityX3{ 0.0f }; + LBMReal bcDensity{ 0.0f }; - LBMReal nx1{0.0f},nx2{0.0f},nx3{0.0f}; + LBMReal bcLodiDensity{ 0.0f }; + LBMReal bcLodiVelocityX1{ 0.0f }; + LBMReal bcLodiVelocityX2{ 0.0f }; + LBMReal bcLodiVelocityX3{ 0.0f }; + LBMReal bcLodiLentgh{ 0.0f }; - char algorithmType{-1}; + LBMReal nx1{ 0.0f }, nx2{ 0.0f }, nx3{ 0.0f }; - private: - friend class MPIIORestartCoProcessor; - friend class MPIIOMigrationCoProcessor; - friend class MPIIOMigrationBECoProcessor; + char algorithmType{ -1 }; +private: + friend class MPIIORestartCoProcessor; + friend class MPIIOMigrationCoProcessor; + friend class MPIIOMigrationBECoProcessor; }; #endif diff --git a/src/cpu/VirtualFluidsCore/BoundaryConditions/DensityBCAdapter.cpp b/src/cpu/VirtualFluidsCore/BoundaryConditions/DensityBCAdapter.cpp index dcdfd989d1dbd1c011769e1d573d282de9a80511..49a4960a1ccee39475f4a7149a7ba819294681eb 100644 --- a/src/cpu/VirtualFluidsCore/BoundaryConditions/DensityBCAdapter.cpp +++ b/src/cpu/VirtualFluidsCore/BoundaryConditions/DensityBCAdapter.cpp @@ -1,157 +1,172 @@ #include "DensityBCAdapter.h" -#include "basics/utilities/UbLogger.h" #include "basics/utilities/UbInfinity.h" +#include "basics/utilities/UbLogger.h" using namespace std; /*==========================================================*/ -DensityBCAdapter::DensityBCAdapter(const double& dens, const double& startTime, const double& endTime ) +DensityBCAdapter::DensityBCAdapter(const double &dens, const double &startTime, const double &endTime) { - this->densBCs.emplace_back(dens,startTime,endTime ); - this->init(); + this->densBCs.emplace_back(dens, startTime, endTime); + this->init(); } /*==========================================================*/ -DensityBCAdapter::DensityBCAdapter(const BCFunction& densBC ) +DensityBCAdapter::DensityBCAdapter(const BCFunction &densBC) { - this->densBCs.push_back(densBC); - this->init(); + this->densBCs.push_back(densBC); + this->init(); } /*==========================================================*/ -DensityBCAdapter::DensityBCAdapter(const std::vector< BCFunction >& densBCs) +DensityBCAdapter::DensityBCAdapter(const std::vector<BCFunction> &densBCs) { - this->densBCs = densBCs; - this->init(); + this->densBCs = densBCs; + this->init(); } /*==========================================================*/ -DensityBCAdapter::DensityBCAdapter(const mu::Parser& function, const double& startTime, const double& endTime ) +DensityBCAdapter::DensityBCAdapter(const mu::Parser &function, const double &startTime, const double &endTime) { - this->densBCs.emplace_back(function,startTime,endTime); - this->init(); + this->densBCs.emplace_back(function, startTime, endTime); + this->init(); } /*==========================================================*/ void DensityBCAdapter::init() { - this->timeStep = 0.0; + this->timeStep = 0.0; - this->x1 = 0.0; - this->x2 = 0.0; - this->x3 = 0.0; + this->x1 = 0.0; + this->x2 = 0.0; + this->x3 = 0.0; - this->tmpDensityFunction = NULL; + this->tmpDensityFunction = NULL; - try //initilialization and validation of functions - { - for(size_t pos=0; pos<densBCs.size(); ++pos) - { - if( !( UbMath::equal( BCFunction::INFCONST, densBCs[pos].getEndTime() ) - && UbMath::greaterEqual( this->timeStep, densBCs[pos].getStartTime() ) ) ) - { - this->setTimeDependent(); - } + try // initilialization and validation of functions + { + for (size_t pos = 0; pos < densBCs.size(); ++pos) { + if (!(UbMath::equal(BCFunction::INFCONST, densBCs[pos].getEndTime()) && + UbMath::greaterEqual(this->timeStep, densBCs[pos].getStartTime()))) { + this->setTimeDependent(); + } - densBCs[pos].getFunction().DefineVar("t" , &this->timeStep); - densBCs[pos].getFunction().DefineVar("x1", &this->x1 ); - densBCs[pos].getFunction().DefineVar("x2", &this->x2 ); - densBCs[pos].getFunction().DefineVar("x3", &this->x3 ); + densBCs[pos].getFunction().DefineVar("t", &this->timeStep); + densBCs[pos].getFunction().DefineVar("x1", &this->x1); + densBCs[pos].getFunction().DefineVar("x2", &this->x2); + densBCs[pos].getFunction().DefineVar("x3", &this->x3); - densBCs[pos].getFunction().Eval(); //<-- validation - } - } - catch(mu::Parser::exception_type& e){ stringstream error; error<<"mu::parser exception occurs, message("<<e.GetMsg()<<"), formula("<<e.GetExpr()+"), token("+e.GetToken()<<")" - <<", pos("<<e.GetPos()<<"), error code("<<e.GetCode(); throw UbException(error.str()); } - catch(...) { throw UbException(UB_EXARGS,"unknown exception" ); } + densBCs[pos].getFunction().Eval(); //<-- validation + } + } catch (mu::Parser::exception_type &e) { + stringstream error; + error << "mu::parser exception occurs, message(" << e.GetMsg() << "), formula(" + << e.GetExpr() + "), token(" + e.GetToken() << ")" + << ", pos(" << e.GetPos() << "), error code(" << e.GetCode(); + throw UbException(error.str()); + } catch (...) { + throw UbException(UB_EXARGS, "unknown exception"); + } } /*==========================================================*/ -void DensityBCAdapter::init(const D3Q27Interactor* const& /*interactor*/, const double& time) +void DensityBCAdapter::init(const D3Q27Interactor *const & /*interactor*/, const double &time) { - this->timeStep = time; - this->tmpDensityFunction = NULL; - double maxEndtime = -Ub::inf; + this->timeStep = time; + this->tmpDensityFunction = NULL; + double maxEndtime = -Ub::inf; - //aktuelle Densityfunction bestimmen - for(size_t pos=0; pos<densBCs.size(); ++pos) - { - if( UbMath::equal(densBCs[pos].getEndTime(),BCFunction::INFTIMEDEPENDENT)) maxEndtime=Ub::inf; - maxEndtime = UbMath::max(maxEndtime,densBCs[pos].getStartTime(),densBCs[pos].getEndTime()); //startTime abfragen, da INFCONST=-10 + // aktuelle Densityfunction bestimmen + for (size_t pos = 0; pos < densBCs.size(); ++pos) { + if (UbMath::equal(densBCs[pos].getEndTime(), BCFunction::INFTIMEDEPENDENT)) + maxEndtime = Ub::inf; + maxEndtime = UbMath::max(maxEndtime, densBCs[pos].getStartTime(), + densBCs[pos].getEndTime()); // startTime abfragen, da INFCONST=-10 - if( UbMath::greaterEqual(this->timeStep,densBCs[pos].getStartTime()) ) - { - if( UbMath::lessEqual(this->timeStep,densBCs[pos].getEndTime()) - || UbMath::equal(densBCs[pos].getEndTime(),(double)BCFunction::INFCONST) - || UbMath::equal(densBCs[pos].getEndTime(),(double)BCFunction::INFTIMEDEPENDENT) ) - { - tmpDensityFunction = &densBCs[pos].getFunction(); - break; - } - } - } + if (UbMath::greaterEqual(this->timeStep, densBCs[pos].getStartTime())) { + if (UbMath::lessEqual(this->timeStep, densBCs[pos].getEndTime()) || + UbMath::equal(densBCs[pos].getEndTime(), (double)BCFunction::INFCONST) || + UbMath::equal(densBCs[pos].getEndTime(), (double)BCFunction::INFTIMEDEPENDENT)) { + tmpDensityFunction = &densBCs[pos].getFunction(); + break; + } + } + } - //wenn funktionen zweitlich konstant sind und bis t=unendlich gelten - //kann man zeitabhaengigkeit deaktivieren - if( UbMath::greaterEqual(time,maxEndtime) ) this->unsetTimeDependent(); + // wenn funktionen zweitlich konstant sind und bis t=unendlich gelten + // kann man zeitabhaengigkeit deaktivieren + if (UbMath::greaterEqual(time, maxEndtime)) + this->unsetTimeDependent(); - UBLOG(logDEBUG4,"D3Q27DensityBCAdapter::init(time="<<time<<") " - <<", rho= \""<<(tmpDensityFunction ? tmpDensityFunction->GetExpr() : "-") - <<"\", timedependant="<<(this->isTimeDependent() ? "true" : "false") ); + UBLOG(logDEBUG4, "D3Q27DensityBCAdapter::init(time=" + << time << ") " + << ", rho= \"" << (tmpDensityFunction ? tmpDensityFunction->GetExpr() : "-") + << "\", timedependant=" << (this->isTimeDependent() ? "true" : "false")); } /*==========================================================*/ -void DensityBCAdapter::update( const D3Q27Interactor* const& interactor, const double& time ) +void DensityBCAdapter::update(const D3Q27Interactor *const &interactor, const double &time) { - this->init(interactor,time); + this->init(interactor, time); } /*==========================================================*/ -void DensityBCAdapter::adaptBCForDirection( const D3Q27Interactor& /*interactor*/, SPtr<BoundaryConditions> bc, const double& /*worldX1*/, const double& /*worldX2*/, const double& /*worldX3*/, const double& q, const int& fdirection, const double& /*time*/ ) +void DensityBCAdapter::adaptBCForDirection(const D3Q27Interactor & /*interactor*/, SPtr<BoundaryConditions> bc, + const double & /*worldX1*/, const double & /*worldX2*/, + const double & /*worldX3*/, const double &q, const int &fdirection, + const double & /*time*/) { - bc->setDensityBoundaryFlag(D3Q27System::INVDIR[fdirection],secondaryBcOption); - bc->setQ((float)q,fdirection); + bc->setDensityBoundaryFlag(D3Q27System::INVDIR[fdirection], secondaryBcOption); + bc->setQ((float)q, fdirection); } /*==========================================================*/ -void DensityBCAdapter::adaptBC( const D3Q27Interactor& interactor, SPtr<BoundaryConditions> bc, const double& worldX1, const double& worldX2, const double& worldX3, const double& time ) +void DensityBCAdapter::adaptBC(const D3Q27Interactor &interactor, SPtr<BoundaryConditions> bc, const double &worldX1, + const double &worldX2, const double &worldX3, const double &time) { - this->setNodeDensity(interactor,bc,worldX1,worldX2,worldX3,time); - bc->setBcAlgorithmType(algorithmType); + this->setNodeDensity(interactor, bc, worldX1, worldX2, worldX3, time); + bc->setBcAlgorithmType(algorithmType); } /*==========================================================*/ -void DensityBCAdapter::setNodeDensity( const D3Q27Interactor& /*interactor*/, SPtr<BoundaryConditions> bc, const double& worldX1, const double& worldX2, const double& worldX3, const double& timestep) +void DensityBCAdapter::setNodeDensity(const D3Q27Interactor & /*interactor*/, SPtr<BoundaryConditions> bc, + const double &worldX1, const double &worldX2, const double &worldX3, + const double ×tep) { - //Geschwindigkeiten setzen - try - { - //PunktKoordinaten bestimmen - this->x1 = worldX1; - this->x2 = worldX2; - this->x3 = worldX3; - this->timeStep = timestep; + // Geschwindigkeiten setzen + try { + // PunktKoordinaten bestimmen + this->x1 = worldX1; + this->x2 = worldX2; + this->x3 = worldX3; + this->timeStep = timestep; - if(tmpDensityFunction) bc->setBoundaryDensity((float)tmpDensityFunction->Eval()); - } - catch(mu::Parser::exception_type& e){ stringstream error; error<<"mu::parser exception occurs, message("<<e.GetMsg()<<"), formula("<<e.GetExpr()+"), token("+e.GetToken()<<")" - <<", pos("<<e.GetPos()<<"), error code("<<e.GetCode(); throw UbException(error.str()); } - catch(...) { throw UbException(UB_EXARGS,"unknown exception" ); } + if (tmpDensityFunction) + bc->setBoundaryDensity((float)tmpDensityFunction->Eval()); + } catch (mu::Parser::exception_type &e) { + stringstream error; + error << "mu::parser exception occurs, message(" << e.GetMsg() << "), formula(" + << e.GetExpr() + "), token(" + e.GetToken() << ")" + << ", pos(" << e.GetPos() << "), error code(" << e.GetCode(); + throw UbException(error.str()); + } catch (...) { + throw UbException(UB_EXARGS, "unknown exception"); + } } /*==========================================================*/ -double DensityBCAdapter::getDensity(const double& x1, const double& x2, const double& x3, const double& timeStep) +double DensityBCAdapter::getDensity(const double &x1, const double &x2, const double &x3, const double &timeStep) { - this->x1 = x1; - this->x2 = x2; - this->x3 = x3; - this->timeStep = timeStep; + this->x1 = x1; + this->x2 = x2; + this->x3 = x3; + this->timeStep = timeStep; - if(!tmpDensityFunction) return 0.0; + if (!tmpDensityFunction) + return 0.0; - return tmpDensityFunction->Eval(); + return tmpDensityFunction->Eval(); } /*==========================================================*/ string DensityBCAdapter::toString() { - stringstream info; - info<<"D3Q27DensityBCAdapter:\n"; - info<<" #dens-functions = "<<(int)densBCs.size()<<endl; - info<<" protected variables: x1, x2, x3, t"<<endl; + stringstream info; + info << "D3Q27DensityBCAdapter:\n"; + info << " #dens-functions = " << (int)densBCs.size() << endl; + info << " protected variables: x1, x2, x3, t" << endl; - for(size_t i=0; i<densBCs.size(); ++i) - { - info<<"\n dens-function nr."<<i<<":"<<endl; - info<<densBCs[i].toString()<<endl; - } - return info.str(); + for (size_t i = 0; i < densBCs.size(); ++i) { + info << "\n dens-function nr." << i << ":" << endl; + info << densBCs[i].toString() << endl; + } + return info.str(); } diff --git a/src/cpu/VirtualFluidsCore/BoundaryConditions/DensityBCAdapter.h b/src/cpu/VirtualFluidsCore/BoundaryConditions/DensityBCAdapter.h index 02bf08a456832142e3bcae3ef6167e4ce7284b2c..a52e06060cdaa3ec3057d9cdbdfda5ac35c53e77 100644 --- a/src/cpu/VirtualFluidsCore/BoundaryConditions/DensityBCAdapter.h +++ b/src/cpu/VirtualFluidsCore/BoundaryConditions/DensityBCAdapter.h @@ -1,9 +1,9 @@ #ifndef DensityBCAdapter_H #define DensityBCAdapter_H - + #include <iostream> -#include <string> #include <sstream> +#include <string> #include <vector> #include "basics/utilities/UbMath.h" @@ -18,57 +18,59 @@ //<BR><BR> //@author <A HREF="mailto:muffmolch@gmx.de">S. Freudiger</A> //@version 1.0 - 06.09.06 -//*/ +//*/ // //* -//usage: ... +// usage: ... //*/ - class DensityBCAdapter : public BCAdapter { public: - //constructors - DensityBCAdapter() { this->init(); } - DensityBCAdapter(const double& dens, const double& startTime=0.0, const double& endTime = BCFunction::INFCONST ); - DensityBCAdapter(const BCFunction& densBC ); - DensityBCAdapter(const std::vector< BCFunction >& densBCs); - DensityBCAdapter(const mu::Parser& function, const double& startTime=0.0, const double& endTime = BCFunction::INFCONST ); + // constructors + DensityBCAdapter() { this->init(); } + DensityBCAdapter(const double &dens, const double &startTime = 0.0, const double &endTime = BCFunction::INFCONST); + DensityBCAdapter(const BCFunction &densBC); + DensityBCAdapter(const std::vector<BCFunction> &densBCs); + DensityBCAdapter(const mu::Parser &function, const double &startTime = 0.0, + const double &endTime = BCFunction::INFCONST); - //------------- implements D3Q27BoundaryConditionAdapter ----- start - std::string toString(); + //------------- implements D3Q27BoundaryConditionAdapter ----- start + std::string toString(); - void init(const D3Q27Interactor* const& interactor, const double& time=0) override; - void update(const D3Q27Interactor* const& interactor, const double& time=0) override; + void init(const D3Q27Interactor *const &interactor, const double &time = 0) override; + void update(const D3Q27Interactor *const &interactor, const double &time = 0) override; - void adaptBCForDirection( const D3Q27Interactor& interactor, SPtr<BoundaryConditions> bc, const double& worldX1, const double& worldX2, const double& worldX3, const double& q, const int& fdirection, const double& time=0 ) override; - void adaptBC( const D3Q27Interactor& interactor, SPtr<BoundaryConditions> bc, const double& worldX1, const double& worldX2, const double& worldX3, const double& time=0 ) override; + void adaptBCForDirection(const D3Q27Interactor &interactor, SPtr<BoundaryConditions> bc, const double &worldX1, + const double &worldX2, const double &worldX3, const double &q, const int &fdirection, + const double &time = 0) override; + void adaptBC(const D3Q27Interactor &interactor, SPtr<BoundaryConditions> bc, const double &worldX1, + const double &worldX2, const double &worldX3, const double &time = 0) override; - double getDensity(const double& x1, const double& x2, const double& x3, const double& timeStep); - - //------------- implements D3Q27BoundaryConditionAdapter ----- end + double getDensity(const double &x1, const double &x2, const double &x3, const double &timeStep); + //------------- implements D3Q27BoundaryConditionAdapter ----- end protected: - void init(); - - //time dependency wird automatisch ueber D3Q27BCFunction Intervalle ermittelt! - void setTimeDependent() { (this->type |= TIMEDEPENDENT);} - void unsetTimeDependent() { (this->type &= ~TIMEDEPENDENT);} - - void clear() { densBCs.clear(); } - void setNodeDensity(const D3Q27Interactor& interactor, SPtr<BoundaryConditions> bc, const double& worldX1, const double& worldX2, const double& worldX3, const double& timestep); + void init(); -private: - mu::value_type x1, x2, x3; //brauch man nicht serialisieren! - mu::value_type timeStep; //brauch man nicht serialisieren! + // time dependency wird automatisch ueber D3Q27BCFunction Intervalle ermittelt! + void setTimeDependent() { (this->type |= TIMEDEPENDENT); } + void unsetTimeDependent() { (this->type &= ~TIMEDEPENDENT); } - mu::Parser* tmpDensityFunction; //brauch man nicht serialisieren! - - std::vector<BCFunction> densBCs; + void clear() { densBCs.clear(); } + void setNodeDensity(const D3Q27Interactor &interactor, SPtr<BoundaryConditions> bc, const double &worldX1, + const double &worldX2, const double &worldX3, const double ×tep); private: + mu::value_type x1, x2, x3; // brauch man nicht serialisieren! + mu::value_type timeStep; // brauch man nicht serialisieren! + + mu::Parser *tmpDensityFunction; // brauch man nicht serialisieren! + std::vector<BCFunction> densBCs; + +private: }; -#endif +#endif diff --git a/src/cpu/VirtualFluidsCore/BoundaryConditions/EqDensityBCAlgorithm.cpp b/src/cpu/VirtualFluidsCore/BoundaryConditions/EqDensityBCAlgorithm.cpp index 05d31244a6c568596a47d00d2bf660230855c2c5..0f809955da3565f74a79a2e9dc8d09d520defc32 100644 --- a/src/cpu/VirtualFluidsCore/BoundaryConditions/EqDensityBCAlgorithm.cpp +++ b/src/cpu/VirtualFluidsCore/BoundaryConditions/EqDensityBCAlgorithm.cpp @@ -1,58 +1,59 @@ #include "EqDensityBCAlgorithm.h" -#include "DistributionArray3D.h" #include "BoundaryConditions.h" - +#include "DistributionArray3D.h" EqDensityBCAlgorithm::EqDensityBCAlgorithm() { - BCAlgorithm::type = BCAlgorithm::EqDensityBCAlgorithm; - BCAlgorithm::preCollision = false; + BCAlgorithm::type = BCAlgorithm::EqDensityBCAlgorithm; + BCAlgorithm::preCollision = false; } ////////////////////////////////////////////////////////////////////////// -EqDensityBCAlgorithm::~EqDensityBCAlgorithm() -= default; +EqDensityBCAlgorithm::~EqDensityBCAlgorithm() = default; ////////////////////////////////////////////////////////////////////////// SPtr<BCAlgorithm> EqDensityBCAlgorithm::clone() { - SPtr<BCAlgorithm> bc(new EqDensityBCAlgorithm()); - return bc; + SPtr<BCAlgorithm> bc(new EqDensityBCAlgorithm()); + return bc; } ////////////////////////////////////////////////////////////////////////// void EqDensityBCAlgorithm::addDistributions(SPtr<DistributionArray3D> distributions) { - this->distributions = distributions; + this->distributions = distributions; } ////////////////////////////////////////////////////////////////////////// void EqDensityBCAlgorithm::applyBC() { - LBMReal f[D3Q27System::ENDF+1]; + LBMReal f[D3Q27System::ENDF + 1]; - distributions->getDistributionInv(f, x1, x2, x3); - int nx1 = x1; - int nx2 = x2; - int nx3 = x3; + distributions->getDistributionInv(f, x1, x2, x3); + int nx1 = x1; + int nx2 = x2; + int nx3 = x3; - //flag points in direction of fluid - if (bcPtr->hasDensityBoundaryFlag(D3Q27System::E)) { nx1 -= 1;} - else if (bcPtr->hasDensityBoundaryFlag(D3Q27System::W)) { nx1 += 1;} - else if (bcPtr->hasDensityBoundaryFlag(D3Q27System::N)) { nx2 -= 1;} - else if (bcPtr->hasDensityBoundaryFlag(D3Q27System::S)) { nx2 += 1;} - else if (bcPtr->hasDensityBoundaryFlag(D3Q27System::T)) { nx3 -= 1;} - else if (bcPtr->hasDensityBoundaryFlag(D3Q27System::B)) { nx3 += 1;} - else UB_THROW(UbException(UB_EXARGS, "Danger...no orthogonal BC-Flag on density boundary...")); - - LBMReal rho, vx1, vx2, vx3; - calcMacrosFct(f, rho, vx1, vx2, vx3); - LBMReal rhoBC = bcPtr->getBoundaryDensity(); - for (int fdir = D3Q27System::STARTF; fdir<=D3Q27System::ENDF; fdir++) - { - if (bcPtr->hasDensityBoundaryFlag(fdir)) - { - //Ehsan: 15.2.2013: - LBMReal ftemp = calcFeqsForDirFct(fdir, rhoBC, vx1, vx2, vx3); - distributions->setDistributionForDirection(ftemp, nx1, nx2, nx3, fdir); - } - } + // flag points in direction of fluid + if (bcPtr->hasDensityBoundaryFlag(D3Q27System::E)) { + nx1 -= 1; + } else if (bcPtr->hasDensityBoundaryFlag(D3Q27System::W)) { + nx1 += 1; + } else if (bcPtr->hasDensityBoundaryFlag(D3Q27System::N)) { + nx2 -= 1; + } else if (bcPtr->hasDensityBoundaryFlag(D3Q27System::S)) { + nx2 += 1; + } else if (bcPtr->hasDensityBoundaryFlag(D3Q27System::T)) { + nx3 -= 1; + } else if (bcPtr->hasDensityBoundaryFlag(D3Q27System::B)) { + nx3 += 1; + } else + UB_THROW(UbException(UB_EXARGS, "Danger...no orthogonal BC-Flag on density boundary...")); + LBMReal rho, vx1, vx2, vx3; + calcMacrosFct(f, rho, vx1, vx2, vx3); + LBMReal rhoBC = bcPtr->getBoundaryDensity(); + for (int fdir = D3Q27System::STARTF; fdir <= D3Q27System::ENDF; fdir++) { + if (bcPtr->hasDensityBoundaryFlag(fdir)) { + // Ehsan: 15.2.2013: + LBMReal ftemp = calcFeqsForDirFct(fdir, rhoBC, vx1, vx2, vx3); + distributions->setDistributionForDirection(ftemp, nx1, nx2, nx3, fdir); + } + } } - diff --git a/src/cpu/VirtualFluidsCore/BoundaryConditions/EqDensityBCAlgorithm.h b/src/cpu/VirtualFluidsCore/BoundaryConditions/EqDensityBCAlgorithm.h index 57686417075f4291d9db8c507f151dd52f626cab..4d6cab77e4b04d9fdf2eaeece14e453c545e90d7 100644 --- a/src/cpu/VirtualFluidsCore/BoundaryConditions/EqDensityBCAlgorithm.h +++ b/src/cpu/VirtualFluidsCore/BoundaryConditions/EqDensityBCAlgorithm.h @@ -9,10 +9,10 @@ class DistributionArray3D; class EqDensityBCAlgorithm : public BCAlgorithm { public: - EqDensityBCAlgorithm(); - ~EqDensityBCAlgorithm() override; - SPtr<BCAlgorithm> clone() override; - void addDistributions(SPtr<DistributionArray3D> distributions) override; - void applyBC() override; + EqDensityBCAlgorithm(); + ~EqDensityBCAlgorithm() override; + SPtr<BCAlgorithm> clone() override; + void addDistributions(SPtr<DistributionArray3D> distributions) override; + void applyBC() override; }; #endif // EqDensityBCAlgorithm_h__ diff --git a/src/cpu/VirtualFluidsCore/BoundaryConditions/HighViscosityNoSlipBCAlgorithm.cpp b/src/cpu/VirtualFluidsCore/BoundaryConditions/HighViscosityNoSlipBCAlgorithm.cpp index d8e86690449a935c26d410def675e9a08416f114..2568a6467acd84d627f61fa7e37243f061fd1bc7 100644 --- a/src/cpu/VirtualFluidsCore/BoundaryConditions/HighViscosityNoSlipBCAlgorithm.cpp +++ b/src/cpu/VirtualFluidsCore/BoundaryConditions/HighViscosityNoSlipBCAlgorithm.cpp @@ -1,46 +1,46 @@ #include "HighViscosityNoSlipBCAlgorithm.h" -#include "DistributionArray3D.h" #include "BoundaryConditions.h" +#include "DistributionArray3D.h" HighViscosityNoSlipBCAlgorithm::HighViscosityNoSlipBCAlgorithm() { - BCAlgorithm::type = BCAlgorithm::HighViscosityNoSlipBCAlgorithm; - BCAlgorithm::preCollision = true; + BCAlgorithm::type = BCAlgorithm::HighViscosityNoSlipBCAlgorithm; + BCAlgorithm::preCollision = true; } ////////////////////////////////////////////////////////////////////////// -HighViscosityNoSlipBCAlgorithm::~HighViscosityNoSlipBCAlgorithm() -= default; +HighViscosityNoSlipBCAlgorithm::~HighViscosityNoSlipBCAlgorithm() = default; ////////////////////////////////////////////////////////////////////////// SPtr<BCAlgorithm> HighViscosityNoSlipBCAlgorithm::clone() { - SPtr<BCAlgorithm> bc(new HighViscosityNoSlipBCAlgorithm()); - return bc; + SPtr<BCAlgorithm> bc(new HighViscosityNoSlipBCAlgorithm()); + return bc; } ////////////////////////////////////////////////////////////////////////// void HighViscosityNoSlipBCAlgorithm::addDistributions(SPtr<DistributionArray3D> distributions) { - this->distributions = distributions; + this->distributions = distributions; } ////////////////////////////////////////////////////////////////////////// void HighViscosityNoSlipBCAlgorithm::applyBC() { - LBMReal f[D3Q27System::ENDF+1]; - LBMReal feq[D3Q27System::ENDF+1]; - distributions->getDistribution(f, x1, x2, x3); - LBMReal rho, vx1, vx2, vx3; - calcMacrosFct(f, rho, vx1, vx2, vx3); - calcFeqFct(feq, rho, vx1, vx2, vx3); + LBMReal f[D3Q27System::ENDF + 1]; + LBMReal feq[D3Q27System::ENDF + 1]; + distributions->getDistribution(f, x1, x2, x3); + LBMReal rho, vx1, vx2, vx3; + calcMacrosFct(f, rho, vx1, vx2, vx3); + calcFeqFct(feq, rho, vx1, vx2, vx3); - for (int fDir = D3Q27System::FSTARTDIR; fDir<=D3Q27System::FENDDIR; fDir++) - { - if (bcPtr->hasNoSlipBoundaryFlag(fDir)) - { - //quadratic bounce back - const int invDir = D3Q27System::INVDIR[fDir]; - LBMReal q = bcPtr->getQ(invDir); - LBMReal fReturn = (f[invDir]+q*f[fDir]+q*collFactor*(feq[invDir]-f[invDir]+feq[fDir]-f[fDir]))/(1.0+q); - distributions->setDistributionInvForDirection(fReturn, x1+D3Q27System::DX1[invDir], x2+D3Q27System::DX2[invDir], x3+D3Q27System::DX3[invDir], invDir); - } - } + for (int fDir = D3Q27System::FSTARTDIR; fDir <= D3Q27System::FENDDIR; fDir++) { + if (bcPtr->hasNoSlipBoundaryFlag(fDir)) { + // quadratic bounce back + const int invDir = D3Q27System::INVDIR[fDir]; + LBMReal q = bcPtr->getQ(invDir); + LBMReal fReturn = + (f[invDir] + q * f[fDir] + q * collFactor * (feq[invDir] - f[invDir] + feq[fDir] - f[fDir])) / + (1.0 + q); + distributions->setDistributionInvForDirection(fReturn, x1 + D3Q27System::DX1[invDir], + x2 + D3Q27System::DX2[invDir], x3 + D3Q27System::DX3[invDir], + invDir); + } + } } - diff --git a/src/cpu/VirtualFluidsCore/BoundaryConditions/HighViscosityNoSlipBCAlgorithm.h b/src/cpu/VirtualFluidsCore/BoundaryConditions/HighViscosityNoSlipBCAlgorithm.h index 78b27969b8fc04ec10a6a523220c8cd2c1f7cad7..02cf215f76b0d974c12156125dd5e06958559b89 100644 --- a/src/cpu/VirtualFluidsCore/BoundaryConditions/HighViscosityNoSlipBCAlgorithm.h +++ b/src/cpu/VirtualFluidsCore/BoundaryConditions/HighViscosityNoSlipBCAlgorithm.h @@ -9,11 +9,10 @@ class DistributionArray3D; class HighViscosityNoSlipBCAlgorithm : public BCAlgorithm { public: - HighViscosityNoSlipBCAlgorithm(); - ~HighViscosityNoSlipBCAlgorithm() override; - SPtr<BCAlgorithm> clone() override; - void addDistributions(SPtr<DistributionArray3D> distributions) override; - void applyBC() override; + HighViscosityNoSlipBCAlgorithm(); + ~HighViscosityNoSlipBCAlgorithm() override; + SPtr<BCAlgorithm> clone() override; + void addDistributions(SPtr<DistributionArray3D> distributions) override; + void applyBC() override; }; #endif // HighViscosityNoSlipBCAlgorithm_h__ - diff --git a/src/cpu/VirtualFluidsCore/BoundaryConditions/NoSlipBCAdapter.cpp b/src/cpu/VirtualFluidsCore/BoundaryConditions/NoSlipBCAdapter.cpp index 335583be25941634504a243856b10231fa07f633..4b272878a4bd30d1031c2894ac9994db6a966a6f 100644 --- a/src/cpu/VirtualFluidsCore/BoundaryConditions/NoSlipBCAdapter.cpp +++ b/src/cpu/VirtualFluidsCore/BoundaryConditions/NoSlipBCAdapter.cpp @@ -1,28 +1,28 @@ //======================================================================================= -// ____ ____ __ ______ __________ __ __ __ __ -// \ \ | | | | | _ \ |___ ___| | | | | / \ | | -// \ \ | | | | | |_) | | | | | | | / \ | | -// \ \ | | | | | _ / | | | | | | / /\ \ | | -// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ -// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| -// \ \ | | ________________________________________________________________ -// \ \ | | | ______________________________________________________________| -// \ \| | | | __ __ __ __ ______ _______ -// \ | | |_____ | | | | | | | | | _ \ / _____) -// \ | | _____| | | | | | | | | | | \ \ \_______ +// ____ ____ __ ______ __________ __ __ __ __ +// \ \ | | | | | _ \ |___ ___| | | | | / \ | | +// \ \ | | | | | |_) | | | | | | | / \ | | +// \ \ | | | | | _ / | | | | | | / /\ \ | | +// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ +// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| +// \ \ | | ________________________________________________________________ +// \ \ | | | ______________________________________________________________| +// \ \| | | | __ __ __ __ ______ _______ +// \ | | |_____ | | | | | | | | | _ \ / _____) +// \ | | _____| | | | | | | | | | | \ \ \_______ // \ | | | | |_____ | \_/ | | | | |_/ / _____ | -// \ _____| |__| |________| \_______/ |__| |______/ (_______/ +// \ _____| |__| |________| \_______/ |__| |______/ (_______/ // -// This file is part of VirtualFluids. VirtualFluids is free software: you can +// This file is part of VirtualFluids. VirtualFluids is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of +// License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. -// -// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// +// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License along // with VirtualFluids (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>. // diff --git a/src/cpu/VirtualFluidsCore/BoundaryConditions/NoSlipBCAdapter.h b/src/cpu/VirtualFluidsCore/BoundaryConditions/NoSlipBCAdapter.h index 53dfd8d5848accf50593be266901707943821b1d..68ebf73ffeafe88f9184c46a1144840fae8b27e1 100644 --- a/src/cpu/VirtualFluidsCore/BoundaryConditions/NoSlipBCAdapter.h +++ b/src/cpu/VirtualFluidsCore/BoundaryConditions/NoSlipBCAdapter.h @@ -1,28 +1,28 @@ //======================================================================================= -// ____ ____ __ ______ __________ __ __ __ __ -// \ \ | | | | | _ \ |___ ___| | | | | / \ | | -// \ \ | | | | | |_) | | | | | | | / \ | | -// \ \ | | | | | _ / | | | | | | / /\ \ | | -// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ -// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| -// \ \ | | ________________________________________________________________ -// \ \ | | | ______________________________________________________________| -// \ \| | | | __ __ __ __ ______ _______ -// \ | | |_____ | | | | | | | | | _ \ / _____) -// \ | | _____| | | | | | | | | | | \ \ \_______ +// ____ ____ __ ______ __________ __ __ __ __ +// \ \ | | | | | _ \ |___ ___| | | | | / \ | | +// \ \ | | | | | |_) | | | | | | | / \ | | +// \ \ | | | | | _ / | | | | | | / /\ \ | | +// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ +// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| +// \ \ | | ________________________________________________________________ +// \ \ | | | ______________________________________________________________| +// \ \| | | | __ __ __ __ ______ _______ +// \ | | |_____ | | | | | | | | | _ \ / _____) +// \ | | _____| | | | | | | | | | | \ \ \_______ // \ | | | | |_____ | \_/ | | | | |_/ / _____ | -// \ _____| |__| |________| \_______/ |__| |______/ (_______/ +// \ _____| |__| |________| \_______/ |__| |______/ (_______/ // -// This file is part of VirtualFluids. VirtualFluids is free software: you can +// This file is part of VirtualFluids. VirtualFluids is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of +// License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. -// -// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// +// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License along // with VirtualFluids (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>. // @@ -40,29 +40,25 @@ class NoSlipBCAdapter : public BCAdapter { public: - NoSlipBCAdapter() - : BCAdapter() - { - } - NoSlipBCAdapter(const short& secondaryBcOption) - : BCAdapter(secondaryBcOption) - { - } + NoSlipBCAdapter() : BCAdapter() {} + NoSlipBCAdapter(const short &secondaryBcOption) : BCAdapter(secondaryBcOption) {} - void init(const D3Q27Interactor* const& interactor, const double& time=0) override {} - void update(const D3Q27Interactor* const& interactor, const double& time=0) override {} + void init(const D3Q27Interactor *const &interactor, const double &time = 0) override {} + void update(const D3Q27Interactor *const &interactor, const double &time = 0) override {} - void adaptBCForDirection( const D3Q27Interactor& /*interactor*/, SPtr<BoundaryConditions> bc, const double& /*worldX1*/, const double& /*worldX2*/, const double& /*worldX3*/, const double& q, const int& fdirection, const double& /*time*/=0 ) override - { - bc->setNoSlipBoundaryFlag(D3Q27System::INVDIR[fdirection],secondaryBcOption); - bc->setQ((float)q,fdirection); - } - void adaptBC( const D3Q27Interactor& /*interactor*/, SPtr<BoundaryConditions> bc, const double& /*worldX1*/, const double& /*worldX2*/, const double& /*worldX3*/, const double& /*time*/=0 ) override - { - bc->setBcAlgorithmType(algorithmType); - } + void adaptBCForDirection(const D3Q27Interactor & /*interactor*/, SPtr<BoundaryConditions> bc, + const double & /*worldX1*/, const double & /*worldX2*/, const double & /*worldX3*/, + const double &q, const int &fdirection, const double & /*time*/ = 0) override + { + bc->setNoSlipBoundaryFlag(D3Q27System::INVDIR[fdirection], secondaryBcOption); + bc->setQ((float)q, fdirection); + } + void adaptBC(const D3Q27Interactor & /*interactor*/, SPtr<BoundaryConditions> bc, const double & /*worldX1*/, + const double & /*worldX2*/, const double & /*worldX3*/, const double & /*time*/ = 0) override + { + bc->setBcAlgorithmType(algorithmType); + } private: - }; -#endif //NoSlipBCAdapter_H +#endif // NoSlipBCAdapter_H diff --git a/src/cpu/VirtualFluidsCore/BoundaryConditions/NoSlipBCAlgorithm.cpp b/src/cpu/VirtualFluidsCore/BoundaryConditions/NoSlipBCAlgorithm.cpp index b5b8e54c1f968327366ed8bae81fb978682f1920..d82a7865b1dc4542025b896914a5320495024bd6 100644 --- a/src/cpu/VirtualFluidsCore/BoundaryConditions/NoSlipBCAlgorithm.cpp +++ b/src/cpu/VirtualFluidsCore/BoundaryConditions/NoSlipBCAlgorithm.cpp @@ -1,28 +1,28 @@ //======================================================================================= -// ____ ____ __ ______ __________ __ __ __ __ -// \ \ | | | | | _ \ |___ ___| | | | | / \ | | -// \ \ | | | | | |_) | | | | | | | / \ | | -// \ \ | | | | | _ / | | | | | | / /\ \ | | -// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ -// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| -// \ \ | | ________________________________________________________________ -// \ \ | | | ______________________________________________________________| -// \ \| | | | __ __ __ __ ______ _______ -// \ | | |_____ | | | | | | | | | _ \ / _____) -// \ | | _____| | | | | | | | | | | \ \ \_______ +// ____ ____ __ ______ __________ __ __ __ __ +// \ \ | | | | | _ \ |___ ___| | | | | / \ | | +// \ \ | | | | | |_) | | | | | | | / \ | | +// \ \ | | | | | _ / | | | | | | / /\ \ | | +// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ +// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| +// \ \ | | ________________________________________________________________ +// \ \ | | | ______________________________________________________________| +// \ \| | | | __ __ __ __ ______ _______ +// \ | | |_____ | | | | | | | | | _ \ / _____) +// \ | | _____| | | | | | | | | | | \ \ \_______ // \ | | | | |_____ | \_/ | | | | |_/ / _____ | -// \ _____| |__| |________| \_______/ |__| |______/ (_______/ +// \ _____| |__| |________| \_______/ |__| |______/ (_______/ // -// This file is part of VirtualFluids. VirtualFluids is free software: you can +// This file is part of VirtualFluids. VirtualFluids is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of +// License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. -// -// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// +// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License along // with VirtualFluids (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>. // @@ -32,44 +32,45 @@ //======================================================================================= #include "NoSlipBCAlgorithm.h" -#include "DistributionArray3D.h" #include "BoundaryConditions.h" +#include "DistributionArray3D.h" NoSlipBCAlgorithm::NoSlipBCAlgorithm() { - BCAlgorithm::type = BCAlgorithm::NoSlipBCAlgorithm; - BCAlgorithm::preCollision = false; + BCAlgorithm::type = BCAlgorithm::NoSlipBCAlgorithm; + BCAlgorithm::preCollision = false; } ////////////////////////////////////////////////////////////////////////// SPtr<BCAlgorithm> NoSlipBCAlgorithm::clone() { - SPtr<BCAlgorithm> bc(new NoSlipBCAlgorithm()); - return bc; + SPtr<BCAlgorithm> bc(new NoSlipBCAlgorithm()); + return bc; } ////////////////////////////////////////////////////////////////////////// void NoSlipBCAlgorithm::addDistributions(SPtr<DistributionArray3D> distributions) { - this->distributions = distributions; + this->distributions = distributions; } ////////////////////////////////////////////////////////////////////////// void NoSlipBCAlgorithm::applyBC() { - LBMReal f[D3Q27System::ENDF+1]; - LBMReal feq[D3Q27System::ENDF+1]; - distributions->getDistributionInv(f, x1, x2, x3); - LBMReal rho, vx1, vx2, vx3; - calcMacrosFct(f, rho, vx1, vx2, vx3); - calcFeqFct(feq, rho, vx1, vx2, vx3); + LBMReal f[D3Q27System::ENDF + 1]; + LBMReal feq[D3Q27System::ENDF + 1]; + distributions->getDistributionInv(f, x1, x2, x3); + LBMReal rho, vx1, vx2, vx3; + calcMacrosFct(f, rho, vx1, vx2, vx3); + calcFeqFct(feq, rho, vx1, vx2, vx3); - for (int fdir = D3Q27System::FSTARTDIR; fdir<=D3Q27System::FENDDIR; fdir++) - { - if (bcPtr->hasNoSlipBoundaryFlag(fdir)) - { - //quadratic bounce back - const int invDir = D3Q27System::INVDIR[fdir]; - LBMReal q = bcPtr->getQ(invDir); - LBMReal fReturn = ((1.0-q)/(1.0+q))*((f[invDir]-feq[invDir])/(1.0-collFactor)+feq[invDir])+((q/(1.0+q))*(f[invDir]+f[fdir])); - distributions->setDistributionForDirection(fReturn, x1+D3Q27System::DX1[invDir], x2+D3Q27System::DX2[invDir], x3+D3Q27System::DX3[invDir], fdir); - } - } + for (int fdir = D3Q27System::FSTARTDIR; fdir <= D3Q27System::FENDDIR; fdir++) { + if (bcPtr->hasNoSlipBoundaryFlag(fdir)) { + // quadratic bounce back + const int invDir = D3Q27System::INVDIR[fdir]; + LBMReal q = bcPtr->getQ(invDir); + LBMReal fReturn = ((1.0 - q) / (1.0 + q)) * ((f[invDir] - feq[invDir]) / (1.0 - collFactor) + feq[invDir]) + + ((q / (1.0 + q)) * (f[invDir] + f[fdir])); + distributions->setDistributionForDirection(fReturn, x1 + D3Q27System::DX1[invDir], + x2 + D3Q27System::DX2[invDir], x3 + D3Q27System::DX3[invDir], + fdir); + } + } } diff --git a/src/cpu/VirtualFluidsCore/BoundaryConditions/NoSlipBCAlgorithm.h b/src/cpu/VirtualFluidsCore/BoundaryConditions/NoSlipBCAlgorithm.h index 163ec5ae89deb614481ecc73fddb436a4086f404..dcf678b4f05bd2c50403bfd758cd27767f45d33a 100644 --- a/src/cpu/VirtualFluidsCore/BoundaryConditions/NoSlipBCAlgorithm.h +++ b/src/cpu/VirtualFluidsCore/BoundaryConditions/NoSlipBCAlgorithm.h @@ -1,28 +1,28 @@ //======================================================================================= -// ____ ____ __ ______ __________ __ __ __ __ -// \ \ | | | | | _ \ |___ ___| | | | | / \ | | -// \ \ | | | | | |_) | | | | | | | / \ | | -// \ \ | | | | | _ / | | | | | | / /\ \ | | -// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ -// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| -// \ \ | | ________________________________________________________________ -// \ \ | | | ______________________________________________________________| -// \ \| | | | __ __ __ __ ______ _______ -// \ | | |_____ | | | | | | | | | _ \ / _____) -// \ | | _____| | | | | | | | | | | \ \ \_______ +// ____ ____ __ ______ __________ __ __ __ __ +// \ \ | | | | | _ \ |___ ___| | | | | / \ | | +// \ \ | | | | | |_) | | | | | | | / \ | | +// \ \ | | | | | _ / | | | | | | / /\ \ | | +// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ +// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| +// \ \ | | ________________________________________________________________ +// \ \ | | | ______________________________________________________________| +// \ \| | | | __ __ __ __ ______ _______ +// \ | | |_____ | | | | | | | | | _ \ / _____) +// \ | | _____| | | | | | | | | | | \ \ \_______ // \ | | | | |_____ | \_/ | | | | |_/ / _____ | -// \ _____| |__| |________| \_______/ |__| |______/ (_______/ +// \ _____| |__| |________| \_______/ |__| |______/ (_______/ // -// This file is part of VirtualFluids. VirtualFluids is free software: you can +// This file is part of VirtualFluids. VirtualFluids is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of +// License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. -// -// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// +// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License along // with VirtualFluids (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>. // @@ -43,10 +43,11 @@ class DistributionArray3D; class NoSlipBCAlgorithm : public BCAlgorithm { public: - NoSlipBCAlgorithm(); - SPtr<BCAlgorithm> clone() override; - void addDistributions(SPtr<DistributionArray3D> distributions) override; - void applyBC() override; + NoSlipBCAlgorithm(); + SPtr<BCAlgorithm> clone() override; + void addDistributions(SPtr<DistributionArray3D> distributions) override; + void applyBC() override; + private: }; -#endif +#endif diff --git a/src/cpu/VirtualFluidsCore/BoundaryConditions/NonEqDensityBCAlgorithm.cpp b/src/cpu/VirtualFluidsCore/BoundaryConditions/NonEqDensityBCAlgorithm.cpp index 87994c7368916679adafa7ed80ade42c87ce0838..24d2ed4ef8e1a05eddf8459eb26a836bd519c3d7 100644 --- a/src/cpu/VirtualFluidsCore/BoundaryConditions/NonEqDensityBCAlgorithm.cpp +++ b/src/cpu/VirtualFluidsCore/BoundaryConditions/NonEqDensityBCAlgorithm.cpp @@ -1,64 +1,66 @@ #include "NonEqDensityBCAlgorithm.h" -#include "DistributionArray3D.h" #include "BoundaryConditions.h" +#include "DistributionArray3D.h" NonEqDensityBCAlgorithm::NonEqDensityBCAlgorithm() { - BCAlgorithm::type = BCAlgorithm::NonEqDensityBCAlgorithm; - BCAlgorithm::preCollision = false; + BCAlgorithm::type = BCAlgorithm::NonEqDensityBCAlgorithm; + BCAlgorithm::preCollision = false; } ////////////////////////////////////////////////////////////////////////// -NonEqDensityBCAlgorithm::~NonEqDensityBCAlgorithm() -= default; +NonEqDensityBCAlgorithm::~NonEqDensityBCAlgorithm() = default; ////////////////////////////////////////////////////////////////////////// SPtr<BCAlgorithm> NonEqDensityBCAlgorithm::clone() { - SPtr<BCAlgorithm> bc(new NonEqDensityBCAlgorithm()); - return bc; + SPtr<BCAlgorithm> bc(new NonEqDensityBCAlgorithm()); + return bc; } ////////////////////////////////////////////////////////////////////////// void NonEqDensityBCAlgorithm::addDistributions(SPtr<DistributionArray3D> distributions) { - this->distributions = distributions; + this->distributions = distributions; } ////////////////////////////////////////////////////////////////////////// void NonEqDensityBCAlgorithm::applyBC() { - LBMReal f[D3Q27System::ENDF+1]; - distributions->getDistributionInv(f, x1, x2, x3); - int nx1 = x1; - int nx2 = x2; - int nx3 = x3; + LBMReal f[D3Q27System::ENDF + 1]; + distributions->getDistributionInv(f, x1, x2, x3); + int nx1 = x1; + int nx2 = x2; + int nx3 = x3; - //flag points in direction of fluid - if (bcPtr->hasDensityBoundaryFlag(D3Q27System::E)) { nx1 -= 1;} - else if (bcPtr->hasDensityBoundaryFlag(D3Q27System::W)) { nx1 += 1;} - else if (bcPtr->hasDensityBoundaryFlag(D3Q27System::N)) { nx2 -= 1;} - else if (bcPtr->hasDensityBoundaryFlag(D3Q27System::S)) { nx2 += 1;} - else if (bcPtr->hasDensityBoundaryFlag(D3Q27System::T)) { nx3 -= 1;} - else if (bcPtr->hasDensityBoundaryFlag(D3Q27System::B)) { nx3 += 1;} - else return; //UB_THROW(UbException(UB_EXARGS, "Danger...no orthogonal BC-Flag on density boundary...")); - - LBMReal rho, vx1, vx2, vx3; - calcMacrosFct(f, rho, vx1, vx2, vx3); - //LBMReal vlimit=0.01; - //vx1=(fabs(vx1)>vlimit) ? vx1/fabs(vx1)*vlimit : vx1; - //vx2=(fabs(vx2)>vlimit) ? vx2/fabs(vx2)*vlimit : vx2; - //vx3=(fabs(vx3)>vlimit) ? vx3/fabs(vx3)*vlimit : vx3; - LBMReal rhoBC = bcPtr->getBoundaryDensity(); - for (int fdir = D3Q27System::STARTF; fdir<=D3Q27System::ENDF; fdir++) - { - if (bcPtr->hasDensityBoundaryFlag(fdir)) - { - // Martins NEQ ADDON - ////original: 15.2.2013: - LBMReal ftemp = calcFeqsForDirFct(fdir, rho, vx1, vx2, vx3); - //rhoBC=(rho>rhoBC)? rhoBC : rho; //Limiter 08.08.2018 - ftemp = calcFeqsForDirFct(fdir, rhoBC, vx1, vx2, vx3)+f[fdir]-ftemp; - distributions->setDistributionForDirection(ftemp, nx1, nx2, nx3, fdir); - } - } + // flag points in direction of fluid + if (bcPtr->hasDensityBoundaryFlag(D3Q27System::E)) { + nx1 -= 1; + } else if (bcPtr->hasDensityBoundaryFlag(D3Q27System::W)) { + nx1 += 1; + } else if (bcPtr->hasDensityBoundaryFlag(D3Q27System::N)) { + nx2 -= 1; + } else if (bcPtr->hasDensityBoundaryFlag(D3Q27System::S)) { + nx2 += 1; + } else if (bcPtr->hasDensityBoundaryFlag(D3Q27System::T)) { + nx3 -= 1; + } else if (bcPtr->hasDensityBoundaryFlag(D3Q27System::B)) { + nx3 += 1; + } else + return; // UB_THROW(UbException(UB_EXARGS, "Danger...no orthogonal BC-Flag on density boundary...")); + LBMReal rho, vx1, vx2, vx3; + calcMacrosFct(f, rho, vx1, vx2, vx3); + // LBMReal vlimit=0.01; + // vx1=(fabs(vx1)>vlimit) ? vx1/fabs(vx1)*vlimit : vx1; + // vx2=(fabs(vx2)>vlimit) ? vx2/fabs(vx2)*vlimit : vx2; + // vx3=(fabs(vx3)>vlimit) ? vx3/fabs(vx3)*vlimit : vx3; + LBMReal rhoBC = bcPtr->getBoundaryDensity(); + for (int fdir = D3Q27System::STARTF; fdir <= D3Q27System::ENDF; fdir++) { + if (bcPtr->hasDensityBoundaryFlag(fdir)) { + // Martins NEQ ADDON + ////original: 15.2.2013: + LBMReal ftemp = calcFeqsForDirFct(fdir, rho, vx1, vx2, vx3); + // rhoBC=(rho>rhoBC)? rhoBC : rho; //Limiter 08.08.2018 + ftemp = calcFeqsForDirFct(fdir, rhoBC, vx1, vx2, vx3) + f[fdir] - ftemp; + distributions->setDistributionForDirection(ftemp, nx1, nx2, nx3, fdir); + } + } } - diff --git a/src/cpu/VirtualFluidsCore/BoundaryConditions/NonEqDensityBCAlgorithm.h b/src/cpu/VirtualFluidsCore/BoundaryConditions/NonEqDensityBCAlgorithm.h index 12ffa4fdc4e803b1ab4bbbb7052cd1e31c120cf1..ecdc70338232f2b6b42e49f9b20ec2b359c302c5 100644 --- a/src/cpu/VirtualFluidsCore/BoundaryConditions/NonEqDensityBCAlgorithm.h +++ b/src/cpu/VirtualFluidsCore/BoundaryConditions/NonEqDensityBCAlgorithm.h @@ -9,10 +9,10 @@ class DistributionArray3D; class NonEqDensityBCAlgorithm : public BCAlgorithm { public: - NonEqDensityBCAlgorithm(); - ~NonEqDensityBCAlgorithm() override; - SPtr<BCAlgorithm> clone() override; - void addDistributions(SPtr<DistributionArray3D> distributions) override; - void applyBC() override; + NonEqDensityBCAlgorithm(); + ~NonEqDensityBCAlgorithm() override; + SPtr<BCAlgorithm> clone() override; + void addDistributions(SPtr<DistributionArray3D> distributions) override; + void applyBC() override; }; #endif // NonEqDensityBCAlgorithm_h__ diff --git a/src/cpu/VirtualFluidsCore/BoundaryConditions/NonReflectingOutflowBCAlgorithm.cpp b/src/cpu/VirtualFluidsCore/BoundaryConditions/NonReflectingOutflowBCAlgorithm.cpp index 6cf262bd638900b14368011fc37f14aa8a5f5ab7..0b5884d12229cfccab6647bd0ec52add2e238bbc 100644 --- a/src/cpu/VirtualFluidsCore/BoundaryConditions/NonReflectingOutflowBCAlgorithm.cpp +++ b/src/cpu/VirtualFluidsCore/BoundaryConditions/NonReflectingOutflowBCAlgorithm.cpp @@ -1,188 +1,198 @@ #include "NonReflectingOutflowBCAlgorithm.h" +#include "BoundaryConditions.h" #include "D3Q27System.h" #include "DistributionArray3D.h" -#include "BoundaryConditions.h" - NonReflectingOutflowBCAlgorithm::NonReflectingOutflowBCAlgorithm() { - BCAlgorithm::type = BCAlgorithm::NonReflectingOutflowBCAlgorithm; - BCAlgorithm::preCollision = true; + BCAlgorithm::type = BCAlgorithm::NonReflectingOutflowBCAlgorithm; + BCAlgorithm::preCollision = true; } ////////////////////////////////////////////////////////////////////////// -NonReflectingOutflowBCAlgorithm::~NonReflectingOutflowBCAlgorithm() -= default; +NonReflectingOutflowBCAlgorithm::~NonReflectingOutflowBCAlgorithm() = default; ////////////////////////////////////////////////////////////////////////// SPtr<BCAlgorithm> NonReflectingOutflowBCAlgorithm::clone() { - SPtr<BCAlgorithm> bc(new NonReflectingOutflowBCAlgorithm()); - return bc; + SPtr<BCAlgorithm> bc(new NonReflectingOutflowBCAlgorithm()); + return bc; } ////////////////////////////////////////////////////////////////////////// void NonReflectingOutflowBCAlgorithm::addDistributions(SPtr<DistributionArray3D> distributions) { - this->distributions = distributions; + this->distributions = distributions; } ////////////////////////////////////////////////////////////////////////// void NonReflectingOutflowBCAlgorithm::applyBC() { - using namespace D3Q27System; - using namespace UbMath; - - LBMReal f[ENDF+1]; - LBMReal ftemp[ENDF+1]; - - int nx1 = x1; - int nx2 = x2; - int nx3 = x3; - int direction = -1; - - //flag points in direction of fluid - if (bcPtr->hasDensityBoundaryFlag(E)) { nx1 += 1; direction = E; } - else if (bcPtr->hasDensityBoundaryFlag(W)) { nx1 -= 1; direction = W; } - else if (bcPtr->hasDensityBoundaryFlag(N)) { nx2 += 1; direction = N; } - else if (bcPtr->hasDensityBoundaryFlag(S)) { nx2 -= 1; direction = S; } - else if (bcPtr->hasDensityBoundaryFlag(T)) { nx3 += 1; direction = T; } - else if (bcPtr->hasDensityBoundaryFlag(B)) { nx3 -= 1; direction = B; } - else UB_THROW(UbException(UB_EXARGS, "Danger...no orthogonal BC-Flag on density boundary...")); - - distributions->getDistribution(f, x1, x2, x3); - distributions->getDistribution(ftemp, nx1, nx2, nx3); - - LBMReal rho, vx1, vx2, vx3; - calcMacrosFct(f, rho, vx1, vx2, vx3); - - switch (direction) - { - case E: - f[E] = ftemp[E] * (one_over_sqrt3 + vx1) + (1.0 - one_over_sqrt3 - vx1)*f[E] ; - f[NE] = ftemp[NE] * (one_over_sqrt3 + vx1) + (1.0 - one_over_sqrt3 - vx1)*f[NE] ; - f[SE] = ftemp[SE] * (one_over_sqrt3 + vx1) + (1.0 - one_over_sqrt3 - vx1)*f[SE] ; - f[TE] = ftemp[TE] * (one_over_sqrt3 + vx1) + (1.0 - one_over_sqrt3 - vx1)*f[TE] ; - f[BE] = ftemp[BE] * (one_over_sqrt3 + vx1) + (1.0 - one_over_sqrt3 - vx1)*f[BE] ; - f[TNE] = ftemp[TNE] * (one_over_sqrt3 + vx1) + (1.0 - one_over_sqrt3 - vx1)*f[TNE] ; - f[TSE] = ftemp[TSE] * (one_over_sqrt3 + vx1) + (1.0 - one_over_sqrt3 - vx1)*f[TSE] ; - f[BNE] = ftemp[BNE] * (one_over_sqrt3 + vx1) + (1.0 - one_over_sqrt3 - vx1)*f[BNE] ; - f[BSE] = ftemp[BSE] * (one_over_sqrt3 + vx1) + (1.0 - one_over_sqrt3 - vx1)*f[BSE] ; - - distributions->setDistributionInvForDirection(f[E], x1+DX1[W], x2+DX2[W], x3+DX3[W], W); - distributions->setDistributionInvForDirection(f[NE], x1+DX1[SW], x2+DX2[SW], x3+DX3[SW], SW); - distributions->setDistributionInvForDirection(f[SE], x1+DX1[NW], x2+DX2[NW], x3+DX3[NW], NW); - distributions->setDistributionInvForDirection(f[TE], x1+DX1[BW], x2+DX2[BW], x3+DX3[BW], BW); - distributions->setDistributionInvForDirection(f[BE], x1+DX1[TW], x2+DX2[TW], x3+DX3[TW], TW); - distributions->setDistributionInvForDirection(f[TNE], x1+DX1[BSW], x2+DX2[BSW], x3+DX3[BSW], BSW); - distributions->setDistributionInvForDirection(f[TSE], x1+DX1[BNW], x2+DX2[BNW], x3+DX3[BNW], BNW); - distributions->setDistributionInvForDirection(f[BNE], x1+DX1[TSW], x2+DX2[TSW], x3+DX3[TSW], TSW); - distributions->setDistributionInvForDirection(f[BSE], x1+DX1[TNW], x2+DX2[TNW], x3+DX3[TNW], TNW); - break; - case W: - f[W] = ftemp[W] * (one_over_sqrt3 - vx1) + (1.0 - one_over_sqrt3 + vx1)*f[W] ; - f[NW] = ftemp[NW] * (one_over_sqrt3 - vx1) + (1.0 - one_over_sqrt3 + vx1)*f[NW] ; - f[SW] = ftemp[SW] * (one_over_sqrt3 - vx1) + (1.0 - one_over_sqrt3 + vx1)*f[SW] ; - f[TW] = ftemp[TW] * (one_over_sqrt3 - vx1) + (1.0 - one_over_sqrt3 + vx1)*f[TW] ; - f[BW] = ftemp[BW] * (one_over_sqrt3 - vx1) + (1.0 - one_over_sqrt3 + vx1)*f[BW] ; - f[TNW] = ftemp[TNW] * (one_over_sqrt3 - vx1) + (1.0 - one_over_sqrt3 + vx1)*f[TNW]; - f[TSW] = ftemp[TSW] * (one_over_sqrt3 - vx1) + (1.0 - one_over_sqrt3 + vx1)*f[TSW]; - f[BNW] = ftemp[BNW] * (one_over_sqrt3 - vx1) + (1.0 - one_over_sqrt3 + vx1)*f[BNW]; - f[BSW] = ftemp[BSW] * (one_over_sqrt3 - vx1) + (1.0 - one_over_sqrt3 + vx1)*f[BSW]; - - distributions->setDistributionInvForDirection(f[W], x1+DX1[E], x2+DX2[E], x3+DX3[E], E); - distributions->setDistributionInvForDirection(f[NW], x1+DX1[SE], x2+DX2[SE], x3+DX3[SE], SE); - distributions->setDistributionInvForDirection(f[SW], x1+DX1[NE], x2+DX2[NE], x3+DX3[NE], NE); - distributions->setDistributionInvForDirection(f[TW], x1+DX1[BE], x2+DX2[BE], x3+DX3[BE], BE); - distributions->setDistributionInvForDirection(f[BW], x1+DX1[TE], x2+DX2[TE], x3+DX3[TE], TE); - distributions->setDistributionInvForDirection(f[TNW], x1+DX1[BSE], x2+DX2[BSE], x3+DX3[BSE], BSE); - distributions->setDistributionInvForDirection(f[TSW], x1+DX1[BNE], x2+DX2[BNE], x3+DX3[BNE], BNE); - distributions->setDistributionInvForDirection(f[BNW], x1+DX1[TSE], x2+DX2[TSE], x3+DX3[TSE], TSE); - distributions->setDistributionInvForDirection(f[BSW], x1+DX1[TNE], x2+DX2[TNE], x3+DX3[TNE], TNE); - break; - case N: - f[N] = ftemp[N] * (one_over_sqrt3 + vx2) + (1.0 - one_over_sqrt3 - vx2)*f[N] ; - f[NE] = ftemp[NE] * (one_over_sqrt3 + vx2) + (1.0 - one_over_sqrt3 - vx2)*f[NE] ; - f[NW] = ftemp[NW] * (one_over_sqrt3 + vx2) + (1.0 - one_over_sqrt3 - vx2)*f[NW] ; - f[TN] = ftemp[TN] * (one_over_sqrt3 + vx2) + (1.0 - one_over_sqrt3 - vx2)*f[TN] ; - f[BN] = ftemp[BN] * (one_over_sqrt3 + vx2) + (1.0 - one_over_sqrt3 - vx2)*f[BN] ; - f[TNE] = ftemp[TNE] * (one_over_sqrt3 + vx2) + (1.0 - one_over_sqrt3 - vx2)*f[TNE] ; - f[TNW] = ftemp[TNW] * (one_over_sqrt3 + vx2) + (1.0 - one_over_sqrt3 - vx2)*f[TNW] ; - f[BNE] = ftemp[BNE] * (one_over_sqrt3 + vx2) + (1.0 - one_over_sqrt3 - vx2)*f[BNE] ; - f[BNW] = ftemp[BNW] * (one_over_sqrt3 + vx2) + (1.0 - one_over_sqrt3 - vx2)*f[BNW] ; - - distributions->setDistributionInvForDirection(f[N], x1+DX1[S], x2+DX2[S], x3+DX3[S], S); - distributions->setDistributionInvForDirection(f[NE], x1+DX1[SW], x2+DX2[SW], x3+DX3[SW], SW); - distributions->setDistributionInvForDirection(f[NW], x1+DX1[SE], x2+DX2[SE], x3+DX3[SE], SE); - distributions->setDistributionInvForDirection(f[TN], x1+DX1[BS], x2+DX2[BS], x3+DX3[BS], BS); - distributions->setDistributionInvForDirection(f[BN], x1+DX1[TS], x2+DX2[TS], x3+DX3[TS], TS); - distributions->setDistributionInvForDirection(f[TNE], x1+DX1[BSW], x2+DX2[BSW], x3+DX3[BSW], BSW); - distributions->setDistributionInvForDirection(f[TNW], x1+DX1[BSE], x2+DX2[BSE], x3+DX3[BSE], BSE); - distributions->setDistributionInvForDirection(f[BNE], x1+DX1[TSW], x2+DX2[TSW], x3+DX3[TSW], TSW); - distributions->setDistributionInvForDirection(f[BNW], x1+DX1[TSE], x2+DX2[TSE], x3+DX3[TSE], TSE); - break; - case S: - f[S] = ftemp[S] * (one_over_sqrt3 - vx2) + (1.0 - one_over_sqrt3 + vx2)*f[S] ; - f[SE] = ftemp[SE] * (one_over_sqrt3 - vx2) + (1.0 - one_over_sqrt3 + vx2)*f[SE] ; - f[SW] = ftemp[SW] * (one_over_sqrt3 - vx2) + (1.0 - one_over_sqrt3 + vx2)*f[SW] ; - f[TS] = ftemp[TS] * (one_over_sqrt3 - vx2) + (1.0 - one_over_sqrt3 + vx2)*f[TS] ; - f[BS] = ftemp[BS] * (one_over_sqrt3 - vx2) + (1.0 - one_over_sqrt3 + vx2)*f[BS] ; - f[TSE] = ftemp[TSE] * (one_over_sqrt3 - vx2) + (1.0 - one_over_sqrt3 + vx2)*f[TSE] ; - f[TSW] = ftemp[TSW] * (one_over_sqrt3 - vx2) + (1.0 - one_over_sqrt3 + vx2)*f[TSW] ; - f[BSE] = ftemp[BSE] * (one_over_sqrt3 - vx2) + (1.0 - one_over_sqrt3 + vx2)*f[BSE] ; - f[BSW] = ftemp[BSW] * (one_over_sqrt3 - vx2) + (1.0 - one_over_sqrt3 + vx2)*f[BSW] ; - - distributions->setDistributionInvForDirection(f[S], x1+DX1[N], x2+DX2[N], x3+DX3[N], N); - distributions->setDistributionInvForDirection(f[SE], x1+DX1[NW], x2+DX2[NW], x3+DX3[NW], NW); - distributions->setDistributionInvForDirection(f[SW], x1+DX1[NE], x2+DX2[NE], x3+DX3[NE], NE); - distributions->setDistributionInvForDirection(f[TS], x1+DX1[BN], x2+DX2[BN], x3+DX3[BN], BN); - distributions->setDistributionInvForDirection(f[BS], x1+DX1[TN], x2+DX2[TN], x3+DX3[TN], TN); - distributions->setDistributionInvForDirection(f[TSE], x1+DX1[BNW], x2+DX2[BNW], x3+DX3[BNW], BNW); - distributions->setDistributionInvForDirection(f[TSW], x1+DX1[BNE], x2+DX2[BNE], x3+DX3[BNE], BNE); - distributions->setDistributionInvForDirection(f[BSE], x1+DX1[TNW], x2+DX2[TNW], x3+DX3[TNW], TNW); - distributions->setDistributionInvForDirection(f[BSW], x1+DX1[TNE], x2+DX2[TNE], x3+DX3[TNE], TNE); - break; - case T: - f[T] = ftemp[T] * (one_over_sqrt3 + vx3) + (1.0 - one_over_sqrt3 - vx3)*f[T] ; - f[TE] = ftemp[TE] * (one_over_sqrt3 + vx3) + (1.0 - one_over_sqrt3 - vx3)*f[TE] ; - f[TW] = ftemp[TW] * (one_over_sqrt3 + vx3) + (1.0 - one_over_sqrt3 - vx3)*f[TW] ; - f[TN] = ftemp[TN] * (one_over_sqrt3 + vx3) + (1.0 - one_over_sqrt3 - vx3)*f[TN] ; - f[TS] = ftemp[TS] * (one_over_sqrt3 + vx3) + (1.0 - one_over_sqrt3 - vx3)*f[TS] ; - f[TNE] = ftemp[TNE] * (one_over_sqrt3 + vx3) + (1.0 - one_over_sqrt3 - vx3)*f[TNE] ; - f[TNW] = ftemp[TNW] * (one_over_sqrt3 + vx3) + (1.0 - one_over_sqrt3 - vx3)*f[TNW] ; - f[TSE] = ftemp[TSE] * (one_over_sqrt3 + vx3) + (1.0 - one_over_sqrt3 - vx3)*f[TSE] ; - f[TSW] = ftemp[TSW] * (one_over_sqrt3 + vx3) + (1.0 - one_over_sqrt3 - vx3)*f[TSW] ; - - distributions->setDistributionInvForDirection(f[T], x1+DX1[B], x2+DX2[B], x3+DX3[B], B); - distributions->setDistributionInvForDirection(f[TE], x1+DX1[BW], x2+DX2[BW], x3+DX3[BW], BW); - distributions->setDistributionInvForDirection(f[TW], x1+DX1[BE], x2+DX2[BE], x3+DX3[BE], BE); - distributions->setDistributionInvForDirection(f[TN], x1+DX1[BS], x2+DX2[BS], x3+DX3[BS], BS); - distributions->setDistributionInvForDirection(f[TS], x1+DX1[BN], x2+DX2[BN], x3+DX3[BN], BN); - distributions->setDistributionInvForDirection(f[TNE], x1+DX1[BSW], x2+DX2[BSW], x3+DX3[BSW], BSW); - distributions->setDistributionInvForDirection(f[TNW], x1+DX1[BSE], x2+DX2[BSE], x3+DX3[BSE], BSE); - distributions->setDistributionInvForDirection(f[TSE], x1+DX1[BNW], x2+DX2[BNW], x3+DX3[BNW], BNW); - distributions->setDistributionInvForDirection(f[TSW], x1+DX1[BNE], x2+DX2[BNE], x3+DX3[BNE], BNE); - break; - case B: - f[B] = ftemp[B] * (one_over_sqrt3 - vx3) + (1.0 - one_over_sqrt3 + vx3)*f[B] ; - f[BE] = ftemp[BE] * (one_over_sqrt3 - vx3) + (1.0 - one_over_sqrt3 + vx3)*f[BE] ; - f[BW] = ftemp[BW] * (one_over_sqrt3 - vx3) + (1.0 - one_over_sqrt3 + vx3)*f[BW] ; - f[BN] = ftemp[BN] * (one_over_sqrt3 - vx3) + (1.0 - one_over_sqrt3 + vx3)*f[BN] ; - f[BS] = ftemp[BS] * (one_over_sqrt3 - vx3) + (1.0 - one_over_sqrt3 + vx3)*f[BS] ; - f[BNE] = ftemp[BNE] * (one_over_sqrt3 - vx3) + (1.0 - one_over_sqrt3 + vx3)*f[BNE] ; - f[BNW] = ftemp[BNW] * (one_over_sqrt3 - vx3) + (1.0 - one_over_sqrt3 + vx3)*f[BNW] ; - f[BSE] = ftemp[BSE] * (one_over_sqrt3 - vx3) + (1.0 - one_over_sqrt3 + vx3)*f[BSE] ; - f[BSW] = ftemp[BSW] * (one_over_sqrt3 - vx3) + (1.0 - one_over_sqrt3 + vx3)*f[BSW] ; - - distributions->setDistributionInvForDirection(f[B], x1+DX1[T], x2+DX2[T], x3+DX3[T], T); - distributions->setDistributionInvForDirection(f[BE], x1+DX1[TW], x2+DX2[TW], x3+DX3[TW], TW); - distributions->setDistributionInvForDirection(f[BW], x1+DX1[TE], x2+DX2[TE], x3+DX3[TE], TE); - distributions->setDistributionInvForDirection(f[BN], x1+DX1[TS], x2+DX2[TS], x3+DX3[TS], TS); - distributions->setDistributionInvForDirection(f[BS], x1+DX1[TN], x2+DX2[TN], x3+DX3[TN], TN); - distributions->setDistributionInvForDirection(f[BNE], x1+DX1[TSW], x2+DX2[TSW], x3+DX3[TSW], TSW); - distributions->setDistributionInvForDirection(f[BNW], x1+DX1[TSE], x2+DX2[TSE], x3+DX3[TSE], TSE); - distributions->setDistributionInvForDirection(f[BSE], x1+DX1[TNW], x2+DX2[TNW], x3+DX3[TNW], TNW); - distributions->setDistributionInvForDirection(f[BSW], x1+DX1[TNE], x2+DX2[TNE], x3+DX3[TNE], TNE); - break; - default: - UB_THROW(UbException(UB_EXARGS, "It isn't implemented non reflecting density boundary for this direction!")); - } + using namespace D3Q27System; + using namespace UbMath; + + LBMReal f[ENDF + 1]; + LBMReal ftemp[ENDF + 1]; + + int nx1 = x1; + int nx2 = x2; + int nx3 = x3; + int direction = -1; + + // flag points in direction of fluid + if (bcPtr->hasDensityBoundaryFlag(E)) { + nx1 += 1; + direction = E; + } else if (bcPtr->hasDensityBoundaryFlag(W)) { + nx1 -= 1; + direction = W; + } else if (bcPtr->hasDensityBoundaryFlag(N)) { + nx2 += 1; + direction = N; + } else if (bcPtr->hasDensityBoundaryFlag(S)) { + nx2 -= 1; + direction = S; + } else if (bcPtr->hasDensityBoundaryFlag(T)) { + nx3 += 1; + direction = T; + } else if (bcPtr->hasDensityBoundaryFlag(B)) { + nx3 -= 1; + direction = B; + } else + UB_THROW(UbException(UB_EXARGS, "Danger...no orthogonal BC-Flag on density boundary...")); + + distributions->getDistribution(f, x1, x2, x3); + distributions->getDistribution(ftemp, nx1, nx2, nx3); + + LBMReal rho, vx1, vx2, vx3; + calcMacrosFct(f, rho, vx1, vx2, vx3); + + switch (direction) { + case E: + f[E] = ftemp[E] * (one_over_sqrt3 + vx1) + (1.0 - one_over_sqrt3 - vx1) * f[E]; + f[NE] = ftemp[NE] * (one_over_sqrt3 + vx1) + (1.0 - one_over_sqrt3 - vx1) * f[NE]; + f[SE] = ftemp[SE] * (one_over_sqrt3 + vx1) + (1.0 - one_over_sqrt3 - vx1) * f[SE]; + f[TE] = ftemp[TE] * (one_over_sqrt3 + vx1) + (1.0 - one_over_sqrt3 - vx1) * f[TE]; + f[BE] = ftemp[BE] * (one_over_sqrt3 + vx1) + (1.0 - one_over_sqrt3 - vx1) * f[BE]; + f[TNE] = ftemp[TNE] * (one_over_sqrt3 + vx1) + (1.0 - one_over_sqrt3 - vx1) * f[TNE]; + f[TSE] = ftemp[TSE] * (one_over_sqrt3 + vx1) + (1.0 - one_over_sqrt3 - vx1) * f[TSE]; + f[BNE] = ftemp[BNE] * (one_over_sqrt3 + vx1) + (1.0 - one_over_sqrt3 - vx1) * f[BNE]; + f[BSE] = ftemp[BSE] * (one_over_sqrt3 + vx1) + (1.0 - one_over_sqrt3 - vx1) * f[BSE]; + + distributions->setDistributionInvForDirection(f[E], x1 + DX1[W], x2 + DX2[W], x3 + DX3[W], W); + distributions->setDistributionInvForDirection(f[NE], x1 + DX1[SW], x2 + DX2[SW], x3 + DX3[SW], SW); + distributions->setDistributionInvForDirection(f[SE], x1 + DX1[NW], x2 + DX2[NW], x3 + DX3[NW], NW); + distributions->setDistributionInvForDirection(f[TE], x1 + DX1[BW], x2 + DX2[BW], x3 + DX3[BW], BW); + distributions->setDistributionInvForDirection(f[BE], x1 + DX1[TW], x2 + DX2[TW], x3 + DX3[TW], TW); + distributions->setDistributionInvForDirection(f[TNE], x1 + DX1[BSW], x2 + DX2[BSW], x3 + DX3[BSW], BSW); + distributions->setDistributionInvForDirection(f[TSE], x1 + DX1[BNW], x2 + DX2[BNW], x3 + DX3[BNW], BNW); + distributions->setDistributionInvForDirection(f[BNE], x1 + DX1[TSW], x2 + DX2[TSW], x3 + DX3[TSW], TSW); + distributions->setDistributionInvForDirection(f[BSE], x1 + DX1[TNW], x2 + DX2[TNW], x3 + DX3[TNW], TNW); + break; + case W: + f[W] = ftemp[W] * (one_over_sqrt3 - vx1) + (1.0 - one_over_sqrt3 + vx1) * f[W]; + f[NW] = ftemp[NW] * (one_over_sqrt3 - vx1) + (1.0 - one_over_sqrt3 + vx1) * f[NW]; + f[SW] = ftemp[SW] * (one_over_sqrt3 - vx1) + (1.0 - one_over_sqrt3 + vx1) * f[SW]; + f[TW] = ftemp[TW] * (one_over_sqrt3 - vx1) + (1.0 - one_over_sqrt3 + vx1) * f[TW]; + f[BW] = ftemp[BW] * (one_over_sqrt3 - vx1) + (1.0 - one_over_sqrt3 + vx1) * f[BW]; + f[TNW] = ftemp[TNW] * (one_over_sqrt3 - vx1) + (1.0 - one_over_sqrt3 + vx1) * f[TNW]; + f[TSW] = ftemp[TSW] * (one_over_sqrt3 - vx1) + (1.0 - one_over_sqrt3 + vx1) * f[TSW]; + f[BNW] = ftemp[BNW] * (one_over_sqrt3 - vx1) + (1.0 - one_over_sqrt3 + vx1) * f[BNW]; + f[BSW] = ftemp[BSW] * (one_over_sqrt3 - vx1) + (1.0 - one_over_sqrt3 + vx1) * f[BSW]; + + distributions->setDistributionInvForDirection(f[W], x1 + DX1[E], x2 + DX2[E], x3 + DX3[E], E); + distributions->setDistributionInvForDirection(f[NW], x1 + DX1[SE], x2 + DX2[SE], x3 + DX3[SE], SE); + distributions->setDistributionInvForDirection(f[SW], x1 + DX1[NE], x2 + DX2[NE], x3 + DX3[NE], NE); + distributions->setDistributionInvForDirection(f[TW], x1 + DX1[BE], x2 + DX2[BE], x3 + DX3[BE], BE); + distributions->setDistributionInvForDirection(f[BW], x1 + DX1[TE], x2 + DX2[TE], x3 + DX3[TE], TE); + distributions->setDistributionInvForDirection(f[TNW], x1 + DX1[BSE], x2 + DX2[BSE], x3 + DX3[BSE], BSE); + distributions->setDistributionInvForDirection(f[TSW], x1 + DX1[BNE], x2 + DX2[BNE], x3 + DX3[BNE], BNE); + distributions->setDistributionInvForDirection(f[BNW], x1 + DX1[TSE], x2 + DX2[TSE], x3 + DX3[TSE], TSE); + distributions->setDistributionInvForDirection(f[BSW], x1 + DX1[TNE], x2 + DX2[TNE], x3 + DX3[TNE], TNE); + break; + case N: + f[N] = ftemp[N] * (one_over_sqrt3 + vx2) + (1.0 - one_over_sqrt3 - vx2) * f[N]; + f[NE] = ftemp[NE] * (one_over_sqrt3 + vx2) + (1.0 - one_over_sqrt3 - vx2) * f[NE]; + f[NW] = ftemp[NW] * (one_over_sqrt3 + vx2) + (1.0 - one_over_sqrt3 - vx2) * f[NW]; + f[TN] = ftemp[TN] * (one_over_sqrt3 + vx2) + (1.0 - one_over_sqrt3 - vx2) * f[TN]; + f[BN] = ftemp[BN] * (one_over_sqrt3 + vx2) + (1.0 - one_over_sqrt3 - vx2) * f[BN]; + f[TNE] = ftemp[TNE] * (one_over_sqrt3 + vx2) + (1.0 - one_over_sqrt3 - vx2) * f[TNE]; + f[TNW] = ftemp[TNW] * (one_over_sqrt3 + vx2) + (1.0 - one_over_sqrt3 - vx2) * f[TNW]; + f[BNE] = ftemp[BNE] * (one_over_sqrt3 + vx2) + (1.0 - one_over_sqrt3 - vx2) * f[BNE]; + f[BNW] = ftemp[BNW] * (one_over_sqrt3 + vx2) + (1.0 - one_over_sqrt3 - vx2) * f[BNW]; + + distributions->setDistributionInvForDirection(f[N], x1 + DX1[S], x2 + DX2[S], x3 + DX3[S], S); + distributions->setDistributionInvForDirection(f[NE], x1 + DX1[SW], x2 + DX2[SW], x3 + DX3[SW], SW); + distributions->setDistributionInvForDirection(f[NW], x1 + DX1[SE], x2 + DX2[SE], x3 + DX3[SE], SE); + distributions->setDistributionInvForDirection(f[TN], x1 + DX1[BS], x2 + DX2[BS], x3 + DX3[BS], BS); + distributions->setDistributionInvForDirection(f[BN], x1 + DX1[TS], x2 + DX2[TS], x3 + DX3[TS], TS); + distributions->setDistributionInvForDirection(f[TNE], x1 + DX1[BSW], x2 + DX2[BSW], x3 + DX3[BSW], BSW); + distributions->setDistributionInvForDirection(f[TNW], x1 + DX1[BSE], x2 + DX2[BSE], x3 + DX3[BSE], BSE); + distributions->setDistributionInvForDirection(f[BNE], x1 + DX1[TSW], x2 + DX2[TSW], x3 + DX3[TSW], TSW); + distributions->setDistributionInvForDirection(f[BNW], x1 + DX1[TSE], x2 + DX2[TSE], x3 + DX3[TSE], TSE); + break; + case S: + f[S] = ftemp[S] * (one_over_sqrt3 - vx2) + (1.0 - one_over_sqrt3 + vx2) * f[S]; + f[SE] = ftemp[SE] * (one_over_sqrt3 - vx2) + (1.0 - one_over_sqrt3 + vx2) * f[SE]; + f[SW] = ftemp[SW] * (one_over_sqrt3 - vx2) + (1.0 - one_over_sqrt3 + vx2) * f[SW]; + f[TS] = ftemp[TS] * (one_over_sqrt3 - vx2) + (1.0 - one_over_sqrt3 + vx2) * f[TS]; + f[BS] = ftemp[BS] * (one_over_sqrt3 - vx2) + (1.0 - one_over_sqrt3 + vx2) * f[BS]; + f[TSE] = ftemp[TSE] * (one_over_sqrt3 - vx2) + (1.0 - one_over_sqrt3 + vx2) * f[TSE]; + f[TSW] = ftemp[TSW] * (one_over_sqrt3 - vx2) + (1.0 - one_over_sqrt3 + vx2) * f[TSW]; + f[BSE] = ftemp[BSE] * (one_over_sqrt3 - vx2) + (1.0 - one_over_sqrt3 + vx2) * f[BSE]; + f[BSW] = ftemp[BSW] * (one_over_sqrt3 - vx2) + (1.0 - one_over_sqrt3 + vx2) * f[BSW]; + + distributions->setDistributionInvForDirection(f[S], x1 + DX1[N], x2 + DX2[N], x3 + DX3[N], N); + distributions->setDistributionInvForDirection(f[SE], x1 + DX1[NW], x2 + DX2[NW], x3 + DX3[NW], NW); + distributions->setDistributionInvForDirection(f[SW], x1 + DX1[NE], x2 + DX2[NE], x3 + DX3[NE], NE); + distributions->setDistributionInvForDirection(f[TS], x1 + DX1[BN], x2 + DX2[BN], x3 + DX3[BN], BN); + distributions->setDistributionInvForDirection(f[BS], x1 + DX1[TN], x2 + DX2[TN], x3 + DX3[TN], TN); + distributions->setDistributionInvForDirection(f[TSE], x1 + DX1[BNW], x2 + DX2[BNW], x3 + DX3[BNW], BNW); + distributions->setDistributionInvForDirection(f[TSW], x1 + DX1[BNE], x2 + DX2[BNE], x3 + DX3[BNE], BNE); + distributions->setDistributionInvForDirection(f[BSE], x1 + DX1[TNW], x2 + DX2[TNW], x3 + DX3[TNW], TNW); + distributions->setDistributionInvForDirection(f[BSW], x1 + DX1[TNE], x2 + DX2[TNE], x3 + DX3[TNE], TNE); + break; + case T: + f[T] = ftemp[T] * (one_over_sqrt3 + vx3) + (1.0 - one_over_sqrt3 - vx3) * f[T]; + f[TE] = ftemp[TE] * (one_over_sqrt3 + vx3) + (1.0 - one_over_sqrt3 - vx3) * f[TE]; + f[TW] = ftemp[TW] * (one_over_sqrt3 + vx3) + (1.0 - one_over_sqrt3 - vx3) * f[TW]; + f[TN] = ftemp[TN] * (one_over_sqrt3 + vx3) + (1.0 - one_over_sqrt3 - vx3) * f[TN]; + f[TS] = ftemp[TS] * (one_over_sqrt3 + vx3) + (1.0 - one_over_sqrt3 - vx3) * f[TS]; + f[TNE] = ftemp[TNE] * (one_over_sqrt3 + vx3) + (1.0 - one_over_sqrt3 - vx3) * f[TNE]; + f[TNW] = ftemp[TNW] * (one_over_sqrt3 + vx3) + (1.0 - one_over_sqrt3 - vx3) * f[TNW]; + f[TSE] = ftemp[TSE] * (one_over_sqrt3 + vx3) + (1.0 - one_over_sqrt3 - vx3) * f[TSE]; + f[TSW] = ftemp[TSW] * (one_over_sqrt3 + vx3) + (1.0 - one_over_sqrt3 - vx3) * f[TSW]; + + distributions->setDistributionInvForDirection(f[T], x1 + DX1[B], x2 + DX2[B], x3 + DX3[B], B); + distributions->setDistributionInvForDirection(f[TE], x1 + DX1[BW], x2 + DX2[BW], x3 + DX3[BW], BW); + distributions->setDistributionInvForDirection(f[TW], x1 + DX1[BE], x2 + DX2[BE], x3 + DX3[BE], BE); + distributions->setDistributionInvForDirection(f[TN], x1 + DX1[BS], x2 + DX2[BS], x3 + DX3[BS], BS); + distributions->setDistributionInvForDirection(f[TS], x1 + DX1[BN], x2 + DX2[BN], x3 + DX3[BN], BN); + distributions->setDistributionInvForDirection(f[TNE], x1 + DX1[BSW], x2 + DX2[BSW], x3 + DX3[BSW], BSW); + distributions->setDistributionInvForDirection(f[TNW], x1 + DX1[BSE], x2 + DX2[BSE], x3 + DX3[BSE], BSE); + distributions->setDistributionInvForDirection(f[TSE], x1 + DX1[BNW], x2 + DX2[BNW], x3 + DX3[BNW], BNW); + distributions->setDistributionInvForDirection(f[TSW], x1 + DX1[BNE], x2 + DX2[BNE], x3 + DX3[BNE], BNE); + break; + case B: + f[B] = ftemp[B] * (one_over_sqrt3 - vx3) + (1.0 - one_over_sqrt3 + vx3) * f[B]; + f[BE] = ftemp[BE] * (one_over_sqrt3 - vx3) + (1.0 - one_over_sqrt3 + vx3) * f[BE]; + f[BW] = ftemp[BW] * (one_over_sqrt3 - vx3) + (1.0 - one_over_sqrt3 + vx3) * f[BW]; + f[BN] = ftemp[BN] * (one_over_sqrt3 - vx3) + (1.0 - one_over_sqrt3 + vx3) * f[BN]; + f[BS] = ftemp[BS] * (one_over_sqrt3 - vx3) + (1.0 - one_over_sqrt3 + vx3) * f[BS]; + f[BNE] = ftemp[BNE] * (one_over_sqrt3 - vx3) + (1.0 - one_over_sqrt3 + vx3) * f[BNE]; + f[BNW] = ftemp[BNW] * (one_over_sqrt3 - vx3) + (1.0 - one_over_sqrt3 + vx3) * f[BNW]; + f[BSE] = ftemp[BSE] * (one_over_sqrt3 - vx3) + (1.0 - one_over_sqrt3 + vx3) * f[BSE]; + f[BSW] = ftemp[BSW] * (one_over_sqrt3 - vx3) + (1.0 - one_over_sqrt3 + vx3) * f[BSW]; + + distributions->setDistributionInvForDirection(f[B], x1 + DX1[T], x2 + DX2[T], x3 + DX3[T], T); + distributions->setDistributionInvForDirection(f[BE], x1 + DX1[TW], x2 + DX2[TW], x3 + DX3[TW], TW); + distributions->setDistributionInvForDirection(f[BW], x1 + DX1[TE], x2 + DX2[TE], x3 + DX3[TE], TE); + distributions->setDistributionInvForDirection(f[BN], x1 + DX1[TS], x2 + DX2[TS], x3 + DX3[TS], TS); + distributions->setDistributionInvForDirection(f[BS], x1 + DX1[TN], x2 + DX2[TN], x3 + DX3[TN], TN); + distributions->setDistributionInvForDirection(f[BNE], x1 + DX1[TSW], x2 + DX2[TSW], x3 + DX3[TSW], TSW); + distributions->setDistributionInvForDirection(f[BNW], x1 + DX1[TSE], x2 + DX2[TSE], x3 + DX3[TSE], TSE); + distributions->setDistributionInvForDirection(f[BSE], x1 + DX1[TNW], x2 + DX2[TNW], x3 + DX3[TNW], TNW); + distributions->setDistributionInvForDirection(f[BSW], x1 + DX1[TNE], x2 + DX2[TNE], x3 + DX3[TNE], TNE); + break; + default: + UB_THROW( + UbException(UB_EXARGS, "It isn't implemented non reflecting density boundary for this direction!")); + } } - diff --git a/src/cpu/VirtualFluidsCore/BoundaryConditions/NonReflectingOutflowBCAlgorithm.h b/src/cpu/VirtualFluidsCore/BoundaryConditions/NonReflectingOutflowBCAlgorithm.h index d41cdc05aeeecc67dfe4c44c7371be2095eeb7d6..e968d69b32963e064c09cbe11c75187f4876476d 100644 --- a/src/cpu/VirtualFluidsCore/BoundaryConditions/NonReflectingOutflowBCAlgorithm.h +++ b/src/cpu/VirtualFluidsCore/BoundaryConditions/NonReflectingOutflowBCAlgorithm.h @@ -9,10 +9,10 @@ class DistributionArray3D; class NonReflectingOutflowBCAlgorithm : public BCAlgorithm { public: - NonReflectingOutflowBCAlgorithm(); - ~NonReflectingOutflowBCAlgorithm() override; - SPtr<BCAlgorithm> clone() override; - void addDistributions(SPtr<DistributionArray3D> distributions) override; - void applyBC() override; + NonReflectingOutflowBCAlgorithm(); + ~NonReflectingOutflowBCAlgorithm() override; + SPtr<BCAlgorithm> clone() override; + void addDistributions(SPtr<DistributionArray3D> distributions) override; + void applyBC() override; }; #endif // NonReflectingDensityBCAlgorithm_h__ diff --git a/src/cpu/VirtualFluidsCore/BoundaryConditions/SlipBCAdapter.cpp b/src/cpu/VirtualFluidsCore/BoundaryConditions/SlipBCAdapter.cpp index 1cb54321d4faa232c15e3d1cfd18595316bc35f0..1954a433822e576de11f4ff3a8eb1fcb7dcf4e0a 100644 --- a/src/cpu/VirtualFluidsCore/BoundaryConditions/SlipBCAdapter.cpp +++ b/src/cpu/VirtualFluidsCore/BoundaryConditions/SlipBCAdapter.cpp @@ -1,35 +1,41 @@ #include "SlipBCAdapter.h" -#include "D3Q27System.h" #include "D3Q27Interactor.h" +#include "D3Q27System.h" #include "geometry3d/GbCuboid3D.h" - //*==========================================================*/ -//ObObject* D3Q27SlipBCAdapterCreator::createObObject() +// ObObject* D3Q27SlipBCAdapterCreator::createObObject() //{ -// return new D3Q27SlipBCAdapter; +// return new D3Q27SlipBCAdapter; //} //*==========================================================*/ -//ObObjectCreator* D3Q27SlipBCAdapter::getCreator() +// ObObjectCreator* D3Q27SlipBCAdapter::getCreator() //{ // return D3Q27SlipBCAdapterCreator::getInstance(); //} //*==========================================================*/ -void SlipBCAdapter::adaptBC(const D3Q27Interactor& interactor, SPtr<BoundaryConditions> bc, const double& /*worldX1*/, const double& /*worldX2*/, const double& /*worldX3*/, const double& /*time*/) +void SlipBCAdapter::adaptBC(const D3Q27Interactor &interactor, SPtr<BoundaryConditions> bc, const double & /*worldX1*/, + const double & /*worldX2*/, const double & /*worldX3*/, const double & /*time*/) { - ////////////////////////////////////////////////////////////////////////// - //>>> nur workaround! -> Hendrick nach normalen berechnung aus qs fragen - - GbCuboid3DPtr geo = dynamicPointerCast<GbCuboid3D>(interactor.getGbObject3D()); - if(!geo) throw UbException(UB_EXARGS,"derzeit nur fuer Cubes valide"); + ////////////////////////////////////////////////////////////////////////// + //>>> nur workaround! -> Hendrick nach normalen berechnung aus qs fragen - if ( bc->hasSlipBoundaryFlag(D3Q27System::E) ) bc->setNormalVector( 1.0, 0.0, 0.0); - else if( bc->hasSlipBoundaryFlag(D3Q27System::W) ) bc->setNormalVector(-1.0, 0.0, 0.0); - else if( bc->hasSlipBoundaryFlag(D3Q27System::N) ) bc->setNormalVector( 0.0, 1.0, 0.0); - else if( bc->hasSlipBoundaryFlag(D3Q27System::S) ) bc->setNormalVector( 0.0,-1.0, 0.0); - else if( bc->hasSlipBoundaryFlag(D3Q27System::T) ) bc->setNormalVector( 0.0, 0.0, 1.0); - else if( bc->hasSlipBoundaryFlag(D3Q27System::B) ) bc->setNormalVector( 0.0, 0.0,-1.0); + GbCuboid3DPtr geo = dynamicPointerCast<GbCuboid3D>(interactor.getGbObject3D()); + if (!geo) + throw UbException(UB_EXARGS, "derzeit nur fuer Cubes valide"); - bc->setBcAlgorithmType(algorithmType); -} + if (bc->hasSlipBoundaryFlag(D3Q27System::E)) + bc->setNormalVector(1.0, 0.0, 0.0); + else if (bc->hasSlipBoundaryFlag(D3Q27System::W)) + bc->setNormalVector(-1.0, 0.0, 0.0); + else if (bc->hasSlipBoundaryFlag(D3Q27System::N)) + bc->setNormalVector(0.0, 1.0, 0.0); + else if (bc->hasSlipBoundaryFlag(D3Q27System::S)) + bc->setNormalVector(0.0, -1.0, 0.0); + else if (bc->hasSlipBoundaryFlag(D3Q27System::T)) + bc->setNormalVector(0.0, 0.0, 1.0); + else if (bc->hasSlipBoundaryFlag(D3Q27System::B)) + bc->setNormalVector(0.0, 0.0, -1.0); + bc->setBcAlgorithmType(algorithmType); +} diff --git a/src/cpu/VirtualFluidsCore/BoundaryConditions/SlipBCAdapter.h b/src/cpu/VirtualFluidsCore/BoundaryConditions/SlipBCAdapter.h index 18bda019003bdecd6cd0bf8beeeeb7a8c56448ab..f9b45299034e2cbb80a46d8e4f99ac5b597c50e9 100644 --- a/src/cpu/VirtualFluidsCore/BoundaryConditions/SlipBCAdapter.h +++ b/src/cpu/VirtualFluidsCore/BoundaryConditions/SlipBCAdapter.h @@ -8,37 +8,37 @@ #define SlipBCAdapter_H #ifdef CAB_RCF - #include <3rdParty/rcf/RcfSerializationIncludes.h> +#include <3rdParty/rcf/RcfSerializationIncludes.h> #endif #include "BCAdapter.h" - /*=======================================================*/ -//D3Q27SlipBCAdapterCreator -//class D3Q27SlipBCAdapterCreator : public ObObjectCreator +// D3Q27SlipBCAdapterCreator +// class D3Q27SlipBCAdapterCreator : public ObObjectCreator //{ -//public: +// public: // static D3Q27SlipBCAdapterCreator* getInstance() // { // static D3Q27SlipBCAdapterCreator instance; // return &instance; // } -// -// ObObject* createObObject(); // -// std::string getTypeID() { return "D3Q27SlipBCAdapter";} +// ObObject* createObObject(); +// +// std::string getTypeID() { return "D3Q27SlipBCAdapter";} // std::string toString() { return "D3Q27SlipBCAdapterCreator"; } // -//private: -// D3Q27SlipBCAdapterCreator( const D3Q27SlipBCAdapterCreator& ); //no copy allowed +// private: +// D3Q27SlipBCAdapterCreator( const D3Q27SlipBCAdapterCreator& ); //no copy allowed // const D3Q27SlipBCAdapterCreator& operator=( const D3Q27SlipBCAdapterCreator& ); //no copy allowed // D3Q27SlipBCAdapterCreator() : ObObjectCreator() {} //}; // //#ifndef SWIG -//UB_AUTO_RUN_NAMED( D3Q27BCAdapterFactory::getInstance()->addObObjectCreator(D3Q27SlipBCAdapterCreator::getInstance()), CAB_D3Q27SlipBCAdapterCreator); -//#endif +// UB_AUTO_RUN_NAMED( +// D3Q27BCAdapterFactory::getInstance()->addObObjectCreator(D3Q27SlipBCAdapterCreator::getInstance()), +// CAB_D3Q27SlipBCAdapterCreator); #endif /*=========================================================================*/ /* D3Q27SlipBCAdapter */ @@ -47,7 +47,7 @@ <BR><BR> @author <A HREF="mailto:muffmolch@gmx.de">S. Freudiger</A> @version 1.0 - 06.09.06 -*/ +*/ /* usage: ... @@ -56,33 +56,27 @@ usage: ... class SlipBCAdapter : public BCAdapter { public: - SlipBCAdapter() - : BCAdapter() - { - } - SlipBCAdapter(const short& secondaryBcOption) - : BCAdapter(secondaryBcOption) - { - } + SlipBCAdapter() : BCAdapter() {} + SlipBCAdapter(const short &secondaryBcOption) : BCAdapter(secondaryBcOption) {} - //------------- implements D3Q27BoundaryConditionAdapter ----- start + //------------- implements D3Q27BoundaryConditionAdapter ----- start - void init(const D3Q27Interactor* const& interactor, const double& timestep=0) override {} - void update(const D3Q27Interactor* const& interactor, const double& timestep=0) override {} + void init(const D3Q27Interactor *const &interactor, const double ×tep = 0) override {} + void update(const D3Q27Interactor *const &interactor, const double ×tep = 0) override {} - void adaptBCForDirection( const D3Q27Interactor& /*interactor*/, SPtr<BoundaryConditions> bc, const double& /*worldX1*/, const double& /*worldX2*/, const double& /*worldX3*/, const double& q, const int& fdirection, const double& /*time*/=0 ) override - { - bc->setSlipBoundaryFlag(D3Q27System::INVDIR[fdirection],secondaryBcOption); - bc->setQ((float)q,fdirection); - } - void adaptBC(const D3Q27Interactor& interactor, SPtr<BoundaryConditions> bc, const double& worldX1, const double& worldX2, const double& worldX3, const double& time=0) override; - - //------------- implements D3Q27BoundaryConditionAdapter ----- end - -private: + void adaptBCForDirection(const D3Q27Interactor & /*interactor*/, SPtr<BoundaryConditions> bc, + const double & /*worldX1*/, const double & /*worldX2*/, const double & /*worldX3*/, + const double &q, const int &fdirection, const double & /*time*/ = 0) override + { + bc->setSlipBoundaryFlag(D3Q27System::INVDIR[fdirection], secondaryBcOption); + bc->setQ((float)q, fdirection); + } + void adaptBC(const D3Q27Interactor &interactor, SPtr<BoundaryConditions> bc, const double &worldX1, + const double &worldX2, const double &worldX3, const double &time = 0) override; + //------------- implements D3Q27BoundaryConditionAdapter ----- end +private: }; #endif - diff --git a/src/cpu/VirtualFluidsCore/BoundaryConditions/SlipBCAlgorithm.cpp b/src/cpu/VirtualFluidsCore/BoundaryConditions/SlipBCAlgorithm.cpp index f61b1fcfb37e526d377869f31567dd9c7668e321..0dbbcd8f0fcb854b1cee03a10e947de8a9c43549 100644 --- a/src/cpu/VirtualFluidsCore/BoundaryConditions/SlipBCAlgorithm.cpp +++ b/src/cpu/VirtualFluidsCore/BoundaryConditions/SlipBCAlgorithm.cpp @@ -1,86 +1,135 @@ #include "SlipBCAlgorithm.h" -#include "DistributionArray3D.h" #include "BoundaryConditions.h" +#include "DistributionArray3D.h" SlipBCAlgorithm::SlipBCAlgorithm() { - BCAlgorithm::type = BCAlgorithm::SlipBCAlgorithm; - BCAlgorithm::preCollision = false; + BCAlgorithm::type = BCAlgorithm::SlipBCAlgorithm; + BCAlgorithm::preCollision = false; } ////////////////////////////////////////////////////////////////////////// -SlipBCAlgorithm::~SlipBCAlgorithm() -= default; +SlipBCAlgorithm::~SlipBCAlgorithm() = default; ////////////////////////////////////////////////////////////////////////// SPtr<BCAlgorithm> SlipBCAlgorithm::clone() { - SPtr<BCAlgorithm> bc(new SlipBCAlgorithm()); - return bc; + SPtr<BCAlgorithm> bc(new SlipBCAlgorithm()); + return bc; } ////////////////////////////////////////////////////////////////////////// -void SlipBCAlgorithm::addDistributions(SPtr<DistributionArray3D> distributions) -{ - this->distributions = distributions; -} +void SlipBCAlgorithm::addDistributions(SPtr<DistributionArray3D> distributions) { this->distributions = distributions; } ////////////////////////////////////////////////////////////////////////// void SlipBCAlgorithm::applyBC() { - LBMReal f[D3Q27System::ENDF+1]; - LBMReal feq[D3Q27System::ENDF+1]; - distributions->getDistributionInv(f, x1, x2, x3); - LBMReal rho, vx1, vx2, vx3, drho; - calcMacrosFct(f, drho, vx1, vx2, vx3); - calcFeqFct(feq, drho, vx1, vx2, vx3); + LBMReal f[D3Q27System::ENDF + 1]; + LBMReal feq[D3Q27System::ENDF + 1]; + distributions->getDistributionInv(f, x1, x2, x3); + LBMReal rho, vx1, vx2, vx3, drho; + calcMacrosFct(f, drho, vx1, vx2, vx3); + calcFeqFct(feq, drho, vx1, vx2, vx3); - UbTupleDouble3 normale = bcPtr->getNormalVector(); - LBMReal amp = vx1*val<1>(normale)+vx2*val<2>(normale)+vx3*val<3>(normale); + UbTupleDouble3 normale = bcPtr->getNormalVector(); + LBMReal amp = vx1 * val<1>(normale) + vx2 * val<2>(normale) + vx3 * val<3>(normale); - vx1 = vx1 - amp * val<1>(normale); //normale zeigt von struktur weg! - vx2 = vx2 - amp * val<2>(normale); //normale zeigt von struktur weg! - vx3 = vx3 - amp * val<3>(normale); //normale zeigt von struktur weg! + vx1 = vx1 - amp * val<1>(normale); // normale zeigt von struktur weg! + vx2 = vx2 - amp * val<2>(normale); // normale zeigt von struktur weg! + vx3 = vx3 - amp * val<3>(normale); // normale zeigt von struktur weg! - rho = 1.0+drho*compressibleFactor; + rho = 1.0 + drho * compressibleFactor; - for (int fdir = D3Q27System::FSTARTDIR; fdir<=D3Q27System::FENDDIR; fdir++) - { - if (bcPtr->hasSlipBoundaryFlag(fdir)) - { - //quadratic bounce back - const int invDir = D3Q27System::INVDIR[fdir]; - LBMReal q = bcPtr->getQ(invDir);// m+m q=0 stabiler - //vx3=0; - LBMReal velocity = 0.0; - switch (invDir) - { - case D3Q27System::E: velocity = (UbMath::c4o9*(+vx1)); break; //(2/cs^2)(=6)*rho_0(=1 bei imkompr)*wi*u*ei mit cs=1/sqrt(3) - case D3Q27System::W: velocity = (UbMath::c4o9*(-vx1)); break; //z.B. aus paper manfred MRT LB models in three dimensions (2002) - case D3Q27System::N: velocity = (UbMath::c4o9*(+vx2)); break; - case D3Q27System::S: velocity = (UbMath::c4o9*(-vx2)); break; - case D3Q27System::T: velocity = (UbMath::c4o9*(+vx3)); break; - case D3Q27System::B: velocity = (UbMath::c4o9*(-vx3)); break; - case D3Q27System::NE: velocity = (UbMath::c1o9*(+vx1+vx2)); break; - case D3Q27System::SW: velocity = (UbMath::c1o9*(-vx1-vx2)); break; - case D3Q27System::SE: velocity = (UbMath::c1o9*(+vx1-vx2)); break; - case D3Q27System::NW: velocity = (UbMath::c1o9*(-vx1+vx2)); break; - case D3Q27System::TE: velocity = (UbMath::c1o9*(+vx1 +vx3)); break; - case D3Q27System::BW: velocity = (UbMath::c1o9*(-vx1 -vx3)); break; - case D3Q27System::BE: velocity = (UbMath::c1o9*(+vx1 -vx3)); break; - case D3Q27System::TW: velocity = (UbMath::c1o9*(-vx1 +vx3)); break; - case D3Q27System::TN: velocity = (UbMath::c1o9*(+vx2+vx3)); break; - case D3Q27System::BS: velocity = (UbMath::c1o9*(-vx2-vx3)); break; - case D3Q27System::BN: velocity = (UbMath::c1o9*(+vx2-vx3)); break; - case D3Q27System::TS: velocity = (UbMath::c1o9*(-vx2+vx3)); break; - case D3Q27System::TNE: velocity = (UbMath::c1o36*(+vx1+vx2+vx3)); break; - case D3Q27System::BSW: velocity = (UbMath::c1o36*(-vx1-vx2-vx3)); break; - case D3Q27System::BNE: velocity = (UbMath::c1o36*(+vx1+vx2-vx3)); break; - case D3Q27System::TSW: velocity = (UbMath::c1o36*(-vx1-vx2+vx3)); break; - case D3Q27System::TSE: velocity = (UbMath::c1o36*(+vx1-vx2+vx3)); break; - case D3Q27System::BNW: velocity = (UbMath::c1o36*(-vx1+vx2-vx3)); break; - case D3Q27System::BSE: velocity = (UbMath::c1o36*(+vx1-vx2-vx3)); break; - case D3Q27System::TNW: velocity = (UbMath::c1o36*(-vx1+vx2+vx3)); break; - default: throw UbException(UB_EXARGS, "unknown error"); - } - LBMReal fReturn = ((1.0-q)/(1.0+q))*((f[invDir]-feq[invDir])/(1.0-collFactor)+feq[invDir])+((q*(f[invDir]+f[fdir])-velocity*rho)/(1.0+q)); - distributions->setDistributionForDirection(fReturn, x1+D3Q27System::DX1[invDir], x2+D3Q27System::DX2[invDir], x3+D3Q27System::DX3[invDir], fdir); - } - } + for (int fdir = D3Q27System::FSTARTDIR; fdir <= D3Q27System::FENDDIR; fdir++) { + if (bcPtr->hasSlipBoundaryFlag(fdir)) { + // quadratic bounce back + const int invDir = D3Q27System::INVDIR[fdir]; + LBMReal q = bcPtr->getQ(invDir); // m+m q=0 stabiler + // vx3=0; + LBMReal velocity = 0.0; + switch (invDir) { + case D3Q27System::E: + velocity = (UbMath::c4o9 * (+vx1)); + break; //(2/cs^2)(=6)*rho_0(=1 bei imkompr)*wi*u*ei mit cs=1/sqrt(3) + case D3Q27System::W: + velocity = (UbMath::c4o9 * (-vx1)); + break; // z.B. aus paper manfred MRT LB models in three dimensions (2002) + case D3Q27System::N: + velocity = (UbMath::c4o9 * (+vx2)); + break; + case D3Q27System::S: + velocity = (UbMath::c4o9 * (-vx2)); + break; + case D3Q27System::T: + velocity = (UbMath::c4o9 * (+vx3)); + break; + case D3Q27System::B: + velocity = (UbMath::c4o9 * (-vx3)); + break; + case D3Q27System::NE: + velocity = (UbMath::c1o9 * (+vx1 + vx2)); + break; + case D3Q27System::SW: + velocity = (UbMath::c1o9 * (-vx1 - vx2)); + break; + case D3Q27System::SE: + velocity = (UbMath::c1o9 * (+vx1 - vx2)); + break; + case D3Q27System::NW: + velocity = (UbMath::c1o9 * (-vx1 + vx2)); + break; + case D3Q27System::TE: + velocity = (UbMath::c1o9 * (+vx1 + vx3)); + break; + case D3Q27System::BW: + velocity = (UbMath::c1o9 * (-vx1 - vx3)); + break; + case D3Q27System::BE: + velocity = (UbMath::c1o9 * (+vx1 - vx3)); + break; + case D3Q27System::TW: + velocity = (UbMath::c1o9 * (-vx1 + vx3)); + break; + case D3Q27System::TN: + velocity = (UbMath::c1o9 * (+vx2 + vx3)); + break; + case D3Q27System::BS: + velocity = (UbMath::c1o9 * (-vx2 - vx3)); + break; + case D3Q27System::BN: + velocity = (UbMath::c1o9 * (+vx2 - vx3)); + break; + case D3Q27System::TS: + velocity = (UbMath::c1o9 * (-vx2 + vx3)); + break; + case D3Q27System::TNE: + velocity = (UbMath::c1o36 * (+vx1 + vx2 + vx3)); + break; + case D3Q27System::BSW: + velocity = (UbMath::c1o36 * (-vx1 - vx2 - vx3)); + break; + case D3Q27System::BNE: + velocity = (UbMath::c1o36 * (+vx1 + vx2 - vx3)); + break; + case D3Q27System::TSW: + velocity = (UbMath::c1o36 * (-vx1 - vx2 + vx3)); + break; + case D3Q27System::TSE: + velocity = (UbMath::c1o36 * (+vx1 - vx2 + vx3)); + break; + case D3Q27System::BNW: + velocity = (UbMath::c1o36 * (-vx1 + vx2 - vx3)); + break; + case D3Q27System::BSE: + velocity = (UbMath::c1o36 * (+vx1 - vx2 - vx3)); + break; + case D3Q27System::TNW: + velocity = (UbMath::c1o36 * (-vx1 + vx2 + vx3)); + break; + default: + throw UbException(UB_EXARGS, "unknown error"); + } + LBMReal fReturn = ((1.0 - q) / (1.0 + q)) * ((f[invDir] - feq[invDir]) / (1.0 - collFactor) + feq[invDir]) + + ((q * (f[invDir] + f[fdir]) - velocity * rho) / (1.0 + q)); + distributions->setDistributionForDirection(fReturn, x1 + D3Q27System::DX1[invDir], + x2 + D3Q27System::DX2[invDir], x3 + D3Q27System::DX3[invDir], + fdir); + } + } } \ No newline at end of file diff --git a/src/cpu/VirtualFluidsCore/BoundaryConditions/SlipBCAlgorithm.h b/src/cpu/VirtualFluidsCore/BoundaryConditions/SlipBCAlgorithm.h index 7f4e39c73756a73db3384497dceb3274b2c26fc3..b7a75969f6895f680bf17c08462f4b788fc31c65 100644 --- a/src/cpu/VirtualFluidsCore/BoundaryConditions/SlipBCAlgorithm.h +++ b/src/cpu/VirtualFluidsCore/BoundaryConditions/SlipBCAlgorithm.h @@ -9,10 +9,10 @@ class DistributionArray3D; class SlipBCAlgorithm : public BCAlgorithm { public: - SlipBCAlgorithm(); - ~SlipBCAlgorithm() override; - SPtr<BCAlgorithm> clone() override; - void addDistributions(SPtr<DistributionArray3D> distributions) override; - void applyBC() override; + SlipBCAlgorithm(); + ~SlipBCAlgorithm() override; + SPtr<BCAlgorithm> clone() override; + void addDistributions(SPtr<DistributionArray3D> distributions) override; + void applyBC() override; }; #endif // SlipBCAlgorithm_h__ diff --git a/src/cpu/VirtualFluidsCore/BoundaryConditions/ThinWallBCProcessor.cpp b/src/cpu/VirtualFluidsCore/BoundaryConditions/ThinWallBCProcessor.cpp index bdb9bf2614279be1550bef3011545e424bd2fd3e..1be8fea8b394f9a3e14bb53fcb680ef4d6961a1b 100644 --- a/src/cpu/VirtualFluidsCore/BoundaryConditions/ThinWallBCProcessor.cpp +++ b/src/cpu/VirtualFluidsCore/BoundaryConditions/ThinWallBCProcessor.cpp @@ -5,30 +5,23 @@ #include "LBMKernel.h" ////////////////////////////////////////////////////////////////////////// -ThinWallBCProcessor::ThinWallBCProcessor(SPtr<ILBMKernel> kernel) : BCProcessor(kernel) -{ - -} +ThinWallBCProcessor::ThinWallBCProcessor(SPtr<ILBMKernel> kernel) : BCProcessor(kernel) {} ////////////////////////////////////////////////////////////////////////// SPtr<BCProcessor> ThinWallBCProcessor::clone(SPtr<ILBMKernel> kernel) { - SPtr<BCProcessor> bcProcessor(new ThinWallBCProcessor(kernel)); - return bcProcessor; + SPtr<BCProcessor> bcProcessor(new ThinWallBCProcessor(kernel)); + return bcProcessor; } ////////////////////////////////////////////////////////////////////////// void ThinWallBCProcessor::applyPostCollisionBC() { - BCProcessor::applyPostCollisionBC(); + BCProcessor::applyPostCollisionBC(); - for(SPtr<BCAlgorithm> bc : postBC) - { - if (bc->getType() == BCAlgorithm::ThinWallNoSlipBCAlgorithm) - { - dynamicPointerCast<ThinWallNoSlipBCAlgorithm>(bc)->setPass(2); - bc->applyBC(); - dynamicPointerCast<ThinWallNoSlipBCAlgorithm>(bc)->setPass(1); - } - } + for (SPtr<BCAlgorithm> bc : postBC) { + if (bc->getType() == BCAlgorithm::ThinWallNoSlipBCAlgorithm) { + dynamicPointerCast<ThinWallNoSlipBCAlgorithm>(bc)->setPass(2); + bc->applyBC(); + dynamicPointerCast<ThinWallNoSlipBCAlgorithm>(bc)->setPass(1); + } + } } - - diff --git a/src/cpu/VirtualFluidsCore/BoundaryConditions/ThinWallBCProcessor.h b/src/cpu/VirtualFluidsCore/BoundaryConditions/ThinWallBCProcessor.h index cd3ac5c496a5ac58d1ce20118f1ef084c05cad1a..6bed45c21e495e0dc9c728996e570ca961da6221 100644 --- a/src/cpu/VirtualFluidsCore/BoundaryConditions/ThinWallBCProcessor.h +++ b/src/cpu/VirtualFluidsCore/BoundaryConditions/ThinWallBCProcessor.h @@ -10,13 +10,12 @@ class ILBMKernel; class ThinWallBCProcessor : public BCProcessor { public: - ThinWallBCProcessor() = default; - explicit ThinWallBCProcessor(SPtr<ILBMKernel> kernel); - SPtr<BCProcessor> clone(SPtr<ILBMKernel> kernel) override; - void applyPostCollisionBC(); //FIXME: should the base method virtual?? + ThinWallBCProcessor() = default; + explicit ThinWallBCProcessor(SPtr<ILBMKernel> kernel); + SPtr<BCProcessor> clone(SPtr<ILBMKernel> kernel) override; + void applyPostCollisionBC(); // FIXME: should the base method virtual?? protected: private: - }; #endif diff --git a/src/cpu/VirtualFluidsCore/BoundaryConditions/ThinWallNoSlipBCAlgorithm.cpp b/src/cpu/VirtualFluidsCore/BoundaryConditions/ThinWallNoSlipBCAlgorithm.cpp index 39c427a53e91368c9e490a183ae6c70173e0a9fd..c1ad04256a7967891f3cd8f5165779527e07d7ae 100644 --- a/src/cpu/VirtualFluidsCore/BoundaryConditions/ThinWallNoSlipBCAlgorithm.cpp +++ b/src/cpu/VirtualFluidsCore/BoundaryConditions/ThinWallNoSlipBCAlgorithm.cpp @@ -1,64 +1,61 @@ #include "ThinWallNoSlipBCAlgorithm.h" -#include "D3Q27EsoTwist3DSplittedVector.h" #include "BoundaryConditions.h" +#include "D3Q27EsoTwist3DSplittedVector.h" ThinWallNoSlipBCAlgorithm::ThinWallNoSlipBCAlgorithm() { - BCAlgorithm::type = BCAlgorithm::ThinWallNoSlipBCAlgorithm; - BCAlgorithm::preCollision = false; - pass = 1; + BCAlgorithm::type = BCAlgorithm::ThinWallNoSlipBCAlgorithm; + BCAlgorithm::preCollision = false; + pass = 1; } ////////////////////////////////////////////////////////////////////////// -ThinWallNoSlipBCAlgorithm::~ThinWallNoSlipBCAlgorithm() -= default; +ThinWallNoSlipBCAlgorithm::~ThinWallNoSlipBCAlgorithm() = default; ////////////////////////////////////////////////////////////////////////// SPtr<BCAlgorithm> ThinWallNoSlipBCAlgorithm::clone() { - SPtr<BCAlgorithm> bc(new ThinWallNoSlipBCAlgorithm()); - return bc; + SPtr<BCAlgorithm> bc(new ThinWallNoSlipBCAlgorithm()); + return bc; } ////////////////////////////////////////////////////////////////////////// void ThinWallNoSlipBCAlgorithm::applyBC() { - LBMReal f[D3Q27System::ENDF + 1]; - LBMReal feq[D3Q27System::ENDF + 1]; - distributions->getDistributionInv(f, x1, x2, x3); - LBMReal rho, vx1, vx2, vx3; - calcMacrosFct(f, rho, vx1, vx2, vx3); - calcFeqFct(feq, rho, vx1, vx2, vx3); + LBMReal f[D3Q27System::ENDF + 1]; + LBMReal feq[D3Q27System::ENDF + 1]; + distributions->getDistributionInv(f, x1, x2, x3); + LBMReal rho, vx1, vx2, vx3; + calcMacrosFct(f, rho, vx1, vx2, vx3); + calcFeqFct(feq, rho, vx1, vx2, vx3); - LBMReal fReturn; + LBMReal fReturn; - for (int fdir = D3Q27System::FSTARTDIR; fdir<=D3Q27System::FENDDIR; fdir++) - { - if (bcPtr->hasNoSlipBoundaryFlag(fdir)) - { - const int invDir = D3Q27System::INVDIR[fdir]; - if (pass == 1) - { - LBMReal q = bcPtr->getQ(invDir); - fReturn = ((1.0 - q) / (1.0 + q))*0.5*(f[invDir] - f[fdir] + (f[invDir] + f[fdir] - collFactor*(feq[fdir] + feq[invDir])) / (1.0 - collFactor)); - //distributionsTemp->setDistributionForDirection(fReturn, x1 + D3Q27System::DX1[invDir], x2 + D3Q27System::DX2[invDir], x3 + D3Q27System::DX3[invDir], fdir); - fTemp[fdir] = fReturn; - } - else - { - //quadratic bounce back with for thin walls - //fReturn = distributionsTemp->getDistributionInvForDirection(x1 + D3Q27System::DX1[invDir], x2 + D3Q27System::DX2[invDir], x3 + D3Q27System::DX3[invDir], fdir); - fReturn = fTemp[fdir]; - distributions->setDistributionForDirection(fReturn, x1 + D3Q27System::DX1[invDir], x2 + D3Q27System::DX2[invDir], x3 + D3Q27System::DX3[invDir], fdir); - } - } - } + for (int fdir = D3Q27System::FSTARTDIR; fdir <= D3Q27System::FENDDIR; fdir++) { + if (bcPtr->hasNoSlipBoundaryFlag(fdir)) { + const int invDir = D3Q27System::INVDIR[fdir]; + if (pass == 1) { + LBMReal q = bcPtr->getQ(invDir); + fReturn = ((1.0 - q) / (1.0 + q)) * 0.5 * + (f[invDir] - f[fdir] + + (f[invDir] + f[fdir] - collFactor * (feq[fdir] + feq[invDir])) / (1.0 - collFactor)); + // distributionsTemp->setDistributionForDirection(fReturn, x1 + D3Q27System::DX1[invDir], x2 + + // D3Q27System::DX2[invDir], x3 + D3Q27System::DX3[invDir], fdir); + fTemp[fdir] = fReturn; + } else { + // quadratic bounce back with for thin walls + // fReturn = distributionsTemp->getDistributionInvForDirection(x1 + D3Q27System::DX1[invDir], x2 + + // D3Q27System::DX2[invDir], x3 + D3Q27System::DX3[invDir], fdir); + fReturn = fTemp[fdir]; + distributions->setDistributionForDirection(fReturn, x1 + D3Q27System::DX1[invDir], + x2 + D3Q27System::DX2[invDir], x3 + D3Q27System::DX3[invDir], + fdir); + } + } + } } ////////////////////////////////////////////////////////////////////////// void ThinWallNoSlipBCAlgorithm::addDistributions(SPtr<DistributionArray3D> distributions) { - this->distributions = distributions; + this->distributions = distributions; } ////////////////////////////////////////////////////////////////////////// -void ThinWallNoSlipBCAlgorithm::setPass(int pass) -{ - this->pass = pass; -} +void ThinWallNoSlipBCAlgorithm::setPass(int pass) { this->pass = pass; } diff --git a/src/cpu/VirtualFluidsCore/BoundaryConditions/ThinWallNoSlipBCAlgorithm.h b/src/cpu/VirtualFluidsCore/BoundaryConditions/ThinWallNoSlipBCAlgorithm.h index db9244d10cc710f260c59471bd373e990fa5b42c..1ba18185e27bafa2c115639469cd7544661acbb5 100644 --- a/src/cpu/VirtualFluidsCore/BoundaryConditions/ThinWallNoSlipBCAlgorithm.h +++ b/src/cpu/VirtualFluidsCore/BoundaryConditions/ThinWallNoSlipBCAlgorithm.h @@ -9,17 +9,18 @@ class DistributionArray3D; class ThinWallNoSlipBCAlgorithm : public BCAlgorithm { public: - ThinWallNoSlipBCAlgorithm(); - ~ThinWallNoSlipBCAlgorithm() override; - SPtr<BCAlgorithm> clone() override; - void addDistributions(SPtr<DistributionArray3D> distributions) override; - void setPass(int pass); - void applyBC() override; + ThinWallNoSlipBCAlgorithm(); + ~ThinWallNoSlipBCAlgorithm() override; + SPtr<BCAlgorithm> clone() override; + void addDistributions(SPtr<DistributionArray3D> distributions) override; + void setPass(int pass); + void applyBC() override; protected: - SPtr<DistributionArray3D> distributionsTemp; + SPtr<DistributionArray3D> distributionsTemp; + private: - int pass; - LBMReal fTemp[D3Q27System::ENDF + 1]; + int pass; + LBMReal fTemp[D3Q27System::ENDF + 1]; }; #endif // ThinWallNoSlipBCAlgorithm_h__ diff --git a/src/cpu/VirtualFluidsCore/BoundaryConditions/VelocityBCAdapter.cpp b/src/cpu/VirtualFluidsCore/BoundaryConditions/VelocityBCAdapter.cpp index f80cb1e2b32afd63b6fd722fcd98726d421a1d9a..55d65f629b0311c8599b81b39a62e8be06f35090 100644 --- a/src/cpu/VirtualFluidsCore/BoundaryConditions/VelocityBCAdapter.cpp +++ b/src/cpu/VirtualFluidsCore/BoundaryConditions/VelocityBCAdapter.cpp @@ -1,28 +1,28 @@ //======================================================================================= -// ____ ____ __ ______ __________ __ __ __ __ -// \ \ | | | | | _ \ |___ ___| | | | | / \ | | -// \ \ | | | | | |_) | | | | | | | / \ | | -// \ \ | | | | | _ / | | | | | | / /\ \ | | -// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ -// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| -// \ \ | | ________________________________________________________________ -// \ \ | | | ______________________________________________________________| -// \ \| | | | __ __ __ __ ______ _______ -// \ | | |_____ | | | | | | | | | _ \ / _____) -// \ | | _____| | | | | | | | | | | \ \ \_______ +// ____ ____ __ ______ __________ __ __ __ __ +// \ \ | | | | | _ \ |___ ___| | | | | / \ | | +// \ \ | | | | | |_) | | | | | | | / \ | | +// \ \ | | | | | _ / | | | | | | / /\ \ | | +// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ +// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| +// \ \ | | ________________________________________________________________ +// \ \ | | | ______________________________________________________________| +// \ \| | | | __ __ __ __ ______ _______ +// \ | | |_____ | | | | | | | | | _ \ / _____) +// \ | | _____| | | | | | | | | | | \ \ \_______ // \ | | | | |_____ | \_/ | | | | |_/ / _____ | -// \ _____| |__| |________| \_______/ |__| |______/ (_______/ +// \ _____| |__| |________| \_______/ |__| |______/ (_______/ // -// This file is part of VirtualFluids. VirtualFluids is free software: you can +// This file is part of VirtualFluids. VirtualFluids is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of +// License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. -// -// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// +// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License along // with VirtualFluids (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>. // @@ -38,302 +38,338 @@ using namespace std; - -VelocityBCAdapter::VelocityBCAdapter(const bool& vx1, const bool& vx2, const bool& vx3, const BCFunction& velVxBC) +VelocityBCAdapter::VelocityBCAdapter(const bool &vx1, const bool &vx2, const bool &vx3, const BCFunction &velVxBC) { - if(vx1) this->vx1BCs.push_back(velVxBC); - if(vx2) this->vx2BCs.push_back(velVxBC); - if(vx3) this->vx3BCs.push_back(velVxBC); - this->init(); + if (vx1) + this->vx1BCs.push_back(velVxBC); + if (vx2) + this->vx2BCs.push_back(velVxBC); + if (vx3) + this->vx3BCs.push_back(velVxBC); + this->init(); } /*==========================================================*/ -VelocityBCAdapter::VelocityBCAdapter(const bool& vx1, const bool& vx2, const bool& vx3, const mu::Parser& function, const double& startTime, const double& endTime ) +VelocityBCAdapter::VelocityBCAdapter(const bool &vx1, const bool &vx2, const bool &vx3, const mu::Parser &function, + const double &startTime, const double &endTime) { - if(vx1) this->vx1BCs.emplace_back(function,startTime,endTime); - if(vx2) this->vx2BCs.emplace_back(function,startTime,endTime); - if(vx3) this->vx3BCs.emplace_back(function,startTime,endTime); - this->init(); + if (vx1) + this->vx1BCs.emplace_back(function, startTime, endTime); + if (vx2) + this->vx2BCs.emplace_back(function, startTime, endTime); + if (vx3) + this->vx3BCs.emplace_back(function, startTime, endTime); + this->init(); } /*==========================================================*/ -VelocityBCAdapter::VelocityBCAdapter(const bool& vx1, const bool& vx2, const bool& vx3, const mu::Parser& function1, const mu::Parser& function2, const mu::Parser& function3, const double& startTime, const double& endTime ) +VelocityBCAdapter::VelocityBCAdapter(const bool &vx1, const bool &vx2, const bool &vx3, const mu::Parser &function1, + const mu::Parser &function2, const mu::Parser &function3, const double &startTime, + const double &endTime) { - if(vx1) this->vx1BCs.emplace_back(function1,startTime,endTime); - if(vx2) this->vx2BCs.emplace_back(function2,startTime,endTime); - if(vx3) this->vx3BCs.emplace_back(function3,startTime,endTime); - this->init(); + if (vx1) + this->vx1BCs.emplace_back(function1, startTime, endTime); + if (vx2) + this->vx2BCs.emplace_back(function2, startTime, endTime); + if (vx3) + this->vx3BCs.emplace_back(function3, startTime, endTime); + this->init(); } /*==========================================================*/ -VelocityBCAdapter::VelocityBCAdapter(const bool& vx1, const bool& vx2, const bool& vx3, const string& functionstring, const double& startTime, const double& endTime ) +VelocityBCAdapter::VelocityBCAdapter(const bool &vx1, const bool &vx2, const bool &vx3, const string &functionstring, + const double &startTime, const double &endTime) { - if(vx1) this->vx1BCs.emplace_back(functionstring,startTime,endTime); - if(vx2) this->vx2BCs.emplace_back(functionstring,startTime,endTime); - if(vx3) this->vx3BCs.emplace_back(functionstring,startTime,endTime); - this->init(); + if (vx1) + this->vx1BCs.emplace_back(functionstring, startTime, endTime); + if (vx2) + this->vx2BCs.emplace_back(functionstring, startTime, endTime); + if (vx3) + this->vx3BCs.emplace_back(functionstring, startTime, endTime); + this->init(); } /*==========================================================*/ -VelocityBCAdapter::VelocityBCAdapter(const BCFunction& velBC, bool x1Dir, bool x2Dir, bool x3Dir) +VelocityBCAdapter::VelocityBCAdapter(const BCFunction &velBC, bool x1Dir, bool x2Dir, bool x3Dir) { - if(x1Dir) this->vx1BCs.push_back(velBC); - if(x2Dir) this->vx2BCs.push_back(velBC); - if(x3Dir) this->vx3BCs.push_back(velBC); - this->init(); + if (x1Dir) + this->vx1BCs.push_back(velBC); + if (x2Dir) + this->vx2BCs.push_back(velBC); + if (x3Dir) + this->vx3BCs.push_back(velBC); + this->init(); } /*==========================================================*/ -VelocityBCAdapter::VelocityBCAdapter(const BCFunction& velVx1BC, const BCFunction& velVx2BC, const BCFunction& velVx3BC) +VelocityBCAdapter::VelocityBCAdapter(const BCFunction &velVx1BC, const BCFunction &velVx2BC, const BCFunction &velVx3BC) { - if( velVx1BC.getEndTime()!=-Ub::inf ) this->vx1BCs.push_back(velVx1BC); - if( velVx2BC.getEndTime()!=-Ub::inf ) this->vx2BCs.push_back(velVx2BC); - if( velVx3BC.getEndTime()!=-Ub::inf ) this->vx3BCs.push_back(velVx3BC); - this->init(); + if (velVx1BC.getEndTime() != -Ub::inf) + this->vx1BCs.push_back(velVx1BC); + if (velVx2BC.getEndTime() != -Ub::inf) + this->vx2BCs.push_back(velVx2BC); + if (velVx3BC.getEndTime() != -Ub::inf) + this->vx3BCs.push_back(velVx3BC); + this->init(); } /*==========================================================*/ -VelocityBCAdapter::VelocityBCAdapter(const vector< BCFunction >& velVx1BCs, const vector< BCFunction >& velVx2BCs, const vector< BCFunction >& velVx3BCs) +VelocityBCAdapter::VelocityBCAdapter(const vector<BCFunction> &velVx1BCs, const vector<BCFunction> &velVx2BCs, + const vector<BCFunction> &velVx3BCs) { - this->vx1BCs = velVx1BCs; - this->vx2BCs = velVx2BCs; - this->vx3BCs = velVx3BCs; - this->init(); + this->vx1BCs = velVx1BCs; + this->vx2BCs = velVx2BCs; + this->vx3BCs = velVx3BCs; + this->init(); } /*==========================================================*/ -VelocityBCAdapter::VelocityBCAdapter(const double& vx1, const double& vx1StartTime, const double& vx1EndTime, - const double& vx2, const double& vx2StartTime, const double& vx2EndTime, - const double& vx3, const double& vx3StartTime, const double& vx3EndTime ) +VelocityBCAdapter::VelocityBCAdapter(const double &vx1, const double &vx1StartTime, const double &vx1EndTime, + const double &vx2, const double &vx2StartTime, const double &vx2EndTime, + const double &vx3, const double &vx3StartTime, const double &vx3EndTime) { - this->vx1BCs.emplace_back(vx1,vx1StartTime,vx1EndTime); - this->vx2BCs.emplace_back(vx2,vx2StartTime,vx2EndTime); - this->vx3BCs.emplace_back(vx3,vx3StartTime,vx3EndTime); - this->init(); + this->vx1BCs.emplace_back(vx1, vx1StartTime, vx1EndTime); + this->vx2BCs.emplace_back(vx2, vx2StartTime, vx2EndTime); + this->vx3BCs.emplace_back(vx3, vx3StartTime, vx3EndTime); + this->init(); } /*==========================================================*/ -VelocityBCAdapter::VelocityBCAdapter(const string& vx1Function, const double& vx1StartTime, const double& vx1EndTime, - const string& vx2Function, const double& vx2StartTime, const double& vx2EndTime, - const string& vx3Function, const double& vx3StartTime, const double& vx3EndTime ) +VelocityBCAdapter::VelocityBCAdapter(const string &vx1Function, const double &vx1StartTime, const double &vx1EndTime, + const string &vx2Function, const double &vx2StartTime, const double &vx2EndTime, + const string &vx3Function, const double &vx3StartTime, const double &vx3EndTime) { - if(vx1Function.size()) this->vx1BCs.emplace_back(vx1Function,vx1StartTime,vx1EndTime); - if(vx2Function.size()) this->vx2BCs.emplace_back(vx2Function,vx2StartTime,vx2EndTime); - if(vx3Function.size()) this->vx3BCs.emplace_back(vx3Function,vx3StartTime,vx3EndTime); - this->init(); + if (vx1Function.size()) + this->vx1BCs.emplace_back(vx1Function, vx1StartTime, vx1EndTime); + if (vx2Function.size()) + this->vx2BCs.emplace_back(vx2Function, vx2StartTime, vx2EndTime); + if (vx3Function.size()) + this->vx3BCs.emplace_back(vx3Function, vx3StartTime, vx3EndTime); + this->init(); } /*==========================================================*/ -void VelocityBCAdapter::setNewVelocities(const double& vx1, const double& vx1StartTime, const double& vx1EndTime, - const double& vx2, const double& vx2StartTime, const double& vx2EndTime, - const double& vx3, const double& vx3StartTime, const double& vx3EndTime ) +void VelocityBCAdapter::setNewVelocities(const double &vx1, const double &vx1StartTime, const double &vx1EndTime, + const double &vx2, const double &vx2StartTime, const double &vx2EndTime, + const double &vx3, const double &vx3StartTime, const double &vx3EndTime) { - this->clear(); - this->vx1BCs.emplace_back(vx1,vx1StartTime,vx1EndTime); - this->vx2BCs.emplace_back(vx2,vx2StartTime,vx2EndTime); - this->vx3BCs.emplace_back(vx3,vx3StartTime,vx3EndTime); - this->init(); + this->clear(); + this->vx1BCs.emplace_back(vx1, vx1StartTime, vx1EndTime); + this->vx2BCs.emplace_back(vx2, vx2StartTime, vx2EndTime); + this->vx3BCs.emplace_back(vx3, vx3StartTime, vx3EndTime); + this->init(); } /*==========================================================*/ void VelocityBCAdapter::init() { - this->unsetTimeDependent(); - - this->timeStep = 0.0; + this->unsetTimeDependent(); + + this->timeStep = 0.0; - this->x1 = 0.0; - this->x2 = 0.0; - this->x3 = 0.0; + this->x1 = 0.0; + this->x2 = 0.0; + this->x3 = 0.0; - this->tmpVx1Function = NULL; - this->tmpVx2Function = NULL; - this->tmpVx3Function = NULL; + this->tmpVx1Function = NULL; + this->tmpVx2Function = NULL; + this->tmpVx3Function = NULL; - try //initilialization and validation of functions - { - this->init(vx1BCs); - this->init(vx2BCs); - this->init(vx3BCs); - } - catch(mu::Parser::exception_type& e){ stringstream error; error<<"mu::parser exception occurs, message("<<e.GetMsg()<<"), formula("<<e.GetExpr()+"), token("+e.GetToken()<<")" - <<", pos("<<e.GetPos()<<"), error code("<<e.GetCode(); throw UbException(error.str()); } - catch(...) { throw UbException(UB_EXARGS,"unknown exception" ); } + try // initilialization and validation of functions + { + this->init(vx1BCs); + this->init(vx2BCs); + this->init(vx3BCs); + } catch (mu::Parser::exception_type &e) { + stringstream error; + error << "mu::parser exception occurs, message(" << e.GetMsg() << "), formula(" + << e.GetExpr() + "), token(" + e.GetToken() << ")" + << ", pos(" << e.GetPos() << "), error code(" << e.GetCode(); + throw UbException(error.str()); + } catch (...) { + throw UbException(UB_EXARGS, "unknown exception"); + } } /*==========================================================*/ -void VelocityBCAdapter::init(std::vector<BCFunction>& vxBCs) +void VelocityBCAdapter::init(std::vector<BCFunction> &vxBCs) { - for(size_t pos=0; pos<vxBCs.size(); ++pos) - { - if( !( UbMath::equal( BCFunction::INFCONST, vxBCs[pos].getEndTime() ) - && UbMath::greaterEqual( this->timeStep, vxBCs[pos].getStartTime() ) ) ) - { - this->setTimeDependent(); - } + for (size_t pos = 0; pos < vxBCs.size(); ++pos) { + if (!(UbMath::equal(BCFunction::INFCONST, vxBCs[pos].getEndTime()) && + UbMath::greaterEqual(this->timeStep, vxBCs[pos].getStartTime()))) { + this->setTimeDependent(); + } - vxBCs[pos].getFunction().DefineVar("t" , &this->timeStep); - vxBCs[pos].getFunction().DefineVar("x1", &this->x1 ); - vxBCs[pos].getFunction().DefineVar("x2", &this->x2 ); - vxBCs[pos].getFunction().DefineVar("x3", &this->x3 ); + vxBCs[pos].getFunction().DefineVar("t", &this->timeStep); + vxBCs[pos].getFunction().DefineVar("x1", &this->x1); + vxBCs[pos].getFunction().DefineVar("x2", &this->x2); + vxBCs[pos].getFunction().DefineVar("x3", &this->x3); - vxBCs[pos].getFunction().Eval(); //<-- validation - } + vxBCs[pos].getFunction().Eval(); //<-- validation + } } /*==========================================================*/ -void VelocityBCAdapter::init(const D3Q27Interactor* const& interactor, const double& time) +void VelocityBCAdapter::init(const D3Q27Interactor *const &interactor, const double &time) { - this->timeStep = time; - this->tmpVx1Function = this->tmpVx2Function = this->tmpVx3Function = NULL; + this->timeStep = time; + this->tmpVx1Function = this->tmpVx2Function = this->tmpVx3Function = NULL; - //aktuelle velocityfunction bestimmen - double maxEndtime = -Ub::inf; - - for(size_t pos=0; pos<vx1BCs.size(); ++pos) - { - if( UbMath::equal(vx1BCs[pos].getEndTime(),BCFunction::INFTIMEDEPENDENT) ) maxEndtime=Ub::inf; - maxEndtime = UbMath::max(maxEndtime,vx1BCs[pos].getStartTime(),vx1BCs[pos].getEndTime()); //startTime abfragen, da INFCONST=-10 - - if( UbMath::greaterEqual(this->timeStep,vx1BCs[pos].getStartTime()) ) - { - if( UbMath::lessEqual( this->timeStep , vx1BCs[pos].getEndTime() ) - || UbMath::equal( vx1BCs[pos].getEndTime(), (double)BCFunction::INFCONST ) - || UbMath::equal( vx1BCs[pos].getEndTime(), (double)BCFunction::INFTIMEDEPENDENT) ) - { - tmpVx1Function = &vx1BCs[pos].getFunction(); - break; - } - } - } - for(size_t pos=0; pos<vx2BCs.size(); ++pos) - { - if( UbMath::equal(vx2BCs[pos].getEndTime(),BCFunction::INFTIMEDEPENDENT)) maxEndtime=Ub::inf; - maxEndtime = UbMath::max(maxEndtime,vx2BCs[pos].getStartTime(),vx2BCs[pos].getEndTime()); //startTime abfragen, da INFCONST=-10 + // aktuelle velocityfunction bestimmen + double maxEndtime = -Ub::inf; - if( UbMath::greaterEqual(this->timeStep,vx2BCs[pos].getStartTime()) ) - { - if( UbMath::lessEqual( this->timeStep , vx2BCs[pos].getEndTime() ) - || UbMath::equal( vx2BCs[pos].getEndTime(), (double)BCFunction::INFCONST ) - || UbMath::equal( vx2BCs[pos].getEndTime(), (double)BCFunction::INFTIMEDEPENDENT ) ) - { - tmpVx2Function = &vx2BCs[pos].getFunction(); - break; - } - } - } - for(size_t pos=0; pos<vx3BCs.size(); ++pos) - { - if( UbMath::equal(vx3BCs[pos].getEndTime(),BCFunction::INFTIMEDEPENDENT)) maxEndtime=Ub::inf; - maxEndtime = UbMath::max(maxEndtime,vx3BCs[pos].getStartTime(),vx3BCs[pos].getEndTime()); //startTime abfragen, da INFCONST=-10 + for (size_t pos = 0; pos < vx1BCs.size(); ++pos) { + if (UbMath::equal(vx1BCs[pos].getEndTime(), BCFunction::INFTIMEDEPENDENT)) + maxEndtime = Ub::inf; + maxEndtime = UbMath::max(maxEndtime, vx1BCs[pos].getStartTime(), + vx1BCs[pos].getEndTime()); // startTime abfragen, da INFCONST=-10 - if( UbMath::greaterEqual(this->timeStep,vx3BCs[pos].getStartTime()) ) - { - if( UbMath::lessEqual( this->timeStep , vx3BCs[pos].getEndTime() ) - || UbMath::equal( vx3BCs[pos].getEndTime(), (double)BCFunction::INFCONST ) - || UbMath::equal( vx3BCs[pos].getEndTime(), (double)BCFunction::INFTIMEDEPENDENT ) ) - { - tmpVx3Function = &vx3BCs[pos].getFunction(); - break; - } - } - } - - if( UbMath::greaterEqual(time,maxEndtime) ) - { - if( !this->isTimePeriodic() ) this->unsetTimeDependent(); - else //bei peridoic die interavalle neu setzen: - { - if( UbMath::equal(maxEndtime,BCFunction::INFCONST) ) - for(size_t pos=0; pos<vx1BCs.size(); ++pos) - { - vx1BCs[pos].setStartTime( vx1BCs[pos].getStartTime() + timeStep ); - vx1BCs[pos].setEndTime( vx1BCs[pos].getEndTime() + timeStep ); + if (UbMath::greaterEqual(this->timeStep, vx1BCs[pos].getStartTime())) { + if (UbMath::lessEqual(this->timeStep, vx1BCs[pos].getEndTime()) || + UbMath::equal(vx1BCs[pos].getEndTime(), (double)BCFunction::INFCONST) || + UbMath::equal(vx1BCs[pos].getEndTime(), (double)BCFunction::INFTIMEDEPENDENT)) { + tmpVx1Function = &vx1BCs[pos].getFunction(); + break; } - if( UbMath::equal(maxEndtime,BCFunction::INFCONST) ) - for(size_t pos=0; pos<vx2BCs.size(); ++pos) - { - vx2BCs[pos].setStartTime( vx2BCs[pos].getStartTime() + timeStep ); - vx2BCs[pos].setEndTime( vx2BCs[pos].getEndTime() + timeStep ); + } + } + for (size_t pos = 0; pos < vx2BCs.size(); ++pos) { + if (UbMath::equal(vx2BCs[pos].getEndTime(), BCFunction::INFTIMEDEPENDENT)) + maxEndtime = Ub::inf; + maxEndtime = UbMath::max(maxEndtime, vx2BCs[pos].getStartTime(), + vx2BCs[pos].getEndTime()); // startTime abfragen, da INFCONST=-10 + + if (UbMath::greaterEqual(this->timeStep, vx2BCs[pos].getStartTime())) { + if (UbMath::lessEqual(this->timeStep, vx2BCs[pos].getEndTime()) || + UbMath::equal(vx2BCs[pos].getEndTime(), (double)BCFunction::INFCONST) || + UbMath::equal(vx2BCs[pos].getEndTime(), (double)BCFunction::INFTIMEDEPENDENT)) { + tmpVx2Function = &vx2BCs[pos].getFunction(); + break; } - if( UbMath::equal(maxEndtime,BCFunction::INFCONST) ) - for(size_t pos=0; pos<vx3BCs.size(); ++pos) - { - vx3BCs[pos].setStartTime( vx3BCs[pos].getStartTime() + timeStep ); - vx3BCs[pos].setEndTime( vx3BCs[pos].getEndTime() + timeStep ); + } + } + for (size_t pos = 0; pos < vx3BCs.size(); ++pos) { + if (UbMath::equal(vx3BCs[pos].getEndTime(), BCFunction::INFTIMEDEPENDENT)) + maxEndtime = Ub::inf; + maxEndtime = UbMath::max(maxEndtime, vx3BCs[pos].getStartTime(), + vx3BCs[pos].getEndTime()); // startTime abfragen, da INFCONST=-10 + + if (UbMath::greaterEqual(this->timeStep, vx3BCs[pos].getStartTime())) { + if (UbMath::lessEqual(this->timeStep, vx3BCs[pos].getEndTime()) || + UbMath::equal(vx3BCs[pos].getEndTime(), (double)BCFunction::INFCONST) || + UbMath::equal(vx3BCs[pos].getEndTime(), (double)BCFunction::INFTIMEDEPENDENT)) { + tmpVx3Function = &vx3BCs[pos].getFunction(); + break; } - this->init(interactor,time); - } - } + } + } - UBLOG(logDEBUG4,"D3Q27VelocityBCAdapter::init(time="<<time<<") " - <<", vx1= \""<<(tmpVx1Function ? tmpVx1Function->GetExpr() : "-")<<"\"" - <<", vx2= \""<<(tmpVx2Function ? tmpVx2Function->GetExpr() : "-")<<"\"" - <<", vx3= \""<<(tmpVx3Function ? tmpVx3Function->GetExpr() : "-")<<"\"" - <<", timedependent="<<boolalpha<<this->isTimeDependent() ); + if (UbMath::greaterEqual(time, maxEndtime)) { + if (!this->isTimePeriodic()) + this->unsetTimeDependent(); + else // bei peridoic die interavalle neu setzen: + { + if (UbMath::equal(maxEndtime, BCFunction::INFCONST)) + for (size_t pos = 0; pos < vx1BCs.size(); ++pos) { + vx1BCs[pos].setStartTime(vx1BCs[pos].getStartTime() + timeStep); + vx1BCs[pos].setEndTime(vx1BCs[pos].getEndTime() + timeStep); + } + if (UbMath::equal(maxEndtime, BCFunction::INFCONST)) + for (size_t pos = 0; pos < vx2BCs.size(); ++pos) { + vx2BCs[pos].setStartTime(vx2BCs[pos].getStartTime() + timeStep); + vx2BCs[pos].setEndTime(vx2BCs[pos].getEndTime() + timeStep); + } + if (UbMath::equal(maxEndtime, BCFunction::INFCONST)) + for (size_t pos = 0; pos < vx3BCs.size(); ++pos) { + vx3BCs[pos].setStartTime(vx3BCs[pos].getStartTime() + timeStep); + vx3BCs[pos].setEndTime(vx3BCs[pos].getEndTime() + timeStep); + } + this->init(interactor, time); + } + } + + UBLOG(logDEBUG4, "D3Q27VelocityBCAdapter::init(time=" + << time << ") " + << ", vx1= \"" << (tmpVx1Function ? tmpVx1Function->GetExpr() : "-") << "\"" + << ", vx2= \"" << (tmpVx2Function ? tmpVx2Function->GetExpr() : "-") << "\"" + << ", vx3= \"" << (tmpVx3Function ? tmpVx3Function->GetExpr() : "-") << "\"" + << ", timedependent=" << boolalpha << this->isTimeDependent()); } /*==========================================================*/ -void VelocityBCAdapter::update( const D3Q27Interactor* const& interactor, const double& time ) +void VelocityBCAdapter::update(const D3Q27Interactor *const &interactor, const double &time) { - this->init(interactor,time); + this->init(interactor, time); } /*==========================================================*/ -void VelocityBCAdapter::adaptBCForDirection( const D3Q27Interactor& /*interactor*/, SPtr<BoundaryConditions> bc, const double& /*worldX1*/, const double& /*worldX2*/, const double& /*worldX3*/, const double& q, const int& fdirection, const double& /*time*/ ) +void VelocityBCAdapter::adaptBCForDirection(const D3Q27Interactor & /*interactor*/, SPtr<BoundaryConditions> bc, + const double & /*worldX1*/, const double & /*worldX2*/, + const double & /*worldX3*/, const double &q, const int &fdirection, + const double & /*time*/) { - bc->setVelocityBoundaryFlag(D3Q27System::INVDIR[fdirection],secondaryBcOption); - bc->setQ((float)q,fdirection); + bc->setVelocityBoundaryFlag(D3Q27System::INVDIR[fdirection], secondaryBcOption); + bc->setQ((float)q, fdirection); } /*==========================================================*/ -void VelocityBCAdapter::adaptBC( const D3Q27Interactor& interactor, SPtr<BoundaryConditions> bc, const double& worldX1, const double& worldX2, const double& worldX3, const double& time ) +void VelocityBCAdapter::adaptBC(const D3Q27Interactor &interactor, SPtr<BoundaryConditions> bc, const double &worldX1, + const double &worldX2, const double &worldX3, const double &time) { - this->setNodeVelocity(interactor,bc,worldX1,worldX2,worldX3,time); - bc->setBcAlgorithmType(algorithmType); + this->setNodeVelocity(interactor, bc, worldX1, worldX2, worldX3, time); + bc->setBcAlgorithmType(algorithmType); } /*==========================================================*/ -void VelocityBCAdapter::setNodeVelocity( const D3Q27Interactor& /*interactor*/, SPtr<BoundaryConditions> bc, const double& worldX1, const double& worldX2, const double& worldX3, const double& timestep) +void VelocityBCAdapter::setNodeVelocity(const D3Q27Interactor & /*interactor*/, SPtr<BoundaryConditions> bc, + const double &worldX1, const double &worldX2, const double &worldX3, + const double ×tep) { - //Geschwindigkeiten setzen - try - { - //PunktKoordinaten bestimmen - this->x1 = worldX1; - this->x2 = worldX2; - this->x3 = worldX3; - this->timeStep = timestep; + // Geschwindigkeiten setzen + try { + // PunktKoordinaten bestimmen + this->x1 = worldX1; + this->x2 = worldX2; + this->x3 = worldX3; + this->timeStep = timestep; - if(tmpVx1Function) bc->setBoundaryVelocityX1((LBMReal)tmpVx1Function->Eval()); - if(tmpVx2Function) bc->setBoundaryVelocityX2((LBMReal)tmpVx2Function->Eval()); - if(tmpVx3Function) bc->setBoundaryVelocityX3((LBMReal)tmpVx3Function->Eval()); - } - catch(mu::Parser::exception_type& e){ stringstream error; error<<"mu::parser exception occurs, message("<<e.GetMsg()<<"), formula("<<e.GetExpr()+"), token("+e.GetToken()<<")" - <<", pos("<<e.GetPos()<<"), error code("<<e.GetCode(); throw UbException(error.str()); } - catch(...) { throw UbException(UB_EXARGS,"unknown exception" ); } + if (tmpVx1Function) + bc->setBoundaryVelocityX1((LBMReal)tmpVx1Function->Eval()); + if (tmpVx2Function) + bc->setBoundaryVelocityX2((LBMReal)tmpVx2Function->Eval()); + if (tmpVx3Function) + bc->setBoundaryVelocityX3((LBMReal)tmpVx3Function->Eval()); + } catch (mu::Parser::exception_type &e) { + stringstream error; + error << "mu::parser exception occurs, message(" << e.GetMsg() << "), formula(" + << e.GetExpr() + "), token(" + e.GetToken() << ")" + << ", pos(" << e.GetPos() << "), error code(" << e.GetCode(); + throw UbException(error.str()); + } catch (...) { + throw UbException(UB_EXARGS, "unknown exception"); + } } /*==========================================================*/ -UbTupleDouble3 VelocityBCAdapter::getVelocity(const double& x1, const double& x2, const double& x3, const double& timeStep) const +UbTupleDouble3 VelocityBCAdapter::getVelocity(const double &x1, const double &x2, const double &x3, + const double &timeStep) const { - double vx1 = 0.0; - double vx2 = 0.0; - double vx3 = 0.0; - this->x1 = x1; - this->x2 = x2; - this->x3 = x3; - this->timeStep = timeStep; - - if(tmpVx1Function) vx1 = tmpVx1Function->Eval(); - if(tmpVx2Function) vx2 = tmpVx2Function->Eval(); - if(tmpVx3Function) vx3 = tmpVx3Function->Eval(); - - return { vx1,vx2,vx3 }; + double vx1 = 0.0; + double vx2 = 0.0; + double vx3 = 0.0; + this->x1 = x1; + this->x2 = x2; + this->x3 = x3; + this->timeStep = timeStep; + + if (tmpVx1Function) + vx1 = tmpVx1Function->Eval(); + if (tmpVx2Function) + vx2 = tmpVx2Function->Eval(); + if (tmpVx3Function) + vx3 = tmpVx3Function->Eval(); + + return { vx1, vx2, vx3 }; } /*==========================================================*/ string VelocityBCAdapter::toString() { - stringstream info; - info<<"D3Q27VelocityBCAdapter:\n"; - info<<" #vx1-functions = "<<(int)vx1BCs.size()<<endl; - info<<" #vx2-functions = "<<(int)vx2BCs.size()<<endl; - info<<" #vx3-functions = "<<(int)vx3BCs.size()<<endl; - info<<" protected variables: x1, x2, x3, t"<<endl; - - const vector<BCFunction>* bcvecs[3] = { &vx1BCs, &vx2BCs, &vx3BCs }; - for(int i=0; i<3; i++) - { - for(size_t pos=0; pos<bcvecs[i]->size(); ++pos) - { - info<<"\n vx"<<(i+1)<<"-function nr."<<pos<<":"<<endl; - info<<(*bcvecs[i])[pos]<<endl; - } - } - return info.str(); -} - + stringstream info; + info << "D3Q27VelocityBCAdapter:\n"; + info << " #vx1-functions = " << (int)vx1BCs.size() << endl; + info << " #vx2-functions = " << (int)vx2BCs.size() << endl; + info << " #vx3-functions = " << (int)vx3BCs.size() << endl; + info << " protected variables: x1, x2, x3, t" << endl; + const vector<BCFunction> *bcvecs[3] = { &vx1BCs, &vx2BCs, &vx3BCs }; + for (int i = 0; i < 3; i++) { + for (size_t pos = 0; pos < bcvecs[i]->size(); ++pos) { + info << "\n vx" << (i + 1) << "-function nr." << pos << ":" << endl; + info << (*bcvecs[i])[pos] << endl; + } + } + return info.str(); +} diff --git a/src/cpu/VirtualFluidsCore/BoundaryConditions/VelocityBCAdapter.h b/src/cpu/VirtualFluidsCore/BoundaryConditions/VelocityBCAdapter.h index 4c2b666fcbe6589b0102942842661a9fb68ad009..c6f5039a3ea3b2612e765235c88d357a25f9a89c 100644 --- a/src/cpu/VirtualFluidsCore/BoundaryConditions/VelocityBCAdapter.h +++ b/src/cpu/VirtualFluidsCore/BoundaryConditions/VelocityBCAdapter.h @@ -1,28 +1,28 @@ //======================================================================================= -// ____ ____ __ ______ __________ __ __ __ __ -// \ \ | | | | | _ \ |___ ___| | | | | / \ | | -// \ \ | | | | | |_) | | | | | | | / \ | | -// \ \ | | | | | _ / | | | | | | / /\ \ | | -// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ -// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| -// \ \ | | ________________________________________________________________ -// \ \ | | | ______________________________________________________________| -// \ \| | | | __ __ __ __ ______ _______ -// \ | | |_____ | | | | | | | | | _ \ / _____) -// \ | | _____| | | | | | | | | | | \ \ \_______ +// ____ ____ __ ______ __________ __ __ __ __ +// \ \ | | | | | _ \ |___ ___| | | | | / \ | | +// \ \ | | | | | |_) | | | | | | | / \ | | +// \ \ | | | | | _ / | | | | | | / /\ \ | | +// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ +// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| +// \ \ | | ________________________________________________________________ +// \ \ | | | ______________________________________________________________| +// \ \| | | | __ __ __ __ ______ _______ +// \ | | |_____ | | | | | | | | | _ \ / _____) +// \ | | _____| | | | | | | | | | | \ \ \_______ // \ | | | | |_____ | \_/ | | | | |_/ / _____ | -// \ _____| |__| |________| \_______/ |__| |______/ (_______/ +// \ _____| |__| |________| \_______/ |__| |______/ (_______/ // -// This file is part of VirtualFluids. VirtualFluids is free software: you can +// This file is part of VirtualFluids. VirtualFluids is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of +// License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. -// -// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// +// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License along // with VirtualFluids (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>. // @@ -34,8 +34,8 @@ #define VelocityBCAdapter_H #include <iostream> -#include <string> #include <sstream> +#include <string> #include <vector> #include <basics/utilities/UbInfinity.h> @@ -45,17 +45,17 @@ //! \brief A class provides an interface for velocity boundary condition in grid generator. -//! \details +//! \details //! Example: //! \code{.cpp} vector<BCFunction> vx1BCs,vx2BCs,vx3BCs; //! vx1BCs.push_back(BCFunction(0.01 , 0 , 100) ); //t=[0 ..100[ -> vx1 = 0.01 //! vx1BCs.push_back(BCFunction(0.004, 100, 200) ); //t=[100..200[ -> vx1 = 0.004 //! vx1BCs.push_back(BCFunction(0.03 , 200, 400) ); //t=[200..400] -> vx1 = 0.03 -//! +//! //! vx2BCs.push_back(BCFunction(0.02 , 0 , 200) ); //t=[0 ..200[ -> vx2 = 0.02 //! vx2BCs.push_back(BCFunction(0.002, 200, 300) ); //t=[200..300[ -> vx2 = 0.002 //! vx2BCs.push_back(BCFunction(0.043, 300, 600) ); //t=[300..600] -> vx2 = 0.043 -//! +//! //! VelocityBCAdapter bcAdapter(vx1BCs,vx2BCs,vx3BCs); //! bcAdapter.setTimePeriodic(); //-> t=[0 ..100[ -> vx1 = 0.01 //! // t=[100..200[ -> vx1 = 0.004 @@ -73,90 +73,100 @@ //! Example of parabolic inflow: //! \code{.cpp} //! mu::Parser fct; -//! fct.SetExpr("max(vmax*(1.0-4.0*((x2-x2_vmax)^2+(x3-x3_vmax)^2)/H^2),0.0)"); //paraboloid (with vmax for (0/x2_vmax/x3_vmax) -//! fct.DefineConst("x2Vmax", 0.0 ); //x2-Pos für vmax -//! fct.DefineConst("x3Vmax", 0.0 ); //x3-Pos für vmax -//! fct.DefineConst("H" , diameterOfPipe); -//! fct.DefineConst("vmax" , vmax ); +//! fct.SetExpr("max(vmax*(1.0-4.0*((x2-x2_vmax)^2+(x3-x3_vmax)^2)/H^2),0.0)"); //paraboloid (with vmax for +//! (0/x2_vmax/x3_vmax) fct.DefineConst("x2Vmax", 0.0 ); //x2-Pos für vmax fct.DefineConst("x3Vmax", 0.0 +//! ); //x3-Pos für vmax fct.DefineConst("H" , diameterOfPipe); fct.DefineConst("vmax" , vmax ); //! VelocityBCAdapter velBC(true, false ,false ,fct, 0, BCFunction::INFCONST); //! \endcode class VelocityBCAdapter : public BCAdapter { public: - //constructors - VelocityBCAdapter() { this->init(); } - - VelocityBCAdapter(const bool& vx1, const bool& vx2, const bool& vx3, const BCFunction& velVxBC ); + // constructors + VelocityBCAdapter() { this->init(); } - VelocityBCAdapter(const bool& vx1, const bool& vx2, const bool& vx3, const mu::Parser& function, const double& startTime, const double& endTime ); + VelocityBCAdapter(const bool &vx1, const bool &vx2, const bool &vx3, const BCFunction &velVxBC); - VelocityBCAdapter(const bool& vx1, const bool& vx2, const bool& vx3, const mu::Parser& function1, const mu::Parser& function2, const mu::Parser& function3, const double& startTime, const double& endTime ); - - VelocityBCAdapter(const bool& vx1, const bool& vx2, const bool& vx3, const std::string& functionstring, const double& startTime, const double& endTime ); + VelocityBCAdapter(const bool &vx1, const bool &vx2, const bool &vx3, const mu::Parser &function, + const double &startTime, const double &endTime); - VelocityBCAdapter(const BCFunction& velBC, bool x1Dir, bool x2Dir, bool x3Dir); + VelocityBCAdapter(const bool &vx1, const bool &vx2, const bool &vx3, const mu::Parser &function1, + const mu::Parser &function2, const mu::Parser &function3, const double &startTime, + const double &endTime); - VelocityBCAdapter(const BCFunction& velVx1BC, const BCFunction& velVx2BC, const BCFunction& velVx3BC); + VelocityBCAdapter(const bool &vx1, const bool &vx2, const bool &vx3, const std::string &functionstring, + const double &startTime, const double &endTime); - VelocityBCAdapter(const std::vector< BCFunction >& velVx1BCs, const std::vector< BCFunction >& velVx2BCs, const std::vector< BCFunction >& velVx3BCs); + VelocityBCAdapter(const BCFunction &velBC, bool x1Dir, bool x2Dir, bool x3Dir); - VelocityBCAdapter(const double& vx1, const double& vx1StartTime, const double& vx1EndTime, - const double& vx2, const double& vx2StartTime, const double& vx2EndTime, - const double& vx3, const double& vx3StartTime, const double& vx3EndTime); + VelocityBCAdapter(const BCFunction &velVx1BC, const BCFunction &velVx2BC, const BCFunction &velVx3BC); - VelocityBCAdapter(const std::string& vx1Function, const double& vx1StartTime, const double& vx1EndTime, - const std::string& vx2Function, const double& vx2StartTime, const double& vx2EndTime, - const std::string& vx3Function, const double& vx3StartTime, const double& vx3EndTime ); + VelocityBCAdapter(const std::vector<BCFunction> &velVx1BCs, const std::vector<BCFunction> &velVx2BCs, + const std::vector<BCFunction> &velVx3BCs); - //methods - void setTimePeriodic() { (this->type |= TIMEPERIODIC); } - void unsetTimePeriodic() { (this->type &= ~TIMEPERIODIC); } - bool isTimePeriodic() { return ((this->type & TIMEPERIODIC) == TIMEPERIODIC); } + VelocityBCAdapter(const double &vx1, const double &vx1StartTime, const double &vx1EndTime, const double &vx2, + const double &vx2StartTime, const double &vx2EndTime, const double &vx3, + const double &vx3StartTime, const double &vx3EndTime); - //The following is meant for moving objects... - void setNewVelocities(const double& vx1, const double& vx1StartTime, const double& vx1EndTime, - const double& vx2, const double& vx2StartTime, const double& vx2EndTime, - const double& vx3, const double& vx3StartTime, const double& vx3EndTime); + VelocityBCAdapter(const std::string &vx1Function, const double &vx1StartTime, const double &vx1EndTime, + const std::string &vx2Function, const double &vx2StartTime, const double &vx2EndTime, + const std::string &vx3Function, const double &vx3StartTime, const double &vx3EndTime); - - //------------- implements BCAdapter ----- start - std::string toString(); - - void init(const D3Q27Interactor* const& interactor, const double& time=0) override; - void update(const D3Q27Interactor* const& interactor, const double& time=0) override; + // methods + void setTimePeriodic() { (this->type |= TIMEPERIODIC); } + void unsetTimePeriodic() { (this->type &= ~TIMEPERIODIC); } + bool isTimePeriodic() { return ((this->type & TIMEPERIODIC) == TIMEPERIODIC); } - void adaptBCForDirection( const D3Q27Interactor& interactor, SPtr<BoundaryConditions> bc, const double& worldX1, const double& worldX2, const double& worldX3, const double& q, const int& fdirection, const double& time=0 ) override; - void adaptBC( const D3Q27Interactor& interactor, SPtr<BoundaryConditions> bc, const double& worldX1, const double& worldX2, const double& worldX3, const double& time=0 ) override; + // The following is meant for moving objects... + void setNewVelocities(const double &vx1, const double &vx1StartTime, const double &vx1EndTime, const double &vx2, + const double &vx2StartTime, const double &vx2EndTime, const double &vx3, + const double &vx3StartTime, const double &vx3EndTime); - //------------- implements BCAdapter ----- end + //------------- implements BCAdapter ----- start + std::string toString(); - UbTupleDouble3 getVelocity(const double& x1, const double& x2, const double& x3, const double& timeStep) const; + void init(const D3Q27Interactor *const &interactor, const double &time = 0) override; + void update(const D3Q27Interactor *const &interactor, const double &time = 0) override; + void adaptBCForDirection(const D3Q27Interactor &interactor, SPtr<BoundaryConditions> bc, const double &worldX1, + const double &worldX2, const double &worldX3, const double &q, const int &fdirection, + const double &time = 0) override; + void adaptBC(const D3Q27Interactor &interactor, SPtr<BoundaryConditions> bc, const double &worldX1, + const double &worldX2, const double &worldX3, const double &time = 0) override; -protected: - void init(); - void init(std::vector<BCFunction>& vxBCs); + //------------- implements BCAdapter ----- end - //time dependency is determined automatically via BCFunction intervals! - void setTimeDependent() { (this->type |= TIMEDEPENDENT); } - void unsetTimeDependent() { (this->type &= ~TIMEDEPENDENT); } + UbTupleDouble3 getVelocity(const double &x1, const double &x2, const double &x3, const double &timeStep) const; - void clear() { vx1BCs.clear(); vx2BCs.clear(); vx3BCs.clear(); this->init(); } - void setNodeVelocity(const D3Q27Interactor& interactor, SPtr<BoundaryConditions> bc, const double& worldX1, const double& worldX2, const double& worldX3, const double& timestep); +protected: + void init(); + void init(std::vector<BCFunction> &vxBCs); + + // time dependency is determined automatically via BCFunction intervals! + void setTimeDependent() { (this->type |= TIMEDEPENDENT); } + void unsetTimeDependent() { (this->type &= ~TIMEDEPENDENT); } + + void clear() + { + vx1BCs.clear(); + vx2BCs.clear(); + vx3BCs.clear(); + this->init(); + } + void setNodeVelocity(const D3Q27Interactor &interactor, SPtr<BoundaryConditions> bc, const double &worldX1, + const double &worldX2, const double &worldX3, const double ×tep); private: - mutable mu::value_type x1, x2, x3; - mutable mu::value_type timeStep; - - mu::Parser* tmpVx1Function; - mu::Parser* tmpVx2Function; - mu::Parser* tmpVx3Function; + mutable mu::value_type x1, x2, x3; + mutable mu::value_type timeStep; - std::vector<BCFunction> vx1BCs; - std::vector<BCFunction> vx2BCs; - std::vector<BCFunction> vx3BCs; + mu::Parser *tmpVx1Function; + mu::Parser *tmpVx2Function; + mu::Parser *tmpVx3Function; + std::vector<BCFunction> vx1BCs; + std::vector<BCFunction> vx2BCs; + std::vector<BCFunction> vx3BCs; }; #endif diff --git a/src/cpu/VirtualFluidsCore/BoundaryConditions/VelocityBCAlgorithm.cpp b/src/cpu/VirtualFluidsCore/BoundaryConditions/VelocityBCAlgorithm.cpp index b08a5bb856bbf1ff787811cb5f7475c3c8ea6b24..4905e76a9f7a3e46848b8d8dbaf81095fe9a5b14 100644 --- a/src/cpu/VirtualFluidsCore/BoundaryConditions/VelocityBCAlgorithm.cpp +++ b/src/cpu/VirtualFluidsCore/BoundaryConditions/VelocityBCAlgorithm.cpp @@ -1,28 +1,28 @@ //======================================================================================= -// ____ ____ __ ______ __________ __ __ __ __ -// \ \ | | | | | _ \ |___ ___| | | | | / \ | | -// \ \ | | | | | |_) | | | | | | | / \ | | -// \ \ | | | | | _ / | | | | | | / /\ \ | | -// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ -// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| -// \ \ | | ________________________________________________________________ -// \ \ | | | ______________________________________________________________| -// \ \| | | | __ __ __ __ ______ _______ -// \ | | |_____ | | | | | | | | | _ \ / _____) -// \ | | _____| | | | | | | | | | | \ \ \_______ +// ____ ____ __ ______ __________ __ __ __ __ +// \ \ | | | | | _ \ |___ ___| | | | | / \ | | +// \ \ | | | | | |_) | | | | | | | / \ | | +// \ \ | | | | | _ / | | | | | | / /\ \ | | +// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ +// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| +// \ \ | | ________________________________________________________________ +// \ \ | | | ______________________________________________________________| +// \ \| | | | __ __ __ __ ______ _______ +// \ | | |_____ | | | | | | | | | _ \ / _____) +// \ | | _____| | | | | | | | | | | \ \ \_______ // \ | | | | |_____ | \_/ | | | | |_/ / _____ | -// \ _____| |__| |________| \_______/ |__| |______/ (_______/ +// \ _____| |__| |________| \_______/ |__| |______/ (_______/ // -// This file is part of VirtualFluids. VirtualFluids is free software: you can +// This file is part of VirtualFluids. VirtualFluids is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of +// License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. -// -// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// +// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License along // with VirtualFluids (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>. // @@ -32,48 +32,47 @@ //======================================================================================= #include "VelocityBCAlgorithm.h" -#include "DistributionArray3D.h" #include "BoundaryConditions.h" +#include "DistributionArray3D.h" VelocityBCAlgorithm::VelocityBCAlgorithm() { - BCAlgorithm::type = BCAlgorithm::VelocityBCAlgorithm; - BCAlgorithm::preCollision = false; + BCAlgorithm::type = BCAlgorithm::VelocityBCAlgorithm; + BCAlgorithm::preCollision = false; } ////////////////////////////////////////////////////////////////////////// SPtr<BCAlgorithm> VelocityBCAlgorithm::clone() { - SPtr<BCAlgorithm> bc(new VelocityBCAlgorithm()); - return bc; + SPtr<BCAlgorithm> bc(new VelocityBCAlgorithm()); + return bc; } ////////////////////////////////////////////////////////////////////////// void VelocityBCAlgorithm::addDistributions(SPtr<DistributionArray3D> distributions) { - this->distributions = distributions; + this->distributions = distributions; } ////////////////////////////////////////////////////////////////////////// void VelocityBCAlgorithm::applyBC() { - LBMReal f[D3Q27System::ENDF+1]; - LBMReal feq[D3Q27System::ENDF+1]; - distributions->getDistributionInv(f, x1, x2, x3); - LBMReal rho, vx1, vx2, vx3, drho; - calcMacrosFct(f, drho, vx1, vx2, vx3); - calcFeqFct(feq, drho, vx1, vx2, vx3); - - rho = 1.0+drho*compressibleFactor; + LBMReal f[D3Q27System::ENDF + 1]; + LBMReal feq[D3Q27System::ENDF + 1]; + distributions->getDistributionInv(f, x1, x2, x3); + LBMReal rho, vx1, vx2, vx3, drho; + calcMacrosFct(f, drho, vx1, vx2, vx3); + calcFeqFct(feq, drho, vx1, vx2, vx3); - for (int fdir = D3Q27System::FSTARTDIR; fdir<=D3Q27System::FENDDIR; fdir++) - { - if (bcPtr->hasVelocityBoundaryFlag(fdir)) - { - const int invDir = D3Q27System::INVDIR[fdir]; - LBMReal q = bcPtr->getQ(invDir); - LBMReal velocity = bcPtr->getBoundaryVelocity(invDir); - LBMReal fReturn = ((1.0-q)/(1.0+q))*((f[invDir]-feq[invDir])/(1.0-collFactor)+feq[invDir])+((q*(f[invDir]+f[fdir])-velocity*rho)/(1.0+q)); - distributions->setDistributionForDirection(fReturn, x1+D3Q27System::DX1[invDir], x2+D3Q27System::DX2[invDir], x3+D3Q27System::DX3[invDir], fdir); - } - } + rho = 1.0 + drho * compressibleFactor; + for (int fdir = D3Q27System::FSTARTDIR; fdir <= D3Q27System::FENDDIR; fdir++) { + if (bcPtr->hasVelocityBoundaryFlag(fdir)) { + const int invDir = D3Q27System::INVDIR[fdir]; + LBMReal q = bcPtr->getQ(invDir); + LBMReal velocity = bcPtr->getBoundaryVelocity(invDir); + LBMReal fReturn = ((1.0 - q) / (1.0 + q)) * ((f[invDir] - feq[invDir]) / (1.0 - collFactor) + feq[invDir]) + + ((q * (f[invDir] + f[fdir]) - velocity * rho) / (1.0 + q)); + distributions->setDistributionForDirection(fReturn, x1 + D3Q27System::DX1[invDir], + x2 + D3Q27System::DX2[invDir], x3 + D3Q27System::DX3[invDir], + fdir); + } + } } - diff --git a/src/cpu/VirtualFluidsCore/BoundaryConditions/VelocityBCAlgorithm.h b/src/cpu/VirtualFluidsCore/BoundaryConditions/VelocityBCAlgorithm.h index fedd86982d400da5458d216640d8bbd634087ffe..44bbd2cee69c12a613e638f4173b371d1260964f 100644 --- a/src/cpu/VirtualFluidsCore/BoundaryConditions/VelocityBCAlgorithm.h +++ b/src/cpu/VirtualFluidsCore/BoundaryConditions/VelocityBCAlgorithm.h @@ -1,28 +1,28 @@ //======================================================================================= -// ____ ____ __ ______ __________ __ __ __ __ -// \ \ | | | | | _ \ |___ ___| | | | | / \ | | -// \ \ | | | | | |_) | | | | | | | / \ | | -// \ \ | | | | | _ / | | | | | | / /\ \ | | -// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ -// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| -// \ \ | | ________________________________________________________________ -// \ \ | | | ______________________________________________________________| -// \ \| | | | __ __ __ __ ______ _______ -// \ | | |_____ | | | | | | | | | _ \ / _____) -// \ | | _____| | | | | | | | | | | \ \ \_______ +// ____ ____ __ ______ __________ __ __ __ __ +// \ \ | | | | | _ \ |___ ___| | | | | / \ | | +// \ \ | | | | | |_) | | | | | | | / \ | | +// \ \ | | | | | _ / | | | | | | / /\ \ | | +// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ +// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| +// \ \ | | ________________________________________________________________ +// \ \ | | | ______________________________________________________________| +// \ \| | | | __ __ __ __ ______ _______ +// \ | | |_____ | | | | | | | | | _ \ / _____) +// \ | | _____| | | | | | | | | | | \ \ \_______ // \ | | | | |_____ | \_/ | | | | |_/ / _____ | -// \ _____| |__| |________| \_______/ |__| |______/ (_______/ +// \ _____| |__| |________| \_______/ |__| |______/ (_______/ // -// This file is part of VirtualFluids. VirtualFluids is free software: you can +// This file is part of VirtualFluids. VirtualFluids is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of +// License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. -// -// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// +// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License along // with VirtualFluids (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>. // @@ -43,11 +43,10 @@ class DistributionArray3D; class VelocityBCAlgorithm : public BCAlgorithm { public: - VelocityBCAlgorithm(); - SPtr<BCAlgorithm> clone() override; - void addDistributions(SPtr<DistributionArray3D> distributions) override; - void applyBC() override; + VelocityBCAlgorithm(); + SPtr<BCAlgorithm> clone() override; + void addDistributions(SPtr<DistributionArray3D> distributions) override; + void applyBC() override; }; -#endif - +#endif diff --git a/src/cpu/VirtualFluidsCore/BoundaryConditions/VelocityWithDensityBCAlgorithm.cpp b/src/cpu/VirtualFluidsCore/BoundaryConditions/VelocityWithDensityBCAlgorithm.cpp index 7ebad4fa02b71f657a7b509759ac9cafae5b6244..98ead1e2d21ba62de5b00e3658af2e9e8cc768ef 100644 --- a/src/cpu/VirtualFluidsCore/BoundaryConditions/VelocityWithDensityBCAlgorithm.cpp +++ b/src/cpu/VirtualFluidsCore/BoundaryConditions/VelocityWithDensityBCAlgorithm.cpp @@ -1,82 +1,85 @@ #include "VelocityWithDensityBCAlgorithm.h" -#include "DistributionArray3D.h" #include "BCArray3D.h" +#include "DistributionArray3D.h" VelocityWithDensityBCAlgorithm::VelocityWithDensityBCAlgorithm() { - BCAlgorithm::type = BCAlgorithm::VelocityWithDensityBCAlgorithm; - BCAlgorithm::preCollision = false; + BCAlgorithm::type = BCAlgorithm::VelocityWithDensityBCAlgorithm; + BCAlgorithm::preCollision = false; } ////////////////////////////////////////////////////////////////////////// -VelocityWithDensityBCAlgorithm::~VelocityWithDensityBCAlgorithm() -= default; +VelocityWithDensityBCAlgorithm::~VelocityWithDensityBCAlgorithm() = default; ////////////////////////////////////////////////////////////////////////// SPtr<BCAlgorithm> VelocityWithDensityBCAlgorithm::clone() { - SPtr<BCAlgorithm> bc(new VelocityWithDensityBCAlgorithm()); - return bc; + SPtr<BCAlgorithm> bc(new VelocityWithDensityBCAlgorithm()); + return bc; } ////////////////////////////////////////////////////////////////////////// void VelocityWithDensityBCAlgorithm::addDistributions(SPtr<DistributionArray3D> distributions) { - this->distributions = distributions; + this->distributions = distributions; } ////////////////////////////////////////////////////////////////////////// void VelocityWithDensityBCAlgorithm::applyBC() { - //velocity bc for non reflecting pressure bc - LBMReal f[D3Q27System::ENDF+1]; - LBMReal feq[D3Q27System::ENDF+1]; - distributions->getDistributionInv(f, x1, x2, x3); - LBMReal rho, vx1, vx2, vx3, drho; - calcMacrosFct(f, drho, vx1, vx2, vx3); - calcFeqFct(feq, drho, vx1, vx2, vx3); - - rho = 1.0+drho*compressibleFactor; + // velocity bc for non reflecting pressure bc + LBMReal f[D3Q27System::ENDF + 1]; + LBMReal feq[D3Q27System::ENDF + 1]; + distributions->getDistributionInv(f, x1, x2, x3); + LBMReal rho, vx1, vx2, vx3, drho; + calcMacrosFct(f, drho, vx1, vx2, vx3); + calcFeqFct(feq, drho, vx1, vx2, vx3); + + rho = 1.0 + drho * compressibleFactor; - for (int fdir = D3Q27System::FSTARTDIR; fdir <= D3Q27System::FENDDIR; fdir++) - { - //if (bcPtr->hasVelocityBoundaryFlag(fdir)) - //{ - // const int invDir = D3Q27System::INVDIR[fdir]; - // LBMReal q = bcPtr->getQ(invDir);// m+m q=0 stabiler - // LBMReal velocity = bcPtr->getBoundaryVelocity(invDir); - // //normal velocity bc: LBMReal fReturn = ((1.0-q)/(1.0+q))*((f[invDir]-feq[invDir])/(1.0-collFactor)+feq[invDir])+((q*(f[invDir]+f[fdir])-velocity*rho)/(1.0+q)); - // //LBMReal fReturn = ((1.0 - q) / (1.0 + q))*((f[invDir] - feq[invDir]) / (1.0 - collFactor) + feq[invDir]) + ((q*(f[invDir] + f[fdir]) - velocity) / (1.0 + q))-drho*D3Q27System::WEIGTH[invDir]; - // //LBMReal fReturn = ((1.0 - q) / (1.0 + q))*((f[invDir] - feq[invDir]) / (1.0 - collFactor) + feq[invDir]) + ((q*(f[invDir] + f[fdir]) - velocity*rho) / (1.0 + q))-drho*D3Q27System::WEIGTH[invDir]; - // LBMReal fReturn = ((1.0 - q) / (1.0 + q))*((f[invDir] - feq[invDir]*collFactor) / (1.0 - collFactor)) + ((q*(f[invDir] + f[fdir]) - velocity*rho) / (1.0 + q))-drho*D3Q27System::WEIGTH[invDir]; - // - // distributions->setDistributionForDirection(fReturn, x1 + D3Q27System::DX1[invDir], x2 + D3Q27System::DX2[invDir], x3 + D3Q27System::DX3[invDir], fdir); - //} - - int nX1 = x1 + D3Q27System::DX1[fdir]; - int nX2 = x2 + D3Q27System::DX2[fdir]; - int nX3 = x3 + D3Q27System::DX3[fdir]; + for (int fdir = D3Q27System::FSTARTDIR; fdir <= D3Q27System::FENDDIR; fdir++) { + // if (bcPtr->hasVelocityBoundaryFlag(fdir)) + //{ + // const int invDir = D3Q27System::INVDIR[fdir]; + // LBMReal q = bcPtr->getQ(invDir);// m+m q=0 stabiler + // LBMReal velocity = bcPtr->getBoundaryVelocity(invDir); + // //normal velocity bc: LBMReal fReturn = + // ((1.0-q)/(1.0+q))*((f[invDir]-feq[invDir])/(1.0-collFactor)+feq[invDir])+((q*(f[invDir]+f[fdir])-velocity*rho)/(1.0+q)); + // //LBMReal fReturn = ((1.0 - q) / (1.0 + q))*((f[invDir] - feq[invDir]) / (1.0 - collFactor) + feq[invDir]) + // + ((q*(f[invDir] + f[fdir]) - velocity) / (1.0 + q))-drho*D3Q27System::WEIGTH[invDir]; + // //LBMReal fReturn = ((1.0 - q) / (1.0 + q))*((f[invDir] - feq[invDir]) / (1.0 - collFactor) + feq[invDir]) + // + ((q*(f[invDir] + f[fdir]) - velocity*rho) / (1.0 + q))-drho*D3Q27System::WEIGTH[invDir]; LBMReal fReturn + // = ((1.0 - q) / (1.0 + q))*((f[invDir] - feq[invDir]*collFactor) / (1.0 - collFactor)) + ((q*(f[invDir] + + // f[fdir]) - velocity*rho) / (1.0 + q))-drho*D3Q27System::WEIGTH[invDir]; + // + // distributions->setDistributionForDirection(fReturn, x1 + D3Q27System::DX1[invDir], x2 + + // D3Q27System::DX2[invDir], x3 + D3Q27System::DX3[invDir], fdir); + //} - int minX1 = 0; - int minX2 = 0; - int minX3 = 0; + int nX1 = x1 + D3Q27System::DX1[fdir]; + int nX2 = x2 + D3Q27System::DX2[fdir]; + int nX3 = x3 + D3Q27System::DX3[fdir]; - int maxX1 = (int)bcArray->getNX1(); - int maxX2 = (int)bcArray->getNX2(); - int maxX3 = (int)bcArray->getNX3(); + int minX1 = 0; + int minX2 = 0; + int minX3 = 0; - if (minX1 <= nX1 && maxX1 > nX1 && minX2 <= nX2 && maxX2 > nX2 && minX3 <= nX3 && maxX3 > nX3) - { - if (bcArray->isSolid(nX1,nX2,nX3)) - { - const int invDir = D3Q27System::INVDIR[fdir]; -// LBMReal q =1.0;// bcPtr->getQ(invDir);// m+m q=0 stabiler - LBMReal velocity = bcPtr->getBoundaryVelocity(fdir); -// LBMReal fReturn = ((1.0 - q) / (1.0 + q))*((f[fdir] - feq[fdir]*collFactor) / (1.0 - collFactor)) + ((q*(f[fdir] + f[invDir]) - velocity*rho) / (1.0 + q))-drho*D3Q27System::WEIGTH[invDir]; + int maxX1 = (int)bcArray->getNX1(); + int maxX2 = (int)bcArray->getNX2(); + int maxX3 = (int)bcArray->getNX3(); - //if q=1 - //LBMReal fReturn = ((q*(f[fdir] + f[invDir]) - velocity*rho) / (1.0 + q))-drho*D3Q27System::WEIGTH[invDir]; - LBMReal fReturn = (f[fdir] + f[invDir] - velocity*rho) / 2.0 - drho*D3Q27System::WEIGTH[invDir]; + if (minX1 <= nX1 && maxX1 > nX1 && minX2 <= nX2 && maxX2 > nX2 && minX3 <= nX3 && maxX3 > nX3) { + if (bcArray->isSolid(nX1, nX2, nX3)) { + const int invDir = D3Q27System::INVDIR[fdir]; + // LBMReal q =1.0;// bcPtr->getQ(invDir);// m+m q=0 stabiler + LBMReal velocity = bcPtr->getBoundaryVelocity(fdir); + // LBMReal fReturn = ((1.0 - q) / (1.0 + q))*((f[fdir] - feq[fdir]*collFactor) / (1.0 - + // collFactor)) + ((q*(f[fdir] + f[invDir]) - velocity*rho) / (1.0 + + // q))-drho*D3Q27System::WEIGTH[invDir]; - distributions->setDistributionForDirection(fReturn, nX1, nX2, nX3, invDir); - } - } + // if q=1 + // LBMReal fReturn = ((q*(f[fdir] + f[invDir]) - velocity*rho) / (1.0 + + // q))-drho*D3Q27System::WEIGTH[invDir]; + LBMReal fReturn = (f[fdir] + f[invDir] - velocity * rho) / 2.0 - drho * D3Q27System::WEIGTH[invDir]; - } + distributions->setDistributionForDirection(fReturn, nX1, nX2, nX3, invDir); + } + } + } } diff --git a/src/cpu/VirtualFluidsCore/BoundaryConditions/VelocityWithDensityBCAlgorithm.h b/src/cpu/VirtualFluidsCore/BoundaryConditions/VelocityWithDensityBCAlgorithm.h index 2216501db041d68b815c0f37b8a3cd0308ca3cba..c590bd4a97dfc5f4f56999116dcb720ccfeefeab 100644 --- a/src/cpu/VirtualFluidsCore/BoundaryConditions/VelocityWithDensityBCAlgorithm.h +++ b/src/cpu/VirtualFluidsCore/BoundaryConditions/VelocityWithDensityBCAlgorithm.h @@ -10,15 +10,16 @@ class DistributionArray3D; -//! \brief Class implements Dirichlet boundary condition for velocity. Set density in system. It is used together with non reflecting outflow. +//! \brief Class implements Dirichlet boundary condition for velocity. Set density in system. It is used together with +//! non reflecting outflow. class VelocityWithDensityBCAlgorithm : public BCAlgorithm { public: - VelocityWithDensityBCAlgorithm(); - ~VelocityWithDensityBCAlgorithm() override; - SPtr<BCAlgorithm> clone() override; - void addDistributions(SPtr<DistributionArray3D> distributions) override; - void applyBC() override; + VelocityWithDensityBCAlgorithm(); + ~VelocityWithDensityBCAlgorithm() override; + SPtr<BCAlgorithm> clone() override; + void addDistributions(SPtr<DistributionArray3D> distributions) override; + void applyBC() override; }; #endif // NonReflectingVelocityBCAlgorithm_h__ diff --git a/src/cpu/VirtualFluidsCore/CoProcessors/AdjustForcingCoProcessor.cpp b/src/cpu/VirtualFluidsCore/CoProcessors/AdjustForcingCoProcessor.cpp index eda63069e6103c1360e16288fd7ea86e5b89d926..2174090103ddfd5c806d62cb30a8e1567403251c 100644 --- a/src/cpu/VirtualFluidsCore/CoProcessors/AdjustForcingCoProcessor.cpp +++ b/src/cpu/VirtualFluidsCore/CoProcessors/AdjustForcingCoProcessor.cpp @@ -1,168 +1,166 @@ /* -* D3Q27AdjustForcingCoProcessor.cpp -* Author: Konstantin Kutscher -*/ + * D3Q27AdjustForcingCoProcessor.cpp + * Author: Konstantin Kutscher + */ #include "AdjustForcingCoProcessor.h" #include <fstream> -#include <SetForcingBlockVisitor.h> -#include "IntegrateValuesHelper.h" #include "Communicator.h" -#include "UbScheduler.h" #include "Grid3D.h" +#include "IntegrateValuesHelper.h" +#include "UbScheduler.h" +#include <SetForcingBlockVisitor.h> + +AdjustForcingCoProcessor::AdjustForcingCoProcessor(SPtr<Grid3D> grid, SPtr<UbScheduler> s, const std::string &path, + SPtr<IntegrateValuesHelper> integrateValues, double vTarged, + SPtr<Communicator> comm) -AdjustForcingCoProcessor::AdjustForcingCoProcessor(SPtr<Grid3D> grid, SPtr<UbScheduler> s, - const std::string& path, - SPtr<IntegrateValuesHelper> integrateValues, - double vTarged, - SPtr<Communicator> comm) - - : CoProcessor(grid, s), - path(path), - integrateValues(integrateValues), - comm(comm), - vx1Targed(vTarged) + : CoProcessor(grid, s), path(path), integrateValues(integrateValues), comm(comm), vx1Targed(vTarged) { - //cnodes = integrateValues->getCNodes(); - root = comm->isRoot(); - - Ta = scheduler->getMaxStep(); - - Kpcrit = 3.0 / Ta;// 0.3; - Tcrit = 3.0 * Ta; // 30.0; - Tn = 0.5 * Tcrit; - Tv = 0.12 * Tcrit; - - Kp = 0.6 * Kpcrit; - Ki = Kp / Tn; - Kd = Kp * Tv; - - y = 0; - e = 0; - esum = 0; - eold = 0; - forcing = 0; - - if (root) - { - std::string fname = path + "/forcing/forcing.csv"; - std::ofstream ostr; - ostr.open(fname.c_str(), std::ios_base::out | std::ios_base::app); - if (!ostr) - { - ostr.clear(); - std::string file_path = UbSystem::getPathFromString(fname); - if (file_path.size() > 0) { UbSystem::makeDirectory(file_path); ostr.open(fname.c_str(), std::ios_base::out | std::ios_base::app); } - if (!ostr) throw UbException(UB_EXARGS, "couldn't open file " + fname); - } - ostr << "step;volume;vx1average;forcing\n"; - ostr.close(); - - ////////////////////////////////////////////////////////////////////////////////////////////////// - //temporary solution - std::string fNameCfg = path + "/forcing/forcing.cfg"; - std::ifstream istr2; - istr2.open(fNameCfg.c_str(), std::ios_base::in); - if (istr2) - { - istr2 >> forcing; - //istr2 >> esum; - //istr2 >> eold; - } - istr2.close(); - } - //////////////////////////////////////////////////////////////////////////////////////////////////////// + // cnodes = integrateValues->getCNodes(); + root = comm->isRoot(); + + Ta = scheduler->getMaxStep(); + + Kpcrit = 3.0 / Ta; // 0.3; + Tcrit = 3.0 * Ta; // 30.0; + Tn = 0.5 * Tcrit; + Tv = 0.12 * Tcrit; + + Kp = 0.6 * Kpcrit; + Ki = Kp / Tn; + Kd = Kp * Tv; + + y = 0; + e = 0; + esum = 0; + eold = 0; + forcing = 0; + + if (root) { + std::string fname = path + "/forcing/forcing.csv"; + std::ofstream ostr; + ostr.open(fname.c_str(), std::ios_base::out | std::ios_base::app); + if (!ostr) { + ostr.clear(); + std::string file_path = UbSystem::getPathFromString(fname); + if (file_path.size() > 0) { + UbSystem::makeDirectory(file_path); + ostr.open(fname.c_str(), std::ios_base::out | std::ios_base::app); + } + if (!ostr) + throw UbException(UB_EXARGS, "couldn't open file " + fname); + } + ostr << "step;volume;vx1average;forcing\n"; + ostr.close(); + + ////////////////////////////////////////////////////////////////////////////////////////////////// + // temporary solution + std::string fNameCfg = path + "/forcing/forcing.cfg"; + std::ifstream istr2; + istr2.open(fNameCfg.c_str(), std::ios_base::in); + if (istr2) { + istr2 >> forcing; + // istr2 >> esum; + // istr2 >> eold; + } + istr2.close(); + } + //////////////////////////////////////////////////////////////////////////////////////////////////////// } ////////////////////////////////////////////////////////////////////////// void AdjustForcingCoProcessor::process(double step) { - if (scheduler->isDue(step)) - collectData(step); + if (scheduler->isDue(step)) + collectData(step); } ////////////////////////////////////////////////////////////////////////// void AdjustForcingCoProcessor::collectData(double step) { - ////////////////////////////////////////////////////////////////////////////////////////////////// - //temporary solution - if (root) - { - std::string fNameCfg = path + "/forcing/forcing.cfg"; - std::ofstream ostr2; - ostr2.open(fNameCfg.c_str(), std::ios_base::out); - if (!ostr2) - { - ostr2.clear(); - std::string path = UbSystem::getPathFromString(fNameCfg); - if (path.size() > 0) { UbSystem::makeDirectory(path); ostr2.open(fNameCfg.c_str(), std::ios_base::out); } - if (!ostr2) throw UbException(UB_EXARGS, "couldn't open file " + fNameCfg); - } - ostr2 << forcing << " " << esum << " " << eold; - ostr2.close(); - } - //////////////////////////////////////////////////////////////////////////////////////////////////////// - - integrateValues->calculateMQ(); - - if (root) - { - cellsVolume = integrateValues->getCellsVolume(); - double vx1 = integrateValues->getVx1(); - vx1Average = (vx1 / cellsVolume); - - ////////////////////////////////////////////////////////////////////////// - //PID-Controller (PID-Regler) - e = vx1Targed - vx1Average; - esum = esum + e; - y = Kp * e + Ki * Ta * esum + Kd * (e - eold) / Ta; - eold = e; - - forcing = forcing + y; - ////////////////////////////////////////////////////////////////////////// - } - ////////////////////////////////////////////////////////////////////////// - comm->broadcast(forcing); - - mu::Parser fctForcingX1, fctForcingX2, fctForcingX3; - fctForcingX1.SetExpr("Fx1"); - fctForcingX1.DefineConst("Fx1", forcing); - fctForcingX2.SetExpr("0.0"); - fctForcingX3.SetExpr("0.0"); - SetForcingBlockVisitor forcingVisitor(fctForcingX1, fctForcingX2, fctForcingX3); - grid->accept(forcingVisitor); - - //for(CalcNodes cn : cnodes) - //{ - // LBMKernel3DPtr kernel = cn.block->getKernel(); - // if (kernel) - // { - // kernel->setForcingX1(fctForcingX1); - // kernel->setWithForcing(true); - // } - // - //} - - if (root) - { - //UBLOG(logINFO, "D3Q27AdjustForcingCoProcessor step: " << static_cast<int>(step)); - //UBLOG(logINFO, "new forcing is: " << forcing); - std::string fname = path + "/forcing/forcing.csv"; - //std::string fname = path + "/forcing/forcing_"+UbSystem::toString(comm->getProcessID())+".csv"; - std::ofstream ostr; - ostr.open(fname.c_str(), std::ios_base::out | std::ios_base::app); - if (!ostr) - { - ostr.clear(); - std::string path = UbSystem::getPathFromString(fname); - if (path.size() > 0) { UbSystem::makeDirectory(path); ostr.open(fname.c_str(), std::ios_base::out | std::ios_base::app); } - if (!ostr) throw UbException(UB_EXARGS, "couldn't open file " + fname); - } - int istep = static_cast<int>(step); - - //ostr << istep << ";" << cellsVolume << ";" << vx1Average << "; " << forcing << "\n"; - ostr << istep << ";" << cellsVolume << ";" << vx1Average << "; " << forcing << "; " << e << "; " << esum << "; " << y <<"\n"; - ostr.close(); - - } + ////////////////////////////////////////////////////////////////////////////////////////////////// + // temporary solution + if (root) { + std::string fNameCfg = path + "/forcing/forcing.cfg"; + std::ofstream ostr2; + ostr2.open(fNameCfg.c_str(), std::ios_base::out); + if (!ostr2) { + ostr2.clear(); + std::string path = UbSystem::getPathFromString(fNameCfg); + if (path.size() > 0) { + UbSystem::makeDirectory(path); + ostr2.open(fNameCfg.c_str(), std::ios_base::out); + } + if (!ostr2) + throw UbException(UB_EXARGS, "couldn't open file " + fNameCfg); + } + ostr2 << forcing << " " << esum << " " << eold; + ostr2.close(); + } + //////////////////////////////////////////////////////////////////////////////////////////////////////// + + integrateValues->calculateMQ(); + + if (root) { + cellsVolume = integrateValues->getCellsVolume(); + double vx1 = integrateValues->getVx1(); + vx1Average = (vx1 / cellsVolume); + + ////////////////////////////////////////////////////////////////////////// + // PID-Controller (PID-Regler) + e = vx1Targed - vx1Average; + esum = esum + e; + y = Kp * e + Ki * Ta * esum + Kd * (e - eold) / Ta; + eold = e; + + forcing = forcing + y; + ////////////////////////////////////////////////////////////////////////// + } + ////////////////////////////////////////////////////////////////////////// + comm->broadcast(forcing); + + mu::Parser fctForcingX1, fctForcingX2, fctForcingX3; + fctForcingX1.SetExpr("Fx1"); + fctForcingX1.DefineConst("Fx1", forcing); + fctForcingX2.SetExpr("0.0"); + fctForcingX3.SetExpr("0.0"); + SetForcingBlockVisitor forcingVisitor(fctForcingX1, fctForcingX2, fctForcingX3); + grid->accept(forcingVisitor); + + // for(CalcNodes cn : cnodes) + //{ + // LBMKernel3DPtr kernel = cn.block->getKernel(); + // if (kernel) + // { + // kernel->setForcingX1(fctForcingX1); + // kernel->setWithForcing(true); + // } + // + //} + + if (root) { + // UBLOG(logINFO, "D3Q27AdjustForcingCoProcessor step: " << static_cast<int>(step)); + // UBLOG(logINFO, "new forcing is: " << forcing); + std::string fname = path + "/forcing/forcing.csv"; + // std::string fname = path + "/forcing/forcing_"+UbSystem::toString(comm->getProcessID())+".csv"; + std::ofstream ostr; + ostr.open(fname.c_str(), std::ios_base::out | std::ios_base::app); + if (!ostr) { + ostr.clear(); + std::string path = UbSystem::getPathFromString(fname); + if (path.size() > 0) { + UbSystem::makeDirectory(path); + ostr.open(fname.c_str(), std::ios_base::out | std::ios_base::app); + } + if (!ostr) + throw UbException(UB_EXARGS, "couldn't open file " + fname); + } + int istep = static_cast<int>(step); + + // ostr << istep << ";" << cellsVolume << ";" << vx1Average << "; " << forcing << "\n"; + ostr << istep << ";" << cellsVolume << ";" << vx1Average << "; " << forcing << "; " << e << "; " << esum << "; " + << y << "\n"; + ostr.close(); + } } diff --git a/src/cpu/VirtualFluidsCore/CoProcessors/AdjustForcingCoProcessor.h b/src/cpu/VirtualFluidsCore/CoProcessors/AdjustForcingCoProcessor.h index 87962f89e33ca2f1d45f203e5ab1dc0a028868b8..93b99dadab125f87a12b1e905c3171559a5ea31f 100644 --- a/src/cpu/VirtualFluidsCore/CoProcessors/AdjustForcingCoProcessor.h +++ b/src/cpu/VirtualFluidsCore/CoProcessors/AdjustForcingCoProcessor.h @@ -6,52 +6,52 @@ #include "CoProcessor.h" - class Communicator; class UbScheduler; class Grid3D; class IntegrateValuesHelper; -//! \brief Computes forcing such that a given velocity (vx1Targed) is reached inside an averaging domain (h1). -//! \details Algorithm based on PID controller (proportional_integral_derivative controller). The parameters of PID controller estimation based on Ziegler�Nichols method. +//! \brief Computes forcing such that a given velocity (vx1Targed) is reached inside an averaging domain (h1). +//! \details Algorithm based on PID controller (proportional_integral_derivative controller). The parameters of PID +//! controller estimation based on Ziegler�Nichols method. //! Integrate values helper, scheduler must be set in test case. //! \author: Konstantin Kutscher -class AdjustForcingCoProcessor: public CoProcessor { +class AdjustForcingCoProcessor : public CoProcessor +{ public: - AdjustForcingCoProcessor(SPtr<Grid3D> grid, SPtr<UbScheduler> s, - const std::string& path, - SPtr<IntegrateValuesHelper> integrateValues, - double vTarged, SPtr<Communicator> comm); - //!< calls collect PostprocessData - void process(double step) override; + AdjustForcingCoProcessor(SPtr<Grid3D> grid, SPtr<UbScheduler> s, const std::string &path, + SPtr<IntegrateValuesHelper> integrateValues, double vTarged, SPtr<Communicator> comm); + //!< calls collect PostprocessData + void process(double step) override; + protected: - //!< object that can compute spacial average values in 3D-subdomain. + //!< object that can compute spacial average values in 3D-subdomain. SPtr<IntegrateValuesHelper> integrateValues; - //!< compares velocity in integrateValues with target velocity and adjusts forcing accordingly. - void collectData(double step); + //!< compares velocity in integrateValues with target velocity and adjusts forcing accordingly. + void collectData(double step); SPtr<Communicator> comm; + private: - double vx1Targed; //!< target velocity. - double forcing; //!< forcing at previous update step. - double cellsVolume; - double vx1Average; - bool root; - double Kpcrit; //Kp critical - double Tcrit; //the oscillation period - double Tn; - double Tv; - double e; - double Ta; - double Kp; - double Ki; - double Kd; - double y; - double esum; - double eold; - //std::vector<CalcNodes> cnodes; - std::string path; + double vx1Targed; //!< target velocity. + double forcing; //!< forcing at previous update step. + double cellsVolume; + double vx1Average; + bool root; + double Kpcrit; // Kp critical + double Tcrit; // the oscillation period + double Tn; + double Tv; + double e; + double Ta; + double Kp; + double Ki; + double Kd; + double y; + double esum; + double eold; + // std::vector<CalcNodes> cnodes; + std::string path; }; - #endif /* D3Q27RHODIFFERENCECoProcessor_H_ */ diff --git a/src/cpu/VirtualFluidsCore/CoProcessors/AverageValuesCoProcessor.cpp b/src/cpu/VirtualFluidsCore/CoProcessors/AverageValuesCoProcessor.cpp index 3cc990b9683de12169d1af26b2d5defd9e10f67c..3684a5791510ed2880ee366403526655f38d7b75 100644 --- a/src/cpu/VirtualFluidsCore/CoProcessors/AverageValuesCoProcessor.cpp +++ b/src/cpu/VirtualFluidsCore/CoProcessors/AverageValuesCoProcessor.cpp @@ -1,486 +1,460 @@ #include "AverageValuesCoProcessor.h" -#include "LBMKernel.h" #include "BCProcessor.h" +#include "LBMKernel.h" #include "basics/writer/WbWriterVtkXmlASCII.h" +#include "BCArray3D.h" +#include "Block3D.h" +#include "Communicator.h" #include "DataSet3D.h" -#include "WbWriter.h" #include "Grid3D.h" -#include "Block3D.h" #include "UbScheduler.h" -#include "Communicator.h" -#include "BCArray3D.h" +#include "WbWriter.h" using namespace std; -AverageValuesCoProcessor::AverageValuesCoProcessor() -= default; +AverageValuesCoProcessor::AverageValuesCoProcessor() = default; ////////////////////////////////////////////////////////////////////////// -AverageValuesCoProcessor::AverageValuesCoProcessor(SPtr<Grid3D> grid, const std::string& path, WbWriter* const writer, - SPtr<UbScheduler> s, SPtr<UbScheduler> Avs, SPtr<UbScheduler> rsMeans, SPtr<UbScheduler> rsRMS, bool restart) - : CoProcessor(grid, s), - averageScheduler(Avs), - resetSchedulerMeans(rsMeans), - resetSchedulerRMS(rsRMS), - path(path), - writer(writer) +AverageValuesCoProcessor::AverageValuesCoProcessor(SPtr<Grid3D> grid, const std::string &path, WbWriter *const writer, + SPtr<UbScheduler> s, SPtr<UbScheduler> Avs, + SPtr<UbScheduler> rsMeans, SPtr<UbScheduler> rsRMS, bool restart) + : CoProcessor(grid, s), averageScheduler(Avs), resetSchedulerMeans(rsMeans), resetSchedulerRMS(rsRMS), path(path), + writer(writer) { - resetStepMeans = (int)rsMeans->getMinBegin(); - resetStepRMS = (int)rsRMS->getMinBegin(); - averageInterval = (double)Avs->getMinStep(); - - gridRank = grid->getRank(); - minInitLevel = this->grid->getCoarsestInitializedLevel(); - maxInitLevel = this->grid->getFinestInitializedLevel(); - - blockVector.resize(maxInitLevel+1); - - for(int level = minInitLevel; level<=maxInitLevel;level++) - { - grid->getBlocks(level, gridRank, true, blockVector[level]); - - if (blockVector[level].size() > 0) - compressible = blockVector[level][0]->getKernel()->getCompressible(); - - if (!restart) - { - for(SPtr<Block3D> block : blockVector[level]) - { - UbTupleInt3 nx = grid->getBlockNX(); - SPtr<AverageValuesArray3D> averageValues = SPtr<AverageValuesArray3D>(new AverageValuesArray3D(11, val<1>(nx)+1, val<2>(nx)+1, val<3>(nx)+1, 0.0)); - block->getKernel()->getDataSet()->setAverageValues(averageValues); - } - } - } - - // for musis special use - //initPlotDataZ(0.0); - //restartStep = 0.0; + resetStepMeans = (int)rsMeans->getMinBegin(); + resetStepRMS = (int)rsRMS->getMinBegin(); + averageInterval = (double)Avs->getMinStep(); + + gridRank = grid->getRank(); + minInitLevel = this->grid->getCoarsestInitializedLevel(); + maxInitLevel = this->grid->getFinestInitializedLevel(); + + blockVector.resize(maxInitLevel + 1); + + for (int level = minInitLevel; level <= maxInitLevel; level++) { + grid->getBlocks(level, gridRank, true, blockVector[level]); + + if (blockVector[level].size() > 0) + compressible = blockVector[level][0]->getKernel()->getCompressible(); + + if (!restart) { + for (SPtr<Block3D> block : blockVector[level]) { + UbTupleInt3 nx = grid->getBlockNX(); + SPtr<AverageValuesArray3D> averageValues = SPtr<AverageValuesArray3D>( + new AverageValuesArray3D(11, val<1>(nx) + 1, val<2>(nx) + 1, val<3>(nx) + 1, 0.0)); + block->getKernel()->getDataSet()->setAverageValues(averageValues); + } + } + } + + // for musis special use + // initPlotDataZ(0.0); + // restartStep = 0.0; } ////////////////////////////////////////////////////////////////////////// void AverageValuesCoProcessor::process(double step) { - //resetRMS(step); - if(resetSchedulerRMS->isDue(step) ) - resetDataRMS(step); - - //reset(step); - if(resetSchedulerMeans->isDue(step) ) - resetDataMeans(step); - - if(averageScheduler->isDue(step) ){ - calculateAverageValues(step); - // for musis special use - //collectPlotDataZ(step); - } - if(scheduler->isDue(step) ){ - collectData(step); - - } - - UBLOG(logDEBUG3, "AverageValuesCoProcessor::update:" << step); + // resetRMS(step); + if (resetSchedulerRMS->isDue(step)) + resetDataRMS(step); + + // reset(step); + if (resetSchedulerMeans->isDue(step)) + resetDataMeans(step); + + if (averageScheduler->isDue(step)) { + calculateAverageValues(step); + // for musis special use + // collectPlotDataZ(step); + } + if (scheduler->isDue(step)) { + collectData(step); + } + + UBLOG(logDEBUG3, "AverageValuesCoProcessor::update:" << step); } void AverageValuesCoProcessor::resetDataRMS(double step) { - resetStepRMS=(int)step; - - for(int level = minInitLevel; level<=maxInitLevel;level++) - { - for(SPtr<Block3D> block : blockVector[level]) - { - if (block) - { - SPtr<ILBMKernel> kernel = block->getKernel(); - SPtr<BCArray3D> bcArray = kernel->getBCProcessor()->getBCArray(); - SPtr<DistributionArray3D> distributions = kernel->getDataSet()->getFdistributions(); - SPtr<AverageValuesArray3D> av = kernel->getDataSet()->getAverageValues(); - - int minX1 = 0; - int minX2 = 0; - int minX3 = 0; - - int maxX1 = int(distributions->getNX1()); - int maxX2 = int(distributions->getNX2()); - int maxX3 = int(distributions->getNX3()); - - for(int ix3=minX3; ix3<maxX3-1; ix3++) - { - for(int ix2=minX2; ix2<maxX2-1; ix2++) - { - for(int ix1=minX1; ix1<maxX1-1; ix1++) - { - if(!bcArray->isUndefined(ix1,ix2,ix3) && !bcArray->isSolid(ix1,ix2,ix3)) - { - ////////////////////////////////////////////////////////////////////////// - //compute average values - ////////////////////////////////////////////////////////////////////////// - (*av)(AvVxx,ix1,ix2,ix3) = 0.0; - (*av)(AvVyy,ix1,ix2,ix3) = 0.0; - (*av)(AvVzz,ix1,ix2,ix3) = 0.0; - (*av)(AvVxy,ix1,ix2,ix3) = 0.0; - (*av)(AvVxz,ix1,ix2,ix3) = 0.0; - (*av)(AvVyz,ix1,ix2,ix3) = 0.0; - (*av)(AvPrms,ix1,ix2,ix3) = 0.0; - ////////////////////////////////////////////////////////////////////////// - } - } - } - } - } - } - } + resetStepRMS = (int)step; + + for (int level = minInitLevel; level <= maxInitLevel; level++) { + for (SPtr<Block3D> block : blockVector[level]) { + if (block) { + SPtr<ILBMKernel> kernel = block->getKernel(); + SPtr<BCArray3D> bcArray = kernel->getBCProcessor()->getBCArray(); + SPtr<DistributionArray3D> distributions = kernel->getDataSet()->getFdistributions(); + SPtr<AverageValuesArray3D> av = kernel->getDataSet()->getAverageValues(); + + int minX1 = 0; + int minX2 = 0; + int minX3 = 0; + + int maxX1 = int(distributions->getNX1()); + int maxX2 = int(distributions->getNX2()); + int maxX3 = int(distributions->getNX3()); + + for (int ix3 = minX3; ix3 < maxX3 - 1; ix3++) { + for (int ix2 = minX2; ix2 < maxX2 - 1; ix2++) { + for (int ix1 = minX1; ix1 < maxX1 - 1; ix1++) { + if (!bcArray->isUndefined(ix1, ix2, ix3) && !bcArray->isSolid(ix1, ix2, ix3)) { + ////////////////////////////////////////////////////////////////////////// + // compute average values + ////////////////////////////////////////////////////////////////////////// + (*av)(AvVxx, ix1, ix2, ix3) = 0.0; + (*av)(AvVyy, ix1, ix2, ix3) = 0.0; + (*av)(AvVzz, ix1, ix2, ix3) = 0.0; + (*av)(AvVxy, ix1, ix2, ix3) = 0.0; + (*av)(AvVxz, ix1, ix2, ix3) = 0.0; + (*av)(AvVyz, ix1, ix2, ix3) = 0.0; + (*av)(AvPrms, ix1, ix2, ix3) = 0.0; + ////////////////////////////////////////////////////////////////////////// + } + } + } + } + } + } + } } ////////////////////////////////////////////////////////////////////////// void AverageValuesCoProcessor::resetDataMeans(double step) { - resetStepMeans=(int)step; - - for(int level = minInitLevel; level<=maxInitLevel;level++) - { - for(SPtr<Block3D> block : blockVector[level]) - { - if (block) - { - SPtr<ILBMKernel> kernel = block->getKernel(); - SPtr<BCArray3D> bcArray = kernel->getBCProcessor()->getBCArray(); - SPtr<DistributionArray3D> distributions = kernel->getDataSet()->getFdistributions(); - SPtr<AverageValuesArray3D> av = kernel->getDataSet()->getAverageValues(); - - int minX1 = 0; - int minX2 = 0; - int minX3 = 0; - - int maxX1 = int(distributions->getNX1()); - int maxX2 = int(distributions->getNX2()); - int maxX3 = int(distributions->getNX3()); - - for(int ix3=minX3; ix3<maxX3-1; ix3++) - { - for(int ix2=minX2; ix2<maxX2-1; ix2++) - { - for(int ix1=minX1; ix1<maxX1-1; ix1++) - { - if(!bcArray->isUndefined(ix1,ix2,ix3) && !bcArray->isSolid(ix1,ix2,ix3)) - { - ////////////////////////////////////////////////////////////////////////// - //compute average values - ////////////////////////////////////////////////////////////////////////// - (*av)(AvVx,ix1,ix2,ix3) = 0.0; - (*av)(AvVy,ix1,ix2,ix3) = 0.0; - (*av)(AvVz,ix1,ix2,ix3) = 0.0; - (*av)(AvP,ix1,ix2,ix3) = 0.0; - ////////////////////////////////////////////////////////////////////////// - } - } - } - } - } - } - } + resetStepMeans = (int)step; + + for (int level = minInitLevel; level <= maxInitLevel; level++) { + for (SPtr<Block3D> block : blockVector[level]) { + if (block) { + SPtr<ILBMKernel> kernel = block->getKernel(); + SPtr<BCArray3D> bcArray = kernel->getBCProcessor()->getBCArray(); + SPtr<DistributionArray3D> distributions = kernel->getDataSet()->getFdistributions(); + SPtr<AverageValuesArray3D> av = kernel->getDataSet()->getAverageValues(); + + int minX1 = 0; + int minX2 = 0; + int minX3 = 0; + + int maxX1 = int(distributions->getNX1()); + int maxX2 = int(distributions->getNX2()); + int maxX3 = int(distributions->getNX3()); + + for (int ix3 = minX3; ix3 < maxX3 - 1; ix3++) { + for (int ix2 = minX2; ix2 < maxX2 - 1; ix2++) { + for (int ix1 = minX1; ix1 < maxX1 - 1; ix1++) { + if (!bcArray->isUndefined(ix1, ix2, ix3) && !bcArray->isSolid(ix1, ix2, ix3)) { + ////////////////////////////////////////////////////////////////////////// + // compute average values + ////////////////////////////////////////////////////////////////////////// + (*av)(AvVx, ix1, ix2, ix3) = 0.0; + (*av)(AvVy, ix1, ix2, ix3) = 0.0; + (*av)(AvVz, ix1, ix2, ix3) = 0.0; + (*av)(AvP, ix1, ix2, ix3) = 0.0; + ////////////////////////////////////////////////////////////////////////// + } + } + } + } + } + } + } } ////////////////////////////////////////////////////////////////////////// void AverageValuesCoProcessor::collectData(double step) { - int istep = int(step); - - for(int level = minInitLevel; level<=maxInitLevel;level++) - { - for(SPtr<Block3D> block : blockVector[level]) - { - if (block) - { - addData(block); - } - } - } - - string pfilePath, partPath, subfolder, cfilePath; - subfolder = "av"+UbSystem::toString(istep); - pfilePath = path+"/av/"+subfolder; - cfilePath = path+"/av/av_collection"; - partPath = pfilePath+"/av"+UbSystem::toString(gridRank)+ "_" + UbSystem::toString(istep); - - string partName = writer->writeOctsWithNodeData(partPath,nodes,cells,datanames,data); - size_t found=partName.find_last_of("/"); - string piece = partName.substr(found+1); - piece = subfolder + "/" + piece; - - vector<string> cellDataNames; - SPtr<Communicator> comm = Communicator::getInstance(); - vector<string> pieces = comm->gather(piece); - if (comm->getProcessID() == comm->getRoot()) - { - string pname = WbWriterVtkXmlASCII::getInstance()->writeParallelFile(pfilePath,pieces,datanames,cellDataNames); - found=pname.find_last_of("/"); - piece = pname.substr(found+1); - - vector<string> filenames; - filenames.push_back(piece); - if (step == CoProcessor::scheduler->getMinBegin()) - { - WbWriterVtkXmlASCII::getInstance()->writeCollection(cfilePath,filenames,istep,false); - } - else - { - WbWriterVtkXmlASCII::getInstance()->addFilesToCollection(cfilePath,filenames,istep,false); - } - UBLOG(logINFO,"AverageValuesCoProcessor step: " << istep); - } - - clearData(); + int istep = int(step); + + for (int level = minInitLevel; level <= maxInitLevel; level++) { + for (SPtr<Block3D> block : blockVector[level]) { + if (block) { + addData(block); + } + } + } + + string pfilePath, partPath, subfolder, cfilePath; + subfolder = "av" + UbSystem::toString(istep); + pfilePath = path + "/av/" + subfolder; + cfilePath = path + "/av/av_collection"; + partPath = pfilePath + "/av" + UbSystem::toString(gridRank) + "_" + UbSystem::toString(istep); + + string partName = writer->writeOctsWithNodeData(partPath, nodes, cells, datanames, data); + size_t found = partName.find_last_of("/"); + string piece = partName.substr(found + 1); + piece = subfolder + "/" + piece; + + vector<string> cellDataNames; + SPtr<Communicator> comm = Communicator::getInstance(); + vector<string> pieces = comm->gather(piece); + if (comm->getProcessID() == comm->getRoot()) { + string pname = + WbWriterVtkXmlASCII::getInstance()->writeParallelFile(pfilePath, pieces, datanames, cellDataNames); + found = pname.find_last_of("/"); + piece = pname.substr(found + 1); + + vector<string> filenames; + filenames.push_back(piece); + if (step == CoProcessor::scheduler->getMinBegin()) { + WbWriterVtkXmlASCII::getInstance()->writeCollection(cfilePath, filenames, istep, false); + } else { + WbWriterVtkXmlASCII::getInstance()->addFilesToCollection(cfilePath, filenames, istep, false); + } + UBLOG(logINFO, "AverageValuesCoProcessor step: " << istep); + } + + clearData(); } ////////////////////////////////////////////////////////////////////////// void AverageValuesCoProcessor::clearData() { - nodes.clear(); - cells.clear(); - datanames.clear(); - data.clear(); + nodes.clear(); + cells.clear(); + datanames.clear(); + data.clear(); } ////////////////////////////////////////////////////////////////////////// void AverageValuesCoProcessor::addData(const SPtr<Block3D> block) { - UbTupleDouble3 org = grid->getBlockWorldCoordinates(block); -// UbTupleDouble3 blockLengths = grid->getBlockLengths(block); - UbTupleDouble3 nodeOffset = grid->getNodeOffset(block); - double dx = grid->getDeltaX(block); - - //Diese Daten werden geschrieben: - datanames.resize(0); - datanames.emplace_back("AvVx"); - datanames.emplace_back("AvVy"); - datanames.emplace_back("AvVz"); - datanames.emplace_back("AvVxx"); - datanames.emplace_back("AvVyy"); - datanames.emplace_back("AvVzz"); - datanames.emplace_back("AvVxy"); - datanames.emplace_back("AvVxz"); - datanames.emplace_back("AvVyz"); - datanames.emplace_back("AvP"); - datanames.emplace_back("AvPrms"); - - - data.resize(datanames.size()); - - SPtr<ILBMKernel> kernel = block->getKernel(); - SPtr<BCArray3D> bcArray = kernel->getBCProcessor()->getBCArray(); - SPtr<DistributionArray3D> distributions = kernel->getDataSet()->getFdistributions(); - SPtr<AverageValuesArray3D> av = kernel->getDataSet()->getAverageValues(); - //int ghostLayerWidth = kernel->getGhostLayerWidth(); - - //knotennummerierung faengt immer bei 0 an! - unsigned int SWB,SEB,NEB,NWB,SWT,SET,NET,NWT; - - int minX1 = 0; - int minX2 = 0; - int minX3 = 0; - - int maxX1 = int(distributions->getNX1()); - int maxX2 = int(distributions->getNX2()); - int maxX3 = int(distributions->getNX3()); - - //nummern vergeben und node vector erstellen + daten sammeln - CbArray3D<int> nodeNumbers((int)maxX1, (int)maxX2, (int)maxX3,-1); - - maxX1 -= 2; - maxX2 -= 2; - maxX3 -= 2; - - //D3Q27BoundaryConditionPtr bcPtr; - - int nr = (int)nodes.size(); - - for(int ix3=minX3; ix3<=maxX3; ix3++) - { - for(int ix2=minX2; ix2<=maxX2; ix2++) - { - for(int ix1=minX1; ix1<=maxX1; ix1++) - { - if(!bcArray->isUndefined(ix1,ix2,ix3) && !bcArray->isSolid(ix1,ix2,ix3)) - { - int index = 0; - nodeNumbers(ix1,ix2,ix3) = nr++; - nodes.push_back( makeUbTuple(float(val<1>(org) - val<1>(nodeOffset) + ix1*dx), - float(val<2>(org) - val<2>(nodeOffset) + ix2*dx), - float(val<3>(org) - val<3>(nodeOffset) + ix3*dx)) ); - - LBMReal vx=(*av)(AvVx,ix1,ix2,ix3); - LBMReal vy=(*av)(AvVy,ix1,ix2,ix3); - LBMReal vz=(*av)(AvVz,ix1,ix2,ix3); - - LBMReal vxx=(*av)(AvVxx,ix1,ix2,ix3); - LBMReal vyy=(*av)(AvVyy,ix1,ix2,ix3); - LBMReal vzz=(*av)(AvVzz,ix1,ix2,ix3); - - LBMReal vxy=(*av)(AvVxy,ix1,ix2,ix3); - LBMReal vxz=(*av)(AvVxz,ix1,ix2,ix3); - LBMReal vyz=(*av)(AvVyz,ix1,ix2,ix3); - - LBMReal vp=(*av)(AvP,ix1,ix2,ix3); - LBMReal vprms=(*av)(AvPrms,ix1,ix2,ix3); - - - data[index++].push_back(vx); - data[index++].push_back(vy); - data[index++].push_back(vz); - - data[index++].push_back(vxx); - data[index++].push_back(vyy); - data[index++].push_back(vzz); - - data[index++].push_back(vxy); - data[index++].push_back(vxz); - data[index++].push_back(vyz); - - data[index++].push_back(vp); - data[index++].push_back(vprms); - } - } - } - } - - maxX1 -= 1; - maxX2 -= 1; - maxX3 -= 1; - - //cell vector erstellen - for(int ix3=minX3; ix3<=maxX3; ix3++) - { - for(int ix2=minX2; ix2<=maxX2; ix2++) - { - for(int ix1=minX1; ix1<=maxX1; ix1++) - { - if( (SWB=nodeNumbers( ix1 , ix2, ix3 )) >= 0 - && (SEB=nodeNumbers( ix1+1, ix2, ix3 )) >= 0 - && (NEB=nodeNumbers( ix1+1, ix2+1, ix3 )) >= 0 - && (NWB=nodeNumbers( ix1 , ix2+1, ix3 )) >= 0 - && (SWT=nodeNumbers( ix1 , ix2, ix3+1 )) >= 0 - && (SET=nodeNumbers( ix1+1, ix2, ix3+1 )) >= 0 - && (NET=nodeNumbers( ix1+1, ix2+1, ix3+1 )) >= 0 - && (NWT=nodeNumbers( ix1 , ix2+1, ix3+1 )) >= 0 ) - { - cells.push_back( makeUbTuple(SWB,SEB,NEB,NWB,SWT,SET,NET,NWT) ); - } - } - } - } + UbTupleDouble3 org = grid->getBlockWorldCoordinates(block); + // UbTupleDouble3 blockLengths = grid->getBlockLengths(block); + UbTupleDouble3 nodeOffset = grid->getNodeOffset(block); + double dx = grid->getDeltaX(block); + + // Diese Daten werden geschrieben: + datanames.resize(0); + datanames.emplace_back("AvVx"); + datanames.emplace_back("AvVy"); + datanames.emplace_back("AvVz"); + datanames.emplace_back("AvVxx"); + datanames.emplace_back("AvVyy"); + datanames.emplace_back("AvVzz"); + datanames.emplace_back("AvVxy"); + datanames.emplace_back("AvVxz"); + datanames.emplace_back("AvVyz"); + datanames.emplace_back("AvP"); + datanames.emplace_back("AvPrms"); + + data.resize(datanames.size()); + + SPtr<ILBMKernel> kernel = block->getKernel(); + SPtr<BCArray3D> bcArray = kernel->getBCProcessor()->getBCArray(); + SPtr<DistributionArray3D> distributions = kernel->getDataSet()->getFdistributions(); + SPtr<AverageValuesArray3D> av = kernel->getDataSet()->getAverageValues(); + // int ghostLayerWidth = kernel->getGhostLayerWidth(); + + // knotennummerierung faengt immer bei 0 an! + unsigned int SWB, SEB, NEB, NWB, SWT, SET, NET, NWT; + + int minX1 = 0; + int minX2 = 0; + int minX3 = 0; + + int maxX1 = int(distributions->getNX1()); + int maxX2 = int(distributions->getNX2()); + int maxX3 = int(distributions->getNX3()); + + // nummern vergeben und node vector erstellen + daten sammeln + CbArray3D<int> nodeNumbers((int)maxX1, (int)maxX2, (int)maxX3, -1); + + maxX1 -= 2; + maxX2 -= 2; + maxX3 -= 2; + + // D3Q27BoundaryConditionPtr bcPtr; + + int nr = (int)nodes.size(); + + for (int ix3 = minX3; ix3 <= maxX3; ix3++) { + for (int ix2 = minX2; ix2 <= maxX2; ix2++) { + for (int ix1 = minX1; ix1 <= maxX1; ix1++) { + if (!bcArray->isUndefined(ix1, ix2, ix3) && !bcArray->isSolid(ix1, ix2, ix3)) { + int index = 0; + nodeNumbers(ix1, ix2, ix3) = nr++; + nodes.push_back(makeUbTuple(float(val<1>(org) - val<1>(nodeOffset) + ix1 * dx), + float(val<2>(org) - val<2>(nodeOffset) + ix2 * dx), + float(val<3>(org) - val<3>(nodeOffset) + ix3 * dx))); + + LBMReal vx = (*av)(AvVx, ix1, ix2, ix3); + LBMReal vy = (*av)(AvVy, ix1, ix2, ix3); + LBMReal vz = (*av)(AvVz, ix1, ix2, ix3); + + LBMReal vxx = (*av)(AvVxx, ix1, ix2, ix3); + LBMReal vyy = (*av)(AvVyy, ix1, ix2, ix3); + LBMReal vzz = (*av)(AvVzz, ix1, ix2, ix3); + + LBMReal vxy = (*av)(AvVxy, ix1, ix2, ix3); + LBMReal vxz = (*av)(AvVxz, ix1, ix2, ix3); + LBMReal vyz = (*av)(AvVyz, ix1, ix2, ix3); + + LBMReal vp = (*av)(AvP, ix1, ix2, ix3); + LBMReal vprms = (*av)(AvPrms, ix1, ix2, ix3); + + data[index++].push_back(vx); + data[index++].push_back(vy); + data[index++].push_back(vz); + + data[index++].push_back(vxx); + data[index++].push_back(vyy); + data[index++].push_back(vzz); + + data[index++].push_back(vxy); + data[index++].push_back(vxz); + data[index++].push_back(vyz); + + data[index++].push_back(vp); + data[index++].push_back(vprms); + } + } + } + } + + maxX1 -= 1; + maxX2 -= 1; + maxX3 -= 1; + + // cell vector erstellen + for (int ix3 = minX3; ix3 <= maxX3; ix3++) { + for (int ix2 = minX2; ix2 <= maxX2; ix2++) { + for (int ix1 = minX1; ix1 <= maxX1; ix1++) { + if ((SWB = nodeNumbers(ix1, ix2, ix3)) >= 0 && (SEB = nodeNumbers(ix1 + 1, ix2, ix3)) >= 0 && + (NEB = nodeNumbers(ix1 + 1, ix2 + 1, ix3)) >= 0 && (NWB = nodeNumbers(ix1, ix2 + 1, ix3)) >= 0 && + (SWT = nodeNumbers(ix1, ix2, ix3 + 1)) >= 0 && (SET = nodeNumbers(ix1 + 1, ix2, ix3 + 1)) >= 0 && + (NET = nodeNumbers(ix1 + 1, ix2 + 1, ix3 + 1)) >= 0 && + (NWT = nodeNumbers(ix1, ix2 + 1, ix3 + 1)) >= 0) { + cells.push_back(makeUbTuple(SWB, SEB, NEB, NWB, SWT, SET, NET, NWT)); + } + } + } + } } ////////////////////////////////////////////////////////////////////////// void AverageValuesCoProcessor::calculateAverageValues(double timeStep) { - using namespace D3Q27System; - - //Funktionszeiger - calcMacros = NULL; - if (compressible) - { - calcMacros = &calcCompMacroscopicValues; - } - else - { - calcMacros = &calcIncompMacroscopicValues; - } - - LBMReal f[27]; - - for(int level = minInitLevel; level<=maxInitLevel;level++) - { - for(SPtr<Block3D> block : blockVector[level]) - { - if (block) - { - SPtr<ILBMKernel> kernel = block->getKernel(); - SPtr<BCArray3D> bcArray = kernel->getBCProcessor()->getBCArray(); - SPtr<DistributionArray3D> distributions = kernel->getDataSet()->getFdistributions(); - SPtr<AverageValuesArray3D> av = kernel->getDataSet()->getAverageValues(); - - int minX1 = 0; - int minX2 = 0; - int minX3 = 0; - - int maxX1 = int(distributions->getNX1()); - int maxX2 = int(distributions->getNX2()); - int maxX3 = int(distributions->getNX3()); - - maxX1 -= 2; - maxX2 -= 2; - maxX3 -= 2; - - for(int ix3=minX3; ix3<=maxX3; ix3++) - { - for(int ix2=minX2; ix2<=maxX2; ix2++) - { - for(int ix1=minX1; ix1<=maxX1; ix1++) - { - if(!bcArray->isUndefined(ix1,ix2,ix3) && !bcArray->isSolid(ix1,ix2,ix3)) - { - ////////////////////////////////////////////////////////////////////////// - //read distribution - //////////////////////////////////////////////////////////////////////////// - distributions->getDistribution(f, ix1, ix2, ix3); - ////////////////////////////////////////////////////////////////////////// - //compute velocity - ////////////////////////////////////////////////////////////////////////// - LBMReal vx,vy,vz,rho; - calcMacros(f,rho,vx,vy,vz); - double press = D3Q27System::calcPress(f,rho,vx,vy,vz); - - ////////////////////////////////////////////////////////////////////////// - //compute average values - ////////////////////////////////////////////////////////////////////////// - - LBMReal timeStepAfterResetRMS=(double)(timeStep-resetStepRMS)/((double)averageInterval); - LBMReal timeStepAfterResetMeans=(double)(timeStep-resetStepMeans)/((double)averageInterval); - - //mean velocity - (*av)(AvVx,ix1,ix2,ix3) = ((*av)(AvVx,ix1,ix2,ix3)*timeStepAfterResetMeans + vx)/(timeStepAfterResetMeans+1.0); - (*av)(AvVy,ix1,ix2,ix3) = ((*av)(AvVy,ix1,ix2,ix3)*timeStepAfterResetMeans + vy)/(timeStepAfterResetMeans+1.0); - (*av)(AvVz,ix1,ix2,ix3) = ((*av)(AvVz,ix1,ix2,ix3)*timeStepAfterResetMeans + vz)/(timeStepAfterResetMeans+1.0); - - //rms - (*av)(AvVxx,ix1,ix2,ix3) = ((vx-(*av)(AvVx,ix1,ix2,ix3))*(vx-(*av)(AvVx,ix1,ix2,ix3)) + - (*av)(AvVxx,ix1,ix2,ix3)*timeStepAfterResetRMS)/(timeStepAfterResetRMS+1.0); - (*av)(AvVyy,ix1,ix2,ix3) = ((vy-(*av)(AvVy,ix1,ix2,ix3))*(vy-(*av)(AvVy,ix1,ix2,ix3)) + - (*av)(AvVyy,ix1,ix2,ix3)*timeStepAfterResetRMS)/(timeStepAfterResetRMS+1.0); - (*av)(AvVzz,ix1,ix2,ix3) = ((vz-(*av)(AvVz,ix1,ix2,ix3))*(vz-(*av)(AvVz,ix1,ix2,ix3)) + - (*av)(AvVzz,ix1,ix2,ix3)*timeStepAfterResetRMS)/(timeStepAfterResetRMS+1.0); - - //cross-correlations - (*av)(AvVxy,ix1,ix2,ix3) = ((vx-(*av)(AvVx,ix1,ix2,ix3))*(vy-(*av)(AvVy,ix1,ix2,ix3)) + - (*av)(AvVxy,ix1,ix2,ix3)*timeStepAfterResetRMS)/(timeStepAfterResetRMS+1.0); - (*av)(AvVxz,ix1,ix2,ix3) = ((vx-(*av)(AvVx,ix1,ix2,ix3))*(vz-(*av)(AvVz,ix1,ix2,ix3)) + - (*av)(AvVxz,ix1,ix2,ix3)*timeStepAfterResetRMS)/(timeStepAfterResetRMS+1.0); - (*av)(AvVyz,ix1,ix2,ix3) = ((vy-(*av)(AvVy,ix1,ix2,ix3))*(vz-(*av)(AvVz,ix1,ix2,ix3)) + - (*av)(AvVyz,ix1,ix2,ix3)*timeStepAfterResetRMS)/(timeStepAfterResetRMS+1.0); - - //mean and rms press - (*av)(AvP,ix1,ix2,ix3) = ((*av)(AvP,ix1,ix2,ix3)*timeStepAfterResetMeans + press)/(timeStepAfterResetMeans+1.0); - (*av)(AvPrms,ix1,ix2,ix3) = ((press-(*av)(AvP,ix1,ix2,ix3))*(press-(*av)(AvP,ix1,ix2,ix3)) + - (*av)(AvPrms,ix1,ix2,ix3)*timeStepAfterResetRMS)/(timeStepAfterResetRMS+1.0); - - ////////////////////////////////////////////////////////////////////////// - } - } - } - } - } - } - } + using namespace D3Q27System; + + // Funktionszeiger + calcMacros = NULL; + if (compressible) { + calcMacros = &calcCompMacroscopicValues; + } else { + calcMacros = &calcIncompMacroscopicValues; + } + + LBMReal f[27]; + + for (int level = minInitLevel; level <= maxInitLevel; level++) { + for (SPtr<Block3D> block : blockVector[level]) { + if (block) { + SPtr<ILBMKernel> kernel = block->getKernel(); + SPtr<BCArray3D> bcArray = kernel->getBCProcessor()->getBCArray(); + SPtr<DistributionArray3D> distributions = kernel->getDataSet()->getFdistributions(); + SPtr<AverageValuesArray3D> av = kernel->getDataSet()->getAverageValues(); + + int minX1 = 0; + int minX2 = 0; + int minX3 = 0; + + int maxX1 = int(distributions->getNX1()); + int maxX2 = int(distributions->getNX2()); + int maxX3 = int(distributions->getNX3()); + + maxX1 -= 2; + maxX2 -= 2; + maxX3 -= 2; + + for (int ix3 = minX3; ix3 <= maxX3; ix3++) { + for (int ix2 = minX2; ix2 <= maxX2; ix2++) { + for (int ix1 = minX1; ix1 <= maxX1; ix1++) { + if (!bcArray->isUndefined(ix1, ix2, ix3) && !bcArray->isSolid(ix1, ix2, ix3)) { + ////////////////////////////////////////////////////////////////////////// + // read distribution + //////////////////////////////////////////////////////////////////////////// + distributions->getDistribution(f, ix1, ix2, ix3); + ////////////////////////////////////////////////////////////////////////// + // compute velocity + ////////////////////////////////////////////////////////////////////////// + LBMReal vx, vy, vz, rho; + calcMacros(f, rho, vx, vy, vz); + double press = D3Q27System::calcPress(f, rho, vx, vy, vz); + + ////////////////////////////////////////////////////////////////////////// + // compute average values + ////////////////////////////////////////////////////////////////////////// + + LBMReal timeStepAfterResetRMS = + (double)(timeStep - resetStepRMS) / ((double)averageInterval); + LBMReal timeStepAfterResetMeans = + (double)(timeStep - resetStepMeans) / ((double)averageInterval); + + // mean velocity + (*av)(AvVx, ix1, ix2, ix3) = + ((*av)(AvVx, ix1, ix2, ix3) * timeStepAfterResetMeans + vx) / + (timeStepAfterResetMeans + 1.0); + (*av)(AvVy, ix1, ix2, ix3) = + ((*av)(AvVy, ix1, ix2, ix3) * timeStepAfterResetMeans + vy) / + (timeStepAfterResetMeans + 1.0); + (*av)(AvVz, ix1, ix2, ix3) = + ((*av)(AvVz, ix1, ix2, ix3) * timeStepAfterResetMeans + vz) / + (timeStepAfterResetMeans + 1.0); + + // rms + (*av)(AvVxx, ix1, ix2, ix3) = + ((vx - (*av)(AvVx, ix1, ix2, ix3)) * (vx - (*av)(AvVx, ix1, ix2, ix3)) + + (*av)(AvVxx, ix1, ix2, ix3) * timeStepAfterResetRMS) / + (timeStepAfterResetRMS + 1.0); + (*av)(AvVyy, ix1, ix2, ix3) = + ((vy - (*av)(AvVy, ix1, ix2, ix3)) * (vy - (*av)(AvVy, ix1, ix2, ix3)) + + (*av)(AvVyy, ix1, ix2, ix3) * timeStepAfterResetRMS) / + (timeStepAfterResetRMS + 1.0); + (*av)(AvVzz, ix1, ix2, ix3) = + ((vz - (*av)(AvVz, ix1, ix2, ix3)) * (vz - (*av)(AvVz, ix1, ix2, ix3)) + + (*av)(AvVzz, ix1, ix2, ix3) * timeStepAfterResetRMS) / + (timeStepAfterResetRMS + 1.0); + + // cross-correlations + (*av)(AvVxy, ix1, ix2, ix3) = + ((vx - (*av)(AvVx, ix1, ix2, ix3)) * (vy - (*av)(AvVy, ix1, ix2, ix3)) + + (*av)(AvVxy, ix1, ix2, ix3) * timeStepAfterResetRMS) / + (timeStepAfterResetRMS + 1.0); + (*av)(AvVxz, ix1, ix2, ix3) = + ((vx - (*av)(AvVx, ix1, ix2, ix3)) * (vz - (*av)(AvVz, ix1, ix2, ix3)) + + (*av)(AvVxz, ix1, ix2, ix3) * timeStepAfterResetRMS) / + (timeStepAfterResetRMS + 1.0); + (*av)(AvVyz, ix1, ix2, ix3) = + ((vy - (*av)(AvVy, ix1, ix2, ix3)) * (vz - (*av)(AvVz, ix1, ix2, ix3)) + + (*av)(AvVyz, ix1, ix2, ix3) * timeStepAfterResetRMS) / + (timeStepAfterResetRMS + 1.0); + + // mean and rms press + (*av)(AvP, ix1, ix2, ix3) = + ((*av)(AvP, ix1, ix2, ix3) * timeStepAfterResetMeans + press) / + (timeStepAfterResetMeans + 1.0); + (*av)(AvPrms, ix1, ix2, ix3) = + ((press - (*av)(AvP, ix1, ix2, ix3)) * (press - (*av)(AvP, ix1, ix2, ix3)) + + (*av)(AvPrms, ix1, ix2, ix3) * timeStepAfterResetRMS) / + (timeStepAfterResetRMS + 1.0); + + ////////////////////////////////////////////////////////////////////////// + } + } + } + } + } + } + } } //////////////////////////////////////////////////////////////////////////// -//void AverageValuesCoProcessor::initPlotData(double step) +// void AverageValuesCoProcessor::initPlotData(double step) //{ // SPtr<Communicator> comm = Communicator::getInstance(); // if (comm->getProcessID() == comm->getRoot()) // { // std::ofstream ostr; -// string fname = path + "_PlotData_" + UbSystem::toString(step) + ".txt"; +// string fname = path + "_PlotData_" + UbSystem::toString(step) + ".txt"; // ostr.open(fname.c_str(), std::ios_base::out); // if(!ostr) -// { +// { // ostr.clear(); // string path = UbSystem::getPathFromString(fname); // if(path.size()>0){ UbSystem::makeDirectory(path); ostr.open(fname.c_str(), std::ios_base::out);} @@ -494,7 +468,7 @@ void AverageValuesCoProcessor::calculateAverageValues(double timeStep) // } //} ////////////////////////////////////////////////////////////////////////////// -//void AverageValuesCoProcessor::collectPlotData(double step) +// void AverageValuesCoProcessor::collectPlotData(double step) //{ // // double hminX1 = 0.9; @@ -516,7 +490,7 @@ void AverageValuesCoProcessor::calculateAverageValues(double timeStep) // ostringstream Str; // Str << step; // string step2string(Str.str()); -// string fname = path + "_PlotZ_" + step2string + ".txt"; +// string fname = path + "_PlotZ_" + step2string + ".txt"; // // // for(int level = minInitLevel; level<=maxInitLevel;level++) @@ -524,8 +498,8 @@ void AverageValuesCoProcessor::calculateAverageValues(double timeStep) // double dx = grid->getDeltaX(level); // // for (double hi =hX3_level[level]; hi >= hX3_level[level+1]; hi=hi-dx ){ -// D3Q27IntegrateValuesHelper h1(grid, comm, -// hminX1, hminX2, hi, +// D3Q27IntegrateValuesHelper h1(grid, comm, +// hminX1, hminX2, hi, // hmaxX1, hmaxX2, hi-dx); // // h1.calculateAV(); @@ -550,11 +524,11 @@ void AverageValuesCoProcessor::calculateAverageValues(double timeStep) // // ostr.open(fname.c_str(), std::ios_base::out | std::ios_base::app); // if(!ostr) -// { +// { // ostr.clear(); // string path = UbSystem::getPathFromString(fname); -// if(path.size()>0){ UbSystem::makeDirectory(path); ostr.open(fname.c_str(), std::ios_base::out | std::ios_base::app);} -// if(!ostr) throw UbException(UB_EXARGS,"couldn't open file "+fname); +// if(path.size()>0){ UbSystem::makeDirectory(path); ostr.open(fname.c_str(), std::ios_base::out | +//std::ios_base::app);} if(!ostr) throw UbException(UB_EXARGS,"couldn't open file "+fname); // } // ostr << istep << "\t" << resetStep << "\t" << hi+0.5*dx << "\t" << nn1/(nn1+ns1)*100.0 << "%\t"; // ostr << AvVx1 << "\t" << AvVx2 << "\t" << AvVx3 << "\t"; @@ -568,4 +542,3 @@ void AverageValuesCoProcessor::calculateAverageValues(double timeStep) // // } //} - diff --git a/src/cpu/VirtualFluidsCore/CoProcessors/AverageValuesCoProcessor.h b/src/cpu/VirtualFluidsCore/CoProcessors/AverageValuesCoProcessor.h index 8fadba91aae54209e4a5b0b7e6438dd9771eb397..5ba922824167c4e6a686a4bc46b0ccc2813dbae7 100644 --- a/src/cpu/VirtualFluidsCore/CoProcessors/AverageValuesCoProcessor.h +++ b/src/cpu/VirtualFluidsCore/CoProcessors/AverageValuesCoProcessor.h @@ -2,8 +2,8 @@ #define AverageValuesCoProcessor_H #include <PointerDefinitions.h> -#include <vector> #include <string> +#include <vector> #include "CoProcessor.h" #include "LBMSystem.h" @@ -15,60 +15,75 @@ class Grid3D; class Block3D; //! \brief Computes the time averaged mean velocity and RMS values and writes to parallel .vtk -//! \details writes at given time intervals specified in scheduler (s), does averaging according to scheduler (Avs) and resets according to scheduler (rs). <br> -//! Computes the time averaged mean velocity \f$ u_{mean}=\frac{1}{N}\sum\limits_{i=1}^n u_{i} \f$ and RMS of fluctuations. You need to calculate a square root before plotting RMS. <br> -// -//! \author Sonja Uphoff, Kostyantyn Kucher +//! \details writes at given time intervals specified in scheduler (s), does averaging according to scheduler (Avs) and +//! resets according to scheduler (rs). <br> +//! Computes the time averaged mean velocity \f$ u_{mean}=\frac{1}{N}\sum\limits_{i=1}^n u_{i} \f$ and RMS of +//! fluctuations. You need to calculate a square root before plotting RMS. <br> +// +//! \author Sonja Uphoff, Kostyantyn Kucher // \f$ u_{mean}=\frac{1}{N}\sum\limits_{i=1}^n u_{i} \f$ class AverageValuesCoProcessor : public CoProcessor { public: - AverageValuesCoProcessor(); - AverageValuesCoProcessor(SPtr<Grid3D> grid, const std::string& path, WbWriter* const writer, - SPtr<UbScheduler> s, SPtr<UbScheduler> Avs, SPtr<UbScheduler> rsMeans, SPtr<UbScheduler> rsRMS, bool restart); - //! Make update - void process(double step) override; - //! Resets averaged velocity and RMS-values according to ResetSceduler - void reset(double step); + AverageValuesCoProcessor(); + AverageValuesCoProcessor(SPtr<Grid3D> grid, const std::string &path, WbWriter *const writer, SPtr<UbScheduler> s, + SPtr<UbScheduler> Avs, SPtr<UbScheduler> rsMeans, SPtr<UbScheduler> rsRMS, bool restart); + //! Make update + void process(double step) override; + //! Resets averaged velocity and RMS-values according to ResetSceduler + void reset(double step); + protected: - //! Prepare data and write in .vtk file - void collectData(double step); - //! Reset data - void resetDataRMS(double step); - void resetDataMeans(double step); - //! prepare data - void addData(const SPtr<Block3D> block); - void clearData(); - //! Computes average and RMS values of macroscopic quantities - void calculateAverageValues(double timeStep); - ////! write .txt file spatial intergrated averaged value, fluctuation, porous features - //void collectPlotDataZ(double step); - ////! create txt file and write head line - //void initPlotDataZ(double step); + //! Prepare data and write in .vtk file + void collectData(double step); + //! Reset data + void resetDataRMS(double step); + void resetDataMeans(double step); + //! prepare data + void addData(const SPtr<Block3D> block); + void clearData(); + //! Computes average and RMS values of macroscopic quantities + void calculateAverageValues(double timeStep); + ////! write .txt file spatial intergrated averaged value, fluctuation, porous features + // void collectPlotDataZ(double step); + ////! create txt file and write head line + // void initPlotDataZ(double step); private: - std::vector<UbTupleFloat3> nodes; - std::vector<UbTupleUInt8> cells; - std::vector<std::string> datanames; - std::vector<std::vector<double> > data; - std::vector<std::vector<SPtr<Block3D>> > blockVector; - int minInitLevel; //min init level - int maxInitLevel; - int gridRank; - int resetStepRMS; - int resetStepMeans; - double averageInterval; - std::string path; - WbWriter* writer; - bool restart, compressible; - SPtr<UbScheduler> averageScheduler; //additional scheduler to averaging after a given interval - SPtr<UbScheduler> resetSchedulerRMS; //additional scheduler to restart averaging after a given interval - SPtr<UbScheduler> resetSchedulerMeans; //additional scheduler to restart averaging after a given interval - //labels for the different components, e.g. AvVxx for time averaged RMS: 1/n SUM((U-Umean)^2) - //you need to calculate a square root before plotting RMS - enum Values{AvVx = 0, AvVy = 1, AvVz = 2, AvVxx = 3, AvVyy = 4, AvVzz = 5, AvVxy = 6, AvVxz = 7, AvVyz = 8, AvP = 9, AvPrms = 10}; + std::vector<UbTupleFloat3> nodes; + std::vector<UbTupleUInt8> cells; + std::vector<std::string> datanames; + std::vector<std::vector<double>> data; + std::vector<std::vector<SPtr<Block3D>>> blockVector; + int minInitLevel; // min init level + int maxInitLevel; + int gridRank; + int resetStepRMS; + int resetStepMeans; + double averageInterval; + std::string path; + WbWriter *writer; + bool restart, compressible; + SPtr<UbScheduler> averageScheduler; // additional scheduler to averaging after a given interval + SPtr<UbScheduler> resetSchedulerRMS; // additional scheduler to restart averaging after a given interval + SPtr<UbScheduler> resetSchedulerMeans; // additional scheduler to restart averaging after a given interval + // labels for the different components, e.g. AvVxx for time averaged RMS: 1/n SUM((U-Umean)^2) + // you need to calculate a square root before plotting RMS + enum Values { + AvVx = 0, + AvVy = 1, + AvVz = 2, + AvVxx = 3, + AvVyy = 4, + AvVzz = 5, + AvVxy = 6, + AvVxz = 7, + AvVyz = 8, + AvP = 9, + AvPrms = 10 + }; - using CalcMacrosFct = void (*)(const LBMReal *const &, LBMReal &, LBMReal &, LBMReal &, LBMReal &); - CalcMacrosFct calcMacros; + using CalcMacrosFct = void (*)(const LBMReal *const &, LBMReal &, LBMReal &, LBMReal &, LBMReal &); + CalcMacrosFct calcMacros; }; #endif diff --git a/src/cpu/VirtualFluidsCore/CoProcessors/CalculateForcesCoProcessor.cpp b/src/cpu/VirtualFluidsCore/CoProcessors/CalculateForcesCoProcessor.cpp index d66562b2d48b5033247433125f7855d43b24c60b..fe347d7864710b9c3bde20d83d63a5758c3d26e8 100644 --- a/src/cpu/VirtualFluidsCore/CoProcessors/CalculateForcesCoProcessor.cpp +++ b/src/cpu/VirtualFluidsCore/CoProcessors/CalculateForcesCoProcessor.cpp @@ -1,241 +1,239 @@ #include "CalculateForcesCoProcessor.h" #include "BCProcessor.h" +#include "BCArray3D.h" +#include "Block3D.h" +#include "BoundaryConditions.h" #include "Communicator.h" #include "D3Q27Interactor.h" -#include "UbScheduler.h" -#include "Grid3D.h" -#include "BoundaryConditions.h" #include "DataSet3D.h" -#include "Block3D.h" -#include "LBMKernel.h" -#include "BCArray3D.h" -#include "EsoTwist3D.h" #include "DistributionArray3D.h" +#include "EsoTwist3D.h" +#include "Grid3D.h" +#include "LBMKernel.h" +#include "UbScheduler.h" -CalculateForcesCoProcessor::CalculateForcesCoProcessor( SPtr<Grid3D> grid, SPtr<UbScheduler> s, - const std::string &path, - SPtr<Communicator> comm , - double v, double a) : - CoProcessor(grid, s), - path(path), comm(comm), - v(v), a(a), - forceX1global(0), forceX2global(0), forceX3global(0) +CalculateForcesCoProcessor::CalculateForcesCoProcessor(SPtr<Grid3D> grid, SPtr<UbScheduler> s, const std::string &path, + SPtr<Communicator> comm, double v, double a) + : CoProcessor(grid, s), path(path), comm(comm), v(v), a(a), forceX1global(0), forceX2global(0), forceX3global(0) { - if (comm->getProcessID() == comm->getRoot()) - { - std::ofstream ostr; - std::string fname = path; - ostr.open(fname.c_str(), std::ios_base::out | std::ios_base::app); - if(!ostr) - { - ostr.clear(); - std::string file_path = UbSystem::getPathFromString(fname); - if(file_path.size()>0){ UbSystem::makeDirectory(file_path); ostr.open(fname.c_str(), std::ios_base::out | std::ios_base::app);} - if(!ostr) throw UbException(UB_EXARGS,"couldn't open file "+fname); - } - ostr.width(12); - ostr << "step" << "\t"; - ostr.width(12); - ostr << "Cx" << "\t"; - ostr.width(12); - ostr << "Cy" << "\t"; - ostr.width(12); - ostr << "Cz" << "\t"; - ostr.width(12); - ostr << "Fx" << "\t"; - ostr.width(12); - ostr << "Fy" << "\t"; - ostr.width(12); - ostr << "Fz" << std::endl; - ostr.close(); - } + if (comm->getProcessID() == comm->getRoot()) { + std::ofstream ostr; + std::string fname = path; + ostr.open(fname.c_str(), std::ios_base::out | std::ios_base::app); + if (!ostr) { + ostr.clear(); + std::string file_path = UbSystem::getPathFromString(fname); + if (file_path.size() > 0) { + UbSystem::makeDirectory(file_path); + ostr.open(fname.c_str(), std::ios_base::out | std::ios_base::app); + } + if (!ostr) + throw UbException(UB_EXARGS, "couldn't open file " + fname); + } + ostr.width(12); + ostr << "step" + << "\t"; + ostr.width(12); + ostr << "Cx" + << "\t"; + ostr.width(12); + ostr << "Cy" + << "\t"; + ostr.width(12); + ostr << "Cz" + << "\t"; + ostr.width(12); + ostr << "Fx" + << "\t"; + ostr.width(12); + ostr << "Fy" + << "\t"; + ostr.width(12); + ostr << "Fz" << std::endl; + ostr.close(); + } } ////////////////////////////////////////////////////////////////////////// -CalculateForcesCoProcessor::~CalculateForcesCoProcessor() -= default; +CalculateForcesCoProcessor::~CalculateForcesCoProcessor() = default; ////////////////////////////////////////////////////////////////////////// -void CalculateForcesCoProcessor::process( double step ) +void CalculateForcesCoProcessor::process(double step) { - if(scheduler->isDue(step) ) - collectData(step); + if (scheduler->isDue(step)) + collectData(step); - UBLOG(logDEBUG3, "D3Q27ForcesCoProcessor::update:" << step); + UBLOG(logDEBUG3, "D3Q27ForcesCoProcessor::update:" << step); } ////////////////////////////////////////////////////////////////////////// -void CalculateForcesCoProcessor::collectData( double step ) +void CalculateForcesCoProcessor::collectData(double step) { - calculateForces(); - - if (comm->getProcessID() == comm->getRoot()) - { - int istep = static_cast<int>(step); - std::ofstream ostr; - std::string fname = path; - ostr.open(fname.c_str(), std::ios_base::out | std::ios_base::app); - if(!ostr) - { - ostr.clear(); - std::string path = UbSystem::getPathFromString(fname); - if(path.size()>0){ UbSystem::makeDirectory(path); ostr.open(fname.c_str(), std::ios_base::out | std::ios_base::app);} - if(!ostr) throw UbException(UB_EXARGS,"couldn't open file "+fname); - } - - calculateCoefficients(); - - ostr.width(12); - ostr.setf(std::ios::fixed); - ostr << istep << "\t"; - write(&ostr, C1, (char*)"\t"); - write(&ostr, C2, (char*)"\t"); - write(&ostr, C3, (char*)"\t"); - write(&ostr, forceX1global, (char*)"\t"); - write(&ostr, forceX2global, (char*)"\t"); - write(&ostr, forceX3global, (char*)"\t"); - ostr << std::endl; - ostr.close(); - } + calculateForces(); + + if (comm->getProcessID() == comm->getRoot()) { + int istep = static_cast<int>(step); + std::ofstream ostr; + std::string fname = path; + ostr.open(fname.c_str(), std::ios_base::out | std::ios_base::app); + if (!ostr) { + ostr.clear(); + std::string path = UbSystem::getPathFromString(fname); + if (path.size() > 0) { + UbSystem::makeDirectory(path); + ostr.open(fname.c_str(), std::ios_base::out | std::ios_base::app); + } + if (!ostr) + throw UbException(UB_EXARGS, "couldn't open file " + fname); + } + + calculateCoefficients(); + + ostr.width(12); + ostr.setf(std::ios::fixed); + ostr << istep << "\t"; + write(&ostr, C1, (char *)"\t"); + write(&ostr, C2, (char *)"\t"); + write(&ostr, C3, (char *)"\t"); + write(&ostr, forceX1global, (char *)"\t"); + write(&ostr, forceX2global, (char *)"\t"); + write(&ostr, forceX3global, (char *)"\t"); + ostr << std::endl; + ostr.close(); + } } ////////////////////////////////////////////////////////////////////////// void CalculateForcesCoProcessor::calculateForces() { - forceX1global = 0.0; - forceX2global = 0.0; - forceX3global = 0.0; - - for(SPtr<D3Q27Interactor> interactor : interactors) - { - for(BcNodeIndicesMap::value_type t : interactor->getBcNodeIndicesMap()) - { - double forceX1 = 0.0; - double forceX2 = 0.0; - double forceX3 = 0.0; - - SPtr<Block3D> block = t.first; - std::set< std::vector<int> >& transNodeIndicesSet = t.second; - - SPtr<ILBMKernel> kernel = block->getKernel(); - SPtr<BCArray3D> bcArray = kernel->getBCProcessor()->getBCArray(); - SPtr<DistributionArray3D> distributions = kernel->getDataSet()->getFdistributions(); - distributions->swap(); - - int ghostLayerWidth = kernel->getGhostLayerWidth(); - int minX1 = ghostLayerWidth; - int maxX1 = (int)bcArray->getNX1() - 1 - ghostLayerWidth; - int minX2 = ghostLayerWidth; - int maxX2 = (int)bcArray->getNX2() - 1 - ghostLayerWidth; - int minX3 = ghostLayerWidth; - int maxX3 = (int)bcArray->getNX3() - 1 - ghostLayerWidth; - - for(std::vector<int> node : transNodeIndicesSet) - { - int x1 = node[0]; - int x2 = node[1]; - int x3 = node[2]; - - //without ghost nodes - if (x1 < minX1 || x1 > maxX1 || x2 < minX2 || x2 > maxX2 ||x3 < minX3 || x3 > maxX3 ) continue; - - if(bcArray->isFluid(x1,x2,x3)) //es kann sein, dass der node von einem anderen interactor z.B. als solid gemarkt wurde!!! - { - SPtr<BoundaryConditions> bc = bcArray->getBC(x1,x2,x3); - UbTupleDouble3 forceVec = getForces(x1,x2,x3,distributions,bc); - forceX1 += val<1>(forceVec); - forceX2 += val<2>(forceVec); - forceX3 += val<3>(forceVec); + forceX1global = 0.0; + forceX2global = 0.0; + forceX3global = 0.0; + + for (SPtr<D3Q27Interactor> interactor : interactors) { + for (BcNodeIndicesMap::value_type t : interactor->getBcNodeIndicesMap()) { + double forceX1 = 0.0; + double forceX2 = 0.0; + double forceX3 = 0.0; + + SPtr<Block3D> block = t.first; + std::set<std::vector<int>> &transNodeIndicesSet = t.second; + + SPtr<ILBMKernel> kernel = block->getKernel(); + SPtr<BCArray3D> bcArray = kernel->getBCProcessor()->getBCArray(); + SPtr<DistributionArray3D> distributions = kernel->getDataSet()->getFdistributions(); + distributions->swap(); + + int ghostLayerWidth = kernel->getGhostLayerWidth(); + int minX1 = ghostLayerWidth; + int maxX1 = (int)bcArray->getNX1() - 1 - ghostLayerWidth; + int minX2 = ghostLayerWidth; + int maxX2 = (int)bcArray->getNX2() - 1 - ghostLayerWidth; + int minX3 = ghostLayerWidth; + int maxX3 = (int)bcArray->getNX3() - 1 - ghostLayerWidth; + + for (std::vector<int> node : transNodeIndicesSet) { + int x1 = node[0]; + int x2 = node[1]; + int x3 = node[2]; + + // without ghost nodes + if (x1 < minX1 || x1 > maxX1 || x2 < minX2 || x2 > maxX2 || x3 < minX3 || x3 > maxX3) + continue; + + if (bcArray->isFluid( + x1, x2, + x3)) // es kann sein, dass der node von einem anderen interactor z.B. als solid gemarkt wurde!!! + { + SPtr<BoundaryConditions> bc = bcArray->getBC(x1, x2, x3); + UbTupleDouble3 forceVec = getForces(x1, x2, x3, distributions, bc); + forceX1 += val<1>(forceVec); + forceX2 += val<2>(forceVec); + forceX3 += val<3>(forceVec); + } } - } - //if we have got discretization with more level - // deltaX is LBM deltaX and equal LBM deltaT - double deltaX = LBMSystem::getDeltaT(block->getLevel()); //grid->getDeltaT(block); - double deltaXquadrat = deltaX*deltaX; - forceX1 *= deltaXquadrat; - forceX2 *= deltaXquadrat; - forceX3 *= deltaXquadrat; - - distributions->swap(); - - forceX1global += forceX1; - forceX2global += forceX2; - forceX3global += forceX3; - } - } - std::vector<double> values; - std::vector<double> rvalues; - values.push_back(forceX1global); - values.push_back(forceX2global); - values.push_back(forceX3global); - - rvalues = comm->gather(values); - if (comm->getProcessID() == comm->getRoot()) - { - forceX1global = 0.0; - forceX2global = 0.0; - forceX3global = 0.0; - - for (int i = 0; i < (int)rvalues.size(); i+=3) - { - forceX1global += rvalues[i]; - forceX2global += rvalues[i+1]; - forceX3global += rvalues[i+2]; - } - } + // if we have got discretization with more level + // deltaX is LBM deltaX and equal LBM deltaT + double deltaX = LBMSystem::getDeltaT(block->getLevel()); // grid->getDeltaT(block); + double deltaXquadrat = deltaX * deltaX; + forceX1 *= deltaXquadrat; + forceX2 *= deltaXquadrat; + forceX3 *= deltaXquadrat; + + distributions->swap(); + + forceX1global += forceX1; + forceX2global += forceX2; + forceX3global += forceX3; + } + } + std::vector<double> values; + std::vector<double> rvalues; + values.push_back(forceX1global); + values.push_back(forceX2global); + values.push_back(forceX3global); + + rvalues = comm->gather(values); + if (comm->getProcessID() == comm->getRoot()) { + forceX1global = 0.0; + forceX2global = 0.0; + forceX3global = 0.0; + + for (int i = 0; i < (int)rvalues.size(); i += 3) { + forceX1global += rvalues[i]; + forceX2global += rvalues[i + 1]; + forceX3global += rvalues[i + 2]; + } + } } ////////////////////////////////////////////////////////////////////////// -UbTupleDouble3 CalculateForcesCoProcessor::getForces(int x1, int x2, int x3, SPtr<DistributionArray3D> distributions, SPtr<BoundaryConditions> bc) +UbTupleDouble3 CalculateForcesCoProcessor::getForces(int x1, int x2, int x3, SPtr<DistributionArray3D> distributions, + SPtr<BoundaryConditions> bc) { - UbTupleDouble3 force(0.0,0.0,0.0); - - if(bc) - { - //references to tuple "force" - double& forceX1 = val<1>(force); - double& forceX2 = val<2>(force); - double& forceX3 = val<3>(force); - double f, fnbr; - - for(int fdir=D3Q27System::FSTARTDIR; fdir<=D3Q27System::FENDDIR; fdir++) - { - if(bc->hasNoSlipBoundaryFlag(fdir)) - { - const int invDir = D3Q27System::INVDIR[fdir]; - f = dynamicPointerCast<EsoTwist3D>(distributions)->getDistributionInvForDirection(x1, x2, x3, invDir); - fnbr = dynamicPointerCast<EsoTwist3D>(distributions)->getDistributionInvForDirection(x1+D3Q27System::DX1[invDir], x2+D3Q27System::DX2[invDir], x3+D3Q27System::DX3[invDir], fdir); - - forceX1 += (f + fnbr)*D3Q27System::DX1[invDir]; - forceX2 += (f + fnbr)*D3Q27System::DX2[invDir]; - forceX3 += (f + fnbr)*D3Q27System::DX3[invDir]; - } - } - } - - return force; + UbTupleDouble3 force(0.0, 0.0, 0.0); + + if (bc) { + // references to tuple "force" + double &forceX1 = val<1>(force); + double &forceX2 = val<2>(force); + double &forceX3 = val<3>(force); + double f, fnbr; + + for (int fdir = D3Q27System::FSTARTDIR; fdir <= D3Q27System::FENDDIR; fdir++) { + if (bc->hasNoSlipBoundaryFlag(fdir)) { + const int invDir = D3Q27System::INVDIR[fdir]; + f = dynamicPointerCast<EsoTwist3D>(distributions)->getDistributionInvForDirection(x1, x2, x3, invDir); + fnbr = + dynamicPointerCast<EsoTwist3D>(distributions) + ->getDistributionInvForDirection(x1 + D3Q27System::DX1[invDir], x2 + D3Q27System::DX2[invDir], + x3 + D3Q27System::DX3[invDir], fdir); + + forceX1 += (f + fnbr) * D3Q27System::DX1[invDir]; + forceX2 += (f + fnbr) * D3Q27System::DX2[invDir]; + forceX3 += (f + fnbr) * D3Q27System::DX3[invDir]; + } + } + } + + return force; } ////////////////////////////////////////////////////////////////////////// void CalculateForcesCoProcessor::calculateCoefficients() { - double F1 = forceX1global; - double F2 = forceX2global; - double F3 = forceX3global; - - //return 2*F/(rho*v*v*a); - C1 = 2.0*F1/(v*v*a); - C2 = 2.0*F2/(v*v*a); - C3 = 2.0*F3/(v*v*a); + double F1 = forceX1global; + double F2 = forceX2global; + double F3 = forceX3global; + + // return 2*F/(rho*v*v*a); + C1 = 2.0 * F1 / (v * v * a); + C2 = 2.0 * F2 / (v * v * a); + C3 = 2.0 * F3 / (v * v * a); } ////////////////////////////////////////////////////////////////////////// -void CalculateForcesCoProcessor::addInteractor( SPtr<D3Q27Interactor> interactor ) +void CalculateForcesCoProcessor::addInteractor(SPtr<D3Q27Interactor> interactor) { interactors.push_back(interactor); } +////////////////////////////////////////////////////////////////////////// +void CalculateForcesCoProcessor::write(std::ofstream *fileObject, double value, char *separator) { - interactors.push_back(interactor); + (*fileObject).width(12); + //(*fileObject).precision(2); + (*fileObject).setf(std::ios::fixed); + (*fileObject) << value; + (*fileObject) << separator; } -////////////////////////////////////////////////////////////////////////// -void CalculateForcesCoProcessor::write(std::ofstream *fileObject, double value, char *separator) -{ - (*fileObject).width(12); - //(*fileObject).precision(2); - (*fileObject).setf(std::ios::fixed); - (*fileObject) << value; - (*fileObject) << separator; -} - - diff --git a/src/cpu/VirtualFluidsCore/CoProcessors/CalculateForcesCoProcessor.h b/src/cpu/VirtualFluidsCore/CoProcessors/CalculateForcesCoProcessor.h index 6c2288dc50263ca897671efd638b3d0aea3b9d5b..c3004cf16b3c70cb5f24526badb69f62683b0b36 100644 --- a/src/cpu/VirtualFluidsCore/CoProcessors/CalculateForcesCoProcessor.h +++ b/src/cpu/VirtualFluidsCore/CoProcessors/CalculateForcesCoProcessor.h @@ -23,36 +23,38 @@ class D3Q27Interactor; class DistributionArray3D; class BoundaryConditions; -class CalculateForcesCoProcessor: public CoProcessor +class CalculateForcesCoProcessor : public CoProcessor { public: - //! Constructor - //! \param v - velocity of fluid in LB units - //! \param a - area of object in LB units - CalculateForcesCoProcessor(SPtr<Grid3D> grid, SPtr<UbScheduler> s, const std::string &path, - SPtr<Communicator> comm, double v, double a); - ~CalculateForcesCoProcessor() override; - void process(double step) override; - void addInteractor(SPtr<D3Q27Interactor> interactor); + //! Constructor + //! \param v - velocity of fluid in LB units + //! \param a - area of object in LB units + CalculateForcesCoProcessor(SPtr<Grid3D> grid, SPtr<UbScheduler> s, const std::string &path, SPtr<Communicator> comm, + double v, double a); + ~CalculateForcesCoProcessor() override; + void process(double step) override; + void addInteractor(SPtr<D3Q27Interactor> interactor); + protected: - void collectData(double step); - void calculateForces(); - UbTupleDouble3 getForces(int x1, int x2, int x3, SPtr<DistributionArray3D> distributions, SPtr<BoundaryConditions> bc); - void calculateCoefficients(); - void write(std::ofstream *fileObject, double value, char *separator); + void collectData(double step); + void calculateForces(); + UbTupleDouble3 getForces(int x1, int x2, int x3, SPtr<DistributionArray3D> distributions, + SPtr<BoundaryConditions> bc); + void calculateCoefficients(); + void write(std::ofstream *fileObject, double value, char *separator); + private: - std::string path; - SPtr<Communicator> comm; - std::vector<SPtr<D3Q27Interactor> > interactors; - double forceX1global; - double forceX2global; - double forceX3global; - double v; //!< is the speed of the object relative to the fluid - double a; //!< is the reference area - double C1; - double C2; - double C3; + std::string path; + SPtr<Communicator> comm; + std::vector<SPtr<D3Q27Interactor>> interactors; + double forceX1global; + double forceX2global; + double forceX3global; + double v; //!< is the speed of the object relative to the fluid + double a; //!< is the reference area + double C1; + double C2; + double C3; }; - #endif /* D3Q27ForcesCoProcessor_H */ diff --git a/src/cpu/VirtualFluidsCore/CoProcessors/CoProcessor.cpp b/src/cpu/VirtualFluidsCore/CoProcessors/CoProcessor.cpp index 081aac9825a92956c2c13298ea6efab2ff810ead..6572ac8b5c6a21eb29c773f0da8bcd1d4fa2e286 100644 --- a/src/cpu/VirtualFluidsCore/CoProcessors/CoProcessor.cpp +++ b/src/cpu/VirtualFluidsCore/CoProcessors/CoProcessor.cpp @@ -1,28 +1,28 @@ //======================================================================================= -// ____ ____ __ ______ __________ __ __ __ __ -// \ \ | | | | | _ \ |___ ___| | | | | / \ | | -// \ \ | | | | | |_) | | | | | | | / \ | | -// \ \ | | | | | _ / | | | | | | / /\ \ | | -// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ -// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| -// \ \ | | ________________________________________________________________ -// \ \ | | | ______________________________________________________________| -// \ \| | | | __ __ __ __ ______ _______ -// \ | | |_____ | | | | | | | | | _ \ / _____) -// \ | | _____| | | | | | | | | | | \ \ \_______ +// ____ ____ __ ______ __________ __ __ __ __ +// \ \ | | | | | _ \ |___ ___| | | | | / \ | | +// \ \ | | | | | |_) | | | | | | | / \ | | +// \ \ | | | | | _ / | | | | | | / /\ \ | | +// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ +// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| +// \ \ | | ________________________________________________________________ +// \ \ | | | ______________________________________________________________| +// \ \| | | | __ __ __ __ ______ _______ +// \ | | |_____ | | | | | | | | | _ \ / _____) +// \ | | _____| | | | | | | | | | | \ \ \_______ // \ | | | | |_____ | \_/ | | | | |_/ / _____ | -// \ _____| |__| |________| \_______/ |__| |______/ (_______/ +// \ _____| |__| |________| \_______/ |__| |______/ (_______/ // -// This file is part of VirtualFluids. VirtualFluids is free software: you can +// This file is part of VirtualFluids. VirtualFluids is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of +// License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. -// -// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// +// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License along // with VirtualFluids (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>. // @@ -36,14 +36,8 @@ #include "Grid3D.h" #include "UbScheduler.h" -CoProcessor::CoProcessor() -= default; - -CoProcessor::CoProcessor(SPtr<Grid3D> grid, SPtr<UbScheduler> s): grid(grid), scheduler(s) -{ - -} +CoProcessor::CoProcessor() = default; -CoProcessor::~CoProcessor() -= default; +CoProcessor::CoProcessor(SPtr<Grid3D> grid, SPtr<UbScheduler> s) : grid(grid), scheduler(s) {} +CoProcessor::~CoProcessor() = default; diff --git a/src/cpu/VirtualFluidsCore/CoProcessors/CoProcessor.h b/src/cpu/VirtualFluidsCore/CoProcessors/CoProcessor.h index 6abcda31a7fe6cb59d207762b9f99675f717eae5..7d8efad7606b57bb24ac11740843b30d3678fcbb 100644 --- a/src/cpu/VirtualFluidsCore/CoProcessors/CoProcessor.h +++ b/src/cpu/VirtualFluidsCore/CoProcessors/CoProcessor.h @@ -1,28 +1,28 @@ //======================================================================================= -// ____ ____ __ ______ __________ __ __ __ __ -// \ \ | | | | | _ \ |___ ___| | | | | / \ | | -// \ \ | | | | | |_) | | | | | | | / \ | | -// \ \ | | | | | _ / | | | | | | / /\ \ | | -// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ -// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| -// \ \ | | ________________________________________________________________ -// \ \ | | | ______________________________________________________________| -// \ \| | | | __ __ __ __ ______ _______ -// \ | | |_____ | | | | | | | | | _ \ / _____) -// \ | | _____| | | | | | | | | | | \ \ \_______ +// ____ ____ __ ______ __________ __ __ __ __ +// \ \ | | | | | _ \ |___ ___| | | | | / \ | | +// \ \ | | | | | |_) | | | | | | | / \ | | +// \ \ | | | | | _ / | | | | | | / /\ \ | | +// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ +// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| +// \ \ | | ________________________________________________________________ +// \ \ | | | ______________________________________________________________| +// \ \| | | | __ __ __ __ ______ _______ +// \ | | |_____ | | | | | | | | | _ \ / _____) +// \ | | _____| | | | | | | | | | | \ \ \_______ // \ | | | | |_____ | \_/ | | | | |_/ / _____ | -// \ _____| |__| |________| \_______/ |__| |______/ (_______/ +// \ _____| |__| |________| \_______/ |__| |______/ (_______/ // -// This file is part of VirtualFluids. VirtualFluids is free software: you can +// This file is part of VirtualFluids. VirtualFluids is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of +// License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. -// -// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// +// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License along // with VirtualFluids (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>. // @@ -44,23 +44,24 @@ class UbScheduler; class CoProcessor { public: - //! Class default constructor - CoProcessor(); - //! \brief Construct CoProcessor object for grid object and scheduler object. - //! \pre The Grid3D and UbScheduler objects must exist. - //! \param grid is observable Grid3D object - //! \param s is UbScheduler object for scheduling of observer - //! \details - //! Class CoProcessor implements the observer design pettern. CoProcessor object is observer. Grid3D object is observable. - CoProcessor(SPtr<Grid3D> grid, SPtr<UbScheduler> s); - //! Class destructor - virtual ~CoProcessor(); - //! \brief Updates observer - //! \param step is the actual time step - virtual void process(double step) = 0; + //! Class default constructor + CoProcessor(); + //! \brief Construct CoProcessor object for grid object and scheduler object. + //! \pre The Grid3D and UbScheduler objects must exist. + //! \param grid is observable Grid3D object + //! \param s is UbScheduler object for scheduling of observer + //! \details + //! Class CoProcessor implements the observer design pettern. CoProcessor object is observer. Grid3D object is + //! observable. + CoProcessor(SPtr<Grid3D> grid, SPtr<UbScheduler> s); + //! Class destructor + virtual ~CoProcessor(); + //! \brief Updates observer + //! \param step is the actual time step + virtual void process(double step) = 0; + protected: - SPtr<Grid3D> grid; - SPtr<UbScheduler> scheduler; + SPtr<Grid3D> grid; + SPtr<UbScheduler> scheduler; }; #endif - diff --git a/src/cpu/VirtualFluidsCore/CoProcessors/DecreaseViscosityCoProcessor.cpp b/src/cpu/VirtualFluidsCore/CoProcessors/DecreaseViscosityCoProcessor.cpp index 040d5f94438cd0c4a8c5bed33bf1a1d6824b2d8c..f7061e9c8f9ebc3a43171d1b075d95ba76818f60 100644 --- a/src/cpu/VirtualFluidsCore/CoProcessors/DecreaseViscosityCoProcessor.cpp +++ b/src/cpu/VirtualFluidsCore/CoProcessors/DecreaseViscosityCoProcessor.cpp @@ -1,82 +1,70 @@ /* -* DecreaseViscosityCoProcessor -* -* Created on: 10.05.2013 -* Author: uphoff -*/ + * DecreaseViscosityCoProcessor + * + * Created on: 10.05.2013 + * Author: uphoff + */ #include "DecreaseViscosityCoProcessor.h" #include <vector> -#include "LBMKernel.h" +#include "Block3D.h" #include "Communicator.h" -#include "UbScheduler.h" #include "Grid3D.h" -#include "Block3D.h" +#include "LBMKernel.h" +#include "UbScheduler.h" -DecreaseViscosityCoProcessor::DecreaseViscosityCoProcessor(SPtr<Grid3D> grid, SPtr<UbScheduler> s, - mu::Parser* nueFunc, SPtr<Communicator> comm) +DecreaseViscosityCoProcessor::DecreaseViscosityCoProcessor(SPtr<Grid3D> grid, SPtr<UbScheduler> s, mu::Parser *nueFunc, + SPtr<Communicator> comm) - : CoProcessor(grid, s) - ,nueFunc(nueFunc) - ,comm(comm) + : CoProcessor(grid, s), nueFunc(nueFunc), comm(comm) { - if (comm->getProcessID() == comm->getRoot()) - { - - } + if (comm->getProcessID() == comm->getRoot()) { + } } ////////////////////////////////////////////////////////////////////////// -DecreaseViscosityCoProcessor::~DecreaseViscosityCoProcessor() -= default; +DecreaseViscosityCoProcessor::~DecreaseViscosityCoProcessor() = default; ////////////////////////////////////////////////////////////////////////// void DecreaseViscosityCoProcessor::process(double step) { - if(scheduler->isDue(step) ) - setViscosity(step); + if (scheduler->isDue(step)) + setViscosity(step); } ////////////////////////////////////////////////////////////////////////// void DecreaseViscosityCoProcessor::setViscosity(double step) { - UBLOG(logDEBUG3, "DecreaseViscosityCoProcessor::update:" << step); - int gridRank = grid->getRank(); - int minInitLevel = this->grid->getCoarsestInitializedLevel(); - int maxInitLevel = this->grid->getFinestInitializedLevel(); + UBLOG(logDEBUG3, "DecreaseViscosityCoProcessor::update:" << step); + int gridRank = grid->getRank(); + int minInitLevel = this->grid->getCoarsestInitializedLevel(); + int maxInitLevel = this->grid->getFinestInitializedLevel(); - if (comm->getProcessID() == comm->getRoot()) - { + if (comm->getProcessID() == comm->getRoot()) { - for(int level = minInitLevel; level<=maxInitLevel;level++) - { - std::vector<SPtr<Block3D>> blockVector; - grid->getBlocks(level, gridRank, blockVector); - for(SPtr<Block3D> block : blockVector) - { - SPtr<ILBMKernel> kernel = block->getKernel(); - } - } + for (int level = minInitLevel; level <= maxInitLevel; level++) { + std::vector<SPtr<Block3D>> blockVector; + grid->getBlocks(level, gridRank, blockVector); + for (SPtr<Block3D> block : blockVector) { + SPtr<ILBMKernel> kernel = block->getKernel(); + } + } - int istep = static_cast<int>(step); - this->timeStep = istep; - nueFunc->DefineVar("t" , &this->timeStep); - double nue=nueFunc->Eval(); + int istep = static_cast<int>(step); + this->timeStep = istep; + nueFunc->DefineVar("t", &this->timeStep); + double nue = nueFunc->Eval(); - for(int level = minInitLevel; level<=maxInitLevel;level++) - { - std::vector<SPtr<Block3D>> blockVector; - grid->getBlocks(level, gridRank, blockVector); - for(SPtr<Block3D> block : blockVector) - { - SPtr<ILBMKernel> kernel =block->getKernel(); - if(kernel) - { - LBMReal collFactor = LBMSystem::calcCollisionFactor(nue, block->getLevel()); - kernel->setCollisionFactor(collFactor); + for (int level = minInitLevel; level <= maxInitLevel; level++) { + std::vector<SPtr<Block3D>> blockVector; + grid->getBlocks(level, gridRank, blockVector); + for (SPtr<Block3D> block : blockVector) { + SPtr<ILBMKernel> kernel = block->getKernel(); + if (kernel) { + LBMReal collFactor = LBMSystem::calcCollisionFactor(nue, block->getLevel()); + kernel->setCollisionFactor(collFactor); + } } - } - } - - } + } + } } diff --git a/src/cpu/VirtualFluidsCore/CoProcessors/DecreaseViscosityCoProcessor.h b/src/cpu/VirtualFluidsCore/CoProcessors/DecreaseViscosityCoProcessor.h index 3885ac399516d80665acdc21ca093e4b4758d90d..75a833be7d95c0f0fbd8a171d96de9e651598693 100644 --- a/src/cpu/VirtualFluidsCore/CoProcessors/DecreaseViscosityCoProcessor.h +++ b/src/cpu/VirtualFluidsCore/CoProcessors/DecreaseViscosityCoProcessor.h @@ -9,40 +9,38 @@ #include "muParser.h" - class UbScheduler; class Grid3D; class Communicator; -//! \brief The class sets viscosity/collision factor according to a previously defined function in time. -//! \details initialization in test case (example): +//! \brief The class sets viscosity/collision factor according to a previously defined function in time. +//! \details initialization in test case (example): //! \code{.cpp} -//! mu::Parser decrViscFunc; //define a mu-parser function -//! decrViscFunc.SetExpr("nue0+c0/(t+1)/(t+1)"); //this function is time-dependent, the viscosity decreases a 1/t^2 -//! decrViscFunc.DefineConst("nue0", nueLB); -//! decrViscFunc.DefineConst("c0", 0.1); //constants such as c0 controll how fast the viscosity decreasis +//! mu::Parser decrViscFunc; //define a mu-parser function +//! decrViscFunc.SetExpr("nue0+c0/(t+1)/(t+1)"); //this function is time-dependent, the viscosity decreases a 1/t^2 +//! decrViscFunc.DefineConst("nue0", nueLB); +//! decrViscFunc.DefineConst("c0", 0.1); //constants such as c0 controll how fast the viscosity decreasis //! SPtr<UbScheduler> DecrViscSch(new UbScheduler()); //the CoProcessor is called according to a Scheduler -//! DecrViscSch->addSchedule(10,10,1000); //in this case the viscosity is reset every 10 timesteps for the first 1000 timesteps -//! DecreaseViscosityCoProcessor decrViscPPPtr(grid, DecrViscSch,&decrViscFunc, comm); -//! \endcode +//! DecrViscSch->addSchedule(10,10,1000); //in this case the viscosity is reset every 10 timesteps for the +//! first 1000 timesteps DecreaseViscosityCoProcessor decrViscPPPtr(grid, DecrViscSch,&decrViscFunc, comm); \endcode //! \author Sonja Uphoff -class DecreaseViscosityCoProcessor: public CoProcessor -{ +class DecreaseViscosityCoProcessor : public CoProcessor +{ public: - DecreaseViscosityCoProcessor(SPtr<Grid3D> grid, SPtr<UbScheduler> s, - mu::Parser* nueFunc, SPtr<Communicator> comm); - ~DecreaseViscosityCoProcessor() override; - //! calls collect PostprocessData. - void process(double step) override; + DecreaseViscosityCoProcessor(SPtr<Grid3D> grid, SPtr<UbScheduler> s, mu::Parser *nueFunc, SPtr<Communicator> comm); + ~DecreaseViscosityCoProcessor() override; + //! calls collect PostprocessData. + void process(double step) override; + protected: - //! resets the collision factor depending on the current timestep. - void setViscosity(double step); - SPtr<Communicator> comm; + //! resets the collision factor depending on the current timestep. + void setViscosity(double step); + SPtr<Communicator> comm; + private: - mutable mu::value_type timeStep; - mu::Parser* nueFunc; + mutable mu::value_type timeStep; + mu::Parser *nueFunc; }; - #endif /* DecreaseViscosityCoProcessor_H_ */ diff --git a/src/cpu/VirtualFluidsCore/CoProcessors/EmergencyExitCoProcessor.cpp b/src/cpu/VirtualFluidsCore/CoProcessors/EmergencyExitCoProcessor.cpp index f8d103396caa187a8def6296ca201e729223bcd1..11251a33660ff72887ce984baba43b820c9a22e5 100644 --- a/src/cpu/VirtualFluidsCore/CoProcessors/EmergencyExitCoProcessor.cpp +++ b/src/cpu/VirtualFluidsCore/CoProcessors/EmergencyExitCoProcessor.cpp @@ -1,73 +1,64 @@ #include "EmergencyExitCoProcessor.h" -#include <basics/utilities/UbFileOutputASCII.h> -#include <basics/utilities/UbFileInputASCII.h> -#include "UbLogger.h" -#include "UbScheduler.h" #include "Communicator.h" -#include "MPIIORestartCoProcessor.h" #include "Grid3D.h" +#include "MPIIORestartCoProcessor.h" +#include "UbLogger.h" +#include "UbScheduler.h" +#include <basics/utilities/UbFileInputASCII.h> +#include <basics/utilities/UbFileOutputASCII.h> -EmergencyExitCoProcessor::EmergencyExitCoProcessor( SPtr<Grid3D> grid, SPtr<UbScheduler> s, - const std::string& path, - SPtr<MPIIORestartCoProcessor> rp, SPtr<Communicator> comm) : - CoProcessor(grid, s), - path(path), - rp(rp), - comm(comm) +EmergencyExitCoProcessor::EmergencyExitCoProcessor(SPtr<Grid3D> grid, SPtr<UbScheduler> s, const std::string &path, + SPtr<MPIIORestartCoProcessor> rp, SPtr<Communicator> comm) + : CoProcessor(grid, s), path(path), rp(rp), comm(comm) { - this->path = path + "/exit"; - metafile = this->path + "/stop.txt"; - if (comm->getProcessID() == comm->getRoot()) - { - //checkMetafile(); - writeMetafile(false); - } - comm->barrier(); + this->path = path + "/exit"; + metafile = this->path + "/stop.txt"; + if (comm->getProcessID() == comm->getRoot()) { + // checkMetafile(); + writeMetafile(false); + } + comm->barrier(); } ////////////////////////////////////////////////////////////////////////// -EmergencyExitCoProcessor::~EmergencyExitCoProcessor() -= default; +EmergencyExitCoProcessor::~EmergencyExitCoProcessor() = default; ////////////////////////////////////////////////////////////////////////// -void EmergencyExitCoProcessor::process( double step ) +void EmergencyExitCoProcessor::process(double step) { - if(scheduler->isDue(step) ) - collectData(step); + if (scheduler->isDue(step)) + collectData(step); - UBLOG(logDEBUG3, "EmergencyExitCoProcessor::update:" << step); + UBLOG(logDEBUG3, "EmergencyExitCoProcessor::update:" << step); } -void EmergencyExitCoProcessor::collectData( double step ) +void EmergencyExitCoProcessor::collectData(double step) { - if(readMetafile()) - { - rp->process((int)step); - if(comm->getProcessID() == comm->getRoot()) UBLOG(logINFO,"EmergencyExitCoProcessor save step: " << step); - comm->barrier(); - exit(EXIT_SUCCESS); - } + if (readMetafile()) { + rp->process((int)step); + if (comm->getProcessID() == comm->getRoot()) + UBLOG(logINFO, "EmergencyExitCoProcessor save step: " << step); + comm->barrier(); + exit(EXIT_SUCCESS); + } } ////////////////////////////////////////////////////////////////////////// -void EmergencyExitCoProcessor::writeMetafile(int /*status*/ ) +void EmergencyExitCoProcessor::writeMetafile(int /*status*/) { - UbFileOutputASCII out(metafile); - out.writeBool(false); + UbFileOutputASCII out(metafile); + out.writeBool(false); } ////////////////////////////////////////////////////////////////////////// bool EmergencyExitCoProcessor::readMetafile() { - UbFileInputASCII in(metafile); - return in.readBool(); + UbFileInputASCII in(metafile); + return in.readBool(); } ////////////////////////////////////////////////////////////////////////// void EmergencyExitCoProcessor::checkMetafile() { - std::ifstream file(metafile.c_str()); - if (!file.is_open()) - { - writeMetafile(false); - return; - } - file.close(); + std::ifstream file(metafile.c_str()); + if (!file.is_open()) { + writeMetafile(false); + return; + } + file.close(); } - - diff --git a/src/cpu/VirtualFluidsCore/CoProcessors/EmergencyExitCoProcessor.h b/src/cpu/VirtualFluidsCore/CoProcessors/EmergencyExitCoProcessor.h index 4dd768a595e5cddc7b767a142ed37184e4464ac4..382083c07a0b1dc900ef59ae2c2d5a5967d32f72 100644 --- a/src/cpu/VirtualFluidsCore/CoProcessors/EmergencyExitCoProcessor.h +++ b/src/cpu/VirtualFluidsCore/CoProcessors/EmergencyExitCoProcessor.h @@ -21,7 +21,8 @@ class UbScheduler; class EmergencyExitCoProcessor : public CoProcessor { public: - EmergencyExitCoProcessor(SPtr<Grid3D> grid, SPtr<UbScheduler> s, const std::string& path, SPtr<MPIIORestartCoProcessor> rp, SPtr<Communicator> comm); + EmergencyExitCoProcessor(SPtr<Grid3D> grid, SPtr<UbScheduler> s, const std::string &path, + SPtr<MPIIORestartCoProcessor> rp, SPtr<Communicator> comm); ~EmergencyExitCoProcessor() override; void process(double step) override; @@ -39,5 +40,4 @@ private: std::string metafile; }; - #endif /* EmergencyExitCoProcessor_H */ diff --git a/src/cpu/VirtualFluidsCore/CoProcessors/ForceCalculator.cpp b/src/cpu/VirtualFluidsCore/CoProcessors/ForceCalculator.cpp index 40a8a61f3a823866abafa6b2f1e63d4c659f11a7..7e04fd4b66a9abb108d07d7d033768f25b769299 100644 --- a/src/cpu/VirtualFluidsCore/CoProcessors/ForceCalculator.cpp +++ b/src/cpu/VirtualFluidsCore/CoProcessors/ForceCalculator.cpp @@ -1,105 +1,93 @@ #include "ForceCalculator.h" #include "BCProcessor.h" -#include "Communicator.h" -#include "D3Q27Interactor.h" -#include "DataSet3D.h" -#include "LBMKernel.h" +#include "BCArray3D.h" #include "Block3D.h" #include "BoundaryConditions.h" -#include "BCArray3D.h" #include "Communicator.h" -#include "DistributionArray3D.h" -#include "BoundaryConditions.h" #include "D3Q27Interactor.h" +#include "DataSet3D.h" +#include "DistributionArray3D.h" +#include "LBMKernel.h" -ForceCalculator::ForceCalculator(SPtr<Communicator> comm) : comm(comm), forceX1global(0), forceX2global(0), forceX3global(0) +ForceCalculator::ForceCalculator(SPtr<Communicator> comm) + : comm(comm), forceX1global(0), forceX2global(0), forceX3global(0) { - } -ForceCalculator::~ForceCalculator() -= default; - - +ForceCalculator::~ForceCalculator() = default; - -Vector3D ForceCalculator::getForces(int x1, int x2, int x3, SPtr<DistributionArray3D> distributions, SPtr<BoundaryConditions> bc, const Vector3D& boundaryVelocity) const +Vector3D ForceCalculator::getForces(int x1, int x2, int x3, SPtr<DistributionArray3D> distributions, + SPtr<BoundaryConditions> bc, const Vector3D &boundaryVelocity) const { double forceX1 = 0; double forceX2 = 0; double forceX3 = 0; - if (bc) - { - for (int fdir = D3Q27System::FSTARTDIR; fdir <= D3Q27System::FENDDIR; fdir++) - { - if (bc->hasNoSlipBoundaryFlag(fdir) || bc->hasVelocityBoundaryFlag(fdir)) - { - const int invDir = D3Q27System::INVDIR[fdir]; - const double f = distributions->getDistributionInvForDirection(x1, x2, x3, invDir); - const double fnbr = distributions->getDistributionInvForDirection(x1 + D3Q27System::DX1[invDir], x2 + D3Q27System::DX2[invDir], x3 + D3Q27System::DX3[invDir], fdir); + if (bc) { + for (int fdir = D3Q27System::FSTARTDIR; fdir <= D3Q27System::FENDDIR; fdir++) { + if (bc->hasNoSlipBoundaryFlag(fdir) || bc->hasVelocityBoundaryFlag(fdir)) { + const int invDir = D3Q27System::INVDIR[fdir]; + const double f = distributions->getDistributionInvForDirection(x1, x2, x3, invDir); + const double fnbr = distributions->getDistributionInvForDirection( + x1 + D3Q27System::DX1[invDir], x2 + D3Q27System::DX2[invDir], x3 + D3Q27System::DX3[invDir], fdir); double correction[3] = { 0.0, 0.0, 0.0 }; - if(bc->hasVelocityBoundaryFlag(fdir)) - { + if (bc->hasVelocityBoundaryFlag(fdir)) { const double forceTerm = f - fnbr; - correction[0] = forceTerm * boundaryVelocity[0]; - correction[1] = forceTerm * boundaryVelocity[1]; - correction[2] = forceTerm * boundaryVelocity[2]; + correction[0] = forceTerm * boundaryVelocity[0]; + correction[1] = forceTerm * boundaryVelocity[1]; + correction[2] = forceTerm * boundaryVelocity[2]; } - //UBLOG(logINFO, "c, c * bv(x,y,z): " << correction << ", " << correction * val<1>(boundaryVelocity) << ", " << correction * val<2>(boundaryVelocity) << ", " << correction * val<3>(boundaryVelocity)); + // UBLOG(logINFO, "c, c * bv(x,y,z): " << correction << ", " << correction * val<1>(boundaryVelocity) << + // ", " << correction * val<2>(boundaryVelocity) << ", " << correction * val<3>(boundaryVelocity)); // force consists of the MEM part and the galilean invariance correction including the boundary velocity forceX1 += (f + fnbr) * D3Q27System::DX1[invDir] - correction[0]; forceX2 += (f + fnbr) * D3Q27System::DX2[invDir] - correction[1]; forceX3 += (f + fnbr) * D3Q27System::DX3[invDir] - correction[2]; } - } + } } return Vector3D(forceX1, forceX2, forceX3); } -void ForceCalculator::calculateForces(std::vector<SPtr<D3Q27Interactor> > interactors) +void ForceCalculator::calculateForces(std::vector<SPtr<D3Q27Interactor>> interactors) { forceX1global = 0.0; forceX2global = 0.0; forceX3global = 0.0; - for (const auto& interactor : interactors) - { - for (const auto& t : interactor->getBcNodeIndicesMap()) - { + for (const auto &interactor : interactors) { + for (const auto &t : interactor->getBcNodeIndicesMap()) { double forceX1 = 0.0; double forceX2 = 0.0; double forceX3 = 0.0; - SPtr<Block3D>block = t.first; - SPtr<ILBMKernel> kernel = block->getKernel(); - SPtr<BCArray3D> bcArray = kernel->getBCProcessor()->getBCArray(); + SPtr<Block3D> block = t.first; + SPtr<ILBMKernel> kernel = block->getKernel(); + SPtr<BCArray3D> bcArray = kernel->getBCProcessor()->getBCArray(); SPtr<DistributionArray3D> distributions = kernel->getDataSet()->getFdistributions(); distributions->swap(); - const std::set< std::vector<int> >& transNodeIndices = t.second; - for (std::vector<int> node : transNodeIndices) - { + const std::set<std::vector<int>> &transNodeIndices = t.second; + for (std::vector<int> node : transNodeIndices) { int x1 = node[0]; int x2 = node[1]; int x3 = node[2]; - if (kernel->isInsideOfDomain(x1, x2, x3) && bcArray->isFluid(x1, x2, x3)) - { + if (kernel->isInsideOfDomain(x1, x2, x3) && bcArray->isFluid(x1, x2, x3)) { SPtr<BoundaryConditions> bc = bcArray->getBC(x1, x2, x3); - Vector3D forceVec = getForces(x1, x2, x3, distributions, bc); + Vector3D forceVec = getForces(x1, x2, x3, distributions, bc); forceX1 += forceVec[0]; forceX2 += forceVec[1]; forceX3 += forceVec[2]; } } - //if we have got discretization with more level - // deltaX is LBM deltaX and equal LBM deltaT - double deltaX = LBMSystem::getDeltaT(block->getLevel()); //grid->getDeltaT(block); - double deltaXquadrat = deltaX*deltaX; + // if we have got discretization with more level + // deltaX is LBM deltaX and equal LBM deltaT + double deltaX = LBMSystem::getDeltaT(block->getLevel()); // grid->getDeltaT(block); + double deltaXquadrat = deltaX * deltaX; forceX1 *= deltaXquadrat; forceX2 *= deltaXquadrat; forceX3 *= deltaXquadrat; @@ -116,20 +104,19 @@ void ForceCalculator::calculateForces(std::vector<SPtr<D3Q27Interactor> > intera void ForceCalculator::gatherGlobalForces() { - std::vector<double> values;// intel compiler 17 dasn't support this { forceX1global , forceX2global, forceX3global }; + std::vector<double> + values; // intel compiler 17 dasn't support this { forceX1global , forceX2global, forceX3global }; values.push_back(forceX1global); values.push_back(forceX2global); values.push_back(forceX3global); std::vector<double> rvalues = comm->gather(values); - if (comm->isRoot()) - { + if (comm->isRoot()) { forceX1global = 0.0; forceX2global = 0.0; forceX3global = 0.0; - for (int i = 0; i < (int)rvalues.size(); i += 3) - { + for (int i = 0; i < (int)rvalues.size(); i += 3) { forceX1global += rvalues[i]; forceX2global += rvalues[i + 1]; forceX3global += rvalues[i + 2]; @@ -137,7 +124,4 @@ void ForceCalculator::gatherGlobalForces() } } -Vector3D ForceCalculator::getGlobalForces() const -{ - return Vector3D(forceX1global, forceX2global, forceX3global); -} +Vector3D ForceCalculator::getGlobalForces() const { return Vector3D(forceX1global, forceX2global, forceX3global); } diff --git a/src/cpu/VirtualFluidsCore/CoProcessors/ForceCalculator.h b/src/cpu/VirtualFluidsCore/CoProcessors/ForceCalculator.h index 8d90d09d8f304a8ef49a7009f879fa6e5651391d..432cc452263deb9206a834251e49612276c2a060 100644 --- a/src/cpu/VirtualFluidsCore/CoProcessors/ForceCalculator.h +++ b/src/cpu/VirtualFluidsCore/CoProcessors/ForceCalculator.h @@ -8,8 +8,8 @@ #ifndef ForceCalculator_H #define ForceCalculator_H -#include <vector> #include <memory> +#include <vector> #include "Vector3D.h" @@ -24,8 +24,10 @@ public: ForceCalculator(std::shared_ptr<Communicator> comm); virtual ~ForceCalculator(); - void calculateForces(std::vector<std::shared_ptr<D3Q27Interactor> > interactors); - Vector3D getForces(int x1, int x2, int x3, std::shared_ptr<DistributionArray3D> distributions, std::shared_ptr<BoundaryConditions> bc, const Vector3D& boundaryVelocity = Vector3D(0.0, 0.0, 0.0)) const; + void calculateForces(std::vector<std::shared_ptr<D3Q27Interactor>> interactors); + Vector3D getForces(int x1, int x2, int x3, std::shared_ptr<DistributionArray3D> distributions, + std::shared_ptr<BoundaryConditions> bc, + const Vector3D &boundaryVelocity = Vector3D(0.0, 0.0, 0.0)) const; Vector3D getGlobalForces() const; @@ -39,5 +41,4 @@ private: double forceX3global; }; - -#endif +#endif diff --git a/src/cpu/VirtualFluidsCore/CoProcessors/InSituCatalystCoProcessor.cpp b/src/cpu/VirtualFluidsCore/CoProcessors/InSituCatalystCoProcessor.cpp index 53916a56ee3698b4b0548b2d1bc84a00bca249df..6955c55dd315a350909695d5693f60a6368f6bb0 100644 --- a/src/cpu/VirtualFluidsCore/CoProcessors/InSituCatalystCoProcessor.cpp +++ b/src/cpu/VirtualFluidsCore/CoProcessors/InSituCatalystCoProcessor.cpp @@ -1,349 +1,337 @@ #ifdef VF_CATALYST #include "InSituCatalystCoProcessor.h" -#include <LBMKernel.h> #include <D3Q27ETBCProcessor.h> -#include <vector> +#include <LBMKernel.h> #include <string> +#include <vector> #include <vtkCellType.h> #include <vtkPointData.h> #include <vtkXMLUnstructuredGridWriter.h> -#include <iostream> #include <fstream> +#include <iostream> using namespace std; -InSituCatalystCoProcessor::InSituCatalystCoProcessor() -{ - -} +InSituCatalystCoProcessor::InSituCatalystCoProcessor() {} ////////////////////////////////////////////////////////////////////////// -InSituCatalystCoProcessor::InSituCatalystCoProcessor(SPtr<Grid3D> grid, SPtr<UbScheduler> s, std::string script) : CoProcessor(grid, s) +InSituCatalystCoProcessor::InSituCatalystCoProcessor(SPtr<Grid3D> grid, SPtr<UbScheduler> s, std::string script) + : CoProcessor(grid, s) { - gridRank = Communicator::getInstance()->getProcessID(); - minInitLevel = this->grid->getCoarsestInitializedLevel(); - maxInitLevel = this->grid->getFinestInitializedLevel(); + gridRank = Communicator::getInstance()->getProcessID(); + minInitLevel = this->grid->getCoarsestInitializedLevel(); + maxInitLevel = this->grid->getFinestInitializedLevel(); - blockVector.resize(maxInitLevel + 1); + blockVector.resize(maxInitLevel + 1); - for (int level = minInitLevel; level <= maxInitLevel; level++) - { - grid->getBlocks(level, gridRank, true, blockVector[level]); - } + for (int level = minInitLevel; level <= maxInitLevel; level++) { + grid->getBlocks(level, gridRank, true, blockVector[level]); + } - Processor = vtkSmartPointer<vtkCPProcessor>::New(); - Processor->Initialize(); + Processor = vtkSmartPointer<vtkCPProcessor>::New(); + Processor->Initialize(); - vtkNew<vtkCPPythonScriptPipeline> pipeline; - pipeline->Initialize(script.c_str()); - Processor->AddPipeline(pipeline.GetPointer()); + vtkNew<vtkCPPythonScriptPipeline> pipeline; + pipeline->Initialize(script.c_str()); + Processor->AddPipeline(pipeline.GetPointer()); - buildVTKGrid(); + buildVTKGrid(); } ////////////////////////////////////////////////////////////////////////// -InSituCatalystCoProcessor::~InSituCatalystCoProcessor() -{ - -} +InSituCatalystCoProcessor::~InSituCatalystCoProcessor() {} ////////////////////////////////////////////////////////////////////////// void InSituCatalystCoProcessor::process(double step) { - if (scheduler->isDue(step)) - collectData(step); + if (scheduler->isDue(step)) + collectData(step); - UBLOG(logDEBUG3, "InSituCatalystCoProcessor::update:" << step); + UBLOG(logDEBUG3, "InSituCatalystCoProcessor::update:" << step); } ////////////////////////////////////////////////////////////////////////// void InSituCatalystCoProcessor::collectData(double step) { - unsigned int istep = static_cast<int>(step); - - vtkNew<vtkCPDataDescription> dataDescription; - dataDescription->AddInput("input"); - dataDescription->SetTimeData(step, istep); - - if (Processor->RequestDataDescription(dataDescription.GetPointer()) != 0) - { - - index = 0; - - for (int level = minInitLevel; level <= maxInitLevel; level++) - { - for(SPtr<Block3D> block : blockVector[level]) - { - if (block) - { - addData(block); + unsigned int istep = static_cast<int>(step); + + vtkNew<vtkCPDataDescription> dataDescription; + dataDescription->AddInput("input"); + dataDescription->SetTimeData(step, istep); + + if (Processor->RequestDataDescription(dataDescription.GetPointer()) != 0) { + + index = 0; + + for (int level = minInitLevel; level <= maxInitLevel; level++) { + for (SPtr<Block3D> block : blockVector[level]) { + if (block) { + addData(block); + } } - } - } + } - vtkDoubleArray* rho = vtkDoubleArray::SafeDownCast(unstructuredGrid->GetPointData()->GetArray("Rho")); - rho->SetArray(&rhoArray[0], static_cast<vtkIdType>(rhoArray.size()), 1); + vtkDoubleArray *rho = vtkDoubleArray::SafeDownCast(unstructuredGrid->GetPointData()->GetArray("Rho")); + rho->SetArray(&rhoArray[0], static_cast<vtkIdType>(rhoArray.size()), 1); - vtkDoubleArray* vx1 = vtkDoubleArray::SafeDownCast(unstructuredGrid->GetPointData()->GetArray("Vx")); - vx1->SetArray(&vx1Array[0], static_cast<vtkIdType>(vx1Array.size()), 1); + vtkDoubleArray *vx1 = vtkDoubleArray::SafeDownCast(unstructuredGrid->GetPointData()->GetArray("Vx")); + vx1->SetArray(&vx1Array[0], static_cast<vtkIdType>(vx1Array.size()), 1); - vtkDoubleArray* vx2 = vtkDoubleArray::SafeDownCast(unstructuredGrid->GetPointData()->GetArray("Vy")); - vx2->SetArray(&vx2Array[0], static_cast<vtkIdType>(vx2Array.size()), 1); + vtkDoubleArray *vx2 = vtkDoubleArray::SafeDownCast(unstructuredGrid->GetPointData()->GetArray("Vy")); + vx2->SetArray(&vx2Array[0], static_cast<vtkIdType>(vx2Array.size()), 1); - vtkDoubleArray* vx3 = vtkDoubleArray::SafeDownCast(unstructuredGrid->GetPointData()->GetArray("Vz")); - vx3->SetArray(&vx3Array[0], static_cast<vtkIdType>(vx3Array.size()), 1); + vtkDoubleArray *vx3 = vtkDoubleArray::SafeDownCast(unstructuredGrid->GetPointData()->GetArray("Vz")); + vx3->SetArray(&vx3Array[0], static_cast<vtkIdType>(vx3Array.size()), 1); - dataDescription->GetInputDescriptionByName("input")->SetGrid(unstructuredGrid); - Processor->CoProcess(dataDescription.GetPointer()); - } + dataDescription->GetInputDescriptionByName("input")->SetGrid(unstructuredGrid); + Processor->CoProcess(dataDescription.GetPointer()); + } - UBLOG(logINFO, "InSituCatalystCoProcessor step: " << istep); + UBLOG(logINFO, "InSituCatalystCoProcessor step: " << istep); } ////////////////////////////////////////////////////////////////////////// void InSituCatalystCoProcessor::addData(SPtr<Block3D> block) { - UbTupleDouble3 org = grid->getBlockWorldCoordinates(block); - UbTupleDouble3 blockLengths = grid->getBlockLengths(block); - UbTupleDouble3 nodeOffset = grid->getNodeOffset(block); - double dx = grid->getDeltaX(block); - - SPtr<LBMKernel> kernel = block->getKernel(); - SPtr<BCArray3D> bcArray = kernel->getBCProcessor()->getBCArray(); - SPtr<DistributionArray3D> distributions = kernel->getDataSet()->getFdistributions(); - LBMReal f[D3Q27System::ENDF + 1]; - LBMReal vx1, vx2, vx3, rho; - - int minX1 = 0; - int minX2 = 0; - int minX3 = 0; - - int maxX1 = (int)(distributions->getNX1()); - int maxX2 = (int)(distributions->getNX2()); - int maxX3 = (int)(distributions->getNX3()); - - //nummern vergeben und node vector erstellen + daten sammeln - CbArray3D<int> nodeNumbers((int)maxX1, (int)maxX2, (int)maxX3, -1); - maxX1 -= 2; - maxX2 -= 2; - maxX3 -= 2; - - - - for (size_t ix3 = minX3; ix3 <= maxX3; ix3++) - { - for (size_t ix2 = minX2; ix2 <= maxX2; ix2++) - { - for (size_t ix1 = minX1; ix1 <= maxX1; ix1++) - { - if (!bcArray->isUndefined(ix1, ix2, ix3) && !bcArray->isSolid(ix1, ix2, ix3)) - { - distributions->getDistribution(f, ix1, ix2, ix3); - calcMacros(f, rho, vx1, vx2, vx3); - double press = D3Q27System::calcPress(f, rho, vx1, vx2, vx3); - - if (UbMath::isNaN(rho) || UbMath::isInfinity(rho)) - UB_THROW(UbException(UB_EXARGS, "rho is not a number (nan or -1.#IND) or infinity number -1.#INF in block=" + block->toString() + - ", node=" + UbSystem::toString(ix1) + "," + UbSystem::toString(ix2) + "," + UbSystem::toString(ix3))); - //rho=999.0; - if (UbMath::isNaN(press) || UbMath::isInfinity(press)) - UB_THROW(UbException(UB_EXARGS, "press is not a number (nan or -1.#IND) or infinity number -1.#INF in block=" + block->toString() + - ", node=" + UbSystem::toString(ix1) + "," + UbSystem::toString(ix2) + "," + UbSystem::toString(ix3))); - //press=999.0; - if (UbMath::isNaN(vx1) || UbMath::isInfinity(vx1)) - UB_THROW(UbException(UB_EXARGS, "vx1 is not a number (nan or -1.#IND) or infinity number -1.#INF in block=" + block->toString() + - ", node=" + UbSystem::toString(ix1) + "," + UbSystem::toString(ix2) + "," + UbSystem::toString(ix3))); - //vx1=999.0; - if (UbMath::isNaN(vx2) || UbMath::isInfinity(vx2)) - UB_THROW(UbException(UB_EXARGS, "vx2 is not a number (nan or -1.#IND) or infinity number -1.#INF in block=" + block->toString() + - ", node=" + UbSystem::toString(ix1) + "," + UbSystem::toString(ix2) + "," + UbSystem::toString(ix3))); - //vx2=999.0; - if (UbMath::isNaN(vx3) || UbMath::isInfinity(vx3)) - UB_THROW(UbException(UB_EXARGS, "vx3 is not a number (nan or -1.#IND) or infinity number -1.#INF in block=" + block->toString() + - ", node=" + UbSystem::toString(ix1) + "," + UbSystem::toString(ix2) + "," + UbSystem::toString(ix3))); - //vx3=999.0; - - rhoArray[index] = rho; - vx1Array[index] = vx1; - vx2Array[index] = vx2; - vx3Array[index] = vx3; - index++; + UbTupleDouble3 org = grid->getBlockWorldCoordinates(block); + UbTupleDouble3 blockLengths = grid->getBlockLengths(block); + UbTupleDouble3 nodeOffset = grid->getNodeOffset(block); + double dx = grid->getDeltaX(block); + + SPtr<LBMKernel> kernel = block->getKernel(); + SPtr<BCArray3D> bcArray = kernel->getBCProcessor()->getBCArray(); + SPtr<DistributionArray3D> distributions = kernel->getDataSet()->getFdistributions(); + LBMReal f[D3Q27System::ENDF + 1]; + LBMReal vx1, vx2, vx3, rho; + + int minX1 = 0; + int minX2 = 0; + int minX3 = 0; + + int maxX1 = (int)(distributions->getNX1()); + int maxX2 = (int)(distributions->getNX2()); + int maxX3 = (int)(distributions->getNX3()); + + // nummern vergeben und node vector erstellen + daten sammeln + CbArray3D<int> nodeNumbers((int)maxX1, (int)maxX2, (int)maxX3, -1); + maxX1 -= 2; + maxX2 -= 2; + maxX3 -= 2; + + for (size_t ix3 = minX3; ix3 <= maxX3; ix3++) { + for (size_t ix2 = minX2; ix2 <= maxX2; ix2++) { + for (size_t ix1 = minX1; ix1 <= maxX1; ix1++) { + if (!bcArray->isUndefined(ix1, ix2, ix3) && !bcArray->isSolid(ix1, ix2, ix3)) { + distributions->getDistribution(f, ix1, ix2, ix3); + calcMacros(f, rho, vx1, vx2, vx3); + double press = D3Q27System::calcPress(f, rho, vx1, vx2, vx3); + + if (UbMath::isNaN(rho) || UbMath::isInfinity(rho)) + UB_THROW(UbException( + UB_EXARGS, "rho is not a number (nan or -1.#IND) or infinity number -1.#INF in block=" + + block->toString() + ", node=" + UbSystem::toString(ix1) + "," + + UbSystem::toString(ix2) + "," + UbSystem::toString(ix3))); + // rho=999.0; + if (UbMath::isNaN(press) || UbMath::isInfinity(press)) + UB_THROW(UbException( + UB_EXARGS, "press is not a number (nan or -1.#IND) or infinity number -1.#INF in block=" + + block->toString() + ", node=" + UbSystem::toString(ix1) + "," + + UbSystem::toString(ix2) + "," + UbSystem::toString(ix3))); + // press=999.0; + if (UbMath::isNaN(vx1) || UbMath::isInfinity(vx1)) + UB_THROW(UbException( + UB_EXARGS, "vx1 is not a number (nan or -1.#IND) or infinity number -1.#INF in block=" + + block->toString() + ", node=" + UbSystem::toString(ix1) + "," + + UbSystem::toString(ix2) + "," + UbSystem::toString(ix3))); + // vx1=999.0; + if (UbMath::isNaN(vx2) || UbMath::isInfinity(vx2)) + UB_THROW(UbException( + UB_EXARGS, "vx2 is not a number (nan or -1.#IND) or infinity number -1.#INF in block=" + + block->toString() + ", node=" + UbSystem::toString(ix1) + "," + + UbSystem::toString(ix2) + "," + UbSystem::toString(ix3))); + // vx2=999.0; + if (UbMath::isNaN(vx3) || UbMath::isInfinity(vx3)) + UB_THROW(UbException( + UB_EXARGS, "vx3 is not a number (nan or -1.#IND) or infinity number -1.#INF in block=" + + block->toString() + ", node=" + UbSystem::toString(ix1) + "," + + UbSystem::toString(ix2) + "," + UbSystem::toString(ix3))); + // vx3=999.0; + + rhoArray[index] = rho; + vx1Array[index] = vx1; + vx2Array[index] = vx2; + vx3Array[index] = vx3; + index++; + } } - } - } - } + } + } } ////////////////////////////////////////////////////////////////////////// void InSituCatalystCoProcessor::buildVTKGrid() { - unstructuredGrid = vtkSmartPointer<vtkUnstructuredGrid>::New(); - points = vtkPoints::New(); - unstructuredGrid->SetPoints(points); - arrays[0] = vtkSmartPointer<vtkDoubleArray>::New(); - arrays[0]->SetNumberOfComponents(1); - arrays[0]->SetName("Rho"); - arrays[1] = vtkSmartPointer<vtkDoubleArray>::New(); - arrays[1]->SetNumberOfComponents(1); - arrays[1]->SetName("Vx"); - arrays[2] = vtkSmartPointer<vtkDoubleArray>::New(); - arrays[2]->SetNumberOfComponents(1); - arrays[2]->SetName("Vy"); - arrays[3] = vtkSmartPointer<vtkDoubleArray>::New(); - arrays[3]->SetNumberOfComponents(1); - arrays[3]->SetName("Vz"); - - numOfPoints = 0; - - for (int level = minInitLevel; level <= maxInitLevel; level++) - { - for(SPtr<Block3D> block : blockVector[level]) - { - if (block) - { - addVTKGridData(block); - } - } - } - - unstructuredGrid->GetPointData()->AddArray(arrays[0]); - unstructuredGrid->GetPointData()->AddArray(arrays[1]); - unstructuredGrid->GetPointData()->AddArray(arrays[2]); - unstructuredGrid->GetPointData()->AddArray(arrays[3]); - unstructuredGrid->GetPointData()->SetScalars(arrays[1]); - - rhoArray.resize(numOfPoints); - vx1Array.resize(numOfPoints); - vx2Array.resize(numOfPoints); - vx3Array.resize(numOfPoints); + unstructuredGrid = vtkSmartPointer<vtkUnstructuredGrid>::New(); + points = vtkPoints::New(); + unstructuredGrid->SetPoints(points); + arrays[0] = vtkSmartPointer<vtkDoubleArray>::New(); + arrays[0]->SetNumberOfComponents(1); + arrays[0]->SetName("Rho"); + arrays[1] = vtkSmartPointer<vtkDoubleArray>::New(); + arrays[1]->SetNumberOfComponents(1); + arrays[1]->SetName("Vx"); + arrays[2] = vtkSmartPointer<vtkDoubleArray>::New(); + arrays[2]->SetNumberOfComponents(1); + arrays[2]->SetName("Vy"); + arrays[3] = vtkSmartPointer<vtkDoubleArray>::New(); + arrays[3]->SetNumberOfComponents(1); + arrays[3]->SetName("Vz"); + + numOfPoints = 0; + + for (int level = minInitLevel; level <= maxInitLevel; level++) { + for (SPtr<Block3D> block : blockVector[level]) { + if (block) { + addVTKGridData(block); + } + } + } + + unstructuredGrid->GetPointData()->AddArray(arrays[0]); + unstructuredGrid->GetPointData()->AddArray(arrays[1]); + unstructuredGrid->GetPointData()->AddArray(arrays[2]); + unstructuredGrid->GetPointData()->AddArray(arrays[3]); + unstructuredGrid->GetPointData()->SetScalars(arrays[1]); + + rhoArray.resize(numOfPoints); + vx1Array.resize(numOfPoints); + vx2Array.resize(numOfPoints); + vx3Array.resize(numOfPoints); } ////////////////////////////////////////////////////////////////////////// void InSituCatalystCoProcessor::addVTKGridData(SPtr<Block3D> block) { - UbTupleDouble3 org = grid->getBlockWorldCoordinates(block); - UbTupleDouble3 blockLengths = grid->getBlockLengths(block); - UbTupleDouble3 nodeOffset = grid->getNodeOffset(block); - double dx = grid->getDeltaX(block); - - SPtr<LBMKernel> kernel = block->getKernel(); - SPtr<BCArray3D> bcArray = kernel->getBCProcessor()->getBCArray(); - SPtr<DistributionArray3D> distributions = kernel->getDataSet()->getFdistributions(); - LBMReal f[D3Q27System::ENDF + 1]; - LBMReal vx1, vx2, vx3, rho; - - //knotennummerierung faengt immer bei 0 an! - int SWB, SEB, NEB, NWB, SWT, SET, NET, NWT; - - //Funktionszeiger - //typedef void(*CalcMacrosFct)(const LBMReal* const& /*feq[27]*/, LBMReal& /*(d)rho*/, LBMReal& /*vx1*/, LBMReal& /*vx2*/, LBMReal& /*vx3*/); - - //CalcMacrosFct calcMacros = NULL; - - if (block->getKernel()->getCompressible()) - { - calcMacros = &D3Q27System::calcCompMacroscopicValues; - } - else - { - calcMacros = &D3Q27System::calcIncompMacroscopicValues; - } - - int minX1 = 0; - int minX2 = 0; - int minX3 = 0; - - int maxX1 = (int)(distributions->getNX1()); - int maxX2 = (int)(distributions->getNX2()); - int maxX3 = (int)(distributions->getNX3()); - - //nummern vergeben und node vector erstellen + daten sammeln - CbArray3D<int> nodeNumbers((int)maxX1, (int)maxX2, (int)maxX3, -1); - maxX1 -= 2; - maxX2 -= 2; - maxX3 -= 2; - - SPtr<BoundaryConditions> bcPtr; - int nr = points->GetNumberOfPoints(); - - double x[3]; - - for (size_t ix3 = minX3; ix3 <= maxX3; ix3++) - { - for (size_t ix2 = minX2; ix2 <= maxX2; ix2++) - { - for (size_t ix1 = minX1; ix1 <= maxX1; ix1++) - { - if (!bcArray->isUndefined(ix1, ix2, ix3) && !bcArray->isSolid(ix1, ix2, ix3)) - { - x[0] = double(val<1>(org) -val<1>(nodeOffset) +ix1*dx); - x[1] = double(val<2>(org) -val<2>(nodeOffset) +ix2*dx); - x[2] = double(val<3>(org) -val<3>(nodeOffset) +ix3*dx); - - points->InsertPoint((vtkIdType)nr, x); - - nodeNumbers(ix1, ix2, ix3) = nr++; - - distributions->getDistribution(f, ix1, ix2, ix3); - calcMacros(f, rho, vx1, vx2, vx3); - double press = D3Q27System::calcPress(f, rho, vx1, vx2, vx3); - - if (UbMath::isNaN(rho) || UbMath::isInfinity(rho)) - UB_THROW(UbException(UB_EXARGS, "rho is not a number (nan or -1.#IND) or infinity number -1.#INF in block=" + block->toString() + - ", node=" + UbSystem::toString(ix1) + "," + UbSystem::toString(ix2) + "," + UbSystem::toString(ix3))); - //rho=999.0; - if (UbMath::isNaN(press) || UbMath::isInfinity(press)) - UB_THROW(UbException(UB_EXARGS, "press is not a number (nan or -1.#IND) or infinity number -1.#INF in block=" + block->toString() + - ", node=" + UbSystem::toString(ix1) + "," + UbSystem::toString(ix2) + "," + UbSystem::toString(ix3))); - //press=999.0; - if (UbMath::isNaN(vx1) || UbMath::isInfinity(vx1)) - UB_THROW(UbException(UB_EXARGS, "vx1 is not a number (nan or -1.#IND) or infinity number -1.#INF in block=" + block->toString() + - ", node=" + UbSystem::toString(ix1) + "," + UbSystem::toString(ix2) + "," + UbSystem::toString(ix3))); - //vx1=999.0; - if (UbMath::isNaN(vx2) || UbMath::isInfinity(vx2)) - UB_THROW(UbException(UB_EXARGS, "vx2 is not a number (nan or -1.#IND) or infinity number -1.#INF in block=" + block->toString() + - ", node=" + UbSystem::toString(ix1) + "," + UbSystem::toString(ix2) + "," + UbSystem::toString(ix3))); - //vx2=999.0; - if (UbMath::isNaN(vx3) || UbMath::isInfinity(vx3)) - UB_THROW(UbException(UB_EXARGS, "vx3 is not a number (nan or -1.#IND) or infinity number -1.#INF in block=" + block->toString() + - ", node=" + UbSystem::toString(ix1) + "," + UbSystem::toString(ix2) + "," + UbSystem::toString(ix3))); - //vx3=999.0; - - arrays[0]->InsertNextValue(rho); - arrays[1]->InsertNextValue(vx1); - arrays[2]->InsertNextValue(vx2); - arrays[3]->InsertNextValue(vx3); - numOfPoints++; + UbTupleDouble3 org = grid->getBlockWorldCoordinates(block); + UbTupleDouble3 blockLengths = grid->getBlockLengths(block); + UbTupleDouble3 nodeOffset = grid->getNodeOffset(block); + double dx = grid->getDeltaX(block); + + SPtr<LBMKernel> kernel = block->getKernel(); + SPtr<BCArray3D> bcArray = kernel->getBCProcessor()->getBCArray(); + SPtr<DistributionArray3D> distributions = kernel->getDataSet()->getFdistributions(); + LBMReal f[D3Q27System::ENDF + 1]; + LBMReal vx1, vx2, vx3, rho; + + // knotennummerierung faengt immer bei 0 an! + int SWB, SEB, NEB, NWB, SWT, SET, NET, NWT; + + // Funktionszeiger + // typedef void(*CalcMacrosFct)(const LBMReal* const& /*feq[27]*/, LBMReal& /*(d)rho*/, LBMReal& /*vx1*/, LBMReal& + // /*vx2*/, LBMReal& /*vx3*/); + + // CalcMacrosFct calcMacros = NULL; + + if (block->getKernel()->getCompressible()) { + calcMacros = &D3Q27System::calcCompMacroscopicValues; + } else { + calcMacros = &D3Q27System::calcIncompMacroscopicValues; + } + + int minX1 = 0; + int minX2 = 0; + int minX3 = 0; + + int maxX1 = (int)(distributions->getNX1()); + int maxX2 = (int)(distributions->getNX2()); + int maxX3 = (int)(distributions->getNX3()); + + // nummern vergeben und node vector erstellen + daten sammeln + CbArray3D<int> nodeNumbers((int)maxX1, (int)maxX2, (int)maxX3, -1); + maxX1 -= 2; + maxX2 -= 2; + maxX3 -= 2; + + SPtr<BoundaryConditions> bcPtr; + int nr = points->GetNumberOfPoints(); + + double x[3]; + + for (size_t ix3 = minX3; ix3 <= maxX3; ix3++) { + for (size_t ix2 = minX2; ix2 <= maxX2; ix2++) { + for (size_t ix1 = minX1; ix1 <= maxX1; ix1++) { + if (!bcArray->isUndefined(ix1, ix2, ix3) && !bcArray->isSolid(ix1, ix2, ix3)) { + x[0] = double(val<1>(org) - val<1>(nodeOffset) + ix1 * dx); + x[1] = double(val<2>(org) - val<2>(nodeOffset) + ix2 * dx); + x[2] = double(val<3>(org) - val<3>(nodeOffset) + ix3 * dx); + + points->InsertPoint((vtkIdType)nr, x); + + nodeNumbers(ix1, ix2, ix3) = nr++; + + distributions->getDistribution(f, ix1, ix2, ix3); + calcMacros(f, rho, vx1, vx2, vx3); + double press = D3Q27System::calcPress(f, rho, vx1, vx2, vx3); + + if (UbMath::isNaN(rho) || UbMath::isInfinity(rho)) + UB_THROW(UbException( + UB_EXARGS, "rho is not a number (nan or -1.#IND) or infinity number -1.#INF in block=" + + block->toString() + ", node=" + UbSystem::toString(ix1) + "," + + UbSystem::toString(ix2) + "," + UbSystem::toString(ix3))); + // rho=999.0; + if (UbMath::isNaN(press) || UbMath::isInfinity(press)) + UB_THROW(UbException( + UB_EXARGS, "press is not a number (nan or -1.#IND) or infinity number -1.#INF in block=" + + block->toString() + ", node=" + UbSystem::toString(ix1) + "," + + UbSystem::toString(ix2) + "," + UbSystem::toString(ix3))); + // press=999.0; + if (UbMath::isNaN(vx1) || UbMath::isInfinity(vx1)) + UB_THROW(UbException( + UB_EXARGS, "vx1 is not a number (nan or -1.#IND) or infinity number -1.#INF in block=" + + block->toString() + ", node=" + UbSystem::toString(ix1) + "," + + UbSystem::toString(ix2) + "," + UbSystem::toString(ix3))); + // vx1=999.0; + if (UbMath::isNaN(vx2) || UbMath::isInfinity(vx2)) + UB_THROW(UbException( + UB_EXARGS, "vx2 is not a number (nan or -1.#IND) or infinity number -1.#INF in block=" + + block->toString() + ", node=" + UbSystem::toString(ix1) + "," + + UbSystem::toString(ix2) + "," + UbSystem::toString(ix3))); + // vx2=999.0; + if (UbMath::isNaN(vx3) || UbMath::isInfinity(vx3)) + UB_THROW(UbException( + UB_EXARGS, "vx3 is not a number (nan or -1.#IND) or infinity number -1.#INF in block=" + + block->toString() + ", node=" + UbSystem::toString(ix1) + "," + + UbSystem::toString(ix2) + "," + UbSystem::toString(ix3))); + // vx3=999.0; + + arrays[0]->InsertNextValue(rho); + arrays[1]->InsertNextValue(vx1); + arrays[2]->InsertNextValue(vx2); + arrays[3]->InsertNextValue(vx3); + numOfPoints++; + } } - } - } - } - maxX1 -= 1; - maxX2 -= 1; - maxX3 -= 1; - - vtkIdType ptIds[8]; - //cell vector erstellen - for (int ix3 = minX3; ix3 <= maxX3; ix3++) - { - for (int ix2 = minX2; ix2 <= maxX2; ix2++) - { - for (int ix1 = minX1; ix1 <= maxX1; ix1++) - { - if ((ptIds[0] = SWB = nodeNumbers(ix1, ix2, ix3)) >= 0 - && (ptIds[1] = SEB = nodeNumbers(ix1 + 1, ix2, ix3)) >= 0 - && (ptIds[2] = NWB = nodeNumbers(ix1, ix2 + 1, ix3)) >= 0 - && (ptIds[3] = NEB = nodeNumbers(ix1 + 1, ix2 + 1, ix3)) >= 0 - && (ptIds[4] = SWT = nodeNumbers(ix1, ix2, ix3 + 1)) >= 0 - && (ptIds[5] = SET = nodeNumbers(ix1 + 1, ix2, ix3 + 1)) >= 0 - && (ptIds[6] = NWT = nodeNumbers(ix1, ix2 + 1, ix3 + 1)) >= 0 - && (ptIds[7] = NET = nodeNumbers(ix1 + 1, ix2 + 1, ix3 + 1)) >= 0 - ) - { - unstructuredGrid->InsertNextCell((int)VTK_VOXEL, (vtkIdType)8, ptIds); + } + } + maxX1 -= 1; + maxX2 -= 1; + maxX3 -= 1; + + vtkIdType ptIds[8]; + // cell vector erstellen + for (int ix3 = minX3; ix3 <= maxX3; ix3++) { + for (int ix2 = minX2; ix2 <= maxX2; ix2++) { + for (int ix1 = minX1; ix1 <= maxX1; ix1++) { + if ((ptIds[0] = SWB = nodeNumbers(ix1, ix2, ix3)) >= 0 && + (ptIds[1] = SEB = nodeNumbers(ix1 + 1, ix2, ix3)) >= 0 && + (ptIds[2] = NWB = nodeNumbers(ix1, ix2 + 1, ix3)) >= 0 && + (ptIds[3] = NEB = nodeNumbers(ix1 + 1, ix2 + 1, ix3)) >= 0 && + (ptIds[4] = SWT = nodeNumbers(ix1, ix2, ix3 + 1)) >= 0 && + (ptIds[5] = SET = nodeNumbers(ix1 + 1, ix2, ix3 + 1)) >= 0 && + (ptIds[6] = NWT = nodeNumbers(ix1, ix2 + 1, ix3 + 1)) >= 0 && + (ptIds[7] = NET = nodeNumbers(ix1 + 1, ix2 + 1, ix3 + 1)) >= 0) { + unstructuredGrid->InsertNextCell((int)VTK_VOXEL, (vtkIdType)8, ptIds); + } } - } - } - } + } + } } ////////////////////////////////////////////////////////////////////////// - #endif - diff --git a/src/cpu/VirtualFluidsCore/CoProcessors/InSituCatalystCoProcessor.h b/src/cpu/VirtualFluidsCore/CoProcessors/InSituCatalystCoProcessor.h index 3d4bb25c62f12ce765cb751175f5ef9cff1374ed..5fa6d3fd13529431c125b799bcbb7ea47dccf1ed 100644 --- a/src/cpu/VirtualFluidsCore/CoProcessors/InSituCatalystCoProcessor.h +++ b/src/cpu/VirtualFluidsCore/CoProcessors/InSituCatalystCoProcessor.h @@ -3,51 +3,53 @@ #ifndef InSituCatalystCoProcessor_h__ #define InSituCatalystCoProcessor_h__ - #include <CoProcessor.h> #include <Grid3D.h> #include <LBMUnitConverter.h> #include <string> -#include <vtkSmartPointer.h> -#include <vtkUnstructuredGrid.h> -#include <vtkDoubleArray.h> #include <vtkCPDataDescription.h> #include <vtkCPInputDataDescription.h> #include <vtkCPProcessor.h> #include <vtkCPPythonScriptPipeline.h> +#include <vtkDoubleArray.h> #include <vtkNew.h> +#include <vtkSmartPointer.h> +#include <vtkUnstructuredGrid.h> class InSituCatalystCoProcessor : public CoProcessor { public: - InSituCatalystCoProcessor(); - InSituCatalystCoProcessor(SPtr<Grid3D> grid, SPtr<UbScheduler> s, std::string script); - virtual ~InSituCatalystCoProcessor(); - void process(double step); + InSituCatalystCoProcessor(); + InSituCatalystCoProcessor(SPtr<Grid3D> grid, SPtr<UbScheduler> s, std::string script); + virtual ~InSituCatalystCoProcessor(); + void process(double step); + protected: - void collectData(double step); - void addData(SPtr<Block3D> block); - void buildVTKGrid(); - void addVTKGridData(SPtr<Block3D> block); + void collectData(double step); + void addData(SPtr<Block3D> block); + void buildVTKGrid(); + void addVTKGridData(SPtr<Block3D> block); + private: - std::vector<std::vector<SPtr<Block3D>> > blockVector; - int minInitLevel; - int maxInitLevel; - int gridRank; - vtkSmartPointer<vtkCPProcessor> Processor; - vtkSmartPointer<vtkUnstructuredGrid> unstructuredGrid; - vtkSmartPointer<vtkPoints> points; - vtkSmartPointer<vtkDoubleArray> arrays[4]; - std::vector<double> vx1Array; - std::vector<double> vx2Array; - std::vector<double> vx3Array; - std::vector<double> rhoArray; - int index; - int numOfPoints; - typedef void(*CalcMacrosFct)(const LBMReal* const& /*feq[27]*/, LBMReal& /*(d)rho*/, LBMReal& /*vx1*/, LBMReal& /*vx2*/, LBMReal& /*vx3*/); - CalcMacrosFct calcMacros; + std::vector<std::vector<SPtr<Block3D>>> blockVector; + int minInitLevel; + int maxInitLevel; + int gridRank; + vtkSmartPointer<vtkCPProcessor> Processor; + vtkSmartPointer<vtkUnstructuredGrid> unstructuredGrid; + vtkSmartPointer<vtkPoints> points; + vtkSmartPointer<vtkDoubleArray> arrays[4]; + std::vector<double> vx1Array; + std::vector<double> vx2Array; + std::vector<double> vx3Array; + std::vector<double> rhoArray; + int index; + int numOfPoints; + typedef void (*CalcMacrosFct)(const LBMReal *const & /*feq[27]*/, LBMReal & /*(d)rho*/, LBMReal & /*vx1*/, + LBMReal & /*vx2*/, LBMReal & /*vx3*/); + CalcMacrosFct calcMacros; }; #endif // InSituCatalystCoProcessor_h__ diff --git a/src/cpu/VirtualFluidsCore/CoProcessors/InSituVTKCoProcessor.cpp b/src/cpu/VirtualFluidsCore/CoProcessors/InSituVTKCoProcessor.cpp index 600488d5865c388292358c779d2ae6b09c32a576..8d5cec10521830ba2aec9f2c06ef2a796da6b954 100644 --- a/src/cpu/VirtualFluidsCore/CoProcessors/InSituVTKCoProcessor.cpp +++ b/src/cpu/VirtualFluidsCore/CoProcessors/InSituVTKCoProcessor.cpp @@ -1,304 +1,289 @@ #ifdef VF_VTK #include "InSituVTKCoProcessor.h" -#include <LBMKernel.h> +#include <BCArray3D.h> #include <BCProcessor.h> +#include <Block3D.h> +#include <BoundaryConditions.h> #include <Communicator.h> -#include <UbScheduler.h> -#include <DistributionArray3D.h> #include <D3Q27System.h> -#include <BoundaryConditions.h> -#include <Block3D.h> -#include <LBMKernel.h> #include <DataSet3D.h> -#include <BCArray3D.h> +#include <DistributionArray3D.h> +#include <LBMKernel.h> +#include <UbScheduler.h> -#include <vector> #include <string> +#include <vector> #include <vtkCellType.h> #include <vtkPointData.h> #include <vtkXMLUnstructuredGridWriter.h> -#include <iostream> #include <fstream> +#include <iostream> using namespace std; -InSituVTKCoProcessor::InSituVTKCoProcessor() -{ - -} +InSituVTKCoProcessor::InSituVTKCoProcessor() {} ////////////////////////////////////////////////////////////////////////// -InSituVTKCoProcessor::InSituVTKCoProcessor( SPtr<Grid3D> grid, SPtr<UbScheduler> s, const std::string& configFile, SPtr<LBMUnitConverter> conv ) : CoProcessor(grid, s), conv(conv) +InSituVTKCoProcessor::InSituVTKCoProcessor(SPtr<Grid3D> grid, SPtr<UbScheduler> s, const std::string &configFile, + SPtr<LBMUnitConverter> conv) + : CoProcessor(grid, s), conv(conv) { - gridRank = Communicator::getInstance()->getProcessID(); - minInitLevel = this->grid->getCoarsestInitializedLevel(); - maxInitLevel = this->grid->getFinestInitializedLevel(); + gridRank = Communicator::getInstance()->getProcessID(); + minInitLevel = this->grid->getCoarsestInitializedLevel(); + maxInitLevel = this->grid->getFinestInitializedLevel(); - readConfigFile(configFile); + readConfigFile(configFile); - blockVector.resize(maxInitLevel+1); + blockVector.resize(maxInitLevel + 1); - for(int level = minInitLevel; level<=maxInitLevel;level++) - { - grid->getBlocks(level, gridRank, true, blockVector[level]); - } + for (int level = minInitLevel; level <= maxInitLevel; level++) { + grid->getBlocks(level, gridRank, true, blockVector[level]); + } - //initialization of communicator - contr = vtkSmartPointer<vtkSocketController>::New(); - contr->Initialize(); + // initialization of communicator + contr = vtkSmartPointer<vtkSocketController>::New(); + contr->Initialize(); - comm = vtkSmartPointer<vtkSocketCommunicator>::New(); + comm = vtkSmartPointer<vtkSocketCommunicator>::New(); - // Establish connection - if (!comm->ConnectTo(wHostname.c_str(), wPort)) - { - cerr << "Client error: Could not connect to the server."<< endl; - return; - } - + // Establish connection + if (!comm->ConnectTo(wHostname.c_str(), wPort)) { + cerr << "Client error: Could not connect to the server." << endl; + return; + } } ////////////////////////////////////////////////////////////////////////// -InSituVTKCoProcessor::~InSituVTKCoProcessor() -{ - comm->CloseConnection(); -} +InSituVTKCoProcessor::~InSituVTKCoProcessor() { comm->CloseConnection(); } ////////////////////////////////////////////////////////////////////////// -void InSituVTKCoProcessor::process( double step ) +void InSituVTKCoProcessor::process(double step) { - if(scheduler->isDue(step) ) - collectData(step); + if (scheduler->isDue(step)) + collectData(step); - UBLOG(logDEBUG3, "InSituVTKCoProcessor::update:" << step); + UBLOG(logDEBUG3, "InSituVTKCoProcessor::update:" << step); } ////////////////////////////////////////////////////////////////////////// -void InSituVTKCoProcessor::collectData( double step ) +void InSituVTKCoProcessor::collectData(double step) { - int istep = static_cast<int>(step); - - unstructuredGrid = vtkSmartPointer<vtkUnstructuredGrid>::New(); - points = vtkPoints::New(); - unstructuredGrid->SetPoints(points); - arrays[0] = vtkSmartPointer<vtkDoubleArray>::New(); - arrays[0]->SetNumberOfComponents(1); - arrays[0]->SetName( "Rho" ); - arrays[1] = vtkSmartPointer<vtkDoubleArray>::New(); - arrays[1]->SetNumberOfComponents(1); - arrays[1]->SetName( "Vx" ); - arrays[2] = vtkSmartPointer<vtkDoubleArray>::New(); - arrays[2]->SetNumberOfComponents(1); - arrays[2]->SetName( "Vy" ); - arrays[3] = vtkSmartPointer<vtkDoubleArray>::New(); - arrays[3]->SetNumberOfComponents(1); - arrays[3]->SetName( "Vz" ); - arrays[4] = vtkSmartPointer<vtkDoubleArray>::New(); - arrays[4]->SetNumberOfComponents(1); - arrays[4]->SetName( "Press" ); - - for(int level = minInitLevel; level<=maxInitLevel;level++) - { - for(SPtr<Block3D> block : blockVector[level]) - { - if (block) - { - addData(block); - } - } - } - - unstructuredGrid->GetPointData()->AddArray(arrays[0]); - unstructuredGrid->GetPointData()->AddArray(arrays[1]); - unstructuredGrid->GetPointData()->AddArray(arrays[2]); - unstructuredGrid->GetPointData()->AddArray(arrays[3]); - unstructuredGrid->GetPointData()->AddArray(arrays[4]); - unstructuredGrid->GetPointData()->SetScalars(arrays[1]); - - if (!comm->Send(&istep, 1, 1, 11)) - { - cerr << "Client error: Error sending data." << endl; - return; - } - - if (!comm->Send(unstructuredGrid, 1, 9)) - { - cerr << "Server error: Error sending data." << endl; - return; - } - - //vtkSmartPointer<vtkXMLUnstructuredGridWriter> writer = vtkSmartPointer<vtkXMLUnstructuredGridWriter>::New(); - //writer->SetInput(unstructuredGrid); - //writer->SetFileName("test.vtu"); - //writer->SetDataModeToAscii(); - //writer->Update(); - - UBLOG(logINFO,"InSituVTKCoProcessor step: " << istep); + int istep = static_cast<int>(step); + + unstructuredGrid = vtkSmartPointer<vtkUnstructuredGrid>::New(); + points = vtkPoints::New(); + unstructuredGrid->SetPoints(points); + arrays[0] = vtkSmartPointer<vtkDoubleArray>::New(); + arrays[0]->SetNumberOfComponents(1); + arrays[0]->SetName("Rho"); + arrays[1] = vtkSmartPointer<vtkDoubleArray>::New(); + arrays[1]->SetNumberOfComponents(1); + arrays[1]->SetName("Vx"); + arrays[2] = vtkSmartPointer<vtkDoubleArray>::New(); + arrays[2]->SetNumberOfComponents(1); + arrays[2]->SetName("Vy"); + arrays[3] = vtkSmartPointer<vtkDoubleArray>::New(); + arrays[3]->SetNumberOfComponents(1); + arrays[3]->SetName("Vz"); + arrays[4] = vtkSmartPointer<vtkDoubleArray>::New(); + arrays[4]->SetNumberOfComponents(1); + arrays[4]->SetName("Press"); + + for (int level = minInitLevel; level <= maxInitLevel; level++) { + for (SPtr<Block3D> block : blockVector[level]) { + if (block) { + addData(block); + } + } + } + + unstructuredGrid->GetPointData()->AddArray(arrays[0]); + unstructuredGrid->GetPointData()->AddArray(arrays[1]); + unstructuredGrid->GetPointData()->AddArray(arrays[2]); + unstructuredGrid->GetPointData()->AddArray(arrays[3]); + unstructuredGrid->GetPointData()->AddArray(arrays[4]); + unstructuredGrid->GetPointData()->SetScalars(arrays[1]); + + if (!comm->Send(&istep, 1, 1, 11)) { + cerr << "Client error: Error sending data." << endl; + return; + } + + if (!comm->Send(unstructuredGrid, 1, 9)) { + cerr << "Server error: Error sending data." << endl; + return; + } + + // vtkSmartPointer<vtkXMLUnstructuredGridWriter> writer = vtkSmartPointer<vtkXMLUnstructuredGridWriter>::New(); + // writer->SetInput(unstructuredGrid); + // writer->SetFileName("test.vtu"); + // writer->SetDataModeToAscii(); + // writer->Update(); + + UBLOG(logINFO, "InSituVTKCoProcessor step: " << istep); } ////////////////////////////////////////////////////////////////////////// -void InSituVTKCoProcessor::addData( SPtr<Block3D> block ) +void InSituVTKCoProcessor::addData(SPtr<Block3D> block) { - UbTupleDouble3 org = grid->getBlockWorldCoordinates(block); - UbTupleDouble3 blockLengths = grid->getBlockLengths(block); - UbTupleDouble3 nodeOffset = grid->getNodeOffset(block); - double dx = grid->getDeltaX(block); - - SPtr<ILBMKernel> kernel = block->getKernel(); - SPtr<BCArray3D> bcArray = kernel->getBCProcessor()->getBCArray(); - SPtr<DistributionArray3D> distributions = kernel->getDataSet()->getFdistributions(); - LBMReal f[D3Q27System::ENDF+1]; - LBMReal vx1,vx2,vx3,rho; - - //knotennummerierung faengt immer bei 0 an! - int SWB,SEB,NEB,NWB,SWT,SET,NET,NWT; - - //Funktionszeiger - typedef void (*CalcMacrosFct)(const LBMReal* const& /*feq[27]*/,LBMReal& /*(d)rho*/, LBMReal& /*vx1*/, LBMReal& /*vx2*/, LBMReal& /*vx3*/); - - CalcMacrosFct calcMacros = NULL; - - if(block->getKernel()->getCompressible()) - { - calcMacros = &D3Q27System::calcCompMacroscopicValues; - } - else - { - calcMacros = &D3Q27System::calcIncompMacroscopicValues; - } - - int minX1 = 0; - int minX2 = 0; - int minX3 = 0; - - int maxX1 = (int)(distributions->getNX1()); - int maxX2 = (int)(distributions->getNX2()); - int maxX3 = (int)(distributions->getNX3()); - - //int minX1 = 1; - //int minX2 = 1; - //int minX3 = 1; - - //int maxX1 = (int)(distributions->getNX1()); - //int maxX2 = (int)(distributions->getNX2()); - //int maxX3 = (int)(distributions->getNX3()); - - //nummern vergeben und node vector erstellen + daten sammeln - CbArray3D<int> nodeNumbers((int)maxX1, (int)maxX2, (int)maxX3,-1); - maxX1 -= 2; - maxX2 -= 2; - maxX3 -= 2; - - SPtr<BoundaryConditions> bcPtr; - int nr = points->GetNumberOfPoints(); - - double x[3]; - - for(size_t ix3=minX3; ix3<=maxX3; ix3++) - { - for(size_t ix2=minX2; ix2<=maxX2; ix2++) - { - for(size_t ix1=minX1; ix1<=maxX1; ix1++) - { - if(!bcArray->isUndefined(ix1,ix2,ix3) && !bcArray->isSolid(ix1,ix2,ix3)) - { - int index = 0; - - x[0] = double(val<1>(org) - val<1>(nodeOffset) + ix1*dx); - x[1] = double(val<2>(org) - val<2>(nodeOffset) + ix2*dx); - x[2] = double(val<3>(org) - val<3>(nodeOffset) + ix3*dx); - - points->InsertPoint((vtkIdType)nr, x); - - nodeNumbers(ix1,ix2,ix3) = nr++; - - distributions->getDistribution(f, ix1, ix2, ix3); - calcMacros(f,rho,vx1,vx2,vx3); - double press = D3Q27System::calcPress(f,rho,vx1,vx2,vx3); - - if (UbMath::isNaN(rho) || UbMath::isInfinity(rho)) - UB_THROW( UbException(UB_EXARGS,"rho is not a number (nan or -1.#IND) or infinity number -1.#INF in block="+block->toString()+ - ", node="+UbSystem::toString(ix1)+","+UbSystem::toString(ix2)+","+UbSystem::toString(ix3))); - //rho=999.0; - if (UbMath::isNaN(press) || UbMath::isInfinity(press)) - UB_THROW( UbException(UB_EXARGS,"press is not a number (nan or -1.#IND) or infinity number -1.#INF in block="+block->toString()+ - ", node="+UbSystem::toString(ix1)+","+UbSystem::toString(ix2)+","+UbSystem::toString(ix3))); - //press=999.0; - if (UbMath::isNaN(vx1) || UbMath::isInfinity(vx1)) - UB_THROW( UbException(UB_EXARGS,"vx1 is not a number (nan or -1.#IND) or infinity number -1.#INF in block="+block->toString()+ - ", node="+UbSystem::toString(ix1)+","+UbSystem::toString(ix2)+","+UbSystem::toString(ix3))); - //vx1=999.0; - if (UbMath::isNaN(vx2) || UbMath::isInfinity(vx2)) - UB_THROW( UbException(UB_EXARGS,"vx2 is not a number (nan or -1.#IND) or infinity number -1.#INF in block="+block->toString()+ - ", node="+UbSystem::toString(ix1)+","+UbSystem::toString(ix2)+","+UbSystem::toString(ix3))); - //vx2=999.0; - if (UbMath::isNaN(vx3) || UbMath::isInfinity(vx3)) - UB_THROW( UbException(UB_EXARGS,"vx3 is not a number (nan or -1.#IND) or infinity number -1.#INF in block="+block->toString()+ - ", node="+UbSystem::toString(ix1)+","+UbSystem::toString(ix2)+","+UbSystem::toString(ix3))); - //vx3=999.0; - - arrays[0]->InsertNextValue(rho * conv->getFactorDensityLbToW2()); - arrays[1]->InsertNextValue(vx1 * conv->getFactorVelocityLbToW2()); - arrays[2]->InsertNextValue(vx2 * conv->getFactorVelocityLbToW2()); - arrays[3]->InsertNextValue(vx3 * conv->getFactorVelocityLbToW2()); - arrays[4]->InsertNextValue(press * conv->getFactorPressureLbToW2()); + UbTupleDouble3 org = grid->getBlockWorldCoordinates(block); + UbTupleDouble3 blockLengths = grid->getBlockLengths(block); + UbTupleDouble3 nodeOffset = grid->getNodeOffset(block); + double dx = grid->getDeltaX(block); + + SPtr<ILBMKernel> kernel = block->getKernel(); + SPtr<BCArray3D> bcArray = kernel->getBCProcessor()->getBCArray(); + SPtr<DistributionArray3D> distributions = kernel->getDataSet()->getFdistributions(); + LBMReal f[D3Q27System::ENDF + 1]; + LBMReal vx1, vx2, vx3, rho; + + // knotennummerierung faengt immer bei 0 an! + int SWB, SEB, NEB, NWB, SWT, SET, NET, NWT; + + // Funktionszeiger + typedef void (*CalcMacrosFct)(const LBMReal *const & /*feq[27]*/, LBMReal & /*(d)rho*/, LBMReal & /*vx1*/, + LBMReal & /*vx2*/, LBMReal & /*vx3*/); + + CalcMacrosFct calcMacros = NULL; + + if (block->getKernel()->getCompressible()) { + calcMacros = &D3Q27System::calcCompMacroscopicValues; + } else { + calcMacros = &D3Q27System::calcIncompMacroscopicValues; + } + + int minX1 = 0; + int minX2 = 0; + int minX3 = 0; + + int maxX1 = (int)(distributions->getNX1()); + int maxX2 = (int)(distributions->getNX2()); + int maxX3 = (int)(distributions->getNX3()); + + // int minX1 = 1; + // int minX2 = 1; + // int minX3 = 1; + + // int maxX1 = (int)(distributions->getNX1()); + // int maxX2 = (int)(distributions->getNX2()); + // int maxX3 = (int)(distributions->getNX3()); + + // nummern vergeben und node vector erstellen + daten sammeln + CbArray3D<int> nodeNumbers((int)maxX1, (int)maxX2, (int)maxX3, -1); + maxX1 -= 2; + maxX2 -= 2; + maxX3 -= 2; + + SPtr<BoundaryConditions> bcPtr; + int nr = points->GetNumberOfPoints(); + + double x[3]; + + for (size_t ix3 = minX3; ix3 <= maxX3; ix3++) { + for (size_t ix2 = minX2; ix2 <= maxX2; ix2++) { + for (size_t ix1 = minX1; ix1 <= maxX1; ix1++) { + if (!bcArray->isUndefined(ix1, ix2, ix3) && !bcArray->isSolid(ix1, ix2, ix3)) { + int index = 0; + + x[0] = double(val<1>(org) - val<1>(nodeOffset) + ix1 * dx); + x[1] = double(val<2>(org) - val<2>(nodeOffset) + ix2 * dx); + x[2] = double(val<3>(org) - val<3>(nodeOffset) + ix3 * dx); + + points->InsertPoint((vtkIdType)nr, x); + + nodeNumbers(ix1, ix2, ix3) = nr++; + + distributions->getDistribution(f, ix1, ix2, ix3); + calcMacros(f, rho, vx1, vx2, vx3); + double press = D3Q27System::calcPress(f, rho, vx1, vx2, vx3); + + if (UbMath::isNaN(rho) || UbMath::isInfinity(rho)) + UB_THROW(UbException( + UB_EXARGS, "rho is not a number (nan or -1.#IND) or infinity number -1.#INF in block=" + + block->toString() + ", node=" + UbSystem::toString(ix1) + "," + + UbSystem::toString(ix2) + "," + UbSystem::toString(ix3))); + // rho=999.0; + if (UbMath::isNaN(press) || UbMath::isInfinity(press)) + UB_THROW(UbException( + UB_EXARGS, "press is not a number (nan or -1.#IND) or infinity number -1.#INF in block=" + + block->toString() + ", node=" + UbSystem::toString(ix1) + "," + + UbSystem::toString(ix2) + "," + UbSystem::toString(ix3))); + // press=999.0; + if (UbMath::isNaN(vx1) || UbMath::isInfinity(vx1)) + UB_THROW(UbException( + UB_EXARGS, "vx1 is not a number (nan or -1.#IND) or infinity number -1.#INF in block=" + + block->toString() + ", node=" + UbSystem::toString(ix1) + "," + + UbSystem::toString(ix2) + "," + UbSystem::toString(ix3))); + // vx1=999.0; + if (UbMath::isNaN(vx2) || UbMath::isInfinity(vx2)) + UB_THROW(UbException( + UB_EXARGS, "vx2 is not a number (nan or -1.#IND) or infinity number -1.#INF in block=" + + block->toString() + ", node=" + UbSystem::toString(ix1) + "," + + UbSystem::toString(ix2) + "," + UbSystem::toString(ix3))); + // vx2=999.0; + if (UbMath::isNaN(vx3) || UbMath::isInfinity(vx3)) + UB_THROW(UbException( + UB_EXARGS, "vx3 is not a number (nan or -1.#IND) or infinity number -1.#INF in block=" + + block->toString() + ", node=" + UbSystem::toString(ix1) + "," + + UbSystem::toString(ix2) + "," + UbSystem::toString(ix3))); + // vx3=999.0; + + arrays[0]->InsertNextValue(rho * conv->getFactorDensityLbToW2()); + arrays[1]->InsertNextValue(vx1 * conv->getFactorVelocityLbToW2()); + arrays[2]->InsertNextValue(vx2 * conv->getFactorVelocityLbToW2()); + arrays[3]->InsertNextValue(vx3 * conv->getFactorVelocityLbToW2()); + arrays[4]->InsertNextValue(press * conv->getFactorPressureLbToW2()); + } } - } - } - } - maxX1 -= 1; - maxX2 -= 1; - maxX3 -= 1; - - vtkIdType ptIds[8]; - //cell vector erstellen - for(int ix3=minX3; ix3<=maxX3; ix3++) - { - for(int ix2=minX2; ix2<=maxX2; ix2++) - { - for(int ix1=minX1; ix1<=maxX1; ix1++) - { - if( (ptIds[0]=SWB=nodeNumbers( ix1 , ix2, ix3 )) >= 0 - && (ptIds[1]=SEB=nodeNumbers( ix1+1, ix2, ix3 )) >= 0 - && (ptIds[2]=NWB=nodeNumbers( ix1 , ix2+1, ix3 )) >= 0 - && (ptIds[3]=NEB=nodeNumbers( ix1+1, ix2+1, ix3 )) >= 0 - && (ptIds[4]=SWT=nodeNumbers( ix1 , ix2, ix3+1 )) >= 0 - && (ptIds[5]=SET=nodeNumbers( ix1+1, ix2, ix3+1 )) >= 0 - && (ptIds[6]=NWT=nodeNumbers( ix1 , ix2+1, ix3+1 )) >= 0 - && (ptIds[7]=NET=nodeNumbers( ix1+1, ix2+1, ix3+1 )) >= 0 - ) - { - unstructuredGrid->InsertNextCell((int)VTK_VOXEL, (vtkIdType)8, ptIds); + } + } + maxX1 -= 1; + maxX2 -= 1; + maxX3 -= 1; + + vtkIdType ptIds[8]; + // cell vector erstellen + for (int ix3 = minX3; ix3 <= maxX3; ix3++) { + for (int ix2 = minX2; ix2 <= maxX2; ix2++) { + for (int ix1 = minX1; ix1 <= maxX1; ix1++) { + if ((ptIds[0] = SWB = nodeNumbers(ix1, ix2, ix3)) >= 0 && + (ptIds[1] = SEB = nodeNumbers(ix1 + 1, ix2, ix3)) >= 0 && + (ptIds[2] = NWB = nodeNumbers(ix1, ix2 + 1, ix3)) >= 0 && + (ptIds[3] = NEB = nodeNumbers(ix1 + 1, ix2 + 1, ix3)) >= 0 && + (ptIds[4] = SWT = nodeNumbers(ix1, ix2, ix3 + 1)) >= 0 && + (ptIds[5] = SET = nodeNumbers(ix1 + 1, ix2, ix3 + 1)) >= 0 && + (ptIds[6] = NWT = nodeNumbers(ix1, ix2 + 1, ix3 + 1)) >= 0 && + (ptIds[7] = NET = nodeNumbers(ix1 + 1, ix2 + 1, ix3 + 1)) >= 0) { + unstructuredGrid->InsertNextCell((int)VTK_VOXEL, (vtkIdType)8, ptIds); + } } - } - } - } + } + } } ////////////////////////////////////////////////////////////////////////// -void InSituVTKCoProcessor::readConfigFile( const std::string& configFile ) +void InSituVTKCoProcessor::readConfigFile(const std::string &configFile) { - ifstream ifs; - ifs.open (configFile, ifstream::in); - if(!ifs) throw UbException(UB_EXARGS,"can not open "+configFile); - - string dummy; - int wRank = 0; - getline(ifs, dummy); - int np = Communicator::getInstance()->getNumberOfProcesses(); - - while (ifs.good()) - { - getline(ifs, dummy, ';'); - getline(ifs, wIP, ';'); - getline(ifs, wHostname, ';'); - getline(ifs, dummy); - wPort = stoi(dummy); - if(wRank == gridRank) break; - wRank++; - } - ifs.close(); + ifstream ifs; + ifs.open(configFile, ifstream::in); + if (!ifs) + throw UbException(UB_EXARGS, "can not open " + configFile); + + string dummy; + int wRank = 0; + getline(ifs, dummy); + int np = Communicator::getInstance()->getNumberOfProcesses(); + + while (ifs.good()) { + getline(ifs, dummy, ';'); + getline(ifs, wIP, ';'); + getline(ifs, wHostname, ';'); + getline(ifs, dummy); + wPort = stoi(dummy); + if (wRank == gridRank) + break; + wRank++; + } + ifs.close(); } ////////////////////////////////////////////////////////////////////////// #endif - - diff --git a/src/cpu/VirtualFluidsCore/CoProcessors/InSituVTKCoProcessor.h b/src/cpu/VirtualFluidsCore/CoProcessors/InSituVTKCoProcessor.h index 0b3b440c488e4012da4f15555ffef5d4a8edeb1a..6789509569cabbdc39319f20749d9e0091736158 100644 --- a/src/cpu/VirtualFluidsCore/CoProcessors/InSituVTKCoProcessor.h +++ b/src/cpu/VirtualFluidsCore/CoProcessors/InSituVTKCoProcessor.h @@ -9,44 +9,45 @@ #include <string> -//VTK headers +// VTK headers +#include <vtkDoubleArray.h> +#include <vtkSmartPointer.h> #include <vtkSocketCommunicator.h> #include <vtkSocketController.h> -#include <vtkSmartPointer.h> #include <vtkUnstructuredGrid.h> -#include <vtkDoubleArray.h> class InSituVTKCoProcessor : public CoProcessor { public: - InSituVTKCoProcessor(); - InSituVTKCoProcessor(SPtr<Grid3D> grid, SPtr<UbScheduler> s, const std::string& configFile, SPtr<LBMUnitConverter> conv); - virtual ~InSituVTKCoProcessor(); - void process(double step); + InSituVTKCoProcessor(); + InSituVTKCoProcessor(SPtr<Grid3D> grid, SPtr<UbScheduler> s, const std::string &configFile, + SPtr<LBMUnitConverter> conv); + virtual ~InSituVTKCoProcessor(); + void process(double step); + protected: - void collectData(double step); - void addData(SPtr<Block3D> block); - void readConfigFile(const std::string& configFile); + void collectData(double step); + void addData(SPtr<Block3D> block); + void readConfigFile(const std::string &configFile); - //void clearData(); + // void clearData(); private: - std::string path; - SPtr<LBMUnitConverter> conv; - std::vector<std::vector<SPtr<Block3D>> > blockVector; - int minInitLevel; - int maxInitLevel; - int gridRank; - vtkSmartPointer<vtkSocketCommunicator> comm; - vtkSmartPointer<vtkSocketController> contr; - vtkSmartPointer<vtkUnstructuredGrid> unstructuredGrid; - vtkSmartPointer<vtkPoints> points; - vtkSmartPointer<vtkDoubleArray> arrays[5]; - int wPort; - std::string wHostname; - std::string wIP; + std::string path; + SPtr<LBMUnitConverter> conv; + std::vector<std::vector<SPtr<Block3D>>> blockVector; + int minInitLevel; + int maxInitLevel; + int gridRank; + vtkSmartPointer<vtkSocketCommunicator> comm; + vtkSmartPointer<vtkSocketController> contr; + vtkSmartPointer<vtkUnstructuredGrid> unstructuredGrid; + vtkSmartPointer<vtkPoints> points; + vtkSmartPointer<vtkDoubleArray> arrays[5]; + int wPort; + std::string wHostname; + std::string wIP; }; #endif // InSituVTKCoProcessor_h__ #endif - diff --git a/src/cpu/VirtualFluidsCore/CoProcessors/IntegrateValuesHelper.cpp b/src/cpu/VirtualFluidsCore/CoProcessors/IntegrateValuesHelper.cpp index 93802d6fcdcdb4d29a6f962318ea490df3ad7cc1..76895f1be4c36a43f5955e82aa0d39dcb2e6ddf4 100644 --- a/src/cpu/VirtualFluidsCore/CoProcessors/IntegrateValuesHelper.cpp +++ b/src/cpu/VirtualFluidsCore/CoProcessors/IntegrateValuesHelper.cpp @@ -1,304 +1,256 @@ #include "IntegrateValuesHelper.h" - -#include <geometry3d/GbCuboid3D.h> #include <geometry3d/CoordinateTransformation3D.h> +#include <geometry3d/GbCuboid3D.h> #include <vector> -#include "LBMKernel.h" +#include "BCArray3D.h" #include "BCProcessor.h" #include "DataSet3D.h" -#include "BCArray3D.h" +#include "LBMKernel.h" ////////////////////////////////////////////////////////////////////////// -IntegrateValuesHelper::IntegrateValuesHelper(SPtr<Grid3D> grid, SPtr<Communicator> comm, - double minX1, double minX2, - double minX3, double maxX1, - double maxX2, double maxX3) : +IntegrateValuesHelper::IntegrateValuesHelper(SPtr<Grid3D> grid, SPtr<Communicator> comm, double minX1, double minX2, + double minX3, double maxX1, double maxX2, double maxX3) + : - grid(grid), - comm(comm), - sVx1(0.0), sVx2(0.0), sVx3(0.0), sRho(0.0), sCellVolume(0.0), - numberOfFluidsNodes(0), - numberOfSolidNodes(0) + grid(grid), comm(comm), sVx1(0.0), sVx2(0.0), sVx3(0.0), sRho(0.0), sCellVolume(0.0), numberOfFluidsNodes(0), + numberOfSolidNodes(0) { - boundingBox = GbCuboid3DPtr(new GbCuboid3D(minX1, minX2, minX3, maxX1, maxX2, maxX3)); - init(-1); + boundingBox = GbCuboid3DPtr(new GbCuboid3D(minX1, minX2, minX3, maxX1, maxX2, maxX3)); + init(-1); } ////////////////////////////////////////////////////////////////////////// -IntegrateValuesHelper::IntegrateValuesHelper(SPtr<Grid3D> grid, SPtr<Communicator> comm, - double minX1, double minX2, - double minX3, double maxX1, - double maxX2, double maxX3, - int level) : +IntegrateValuesHelper::IntegrateValuesHelper(SPtr<Grid3D> grid, SPtr<Communicator> comm, double minX1, double minX2, + double minX3, double maxX1, double maxX2, double maxX3, int level) + : - grid(grid), - comm(comm), - sVx1(0.0), sVx2(0.0), sVx3(0.0), sRho(0.0), sCellVolume(0.0), - numberOfFluidsNodes(0), - numberOfSolidNodes(0) + grid(grid), comm(comm), sVx1(0.0), sVx2(0.0), sVx3(0.0), sRho(0.0), sCellVolume(0.0), numberOfFluidsNodes(0), + numberOfSolidNodes(0) { - boundingBox = GbCuboid3DPtr(new GbCuboid3D(minX1, minX2, minX3, maxX1, maxX2, maxX3)); - init(level); + boundingBox = GbCuboid3DPtr(new GbCuboid3D(minX1, minX2, minX3, maxX1, maxX2, maxX3)); + init(level); } ////////////////////////////////////////////////////////////////////////// -IntegrateValuesHelper::~IntegrateValuesHelper() -= default; +IntegrateValuesHelper::~IntegrateValuesHelper() = default; ////////////////////////////////////////////////////////////////////////// void IntegrateValuesHelper::init(int level) { - root = comm->isRoot(); + root = comm->isRoot(); - double orgX1, orgX2, orgX3; - int gridRank = grid->getRank(); - int minInitLevel, maxInitLevel; - if (level < 0) - { - minInitLevel = this->grid->getCoarsestInitializedLevel(); - maxInitLevel = this->grid->getFinestInitializedLevel(); - } - else - { - minInitLevel = level; - maxInitLevel = level; - } + double orgX1, orgX2, orgX3; + int gridRank = grid->getRank(); + int minInitLevel, maxInitLevel; + if (level < 0) { + minInitLevel = this->grid->getCoarsestInitializedLevel(); + maxInitLevel = this->grid->getFinestInitializedLevel(); + } else { + minInitLevel = level; + maxInitLevel = level; + } - double numSolids = 0.0; - double numFluids = 0.0; - for (int level_it = minInitLevel; level_it <= maxInitLevel; level_it++) - { - std::vector<SPtr<Block3D>> blockVector; - grid->getBlocks(level_it, gridRank, blockVector); - for(SPtr<Block3D> block : blockVector) - { - CalcNodes cn; - cn.block = block; - //Koords bestimmen - UbTupleDouble3 org = grid->getBlockWorldCoordinates(block); + double numSolids = 0.0; + double numFluids = 0.0; + for (int level_it = minInitLevel; level_it <= maxInitLevel; level_it++) { + std::vector<SPtr<Block3D>> blockVector; + grid->getBlocks(level_it, gridRank, blockVector); + for (SPtr<Block3D> block : blockVector) { + CalcNodes cn; + cn.block = block; + // Koords bestimmen + UbTupleDouble3 org = grid->getBlockWorldCoordinates(block); - orgX1 = val<1>(org); - orgX2 = val<2>(org); - orgX3 = val<3>(org); + orgX1 = val<1>(org); + orgX2 = val<2>(org); + orgX3 = val<3>(org); - SPtr<LBMKernel> kernel = dynamicPointerCast<LBMKernel>(block->getKernel()); - SPtr<BCArray3D> bcArray = kernel->getBCProcessor()->getBCArray(); - int ghostLayerWitdh = kernel->getGhostLayerWidth(); - SPtr<DistributionArray3D> distributions = kernel->getDataSet()->getFdistributions(); - double internX1, internX2, internX3; + SPtr<LBMKernel> kernel = dynamicPointerCast<LBMKernel>(block->getKernel()); + SPtr<BCArray3D> bcArray = kernel->getBCProcessor()->getBCArray(); + int ghostLayerWitdh = kernel->getGhostLayerWidth(); + SPtr<DistributionArray3D> distributions = kernel->getDataSet()->getFdistributions(); + double internX1, internX2, internX3; - double dx = grid->getDeltaX(block); - UbTupleDouble3 orgDelta = grid->getNodeOffset(block); + double dx = grid->getDeltaX(block); + UbTupleDouble3 orgDelta = grid->getNodeOffset(block); - for (int ix3 = ghostLayerWitdh; ix3 < (int)distributions->getNX3() - ghostLayerWitdh; ix3++) - { - for (int ix2 = ghostLayerWitdh; ix2 < (int)distributions->getNX2() - ghostLayerWitdh; ix2++) - { - for (int ix1 = ghostLayerWitdh; ix1 < (int)distributions->getNX1() - ghostLayerWitdh; ix1++) - { - internX1 = orgX1 - val<1>(orgDelta) + ix1 * dx; - internX2 = orgX2 - val<2>(orgDelta) + ix2 * dx; - internX3 = orgX3 - val<3>(orgDelta) + ix3 * dx; - if (boundingBox->isPointInGbObject3D(internX1, internX2, internX3)) - { - if (!bcArray->isSolid(ix1, ix2, ix3) && !bcArray->isUndefined(ix1, ix2, ix3)) - { - cn.nodes.emplace_back(ix1, ix2, ix3); - numFluids++; - } - else if (bcArray->isSolid(ix1, ix2, ix3)) - { - numSolids++; - } - } - } + for (int ix3 = ghostLayerWitdh; ix3 < (int)distributions->getNX3() - ghostLayerWitdh; ix3++) { + for (int ix2 = ghostLayerWitdh; ix2 < (int)distributions->getNX2() - ghostLayerWitdh; ix2++) { + for (int ix1 = ghostLayerWitdh; ix1 < (int)distributions->getNX1() - ghostLayerWitdh; ix1++) { + internX1 = orgX1 - val<1>(orgDelta) + ix1 * dx; + internX2 = orgX2 - val<2>(orgDelta) + ix2 * dx; + internX3 = orgX3 - val<3>(orgDelta) + ix3 * dx; + if (boundingBox->isPointInGbObject3D(internX1, internX2, internX3)) { + if (!bcArray->isSolid(ix1, ix2, ix3) && !bcArray->isUndefined(ix1, ix2, ix3)) { + cn.nodes.emplace_back(ix1, ix2, ix3); + numFluids++; + } else if (bcArray->isSolid(ix1, ix2, ix3)) { + numSolids++; + } + } + } + } } - } - if (cn.nodes.size() > 0) - cnodes.push_back(cn); - } - } - std::vector<double> rvalues; - std::vector<double> values; - values.push_back(numSolids); - values.push_back(numFluids); - rvalues = comm->gather(values); - - if (root) - { - numberOfSolidNodes = 0.0; - numberOfFluidsNodes = 0.0; - int rsize = (int)rvalues.size(); - int vsize = (int)values.size(); - for (int i = 0; i < rsize; i += vsize) - { - numberOfSolidNodes += rvalues[i]; - numberOfFluidsNodes += rvalues[i + 1]; - } - } + if (cn.nodes.size() > 0) + cnodes.push_back(cn); + } + } + std::vector<double> rvalues; + std::vector<double> values; + values.push_back(numSolids); + values.push_back(numFluids); + rvalues = comm->gather(values); + if (root) { + numberOfSolidNodes = 0.0; + numberOfFluidsNodes = 0.0; + int rsize = (int)rvalues.size(); + int vsize = (int)values.size(); + for (int i = 0; i < rsize; i += vsize) { + numberOfSolidNodes += rvalues[i]; + numberOfFluidsNodes += rvalues[i + 1]; + } + } } ////////////////////////////////////////////////////////////////////////// // calculation conventional rho, velocity and averaged data void IntegrateValuesHelper::calculateAV() { - clearData(); + clearData(); - for(CalcNodes cn : cnodes) - { - SPtr<ILBMKernel> kernel = cn.block->getKernel(); - SPtr<AverageValuesArray3D> averagedValues = kernel->getDataSet()->getAverageValues(); + for (CalcNodes cn : cnodes) { + SPtr<ILBMKernel> kernel = cn.block->getKernel(); + SPtr<AverageValuesArray3D> averagedValues = kernel->getDataSet()->getAverageValues(); - for(UbTupleInt3 node : cn.nodes) - { - double Avx = (*averagedValues)(val<1>(node), val<2>(node), val<3>(node), AvVx); - double Avy = (*averagedValues)(val<1>(node), val<2>(node), val<3>(node), AvVy); - double Avz = (*averagedValues)(val<1>(node), val<2>(node), val<3>(node), AvVz); + for (UbTupleInt3 node : cn.nodes) { + double Avx = (*averagedValues)(val<1>(node), val<2>(node), val<3>(node), AvVx); + double Avy = (*averagedValues)(val<1>(node), val<2>(node), val<3>(node), AvVy); + double Avz = (*averagedValues)(val<1>(node), val<2>(node), val<3>(node), AvVz); - double Avxx = (*averagedValues)(val<1>(node), val<2>(node), val<3>(node), AvVxx); - double Avyy = (*averagedValues)(val<1>(node), val<2>(node), val<3>(node), AvVyy); - double Avzz = (*averagedValues)(val<1>(node), val<2>(node), val<3>(node), AvVzz); + double Avxx = (*averagedValues)(val<1>(node), val<2>(node), val<3>(node), AvVxx); + double Avyy = (*averagedValues)(val<1>(node), val<2>(node), val<3>(node), AvVyy); + double Avzz = (*averagedValues)(val<1>(node), val<2>(node), val<3>(node), AvVzz); - double Avxz = (*averagedValues)(val<1>(node), val<2>(node), val<3>(node), AvVxz); - sAvVx1 += abs(Avx); - sAvVx2 += abs(Avy); - sAvVx3 += abs(Avz); + double Avxz = (*averagedValues)(val<1>(node), val<2>(node), val<3>(node), AvVxz); + sAvVx1 += abs(Avx); + sAvVx2 += abs(Avy); + sAvVx3 += abs(Avz); - sTSx1 += sqrt(Avxx); - sTSx2 += sqrt(Avyy); - sTSx3 += sqrt(Avzz); + sTSx1 += sqrt(Avxx); + sTSx2 += sqrt(Avyy); + sTSx3 += sqrt(Avzz); - sTSx1x3 += Avxz; - numberOfFluidsNodes++; - } - } - std::vector<double> values; - std::vector<double> rvalues; - values.push_back(sAvVx1); - values.push_back(sAvVx2); - values.push_back(sAvVx3); - values.push_back(sTSx1); - values.push_back(sTSx2); - values.push_back(sTSx3); - values.push_back(sTSx1x3); - values.push_back(numberOfFluidsNodes); + sTSx1x3 += Avxz; + numberOfFluidsNodes++; + } + } + std::vector<double> values; + std::vector<double> rvalues; + values.push_back(sAvVx1); + values.push_back(sAvVx2); + values.push_back(sAvVx3); + values.push_back(sTSx1); + values.push_back(sTSx2); + values.push_back(sTSx3); + values.push_back(sTSx1x3); + values.push_back(numberOfFluidsNodes); - rvalues = comm->gather(values); - if (root) - { - clearData(); - for (int i = 0; i < (int)rvalues.size(); i += 8) - { - sAvVx1 += rvalues[i]; - sAvVx2 += rvalues[i + 1]; - sAvVx3 += rvalues[i + 2]; - sTSx1 += rvalues[i + 3]; - sTSx2 += rvalues[i + 4]; - sTSx3 += rvalues[i + 5]; - sTSx1x3 += rvalues[i + 6]; - numberOfFluidsNodes += rvalues[i + 7]; - } - } + rvalues = comm->gather(values); + if (root) { + clearData(); + for (int i = 0; i < (int)rvalues.size(); i += 8) { + sAvVx1 += rvalues[i]; + sAvVx2 += rvalues[i + 1]; + sAvVx3 += rvalues[i + 2]; + sTSx1 += rvalues[i + 3]; + sTSx2 += rvalues[i + 4]; + sTSx3 += rvalues[i + 5]; + sTSx1x3 += rvalues[i + 6]; + numberOfFluidsNodes += rvalues[i + 7]; + } + } } ////////////////////////////////////////////////////////////////////////// void IntegrateValuesHelper::calculateMQ() { - LBMReal f[D3Q27System::ENDF + 1]; - LBMReal vx1, vx2, vx3, rho; - clearData(); + LBMReal f[D3Q27System::ENDF + 1]; + LBMReal vx1, vx2, vx3, rho; + clearData(); - //Funktionszeiger - typedef void(*CalcMacrosFct)(const LBMReal* const& /*feq[27]*/, LBMReal& /*(d)rho*/, LBMReal& /*vx1*/, LBMReal& /*vx2*/, LBMReal& /*vx3*/); + // Funktionszeiger + typedef void (*CalcMacrosFct)(const LBMReal *const & /*feq[27]*/, LBMReal & /*(d)rho*/, LBMReal & /*vx1*/, + LBMReal & /*vx2*/, LBMReal & /*vx3*/); - CalcMacrosFct calcMacros = NULL; + CalcMacrosFct calcMacros = NULL; - for(CalcNodes cn : cnodes) - { - SPtr<ILBMKernel> kernel = cn.block->getKernel(); - LBMReal dx = 1.0 / (LBMReal)(1 << cn.block->getLevel()); - LBMReal cellVolume = dx*dx*dx; + for (CalcNodes cn : cnodes) { + SPtr<ILBMKernel> kernel = cn.block->getKernel(); + LBMReal dx = 1.0 / (LBMReal)(1 << cn.block->getLevel()); + LBMReal cellVolume = dx * dx * dx; - if (kernel->getCompressible()) - { - calcMacros = &D3Q27System::calcCompMacroscopicValues; - } - else - { - calcMacros = &D3Q27System::calcIncompMacroscopicValues; - } + if (kernel->getCompressible()) { + calcMacros = &D3Q27System::calcCompMacroscopicValues; + } else { + calcMacros = &D3Q27System::calcIncompMacroscopicValues; + } - SPtr<BCArray3D> bcArray = kernel->getBCProcessor()->getBCArray(); - SPtr<DistributionArray3D> distributions = kernel->getDataSet()->getFdistributions(); - for(UbTupleInt3 node : cn.nodes) - { - distributions->getDistribution(f, val<1>(node), val<2>(node), val<3>(node)); - calcMacros(f, rho, vx1, vx2, vx3); - sRho += rho*cellVolume; - sVx1 += vx1*cellVolume; - sVx2 += vx2*cellVolume; - sVx3 += vx3*cellVolume; - sCellVolume += cellVolume; - } - } - std::vector<double> values(5); - std::vector<double> rvalues; - values[0] = sRho; - values[1] = sVx1; - values[2] = sVx2; - values[3] = sVx3; - values[4] = sCellVolume; + SPtr<BCArray3D> bcArray = kernel->getBCProcessor()->getBCArray(); + SPtr<DistributionArray3D> distributions = kernel->getDataSet()->getFdistributions(); + for (UbTupleInt3 node : cn.nodes) { + distributions->getDistribution(f, val<1>(node), val<2>(node), val<3>(node)); + calcMacros(f, rho, vx1, vx2, vx3); + sRho += rho * cellVolume; + sVx1 += vx1 * cellVolume; + sVx2 += vx2 * cellVolume; + sVx3 += vx3 * cellVolume; + sCellVolume += cellVolume; + } + } + std::vector<double> values(5); + std::vector<double> rvalues; + values[0] = sRho; + values[1] = sVx1; + values[2] = sVx2; + values[3] = sVx3; + values[4] = sCellVolume; - rvalues = comm->gather(values); - if (root) - { - clearData(); - int rsize = (int)rvalues.size(); - int vsize = (int)values.size(); - for (int i = 0; i < rsize; i += vsize) - { - sRho += rvalues[i]; - sVx1 += rvalues[i + 1]; - sVx2 += rvalues[i + 2]; - sVx3 += rvalues[i + 3]; - sCellVolume += rvalues[i + 4]; - } - } + rvalues = comm->gather(values); + if (root) { + clearData(); + int rsize = (int)rvalues.size(); + int vsize = (int)values.size(); + for (int i = 0; i < rsize; i += vsize) { + sRho += rvalues[i]; + sVx1 += rvalues[i + 1]; + sVx2 += rvalues[i + 2]; + sVx3 += rvalues[i + 3]; + sCellVolume += rvalues[i + 4]; + } + } } ////////////////////////////////////////////////////////////////////////// void IntegrateValuesHelper::clearData() { - sRho = 0.0; - sVx1 = 0.0; - sVx2 = 0.0; - sVx3 = 0.0; - sCellVolume = 0.0; - //sVm = 0.0; - //sPress = 0.0; - //numberOfFluidsNodes = 0.0; - sAvVx1 = 0.0; - sAvVx2 = 0.0; - sAvVx3 = 0.0; - sTSx1 = 0.0; - sTSx2 = 0.0; - sTSx3 = 0.0; - sTSx1x3 = 0.0; + sRho = 0.0; + sVx1 = 0.0; + sVx2 = 0.0; + sVx3 = 0.0; + sCellVolume = 0.0; + // sVm = 0.0; + // sPress = 0.0; + // numberOfFluidsNodes = 0.0; + sAvVx1 = 0.0; + sAvVx2 = 0.0; + sAvVx3 = 0.0; + sTSx1 = 0.0; + sTSx2 = 0.0; + sTSx3 = 0.0; + sTSx1x3 = 0.0; } ////////////////////////////////////////////////////////////////////////// -LBMReal IntegrateValuesHelper::getNumberOfFluidsNodes() -{ - return this->numberOfFluidsNodes; -} +LBMReal IntegrateValuesHelper::getNumberOfFluidsNodes() { return this->numberOfFluidsNodes; } ////////////////////////////////////////////////////////////////////////// -LBMReal IntegrateValuesHelper::getNumberOfSolidNodes() -{ - return this->numberOfSolidNodes; -} +LBMReal IntegrateValuesHelper::getNumberOfSolidNodes() { return this->numberOfSolidNodes; } ////////////////////////////////////////////////////////////////////////// -GbCuboid3DPtr IntegrateValuesHelper::getBoundingBox() -{ - return this->boundingBox; -} +GbCuboid3DPtr IntegrateValuesHelper::getBoundingBox() { return this->boundingBox; } ////////////////////////////////////////////////////////////////////////// -std::vector<IntegrateValuesHelper::CalcNodes> IntegrateValuesHelper::getCNodes() -{ - return cnodes; -} +std::vector<IntegrateValuesHelper::CalcNodes> IntegrateValuesHelper::getCNodes() { return cnodes; } diff --git a/src/cpu/VirtualFluidsCore/CoProcessors/IntegrateValuesHelper.h b/src/cpu/VirtualFluidsCore/CoProcessors/IntegrateValuesHelper.h index 457d24ef527045fad27e1cc5b8229d053197315f..f5d846f98317d56f6c0ccf3e267a382ead1cd2a6 100644 --- a/src/cpu/VirtualFluidsCore/CoProcessors/IntegrateValuesHelper.h +++ b/src/cpu/VirtualFluidsCore/CoProcessors/IntegrateValuesHelper.h @@ -3,87 +3,83 @@ #include <PointerDefinitions.h> -#include "Grid3D.h" -#include "D3Q27System.h" +#include "Block3D.h" +#include "CbArray2D.h" #include "Communicator.h" +#include "D3Q27System.h" #include "GbCuboid3D.h" -#include "CbArray2D.h" -#include "Block3D.h" +#include "Grid3D.h" -//struct CalcNodes +// struct CalcNodes //{ // SPtr<Block3D> block; // std::vector<UbTupleInt3> nodes; //}; // -//struct Nodes +// struct Nodes //{ // SPtr<Block3D> block; // UbTupleInt3 nodes; //}; - class IntegrateValuesHelper { public: - struct CalcNodes - { - SPtr<Block3D> block; - std::vector<UbTupleInt3> nodes; - }; + struct CalcNodes { + SPtr<Block3D> block; + std::vector<UbTupleInt3> nodes; + }; + + struct Node { + SPtr<Block3D> block; + UbTupleInt3 node; + }; - struct Node - { - SPtr<Block3D> block; - UbTupleInt3 node; - }; public: - IntegrateValuesHelper(SPtr<Grid3D> grid, SPtr<Communicator> comm, - double minX1, double minX2, double minX3, - double maxX1, double maxX2, double maxX3); - IntegrateValuesHelper(SPtr<Grid3D> grid, SPtr<Communicator> comm, - double minX1, double minX2, double minX3, - double maxX1, double maxX2, double maxX3, int level); - virtual ~IntegrateValuesHelper(); + IntegrateValuesHelper(SPtr<Grid3D> grid, SPtr<Communicator> comm, double minX1, double minX2, double minX3, + double maxX1, double maxX2, double maxX3); + IntegrateValuesHelper(SPtr<Grid3D> grid, SPtr<Communicator> comm, double minX1, double minX2, double minX3, + double maxX1, double maxX2, double maxX3, int level); + virtual ~IntegrateValuesHelper(); - void calculateMQ(); - void calculateAV(); - void clearData(); + void calculateMQ(); + void calculateAV(); + void clearData(); - double getRho() {return sRho;} - double getVx1() {return sVx1;} - double getVx2() {return sVx2;} - double getVx3() {return sVx3;} - double getCellsVolume() { return sCellVolume; } - // LBMReal getVm() { return sVm; } - //LBMReal getPress() {return sPress;} - double getAvVx1(){return sAvVx1;} - double getAvVx2(){return sAvVx2;} - double getAvVx3(){return sAvVx3;} - double getTSx1(){return sTSx1;} - double getTSx2(){return sTSx2;} - double getTSx3(){return sTSx3;} - double getTSx1x3(){return sTSx1x3;} + double getRho() { return sRho; } + double getVx1() { return sVx1; } + double getVx2() { return sVx2; } + double getVx3() { return sVx3; } + double getCellsVolume() { return sCellVolume; } + // LBMReal getVm() { return sVm; } + // LBMReal getPress() {return sPress;} + double getAvVx1() { return sAvVx1; } + double getAvVx2() { return sAvVx2; } + double getAvVx3() { return sAvVx3; } + double getTSx1() { return sTSx1; } + double getTSx2() { return sTSx2; } + double getTSx3() { return sTSx3; } + double getTSx1x3() { return sTSx1x3; } - LBMReal getNumberOfFluidsNodes(); - LBMReal getNumberOfSolidNodes(); - GbCuboid3DPtr getBoundingBox(); - std::vector<CalcNodes> getCNodes(); + LBMReal getNumberOfFluidsNodes(); + LBMReal getNumberOfSolidNodes(); + GbCuboid3DPtr getBoundingBox(); + std::vector<CalcNodes> getCNodes(); protected: private: - void init(int level); + void init(int level); - bool root; - SPtr<Grid3D> grid; - double sVx1, sVx2, sVx3, sRho, sCellVolume;// sPress, sVm; - double numberOfFluidsNodes, numberOfSolidNodes; - double sAvVx1, sAvVx2, sAvVx3, sTSx1, sTSx2, sTSx3, sTSx1x3; - std::vector<CalcNodes> cnodes; - GbCuboid3DPtr boundingBox; - SPtr<Communicator> comm; - CbArray2D<Node> cnodes2DMatrix; - enum Values{AvVx = 0, AvVy = 1, AvVz = 2, AvVxx = 3, AvVyy = 4, AvVzz = 5, AvVxy = 6, AvVyz = 7, AvVxz = 8}; + bool root; + SPtr<Grid3D> grid; + double sVx1, sVx2, sVx3, sRho, sCellVolume; // sPress, sVm; + double numberOfFluidsNodes, numberOfSolidNodes; + double sAvVx1, sAvVx2, sAvVx3, sTSx1, sTSx2, sTSx3, sTSx1x3; + std::vector<CalcNodes> cnodes; + GbCuboid3DPtr boundingBox; + SPtr<Communicator> comm; + CbArray2D<Node> cnodes2DMatrix; + enum Values { AvVx = 0, AvVy = 1, AvVz = 2, AvVxx = 3, AvVyy = 4, AvVzz = 5, AvVxy = 6, AvVyz = 7, AvVxz = 8 }; }; #endif diff --git a/src/cpu/VirtualFluidsCore/CoProcessors/LineTimeSeriesCoProcessor.cpp b/src/cpu/VirtualFluidsCore/CoProcessors/LineTimeSeriesCoProcessor.cpp index 559303616330da359f79d38df2f02f536d92fd85..fe04f4f9c98f8c41a33ee298df0689e2d254c2a7 100644 --- a/src/cpu/VirtualFluidsCore/CoProcessors/LineTimeSeriesCoProcessor.cpp +++ b/src/cpu/VirtualFluidsCore/CoProcessors/LineTimeSeriesCoProcessor.cpp @@ -2,246 +2,203 @@ #include "BCProcessor.h" #include "WbWriterVtkXmlASCII.h" -#include "DataSet3D.h" -#include "LBMKernel.h" -#include "CoordinateTransformation3D.h" #include "Block3D.h" -#include "GbLine3D.h" -#include "UbScheduler.h" -#include "Grid3D.h" #include "Communicator.h" #include "CompressibleCumulantLBMKernel.h" +#include "CoordinateTransformation3D.h" +#include "DataSet3D.h" +#include "GbLine3D.h" +#include "Grid3D.h" +#include "LBMKernel.h" +#include "UbScheduler.h" -LineTimeSeriesCoProcessor::LineTimeSeriesCoProcessor(SPtr<Grid3D> grid, SPtr<UbScheduler> s, const std::string& path, SPtr<GbLine3D> line, int level, SPtr<Communicator> comm) : - CoProcessor(grid, s), - path(path), - length(0), - ix1(0), - ix2(0), - ix3(0), - level(level), - line(line) +LineTimeSeriesCoProcessor::LineTimeSeriesCoProcessor(SPtr<Grid3D> grid, SPtr<UbScheduler> s, const std::string &path, + SPtr<GbLine3D> line, int level, SPtr<Communicator> comm) + : CoProcessor(grid, s), path(path), length(0), ix1(0), ix2(0), ix3(0), level(level), line(line) { - root = comm->isRoot(); - fname = path; - - mpi_comm = *((MPI_Comm*)comm->getNativeCommunicator()); - numOfProc = comm->getNumberOfProcesses(); - gridRank = comm->getProcessID(); - - double dx = CoProcessor::grid->getDeltaX(level); - - SPtr<CoordinateTransformation3D> trafo = grid->getCoordinateTransformator(); - double orgX1 = trafo->getX1CoordinateOffset(); - double orgX2 = trafo->getX2CoordinateOffset(); - double orgX3 = trafo->getX3CoordinateOffset(); - - - int x1min = (int)((line->getX1Minimum()-orgX1)/dx); - int x1max = (int)((line->getX1Maximum()-orgX1)/dx); - int x2min = (int)((line->getX2Minimum()-orgX2)/dx); - int x2max = (int)((line->getX2Maximum()-orgX2)/dx); - int x3min = (int)((line->getX3Minimum()-orgX3)/dx); - int x3max = (int)((line->getX3Maximum()-orgX3)/dx); - - UbTupleInt3 blockNx = grid->getBlockNX(); - - if (x1min!=x1max) - { - dir = X1; - blocknx = val<1>(blockNx); - length = x1max; - } - else if (x2min!=x2max) - { - dir = X2; - blocknx = val<2>(blockNx); - length = x2max; - } - else if (x3min!=x3max) - { - dir = X3; - blocknx = val<3>(blockNx); - length = x3max; - } - blockix1 = x1min/val<1>(blockNx); - blockix2 = x2min/val<2>(blockNx); - blockix3 = x3min/val<3>(blockNx); - - ix1 = x1min%val<1>(blockNx)+1; - ix2 = x2min%val<2>(blockNx)+1; - ix3 = x3min%val<3>(blockNx)+1; + root = comm->isRoot(); + fname = path; + + mpi_comm = *((MPI_Comm *)comm->getNativeCommunicator()); + numOfProc = comm->getNumberOfProcesses(); + gridRank = comm->getProcessID(); + + double dx = CoProcessor::grid->getDeltaX(level); + + SPtr<CoordinateTransformation3D> trafo = grid->getCoordinateTransformator(); + double orgX1 = trafo->getX1CoordinateOffset(); + double orgX2 = trafo->getX2CoordinateOffset(); + double orgX3 = trafo->getX3CoordinateOffset(); + + int x1min = (int)((line->getX1Minimum() - orgX1) / dx); + int x1max = (int)((line->getX1Maximum() - orgX1) / dx); + int x2min = (int)((line->getX2Minimum() - orgX2) / dx); + int x2max = (int)((line->getX2Maximum() - orgX2) / dx); + int x3min = (int)((line->getX3Minimum() - orgX3) / dx); + int x3max = (int)((line->getX3Maximum() - orgX3) / dx); + + UbTupleInt3 blockNx = grid->getBlockNX(); + + if (x1min != x1max) { + dir = X1; + blocknx = val<1>(blockNx); + length = x1max; + } else if (x2min != x2max) { + dir = X2; + blocknx = val<2>(blockNx); + length = x2max; + } else if (x3min != x3max) { + dir = X3; + blocknx = val<3>(blockNx); + length = x3max; + } + blockix1 = x1min / val<1>(blockNx); + blockix2 = x2min / val<2>(blockNx); + blockix3 = x3min / val<3>(blockNx); + + ix1 = x1min % val<1>(blockNx) + 1; + ix2 = x2min % val<2>(blockNx) + 1; + ix3 = x3min % val<3>(blockNx) + 1; } ////////////////////////////////////////////////////////////////////////// void LineTimeSeriesCoProcessor::process(double step) { - if (scheduler->isDue(step)) - { - collectData(); - } + if (scheduler->isDue(step)) { + collectData(); + } - UBLOG(logDEBUG3, "MacroscopicQuantitiesCoProcessor::update:"<<step); + UBLOG(logDEBUG3, "MacroscopicQuantitiesCoProcessor::update:" << step); } ////////////////////////////////////////////////////////////////////////// -void LineTimeSeriesCoProcessor::writeLine(const std::string& path) +void LineTimeSeriesCoProcessor::writeLine(const std::string &path) { - std::vector<UbTupleFloat3 > nodes(2); - std::vector<UbTupleInt2 > lines(1); - val<1>(nodes[0]) = (float)line->getX1Minimum(); - val<2>(nodes[0]) = (float)line->getX2Minimum(); - val<3>(nodes[0]) = (float)line->getX3Minimum(); - val<1>(nodes[1]) = (float)line->getX1Maximum(); - val<2>(nodes[1]) = (float)line->getX2Maximum(); - val<3>(nodes[1]) = (float)line->getX3Maximum(); - val<1>(lines[0]) = 0; - val<1>(lines[0]) = 1; - WbWriterVtkXmlASCII *writer = WbWriterVtkXmlASCII::getInstance(); - writer->writeLines(path, nodes, lines); + std::vector<UbTupleFloat3> nodes(2); + std::vector<UbTupleInt2> lines(1); + val<1>(nodes[0]) = (float)line->getX1Minimum(); + val<2>(nodes[0]) = (float)line->getX2Minimum(); + val<3>(nodes[0]) = (float)line->getX3Minimum(); + val<1>(nodes[1]) = (float)line->getX1Maximum(); + val<2>(nodes[1]) = (float)line->getX2Maximum(); + val<3>(nodes[1]) = (float)line->getX3Maximum(); + val<1>(lines[0]) = 0; + val<1>(lines[0]) = 1; + WbWriterVtkXmlASCII *writer = WbWriterVtkXmlASCII::getInstance(); + writer->writeLines(path, nodes, lines); } ////////////////////////////////////////////////////////////////////////// void LineTimeSeriesCoProcessor::collectData() { - LBMReal f[27]; - LBMReal vx1, vx2, vx3, rho; - MPI_Status status; - std::vector<double> v1(length, 0); - std::vector<double> v2(length, 0); - std::vector<double> v3(length, 0); - std::vector<double> p(length, 0); - for (int x = 0; x<length; x += blocknx) - { - if (dir == X1) - { - blockix1 = x/blocknx; - } - else if (dir == X2) - { - blockix2 = x/blocknx; - } - else if (dir == X3) - { - blockix3 = x/blocknx; - } - - SPtr<Block3D> block = CoProcessor::grid->getBlock(blockix1, blockix2, blockix3, level); - if (block) - { - if (block->getRank()==gridRank) - { - SPtr<ILBMKernel> kernel = block->getKernel(); - calcMacros = NULL; - if (kernel->getCompressible()) - { - calcMacros = &D3Q27System::calcCompMacroscopicValues; + LBMReal f[27]; + LBMReal vx1, vx2, vx3, rho; + MPI_Status status; + std::vector<double> v1(length, 0); + std::vector<double> v2(length, 0); + std::vector<double> v3(length, 0); + std::vector<double> p(length, 0); + for (int x = 0; x < length; x += blocknx) { + if (dir == X1) { + blockix1 = x / blocknx; + } else if (dir == X2) { + blockix2 = x / blocknx; + } else if (dir == X3) { + blockix3 = x / blocknx; + } + + SPtr<Block3D> block = CoProcessor::grid->getBlock(blockix1, blockix2, blockix3, level); + if (block) { + if (block->getRank() == gridRank) { + SPtr<ILBMKernel> kernel = block->getKernel(); + calcMacros = NULL; + if (kernel->getCompressible()) { + calcMacros = &D3Q27System::calcCompMacroscopicValues; + } else { + calcMacros = &D3Q27System::calcIncompMacroscopicValues; + } + SPtr<DistributionArray3D> distributions = kernel->getDataSet()->getFdistributions(); + + for (int ix = 1; ix <= blocknx; ix++) { + if (dir == X1) { + ix1 = ix; + } else if (dir == X2) { + ix2 = ix; + } else if (dir == X3) { + ix3 = ix; + } + distributions->getDistribution(f, ix1, ix2, ix3); + calcMacros(f, rho, vx1, vx2, vx3); + v1[x + (ix - 1)] = vx1; + v2[x + (ix - 1)] = vx2; + v3[x + (ix - 1)] = vx3; + p[x + (ix - 1)] = rho; + } } - else - { - calcMacros = &D3Q27System::calcIncompMacroscopicValues; + } + } + + if (root) { + for (int i = 1; i < numOfProc; i++) { + std::vector<double> v1temp(length, 0); + std::vector<double> v2temp(length, 0); + std::vector<double> v3temp(length, 0); + std::vector<double> ptemp(length, 0); + MPI_Recv(&v1temp[0], length, MPI_DOUBLE, i, 1, mpi_comm, &status); + MPI_Recv(&v2temp[0], length, MPI_DOUBLE, i, 2, mpi_comm, &status); + MPI_Recv(&v3temp[0], length, MPI_DOUBLE, i, 3, mpi_comm, &status); + MPI_Recv(&ptemp[0], length, MPI_DOUBLE, i, 4, mpi_comm, &status); + for (int j = 0; j < length; j++) { + v1[j] += v1temp[j]; + v2[j] += v2temp[j]; + v3[j] += v3temp[j]; + p[j] += ptemp[j]; } - SPtr<DistributionArray3D> distributions = kernel->getDataSet()->getFdistributions(); - - for (int ix = 1; ix<=blocknx; ix++) - { - if (dir==X1) - { - ix1 = ix; - } - else if (dir==X2) - { - ix2 = ix; - } - else if (dir==X3) - { - ix3 = ix; - } - distributions->getDistribution(f, ix1, ix2, ix3); - calcMacros(f, rho, vx1, vx2, vx3); - v1[x+(ix-1)] = vx1; - v2[x+(ix-1)] = vx2; - v3[x+(ix-1)] = vx3; - p[x+(ix-1)] = rho; + } + + std::ofstream ostr; + ostr.open(fname.c_str(), std::ios_base::out | std::ios_base::app); + if (!ostr) { + ostr.clear(); + std::string path = UbSystem::getPathFromString(fname); + if (path.size() > 0) { + UbSystem::makeDirectory(path); + ostr.open(fname.c_str(), std::ios_base::out | std::ios_base::app); } - } - } - - } - - if (root) - { - for (int i = 1; i<numOfProc; i++) - { - std::vector<double> v1temp(length, 0); - std::vector<double> v2temp(length, 0); - std::vector<double> v3temp(length, 0); - std::vector<double> ptemp(length, 0); - MPI_Recv(&v1temp[0], length, MPI_DOUBLE, i, 1, mpi_comm, &status); - MPI_Recv(&v2temp[0], length, MPI_DOUBLE, i, 2, mpi_comm, &status); - MPI_Recv(&v3temp[0], length, MPI_DOUBLE, i, 3, mpi_comm, &status); - MPI_Recv( &ptemp[0], length, MPI_DOUBLE, i, 4, mpi_comm, &status); - for (int j = 0; j<length; j++) - { - v1[j] += v1temp[j]; - v2[j] += v2temp[j]; - v3[j] += v3temp[j]; - p[j] += ptemp[j]; - } - } - - std::ofstream ostr; - ostr.open(fname.c_str(), std::ios_base::out|std::ios_base::app); - if (!ostr) - { - ostr.clear(); - std::string path = UbSystem::getPathFromString(fname); - if (path.size()>0) { UbSystem::makeDirectory(path); ostr.open(fname.c_str(), std::ios_base::out|std::ios_base::app); } - if (!ostr) throw UbException(UB_EXARGS, "couldn't open file "+fname); - } - - for (int x = 0; x<length; x++) - { - ostr<<v1[x]; - if (x<length-1) - { - ostr<<";"; - } - } - ostr<<"\n"; - for (int x = 0; x<length; x++) - { - ostr<<v2[x]; - if (x<length-1) - { - ostr<<";"; - } - } - ostr<<"\n"; - for (int x = 0; x<length; x++) - { - ostr<<v3[x]; - if (x<length-1) - { - ostr<<";"; - } - } - ostr<<"\n"; - for (int x = 0; x<length; x++) - { - ostr<<p[x]; - if (x<length-1) - { - ostr<<";"; - } - } - ostr<<"\n"; - ostr.close(); - } - else - { - MPI_Send(&v1[0], length, MPI_DOUBLE, 0, 1, mpi_comm); - MPI_Send(&v2[0], length, MPI_DOUBLE, 0, 2, mpi_comm); - MPI_Send(&v3[0], length, MPI_DOUBLE, 0, 3, mpi_comm); - MPI_Send( &p[0], length, MPI_DOUBLE, 0, 4, mpi_comm); - } + if (!ostr) + throw UbException(UB_EXARGS, "couldn't open file " + fname); + } + + for (int x = 0; x < length; x++) { + ostr << v1[x]; + if (x < length - 1) { + ostr << ";"; + } + } + ostr << "\n"; + for (int x = 0; x < length; x++) { + ostr << v2[x]; + if (x < length - 1) { + ostr << ";"; + } + } + ostr << "\n"; + for (int x = 0; x < length; x++) { + ostr << v3[x]; + if (x < length - 1) { + ostr << ";"; + } + } + ostr << "\n"; + for (int x = 0; x < length; x++) { + ostr << p[x]; + if (x < length - 1) { + ostr << ";"; + } + } + ostr << "\n"; + ostr.close(); + } else { + MPI_Send(&v1[0], length, MPI_DOUBLE, 0, 1, mpi_comm); + MPI_Send(&v2[0], length, MPI_DOUBLE, 0, 2, mpi_comm); + MPI_Send(&v3[0], length, MPI_DOUBLE, 0, 3, mpi_comm); + MPI_Send(&p[0], length, MPI_DOUBLE, 0, 4, mpi_comm); + } } - - diff --git a/src/cpu/VirtualFluidsCore/CoProcessors/LineTimeSeriesCoProcessor.h b/src/cpu/VirtualFluidsCore/CoProcessors/LineTimeSeriesCoProcessor.h index ba8ec0ecfe88b67dad14eb7118c2243c6ca0ed6a..76f933c0599c38d8c84eb4e872a307c951113d4b 100644 --- a/src/cpu/VirtualFluidsCore/CoProcessors/LineTimeSeriesCoProcessor.h +++ b/src/cpu/VirtualFluidsCore/CoProcessors/LineTimeSeriesCoProcessor.h @@ -17,42 +17,45 @@ class GbLine3D; //! \brief Writes to .csv file time series for a line in x1 direction. //! \details It can be used to compute for given time range the time averaged two-point correlations for a line. <br> //! \f$ R_{ij}(x_{a},x{b},t) = <u_{i}(x_{a},t)u_{j}(x_{a}+r,t)> \f$ <br> -// -//! \author Konstantin Kutscher +// +//! \author Konstantin Kutscher class LineTimeSeriesCoProcessor : public CoProcessor { public: -enum Direction {X1, X2, X3}; + enum Direction { X1, X2, X3 }; + public: - LineTimeSeriesCoProcessor(SPtr<Grid3D> grid, SPtr<UbScheduler> s, const std::string& path, SPtr<GbLine3D> line, int level,SPtr<Communicator> comm); - ~LineTimeSeriesCoProcessor() override= default; + LineTimeSeriesCoProcessor(SPtr<Grid3D> grid, SPtr<UbScheduler> s, const std::string &path, SPtr<GbLine3D> line, + int level, SPtr<Communicator> comm); + ~LineTimeSeriesCoProcessor() override = default; - void process(double step) override; - void writeLine(const std::string& path); + void process(double step) override; + void writeLine(const std::string &path); protected: - void collectData(); + void collectData(); + private: - std::string path; - std::string fname; - bool root; - SPtr<GbLine3D> line; - //function pointer - using CalcMacrosFct = void (*)(const LBMReal *const &, LBMReal &, LBMReal &, LBMReal &, LBMReal &); - CalcMacrosFct calcMacros; - int blocknx; - int blockix1; - int blockix2; - int blockix3; - int level; - int ix1; - int ix2; - int ix3; - int length; - MPI_Comm mpi_comm; - int numOfProc; - int gridRank; - Direction dir; + std::string path; + std::string fname; + bool root; + SPtr<GbLine3D> line; + // function pointer + using CalcMacrosFct = void (*)(const LBMReal *const &, LBMReal &, LBMReal &, LBMReal &, LBMReal &); + CalcMacrosFct calcMacros; + int blocknx; + int blockix1; + int blockix2; + int blockix3; + int level; + int ix1; + int ix2; + int ix3; + int length; + MPI_Comm mpi_comm; + int numOfProc; + int gridRank; + Direction dir; }; #endif // LineTimeSeriesCoProcessor_h__ diff --git a/src/cpu/VirtualFluidsCore/CoProcessors/MPIIOCoProcessor.cpp b/src/cpu/VirtualFluidsCore/CoProcessors/MPIIOCoProcessor.cpp index 2c032d6dc6d667c8f5e3227b08209a596054d646..74c8e22b7f5f6e4f63c657b01c29d15c56319208 100644 --- a/src/cpu/VirtualFluidsCore/CoProcessors/MPIIOCoProcessor.cpp +++ b/src/cpu/VirtualFluidsCore/CoProcessors/MPIIOCoProcessor.cpp @@ -1,461 +1,471 @@ #include "MPIIOCoProcessor.h" #include "Block3D.h" +#include "Communicator.h" #include "CoordinateTransformation3D.h" #include "Grid3D.h" -#include "Communicator.h" -#include "UbScheduler.h" #include "MPIIODataStructures.h" -#include "UbLogger.h" #include "MemoryUtil.h" -#include "UbFileOutputASCII.h" #include "UbFileInputASCII.h" +#include "UbFileOutputASCII.h" +#include "UbLogger.h" +#include "UbScheduler.h" using namespace MPIIODataStructures; -MPIIOCoProcessor::MPIIOCoProcessor(SPtr<Grid3D> grid, SPtr<UbScheduler> s, const std::string& path, SPtr<Communicator> comm) : - CoProcessor(grid, s), - path(path), - comm(comm) +MPIIOCoProcessor::MPIIOCoProcessor(SPtr<Grid3D> grid, SPtr<UbScheduler> s, const std::string &path, + SPtr<Communicator> comm) + : CoProcessor(grid, s), path(path), comm(comm) { - UbSystem::makeDirectory(path + "/mpi_io_cp"); - - //------------------------- define MPI types --------------------------------- + UbSystem::makeDirectory(path + "/mpi_io_cp"); - MPI_Datatype typesGP[3] = { MPI_DOUBLE, MPI_INT, MPI_CHAR }; - int blocksGP[3] = { 34, 6, 5 }; - MPI_Aint offsetsGP[3], lbGP, extentGP; + //------------------------- define MPI types --------------------------------- - offsetsGP[0] = 0; - MPI_Type_get_extent(MPI_DOUBLE, &lbGP, &extentGP); - offsetsGP[1] = blocksGP[0] * extentGP; + MPI_Datatype typesGP[3] = { MPI_DOUBLE, MPI_INT, MPI_CHAR }; + int blocksGP[3] = { 34, 6, 5 }; + MPI_Aint offsetsGP[3], lbGP, extentGP; - MPI_Type_get_extent(MPI_INT, &lbGP, &extentGP); - offsetsGP[2] = offsetsGP[1] + blocksGP[1] * extentGP; + offsetsGP[0] = 0; + MPI_Type_get_extent(MPI_DOUBLE, &lbGP, &extentGP); + offsetsGP[1] = blocksGP[0] * extentGP; - MPI_Type_create_struct(3, blocksGP, offsetsGP, typesGP, &gridParamType); - MPI_Type_commit(&gridParamType); + MPI_Type_get_extent(MPI_INT, &lbGP, &extentGP); + offsetsGP[2] = offsetsGP[1] + blocksGP[1] * extentGP; - //----------------------------------------------------------------------- + MPI_Type_create_struct(3, blocksGP, offsetsGP, typesGP, &gridParamType); + MPI_Type_commit(&gridParamType); - MPI_Datatype typesBlock[2] = { MPI_INT, MPI_CHAR }; - int blocksBlock[2] = { 13, 1 }; - MPI_Aint offsetsBlock[2], lbBlock, extentBlock; + //----------------------------------------------------------------------- - offsetsBlock[0] = 0; - MPI_Type_get_extent(MPI_INT, &lbBlock, &extentBlock); - offsetsBlock[1] = blocksBlock[0] * extentBlock; + MPI_Datatype typesBlock[2] = { MPI_INT, MPI_CHAR }; + int blocksBlock[2] = { 13, 1 }; + MPI_Aint offsetsBlock[2], lbBlock, extentBlock; - MPI_Type_create_struct(2, blocksBlock, offsetsBlock, typesBlock, &block3dType); - MPI_Type_commit(&block3dType); + offsetsBlock[0] = 0; + MPI_Type_get_extent(MPI_INT, &lbBlock, &extentBlock); + offsetsBlock[1] = blocksBlock[0] * extentBlock; - //--------------------------------------- + MPI_Type_create_struct(2, blocksBlock, offsetsBlock, typesBlock, &block3dType); + MPI_Type_commit(&block3dType); - MPI_Type_contiguous(7, MPI_INT, &dataSetParamType); - MPI_Type_commit(&dataSetParamType); + //--------------------------------------- - //----------------------------------------------------------------------- + MPI_Type_contiguous(7, MPI_INT, &dataSetParamType); + MPI_Type_commit(&dataSetParamType); - MPI_Datatype typesBC[3] = { MPI_LONG_LONG_INT, MPI_FLOAT, MPI_CHAR }; - int blocksBC[3] = { 5, 38, 1 }; - MPI_Aint offsetsBC[3], lbBC, extentBC; + //----------------------------------------------------------------------- - offsetsBC[0] = 0; - MPI_Type_get_extent(MPI_LONG_LONG_INT, &lbBC, &extentBC); - offsetsBC[1] = blocksBC[0] * extentBC; + MPI_Datatype typesBC[3] = { MPI_LONG_LONG_INT, MPI_FLOAT, MPI_CHAR }; + int blocksBC[3] = { 5, 38, 1 }; + MPI_Aint offsetsBC[3], lbBC, extentBC; - MPI_Type_get_extent(MPI_FLOAT, &lbBC, &extentBC); - offsetsBC[2] = offsetsBC[1] + blocksBC[1] * extentBC; + offsetsBC[0] = 0; + MPI_Type_get_extent(MPI_LONG_LONG_INT, &lbBC, &extentBC); + offsetsBC[1] = blocksBC[0] * extentBC; - MPI_Type_create_struct(3, blocksBC, offsetsBC, typesBC, &boundCondType); - MPI_Type_commit(&boundCondType); + MPI_Type_get_extent(MPI_FLOAT, &lbBC, &extentBC); + offsetsBC[2] = offsetsBC[1] + blocksBC[1] * extentBC; - //--------------------------------------- + MPI_Type_create_struct(3, blocksBC, offsetsBC, typesBC, &boundCondType); + MPI_Type_commit(&boundCondType); - MPI_Type_contiguous(6, MPI_CHAR, &arrayPresenceType); - MPI_Type_commit(&arrayPresenceType); + //--------------------------------------- + MPI_Type_contiguous(6, MPI_CHAR, &arrayPresenceType); + MPI_Type_commit(&arrayPresenceType); } MPIIOCoProcessor::~MPIIOCoProcessor() { - MPI_Type_free(&gridParamType); - MPI_Type_free(&block3dType); - MPI_Type_free(&dataSetParamType); - MPI_Type_free(&boundCondType); - MPI_Type_free(&arrayPresenceType); + MPI_Type_free(&gridParamType); + MPI_Type_free(&block3dType); + MPI_Type_free(&dataSetParamType); + MPI_Type_free(&boundCondType); + MPI_Type_free(&arrayPresenceType); } void MPIIOCoProcessor::writeBlocks(int step) { - int rank, size; - MPI_Comm_rank(MPI_COMM_WORLD, &rank); - //MPI_Comm_size(MPI_COMM_WORLD, &size); - size = 1; - - if (comm->isRoot()) - { - UBLOG(logINFO, "MPIIOCoProcessor::writeBlocks start collect data rank = " << rank); - UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); - } - - int blocksCount = 0; // quantity of all the blocks in the grid, max 2147483648 blocks! - int minInitLevel = this->grid->getCoarsestInitializedLevel(); - int maxInitLevel = this->grid->getFinestInitializedLevel(); - - std::vector<SPtr<Block3D>> blocksVector[25]; // max 25 levels - for (int level = minInitLevel; level <= maxInitLevel; level++) - { - //grid->getBlocks(level, rank, blockVector[level]); - grid->getBlocks(level, blocksVector[level]); - blocksCount += static_cast<int>(blocksVector[level].size()); - } - - GridParam* gridParameters = new GridParam; - gridParameters->trafoParams[0] = grid->getCoordinateTransformator()->Tx1; - gridParameters->trafoParams[1] = grid->getCoordinateTransformator()->Tx2; - gridParameters->trafoParams[2] = grid->getCoordinateTransformator()->Tx3; - gridParameters->trafoParams[3] = grid->getCoordinateTransformator()->Sx1; - gridParameters->trafoParams[4] = grid->getCoordinateTransformator()->Sx2; - gridParameters->trafoParams[5] = grid->getCoordinateTransformator()->Sx3; - gridParameters->trafoParams[6] = grid->getCoordinateTransformator()->alpha; - gridParameters->trafoParams[7] = grid->getCoordinateTransformator()->beta; - gridParameters->trafoParams[8] = grid->getCoordinateTransformator()->gamma; - - gridParameters->trafoParams[9] = grid->getCoordinateTransformator()->toX1factorX1; - gridParameters->trafoParams[10] = grid->getCoordinateTransformator()->toX1factorX2; - gridParameters->trafoParams[11] = grid->getCoordinateTransformator()->toX1factorX3; - gridParameters->trafoParams[12] = grid->getCoordinateTransformator()->toX1delta; - gridParameters->trafoParams[13] = grid->getCoordinateTransformator()->toX2factorX1; - gridParameters->trafoParams[14] = grid->getCoordinateTransformator()->toX2factorX2; - gridParameters->trafoParams[15] = grid->getCoordinateTransformator()->toX2factorX3; - gridParameters->trafoParams[16] = grid->getCoordinateTransformator()->toX2delta; - gridParameters->trafoParams[17] = grid->getCoordinateTransformator()->toX3factorX1; - gridParameters->trafoParams[18] = grid->getCoordinateTransformator()->toX3factorX2; - gridParameters->trafoParams[19] = grid->getCoordinateTransformator()->toX3factorX3; - gridParameters->trafoParams[20] = grid->getCoordinateTransformator()->toX3delta; - - gridParameters->trafoParams[21] = grid->getCoordinateTransformator()->fromX1factorX1; - gridParameters->trafoParams[22] = grid->getCoordinateTransformator()->fromX1factorX2; - gridParameters->trafoParams[23] = grid->getCoordinateTransformator()->fromX1factorX3; - gridParameters->trafoParams[24] = grid->getCoordinateTransformator()->fromX1delta; - gridParameters->trafoParams[25] = grid->getCoordinateTransformator()->fromX2factorX1; - gridParameters->trafoParams[26] = grid->getCoordinateTransformator()->fromX2factorX2; - gridParameters->trafoParams[27] = grid->getCoordinateTransformator()->fromX2factorX3; - gridParameters->trafoParams[28] = grid->getCoordinateTransformator()->fromX2delta; - gridParameters->trafoParams[29] = grid->getCoordinateTransformator()->fromX3factorX1; - gridParameters->trafoParams[30] = grid->getCoordinateTransformator()->fromX3factorX2; - gridParameters->trafoParams[31] = grid->getCoordinateTransformator()->fromX3factorX3; - gridParameters->trafoParams[32] = grid->getCoordinateTransformator()->fromX3delta; - - gridParameters->active = grid->getCoordinateTransformator()->active; - gridParameters->transformation = grid->getCoordinateTransformator()->transformation; - - gridParameters->deltaX = grid->getDeltaX(minInitLevel); - UbTupleInt3 blocknx = grid->getBlockNX(); - gridParameters->blockNx1 = val<1>(blocknx); - gridParameters->blockNx2 = val<2>(blocknx); - gridParameters->blockNx3 = val<3>(blocknx); - gridParameters->nx1 = grid->getNX1(); - gridParameters->nx2 = grid->getNX2(); - gridParameters->nx3 = grid->getNX3(); - gridParameters->periodicX1 = grid->isPeriodicX1(); - gridParameters->periodicX2 = grid->isPeriodicX2(); - gridParameters->periodicX3 = grid->isPeriodicX3(); - - //---------------------------------------------------------------------- - - Block3d* block3dArray = new Block3d[blocksCount]; - int ic = 0; - for (int level = minInitLevel; level <= maxInitLevel; level++) - { - for (SPtr<Block3D> block : blocksVector[level]) // all the blocks of the current level - { - // save data describing the block - block3dArray[ic].x1 = block->getX1(); - block3dArray[ic].x2 = block->getX2(); - block3dArray[ic].x3 = block->getX3(); - block3dArray[ic].bundle = block->getBundle(); - block3dArray[ic].rank = block->getRank(); - block3dArray[ic].lrank = block->getLocalRank(); - block3dArray[ic].part = block->getPart(); - block3dArray[ic].globalID = block->getGlobalID(); - block3dArray[ic].localID = block->getLocalID(); - block3dArray[ic].level = block->getLevel(); - block3dArray[ic].interpolationFlagCF = block->getCollectionOfInterpolationFlagCF(); - block3dArray[ic].interpolationFlagFC = block->getCollectionOfInterpolationFlagFC(); - block3dArray[ic].counter = block->getMaxGlobalID(); - block3dArray[ic].active = block->isActive(); - - ic++; - } - } - - if (comm->isRoot()) - { - UBLOG(logINFO, "MPIIOCoProcessor::writeBlocks start MPI IO rank = " << rank); - UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); - } - - // write to the file - MPI_File file_handler; -// MPI_Info info = MPI_INFO_NULL; - - UbSystem::makeDirectory(path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step)); - std::string filename = path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + "/cpBlocks.bin"; - int rc = MPI_File_open(MPI_COMM_WORLD, filename.c_str(), MPI_MODE_CREATE | MPI_MODE_WRONLY, MPI_INFO_NULL, &file_handler); - if (rc != MPI_SUCCESS) throw UbException(UB_EXARGS, "couldn't open file " + filename); - - double start, finish; - MPI_Offset write_offset = (MPI_Offset)(size * sizeof(int)); - - if (comm->isRoot()) - { - start = MPI_Wtime(); - - // each process writes the quantity of it's blocks - MPI_File_write_at(file_handler, 0/*rank*sizeof(int)*/, &blocksCount, 1, MPI_INT, MPI_STATUS_IGNORE); - // each process writes parameters of the grid - MPI_File_write_at(file_handler, write_offset, gridParameters, 1, gridParamType, MPI_STATUS_IGNORE); - // each process writes it's blocks - MPI_File_write_at(file_handler, (MPI_Offset)(write_offset + sizeof(GridParam)), &block3dArray[0], blocksCount, block3dType, MPI_STATUS_IGNORE); - //MPI_File_sync(file_handler); - } - MPI_File_close(&file_handler); - - if (comm->isRoot()) - { - finish = MPI_Wtime(); - UBLOG(logINFO, "MPIIOCoProcessor::writeBlocks time: " << finish - start << " s"); - } - - delete[] block3dArray; - delete gridParameters; + int rank, size; + MPI_Comm_rank(MPI_COMM_WORLD, &rank); + // MPI_Comm_size(MPI_COMM_WORLD, &size); + size = 1; + + if (comm->isRoot()) { + UBLOG(logINFO, "MPIIOCoProcessor::writeBlocks start collect data rank = " << rank); + UBLOG(logINFO, "Physical Memory currently used by current process: " + << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); + } + + int blocksCount = 0; // quantity of all the blocks in the grid, max 2147483648 blocks! + int minInitLevel = this->grid->getCoarsestInitializedLevel(); + int maxInitLevel = this->grid->getFinestInitializedLevel(); + + std::vector<SPtr<Block3D>> blocksVector[25]; // max 25 levels + for (int level = minInitLevel; level <= maxInitLevel; level++) { + // grid->getBlocks(level, rank, blockVector[level]); + grid->getBlocks(level, blocksVector[level]); + blocksCount += static_cast<int>(blocksVector[level].size()); + } + + GridParam *gridParameters = new GridParam; + gridParameters->trafoParams[0] = grid->getCoordinateTransformator()->Tx1; + gridParameters->trafoParams[1] = grid->getCoordinateTransformator()->Tx2; + gridParameters->trafoParams[2] = grid->getCoordinateTransformator()->Tx3; + gridParameters->trafoParams[3] = grid->getCoordinateTransformator()->Sx1; + gridParameters->trafoParams[4] = grid->getCoordinateTransformator()->Sx2; + gridParameters->trafoParams[5] = grid->getCoordinateTransformator()->Sx3; + gridParameters->trafoParams[6] = grid->getCoordinateTransformator()->alpha; + gridParameters->trafoParams[7] = grid->getCoordinateTransformator()->beta; + gridParameters->trafoParams[8] = grid->getCoordinateTransformator()->gamma; + + gridParameters->trafoParams[9] = grid->getCoordinateTransformator()->toX1factorX1; + gridParameters->trafoParams[10] = grid->getCoordinateTransformator()->toX1factorX2; + gridParameters->trafoParams[11] = grid->getCoordinateTransformator()->toX1factorX3; + gridParameters->trafoParams[12] = grid->getCoordinateTransformator()->toX1delta; + gridParameters->trafoParams[13] = grid->getCoordinateTransformator()->toX2factorX1; + gridParameters->trafoParams[14] = grid->getCoordinateTransformator()->toX2factorX2; + gridParameters->trafoParams[15] = grid->getCoordinateTransformator()->toX2factorX3; + gridParameters->trafoParams[16] = grid->getCoordinateTransformator()->toX2delta; + gridParameters->trafoParams[17] = grid->getCoordinateTransformator()->toX3factorX1; + gridParameters->trafoParams[18] = grid->getCoordinateTransformator()->toX3factorX2; + gridParameters->trafoParams[19] = grid->getCoordinateTransformator()->toX3factorX3; + gridParameters->trafoParams[20] = grid->getCoordinateTransformator()->toX3delta; + + gridParameters->trafoParams[21] = grid->getCoordinateTransformator()->fromX1factorX1; + gridParameters->trafoParams[22] = grid->getCoordinateTransformator()->fromX1factorX2; + gridParameters->trafoParams[23] = grid->getCoordinateTransformator()->fromX1factorX3; + gridParameters->trafoParams[24] = grid->getCoordinateTransformator()->fromX1delta; + gridParameters->trafoParams[25] = grid->getCoordinateTransformator()->fromX2factorX1; + gridParameters->trafoParams[26] = grid->getCoordinateTransformator()->fromX2factorX2; + gridParameters->trafoParams[27] = grid->getCoordinateTransformator()->fromX2factorX3; + gridParameters->trafoParams[28] = grid->getCoordinateTransformator()->fromX2delta; + gridParameters->trafoParams[29] = grid->getCoordinateTransformator()->fromX3factorX1; + gridParameters->trafoParams[30] = grid->getCoordinateTransformator()->fromX3factorX2; + gridParameters->trafoParams[31] = grid->getCoordinateTransformator()->fromX3factorX3; + gridParameters->trafoParams[32] = grid->getCoordinateTransformator()->fromX3delta; + + gridParameters->active = grid->getCoordinateTransformator()->active; + gridParameters->transformation = grid->getCoordinateTransformator()->transformation; + + gridParameters->deltaX = grid->getDeltaX(minInitLevel); + UbTupleInt3 blocknx = grid->getBlockNX(); + gridParameters->blockNx1 = val<1>(blocknx); + gridParameters->blockNx2 = val<2>(blocknx); + gridParameters->blockNx3 = val<3>(blocknx); + gridParameters->nx1 = grid->getNX1(); + gridParameters->nx2 = grid->getNX2(); + gridParameters->nx3 = grid->getNX3(); + gridParameters->periodicX1 = grid->isPeriodicX1(); + gridParameters->periodicX2 = grid->isPeriodicX2(); + gridParameters->periodicX3 = grid->isPeriodicX3(); + + //---------------------------------------------------------------------- + + Block3d *block3dArray = new Block3d[blocksCount]; + int ic = 0; + for (int level = minInitLevel; level <= maxInitLevel; level++) { + for (SPtr<Block3D> block : blocksVector[level]) // all the blocks of the current level + { + // save data describing the block + block3dArray[ic].x1 = block->getX1(); + block3dArray[ic].x2 = block->getX2(); + block3dArray[ic].x3 = block->getX3(); + block3dArray[ic].bundle = block->getBundle(); + block3dArray[ic].rank = block->getRank(); + block3dArray[ic].lrank = block->getLocalRank(); + block3dArray[ic].part = block->getPart(); + block3dArray[ic].globalID = block->getGlobalID(); + block3dArray[ic].localID = block->getLocalID(); + block3dArray[ic].level = block->getLevel(); + block3dArray[ic].interpolationFlagCF = block->getCollectionOfInterpolationFlagCF(); + block3dArray[ic].interpolationFlagFC = block->getCollectionOfInterpolationFlagFC(); + block3dArray[ic].counter = block->getMaxGlobalID(); + block3dArray[ic].active = block->isActive(); + + ic++; + } + } + + if (comm->isRoot()) { + UBLOG(logINFO, "MPIIOCoProcessor::writeBlocks start MPI IO rank = " << rank); + UBLOG(logINFO, "Physical Memory currently used by current process: " + << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); + } + + // write to the file + MPI_File file_handler; + // MPI_Info info = MPI_INFO_NULL; + + UbSystem::makeDirectory(path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step)); + std::string filename = path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + "/cpBlocks.bin"; + int rc = MPI_File_open(MPI_COMM_WORLD, filename.c_str(), MPI_MODE_CREATE | MPI_MODE_WRONLY, MPI_INFO_NULL, + &file_handler); + if (rc != MPI_SUCCESS) + throw UbException(UB_EXARGS, "couldn't open file " + filename); + + double start, finish; + MPI_Offset write_offset = (MPI_Offset)(size * sizeof(int)); + + if (comm->isRoot()) { + start = MPI_Wtime(); + + // each process writes the quantity of it's blocks + MPI_File_write_at(file_handler, 0 /*rank*sizeof(int)*/, &blocksCount, 1, MPI_INT, MPI_STATUS_IGNORE); + // each process writes parameters of the grid + MPI_File_write_at(file_handler, write_offset, gridParameters, 1, gridParamType, MPI_STATUS_IGNORE); + // each process writes it's blocks + MPI_File_write_at(file_handler, (MPI_Offset)(write_offset + sizeof(GridParam)), &block3dArray[0], blocksCount, + block3dType, MPI_STATUS_IGNORE); + // MPI_File_sync(file_handler); + } + MPI_File_close(&file_handler); + + if (comm->isRoot()) { + finish = MPI_Wtime(); + UBLOG(logINFO, "MPIIOCoProcessor::writeBlocks time: " << finish - start << " s"); + } + + delete[] block3dArray; + delete gridParameters; } void MPIIOCoProcessor::readBlocks(int step) { - int rank; -// int size; - MPI_Comm_rank(MPI_COMM_WORLD, &rank); -// size = 1; - if (comm->isRoot()) - { - UBLOG(logINFO, "MPIIOCoProcessor::readBlocks start MPI IO rank = " << rank); - UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); - } - double start, finish; - if (comm->isRoot()) start = MPI_Wtime(); - - MPI_File file_handler; - std::string filename = path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + "/cpBlocks.bin"; - int rc = MPI_File_open(MPI_COMM_WORLD, filename.c_str(), MPI_MODE_RDONLY, MPI_INFO_NULL, &file_handler); - if (rc != MPI_SUCCESS) throw UbException(UB_EXARGS, "couldn't open file " + filename); - - // read count of blocks - int blocksCount = 0; - MPI_File_read_at(file_handler, 0, &blocksCount, 1, MPI_INT, MPI_STATUS_IGNORE); - Block3d* block3dArray = new Block3d[blocksCount]; - - GridParam* gridParameters = new GridParam; - - // calculate the read offset - MPI_Offset read_offset = (MPI_Offset)(sizeof(int)); - - // read parameters of the grid - MPI_File_read_at(file_handler, read_offset, gridParameters, 1, gridParamType, MPI_STATUS_IGNORE); - // read all the blocks - if (comm->isRoot()) - MPI_File_read_at(file_handler, (MPI_Offset)(read_offset + sizeof(GridParam)), &block3dArray[0], blocksCount, block3dType, MPI_STATUS_IGNORE); - - MPI_Bcast(block3dArray, blocksCount, block3dType, comm->getRoot(), MPI_COMM_WORLD); - - MPI_File_close(&file_handler); - - if (comm->isRoot()) - { - finish = MPI_Wtime(); - UBLOG(logINFO, "MPIIOCoProcessor::readBlocks time: " << finish - start << " s"); - UBLOG(logINFO, "MPIIOCoProcessor::readBlocks start of restore of data, rank = " << rank); - UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); - } - - // clear the grid - grid->deleteBlocks(); - - // restore the grid - SPtr<CoordinateTransformation3D> trafo(new CoordinateTransformation3D()); - trafo->Tx1 = gridParameters->trafoParams[0]; - trafo->Tx2 = gridParameters->trafoParams[1]; - trafo->Tx3 = gridParameters->trafoParams[2]; - trafo->Sx1 = gridParameters->trafoParams[3]; - trafo->Sx2 = gridParameters->trafoParams[4]; - trafo->Sx3 = gridParameters->trafoParams[5]; - trafo->alpha = gridParameters->trafoParams[6]; - trafo->beta = gridParameters->trafoParams[7]; - trafo->gamma = gridParameters->trafoParams[8]; - - trafo->toX1factorX1 = gridParameters->trafoParams[9]; - trafo->toX1factorX2 = gridParameters->trafoParams[10]; - trafo->toX1factorX3 = gridParameters->trafoParams[11]; - trafo->toX1delta = gridParameters->trafoParams[12]; - trafo->toX2factorX1 = gridParameters->trafoParams[13]; - trafo->toX2factorX2 = gridParameters->trafoParams[14]; - trafo->toX2factorX3 = gridParameters->trafoParams[15]; - trafo->toX2delta = gridParameters->trafoParams[16]; - trafo->toX3factorX1 = gridParameters->trafoParams[17]; - trafo->toX3factorX2 = gridParameters->trafoParams[18]; - trafo->toX3factorX3 = gridParameters->trafoParams[19]; - trafo->toX3delta = gridParameters->trafoParams[20]; - - trafo->fromX1factorX1 = gridParameters->trafoParams[21]; - trafo->fromX1factorX2 = gridParameters->trafoParams[22]; - trafo->fromX1factorX3 = gridParameters->trafoParams[23]; - trafo->fromX1delta = gridParameters->trafoParams[24]; - trafo->fromX2factorX1 = gridParameters->trafoParams[25]; - trafo->fromX2factorX2 = gridParameters->trafoParams[26]; - trafo->fromX2factorX3 = gridParameters->trafoParams[27]; - trafo->fromX2delta = gridParameters->trafoParams[28]; - trafo->fromX3factorX1 = gridParameters->trafoParams[29]; - trafo->fromX3factorX2 = gridParameters->trafoParams[30]; - trafo->fromX3factorX3 = gridParameters->trafoParams[31]; - trafo->fromX3delta = gridParameters->trafoParams[32]; - - trafo->active = gridParameters->active; - trafo->transformation = gridParameters->transformation; - - grid->setCoordinateTransformator(trafo); - - grid->setDeltaX(gridParameters->deltaX); - grid->setBlockNX(gridParameters->blockNx1, gridParameters->blockNx2, gridParameters->blockNx3); - grid->setNX1(gridParameters->nx1); - grid->setNX2(gridParameters->nx2); - grid->setNX3(gridParameters->nx3); - grid->setPeriodicX1(gridParameters->periodicX1); - grid->setPeriodicX2(gridParameters->periodicX2); - grid->setPeriodicX3(gridParameters->periodicX3); - - // regenerate blocks - for (int n = 0; n < blocksCount; n++) - { - SPtr<Block3D> block(new Block3D(block3dArray[n].x1, block3dArray[n].x2, block3dArray[n].x3, block3dArray[n].level)); - block->setActive(block3dArray[n].active); - block->setBundle(block3dArray[n].bundle); - block->setRank(block3dArray[n].rank); - block->setLocalRank(block3dArray[n].lrank); - block->setGlobalID(block3dArray[n].globalID); - block->setLocalID(block3dArray[n].localID); - block->setPart(block3dArray[n].part); - block->setLevel(block3dArray[n].level); - block->setCollectionOfInterpolationFlagCF(block3dArray[n].interpolationFlagCF); - block->setCollectionOfInterpolationFlagFC(block3dArray[n].interpolationFlagFC); - - grid->addBlock(block); - } - - delete gridParameters; - delete[] block3dArray; - - if (comm->isRoot()) - { - UBLOG(logINFO, "MPIIOCoProcessor::readBlocks end of restore of data, rank = " << rank); - UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); - } + int rank; + // int size; + MPI_Comm_rank(MPI_COMM_WORLD, &rank); + // size = 1; + if (comm->isRoot()) { + UBLOG(logINFO, "MPIIOCoProcessor::readBlocks start MPI IO rank = " << rank); + UBLOG(logINFO, "Physical Memory currently used by current process: " + << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); + } + double start, finish; + if (comm->isRoot()) + start = MPI_Wtime(); + + MPI_File file_handler; + std::string filename = path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + "/cpBlocks.bin"; + int rc = MPI_File_open(MPI_COMM_WORLD, filename.c_str(), MPI_MODE_RDONLY, MPI_INFO_NULL, &file_handler); + if (rc != MPI_SUCCESS) + throw UbException(UB_EXARGS, "couldn't open file " + filename); + + // read count of blocks + int blocksCount = 0; + MPI_File_read_at(file_handler, 0, &blocksCount, 1, MPI_INT, MPI_STATUS_IGNORE); + Block3d *block3dArray = new Block3d[blocksCount]; + + GridParam *gridParameters = new GridParam; + + // calculate the read offset + MPI_Offset read_offset = (MPI_Offset)(sizeof(int)); + + // read parameters of the grid + MPI_File_read_at(file_handler, read_offset, gridParameters, 1, gridParamType, MPI_STATUS_IGNORE); + // read all the blocks + if (comm->isRoot()) + MPI_File_read_at(file_handler, (MPI_Offset)(read_offset + sizeof(GridParam)), &block3dArray[0], blocksCount, + block3dType, MPI_STATUS_IGNORE); + + MPI_Bcast(block3dArray, blocksCount, block3dType, comm->getRoot(), MPI_COMM_WORLD); + + MPI_File_close(&file_handler); + + if (comm->isRoot()) { + finish = MPI_Wtime(); + UBLOG(logINFO, "MPIIOCoProcessor::readBlocks time: " << finish - start << " s"); + UBLOG(logINFO, "MPIIOCoProcessor::readBlocks start of restore of data, rank = " << rank); + UBLOG(logINFO, "Physical Memory currently used by current process: " + << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); + } + + // clear the grid + grid->deleteBlocks(); + + // restore the grid + SPtr<CoordinateTransformation3D> trafo(new CoordinateTransformation3D()); + trafo->Tx1 = gridParameters->trafoParams[0]; + trafo->Tx2 = gridParameters->trafoParams[1]; + trafo->Tx3 = gridParameters->trafoParams[2]; + trafo->Sx1 = gridParameters->trafoParams[3]; + trafo->Sx2 = gridParameters->trafoParams[4]; + trafo->Sx3 = gridParameters->trafoParams[5]; + trafo->alpha = gridParameters->trafoParams[6]; + trafo->beta = gridParameters->trafoParams[7]; + trafo->gamma = gridParameters->trafoParams[8]; + + trafo->toX1factorX1 = gridParameters->trafoParams[9]; + trafo->toX1factorX2 = gridParameters->trafoParams[10]; + trafo->toX1factorX3 = gridParameters->trafoParams[11]; + trafo->toX1delta = gridParameters->trafoParams[12]; + trafo->toX2factorX1 = gridParameters->trafoParams[13]; + trafo->toX2factorX2 = gridParameters->trafoParams[14]; + trafo->toX2factorX3 = gridParameters->trafoParams[15]; + trafo->toX2delta = gridParameters->trafoParams[16]; + trafo->toX3factorX1 = gridParameters->trafoParams[17]; + trafo->toX3factorX2 = gridParameters->trafoParams[18]; + trafo->toX3factorX3 = gridParameters->trafoParams[19]; + trafo->toX3delta = gridParameters->trafoParams[20]; + + trafo->fromX1factorX1 = gridParameters->trafoParams[21]; + trafo->fromX1factorX2 = gridParameters->trafoParams[22]; + trafo->fromX1factorX3 = gridParameters->trafoParams[23]; + trafo->fromX1delta = gridParameters->trafoParams[24]; + trafo->fromX2factorX1 = gridParameters->trafoParams[25]; + trafo->fromX2factorX2 = gridParameters->trafoParams[26]; + trafo->fromX2factorX3 = gridParameters->trafoParams[27]; + trafo->fromX2delta = gridParameters->trafoParams[28]; + trafo->fromX3factorX1 = gridParameters->trafoParams[29]; + trafo->fromX3factorX2 = gridParameters->trafoParams[30]; + trafo->fromX3factorX3 = gridParameters->trafoParams[31]; + trafo->fromX3delta = gridParameters->trafoParams[32]; + + trafo->active = gridParameters->active; + trafo->transformation = gridParameters->transformation; + + grid->setCoordinateTransformator(trafo); + + grid->setDeltaX(gridParameters->deltaX); + grid->setBlockNX(gridParameters->blockNx1, gridParameters->blockNx2, gridParameters->blockNx3); + grid->setNX1(gridParameters->nx1); + grid->setNX2(gridParameters->nx2); + grid->setNX3(gridParameters->nx3); + grid->setPeriodicX1(gridParameters->periodicX1); + grid->setPeriodicX2(gridParameters->periodicX2); + grid->setPeriodicX3(gridParameters->periodicX3); + + // regenerate blocks + for (int n = 0; n < blocksCount; n++) { + SPtr<Block3D> block( + new Block3D(block3dArray[n].x1, block3dArray[n].x2, block3dArray[n].x3, block3dArray[n].level)); + block->setActive(block3dArray[n].active); + block->setBundle(block3dArray[n].bundle); + block->setRank(block3dArray[n].rank); + block->setLocalRank(block3dArray[n].lrank); + block->setGlobalID(block3dArray[n].globalID); + block->setLocalID(block3dArray[n].localID); + block->setPart(block3dArray[n].part); + block->setLevel(block3dArray[n].level); + block->setCollectionOfInterpolationFlagCF(block3dArray[n].interpolationFlagCF); + block->setCollectionOfInterpolationFlagFC(block3dArray[n].interpolationFlagFC); + + grid->addBlock(block); + } + + delete gridParameters; + delete[] block3dArray; + + if (comm->isRoot()) { + UBLOG(logINFO, "MPIIOCoProcessor::readBlocks end of restore of data, rank = " << rank); + UBLOG(logINFO, "Physical Memory currently used by current process: " + << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); + } } void MPIIOCoProcessor::clearAllFiles(int step) { - MPI_File file_handler; - MPI_Info info = MPI_INFO_NULL; - MPI_Offset new_size = 0; - - UbSystem::makeDirectory(path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step)); - - std::string filename1 = path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + "/cpBlocks.bin"; - int rc1 = MPI_File_open(MPI_COMM_WORLD, filename1.c_str(), MPI_MODE_CREATE | MPI_MODE_WRONLY, MPI_INFO_NULL, &file_handler); - if (rc1 != MPI_SUCCESS) throw UbException(UB_EXARGS, "couldn't open file " + filename1); - MPI_File_set_size(file_handler, new_size); - MPI_File_close(&file_handler); - - std::string filename2 = path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + "/cpDataSet.bin"; - int rc2 = MPI_File_open(MPI_COMM_WORLD, filename2.c_str(), MPI_MODE_CREATE | MPI_MODE_WRONLY, info, &file_handler); - if (rc2 != MPI_SUCCESS) throw UbException(UB_EXARGS, "couldn't open file " + filename2); - MPI_File_set_size(file_handler, new_size); - MPI_File_close(&file_handler); - - std::string filename3 = path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + "/cpArrays.bin"; - int rc3 = MPI_File_open(MPI_COMM_WORLD, filename3.c_str(), MPI_MODE_CREATE | MPI_MODE_WRONLY, info, &file_handler); - if (rc3 != MPI_SUCCESS) throw UbException(UB_EXARGS, "couldn't open file " + filename3); - MPI_File_set_size(file_handler, new_size); - MPI_File_close(&file_handler); - - std::string filename4 = path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + "/cpAverageDensityArray.bin"; - //MPI_File_delete(filename4.c_str(), info); - int rc4 = MPI_File_open(MPI_COMM_WORLD, filename4.c_str(), MPI_MODE_CREATE | MPI_MODE_WRONLY, info, &file_handler); - if (rc4 != MPI_SUCCESS) throw UbException(UB_EXARGS, "couldn't open file " + filename4); - MPI_File_set_size(file_handler, new_size); - MPI_File_close(&file_handler); - - std::string filename5 = path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + "/cpAverageVelocityArray.bin"; - //MPI_File_delete(filename5.c_str(), info); - int rc5 = MPI_File_open(MPI_COMM_WORLD, filename5.c_str(), MPI_MODE_CREATE | MPI_MODE_WRONLY, info, &file_handler); - if (rc5 != MPI_SUCCESS) throw UbException(UB_EXARGS, "couldn't open file " + filename5); - MPI_File_set_size(file_handler, new_size); - MPI_File_close(&file_handler); - - std::string filename6 = path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + "/cpAverageFluktuationsArray.bin"; - //MPI_File_delete(filename6.c_str(), info); - int rc6 = MPI_File_open(MPI_COMM_WORLD, filename6.c_str(), MPI_MODE_CREATE | MPI_MODE_WRONLY, info, &file_handler); - if (rc6 != MPI_SUCCESS) throw UbException(UB_EXARGS, "couldn't open file " + filename6); - MPI_File_set_size(file_handler, new_size); - MPI_File_close(&file_handler); - - std::string filename7 = path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + "/cpAverageTripleArray.bin"; - //MPI_File_delete(filename7.c_str(), info); - int rc7 = MPI_File_open(MPI_COMM_WORLD, filename7.c_str(), MPI_MODE_CREATE | MPI_MODE_WRONLY, info, &file_handler); - if (rc7 != MPI_SUCCESS) throw UbException(UB_EXARGS, "couldn't open file " + filename7); - MPI_File_set_size(file_handler, new_size); - MPI_File_close(&file_handler); - - std::string filename8 = path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + "/cpShearStressValArray.bin"; - //MPI_File_delete(filename8.c_str(), info); - int rc8 = MPI_File_open(MPI_COMM_WORLD, filename8.c_str(), MPI_MODE_CREATE | MPI_MODE_WRONLY, info, &file_handler); - if (rc8 != MPI_SUCCESS) throw UbException(UB_EXARGS, "couldn't open file " + filename8); - MPI_File_set_size(file_handler, new_size); - MPI_File_close(&file_handler); - - std::string filename9 = path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + "/cpRelaxationFactor.bin"; - //MPI_File_delete(filename9.c_str(), info); - int rc9 = MPI_File_open(MPI_COMM_WORLD, filename9.c_str(), MPI_MODE_CREATE | MPI_MODE_WRONLY, info, &file_handler); - if (rc9 != MPI_SUCCESS) throw UbException(UB_EXARGS, "couldn't open file " + filename9); - MPI_File_set_size(file_handler, new_size); - MPI_File_close(&file_handler); - - /*std::string filename10 = path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + "/cpBC1.bin"; - int rc10 = MPI_File_open(MPI_COMM_WORLD, filename10.c_str(), MPI_MODE_CREATE | MPI_MODE_WRONLY, info, &file_handler); - if (rc10 != MPI_SUCCESS) throw UbException(UB_EXARGS, "couldn't open file " + filename10); - MPI_File_set_size(file_handler, new_size); - MPI_File_close(&file_handler); - - std::string filename11 = path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + "/cpBC2.bin"; - int rc11 = MPI_File_open(MPI_COMM_WORLD, filename11.c_str(), MPI_MODE_CREATE | MPI_MODE_WRONLY, info, &file_handler); - if (rc11 != MPI_SUCCESS) throw UbException(UB_EXARGS, "couldn't open file " + filename11); - MPI_File_set_size(file_handler, new_size); - MPI_File_close(&file_handler);*/ + MPI_File file_handler; + MPI_Info info = MPI_INFO_NULL; + MPI_Offset new_size = 0; + + UbSystem::makeDirectory(path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step)); + + std::string filename1 = path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + "/cpBlocks.bin"; + int rc1 = MPI_File_open(MPI_COMM_WORLD, filename1.c_str(), MPI_MODE_CREATE | MPI_MODE_WRONLY, MPI_INFO_NULL, + &file_handler); + if (rc1 != MPI_SUCCESS) + throw UbException(UB_EXARGS, "couldn't open file " + filename1); + MPI_File_set_size(file_handler, new_size); + MPI_File_close(&file_handler); + + std::string filename2 = path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + "/cpDataSet.bin"; + int rc2 = MPI_File_open(MPI_COMM_WORLD, filename2.c_str(), MPI_MODE_CREATE | MPI_MODE_WRONLY, info, &file_handler); + if (rc2 != MPI_SUCCESS) + throw UbException(UB_EXARGS, "couldn't open file " + filename2); + MPI_File_set_size(file_handler, new_size); + MPI_File_close(&file_handler); + + std::string filename3 = path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + "/cpArrays.bin"; + int rc3 = MPI_File_open(MPI_COMM_WORLD, filename3.c_str(), MPI_MODE_CREATE | MPI_MODE_WRONLY, info, &file_handler); + if (rc3 != MPI_SUCCESS) + throw UbException(UB_EXARGS, "couldn't open file " + filename3); + MPI_File_set_size(file_handler, new_size); + MPI_File_close(&file_handler); + + std::string filename4 = path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + "/cpAverageDensityArray.bin"; + // MPI_File_delete(filename4.c_str(), info); + int rc4 = MPI_File_open(MPI_COMM_WORLD, filename4.c_str(), MPI_MODE_CREATE | MPI_MODE_WRONLY, info, &file_handler); + if (rc4 != MPI_SUCCESS) + throw UbException(UB_EXARGS, "couldn't open file " + filename4); + MPI_File_set_size(file_handler, new_size); + MPI_File_close(&file_handler); + + std::string filename5 = path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + "/cpAverageVelocityArray.bin"; + // MPI_File_delete(filename5.c_str(), info); + int rc5 = MPI_File_open(MPI_COMM_WORLD, filename5.c_str(), MPI_MODE_CREATE | MPI_MODE_WRONLY, info, &file_handler); + if (rc5 != MPI_SUCCESS) + throw UbException(UB_EXARGS, "couldn't open file " + filename5); + MPI_File_set_size(file_handler, new_size); + MPI_File_close(&file_handler); + + std::string filename6 = + path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + "/cpAverageFluktuationsArray.bin"; + // MPI_File_delete(filename6.c_str(), info); + int rc6 = MPI_File_open(MPI_COMM_WORLD, filename6.c_str(), MPI_MODE_CREATE | MPI_MODE_WRONLY, info, &file_handler); + if (rc6 != MPI_SUCCESS) + throw UbException(UB_EXARGS, "couldn't open file " + filename6); + MPI_File_set_size(file_handler, new_size); + MPI_File_close(&file_handler); + + std::string filename7 = path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + "/cpAverageTripleArray.bin"; + // MPI_File_delete(filename7.c_str(), info); + int rc7 = MPI_File_open(MPI_COMM_WORLD, filename7.c_str(), MPI_MODE_CREATE | MPI_MODE_WRONLY, info, &file_handler); + if (rc7 != MPI_SUCCESS) + throw UbException(UB_EXARGS, "couldn't open file " + filename7); + MPI_File_set_size(file_handler, new_size); + MPI_File_close(&file_handler); + + std::string filename8 = path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + "/cpShearStressValArray.bin"; + // MPI_File_delete(filename8.c_str(), info); + int rc8 = MPI_File_open(MPI_COMM_WORLD, filename8.c_str(), MPI_MODE_CREATE | MPI_MODE_WRONLY, info, &file_handler); + if (rc8 != MPI_SUCCESS) + throw UbException(UB_EXARGS, "couldn't open file " + filename8); + MPI_File_set_size(file_handler, new_size); + MPI_File_close(&file_handler); + + std::string filename9 = path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + "/cpRelaxationFactor.bin"; + // MPI_File_delete(filename9.c_str(), info); + int rc9 = MPI_File_open(MPI_COMM_WORLD, filename9.c_str(), MPI_MODE_CREATE | MPI_MODE_WRONLY, info, &file_handler); + if (rc9 != MPI_SUCCESS) + throw UbException(UB_EXARGS, "couldn't open file " + filename9); + MPI_File_set_size(file_handler, new_size); + MPI_File_close(&file_handler); + + /*std::string filename10 = path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + "/cpBC1.bin"; + int rc10 = MPI_File_open(MPI_COMM_WORLD, filename10.c_str(), MPI_MODE_CREATE | MPI_MODE_WRONLY, info, + &file_handler); if (rc10 != MPI_SUCCESS) throw UbException(UB_EXARGS, "couldn't open file " + filename10); + MPI_File_set_size(file_handler, new_size); + MPI_File_close(&file_handler); + + std::string filename11 = path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + "/cpBC2.bin"; + int rc11 = MPI_File_open(MPI_COMM_WORLD, filename11.c_str(), MPI_MODE_CREATE | MPI_MODE_WRONLY, info, + &file_handler); if (rc11 != MPI_SUCCESS) throw UbException(UB_EXARGS, "couldn't open file " + filename11); + MPI_File_set_size(file_handler, new_size); + MPI_File_close(&file_handler);*/ } void MPIIOCoProcessor::writeCpTimeStep(int step) { - if (comm->isRoot()) - { - UbFileOutputASCII f(path + "/mpi_io_cp/cp.txt"); - f.writeInteger(step); - } + if (comm->isRoot()) { + UbFileOutputASCII f(path + "/mpi_io_cp/cp.txt"); + f.writeInteger(step); + } } ////////////////////////////////////////////////////////////////////////// int MPIIOCoProcessor::readCpTimeStep() { - UbFileInputASCII f(path + "/mpi_io_cp/cp.txt"); - int step = f.readInteger(); - return step; + UbFileInputASCII f(path + "/mpi_io_cp/cp.txt"); + int step = f.readInteger(); + return step; } ////////////////////////////////////////////////////////////////////////// diff --git a/src/cpu/VirtualFluidsCore/CoProcessors/MPIIOCoProcessor.h b/src/cpu/VirtualFluidsCore/CoProcessors/MPIIOCoProcessor.h index 33a63f02c2d28f5586ecc5e5ddf290c3dd10c111..8997a39d1fc16136d06e507f493e743662e189a5 100644 --- a/src/cpu/VirtualFluidsCore/CoProcessors/MPIIOCoProcessor.h +++ b/src/cpu/VirtualFluidsCore/CoProcessors/MPIIOCoProcessor.h @@ -1,44 +1,44 @@ -#ifndef _MPIIOCoProcessor_H_ +#ifndef _MPIIOCoProcessor_H_ #define _MPIIOCoProcessor_H_ #include "CoProcessor.h" #include <PointerDefinitions.h> -#include <string> #include <mpi.h> +#include <string> class Grid3D; class UbScheduler; class Communicator; -//! \class MPIWriteBlocksBECoProcessor -//! \brief Writes the grid each timestep into the files and reads the grip from the files before regenerating +//! \class MPIWriteBlocksBECoProcessor +//! \brief Writes the grid each timestep into the files and reads the grip from the files before regenerating class MPIIOCoProcessor : public CoProcessor { public: - MPIIOCoProcessor(SPtr<Grid3D> grid, SPtr<UbScheduler> s, const std::string& path, SPtr<Communicator> comm); - ~MPIIOCoProcessor() override; + MPIIOCoProcessor(SPtr<Grid3D> grid, SPtr<UbScheduler> s, const std::string &path, SPtr<Communicator> comm); + ~MPIIOCoProcessor() override; - //! Each timestep writes the grid into the files - void process(double step) override = 0; + //! Each timestep writes the grid into the files + void process(double step) override = 0; - //! Writes the blocks of the grid into the file cpBlocks.bin - void writeBlocks(int step); + //! Writes the blocks of the grid into the file cpBlocks.bin + void writeBlocks(int step); - //! Reads the blocks of the grid from the file cpBlocks.bin - void readBlocks(int step); + //! Reads the blocks of the grid from the file cpBlocks.bin + void readBlocks(int step); - //!The function truncates the data files - void clearAllFiles(int step); + //! The function truncates the data files + void clearAllFiles(int step); - //!The function write a time step of last check point - void writeCpTimeStep(int step); - //!The function read a time step of last check point - int readCpTimeStep(); + //! The function write a time step of last check point + void writeCpTimeStep(int step); + //! The function read a time step of last check point + int readCpTimeStep(); protected: - std::string path; - SPtr<Communicator> comm; - MPI_Datatype gridParamType, block3dType, dataSetParamType, boundCondType, arrayPresenceType; + std::string path; + SPtr<Communicator> comm; + MPI_Datatype gridParamType, block3dType, dataSetParamType, boundCondType, arrayPresenceType; }; #endif // ! _MPIIOCoProcessor_H_ #define _MPIIOCoProcessor_H_ diff --git a/src/cpu/VirtualFluidsCore/CoProcessors/MPIIOMigrationBECoProcessor.cpp b/src/cpu/VirtualFluidsCore/CoProcessors/MPIIOMigrationBECoProcessor.cpp index 5d864a190eadba32e6ff89946bc73f0d6c953a13..6461e847a951f2ae284bdfdae8374117ff0560c3 100644 --- a/src/cpu/VirtualFluidsCore/CoProcessors/MPIIOMigrationBECoProcessor.cpp +++ b/src/cpu/VirtualFluidsCore/CoProcessors/MPIIOMigrationBECoProcessor.cpp @@ -1,1449 +1,1513 @@ #include "MPIIOMigrationBECoProcessor.h" -#include "D3Q27System.h" -#include "LBMKernel.h" -#include "D3Q27EsoTwist3DSplittedVector.h" -#include <UbSystem.h> -#include <MemoryUtil.h> -#include "BoundaryConditions.h" +#include "BCArray3D.h" +#include "BCProcessor.h" #include "Block3D.h" +#include "BoundaryConditions.h" +#include "Communicator.h" #include "CoordinateTransformation3D.h" +#include "D3Q27EsoTwist3DSplittedVector.h" +#include "D3Q27System.h" #include "DataSet3D.h" #include "Grid3D.h" -#include "BCArray3D.h" -#include "Communicator.h" -#include "WbWriter.h" -#include "UbScheduler.h" #include "LBMKernel.h" -#include "BCProcessor.h" #include "MetisPartitioningGridVisitor.h" #include "PointerDefinitions.h" #include "RenumberGridVisitor.h" -#include "UbFileOutputASCII.h" #include "UbFileInputASCII.h" +#include "UbFileOutputASCII.h" +#include "UbScheduler.h" +#include "WbWriter.h" +#include <MemoryUtil.h> +#include <UbSystem.h> using namespace MPIIODataStructures; #define MESSAGE_TAG 80 #define SEND_BLOCK_SIZE 100000 -MPIIOMigrationBECoProcessor::MPIIOMigrationBECoProcessor(SPtr<Grid3D> grid, SPtr<UbScheduler> s, const std::string& path, SPtr<Communicator> comm) : MPIIOCoProcessor(grid, s, path, comm), nue(-999.999) +MPIIOMigrationBECoProcessor::MPIIOMigrationBECoProcessor(SPtr<Grid3D> grid, SPtr<UbScheduler> s, + const std::string &path, SPtr<Communicator> comm) + : MPIIOCoProcessor(grid, s, path, comm), nue(-999.999) { - memset(&boundCondParamStr, 0, sizeof(boundCondParamStr)); + memset(&boundCondParamStr, 0, sizeof(boundCondParamStr)); - //------------------------- define MPI types --------------------------------- - - MPI_Type_contiguous(SEND_BLOCK_SIZE, MPI_INT, &sendBlockIntType); - MPI_Type_commit(&sendBlockIntType); + //------------------------- define MPI types --------------------------------- + MPI_Type_contiguous(SEND_BLOCK_SIZE, MPI_INT, &sendBlockIntType); + MPI_Type_commit(&sendBlockIntType); } ////////////////////////////////////////////////////////////////////////// -MPIIOMigrationBECoProcessor::~MPIIOMigrationBECoProcessor() -{ - MPI_Type_free(&sendBlockIntType); -} +MPIIOMigrationBECoProcessor::~MPIIOMigrationBECoProcessor() { MPI_Type_free(&sendBlockIntType); } void MPIIOMigrationBECoProcessor::process(double step) { - if (scheduler->isDue(step)) - { - if (comm->isRoot()) UBLOG(logINFO, "MPIIOMigrationBECoProcessor save step: " << step); - if (comm->isRoot()) UBLOG(logINFO, "Save check point - start"); - clearAllFiles((int)step); + if (scheduler->isDue(step)) { + if (comm->isRoot()) + UBLOG(logINFO, "MPIIOMigrationBECoProcessor save step: " << step); + if (comm->isRoot()) + UBLOG(logINFO, "Save check point - start"); + clearAllFiles((int)step); - writeBlocks((int)step); - writeDataSet((int)step); - writeBoundaryConds((int)step); + writeBlocks((int)step); + writeDataSet((int)step); + writeBoundaryConds((int)step); - writeCpTimeStep((int)step); + writeCpTimeStep((int)step); - if (comm->isRoot()) UBLOG(logINFO, "Save check point - end"); - } + if (comm->isRoot()) + UBLOG(logINFO, "Save check point - end"); + } } void MPIIOMigrationBECoProcessor::clearAllFiles(int step) { - MPI_File file_handler; - MPI_Info info = MPI_INFO_NULL; - MPI_Offset new_size = 0; - - MPIIOCoProcessor::clearAllFiles(step); - - UbSystem::makeDirectory(path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step)); - - std::string filename10 = path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + "/cpBC1.bin"; - int rc10 = MPI_File_open(MPI_COMM_WORLD, filename10.c_str(), MPI_MODE_CREATE | MPI_MODE_WRONLY, info, &file_handler); - if (rc10 != MPI_SUCCESS) throw UbException(UB_EXARGS, "couldn't open file " + filename10); - MPI_File_set_size(file_handler, new_size); - MPI_File_close(&file_handler); - - std::string filename11 = path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + "/cpBC2.bin"; - int rc11 = MPI_File_open(MPI_COMM_WORLD, filename11.c_str(), MPI_MODE_CREATE | MPI_MODE_WRONLY, info, &file_handler); - if (rc11 != MPI_SUCCESS) throw UbException(UB_EXARGS, "couldn't open file " + filename11); - MPI_File_set_size(file_handler, new_size); - MPI_File_close(&file_handler); + MPI_File file_handler; + MPI_Info info = MPI_INFO_NULL; + MPI_Offset new_size = 0; + + MPIIOCoProcessor::clearAllFiles(step); + + UbSystem::makeDirectory(path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step)); + + std::string filename10 = path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + "/cpBC1.bin"; + int rc10 = + MPI_File_open(MPI_COMM_WORLD, filename10.c_str(), MPI_MODE_CREATE | MPI_MODE_WRONLY, info, &file_handler); + if (rc10 != MPI_SUCCESS) + throw UbException(UB_EXARGS, "couldn't open file " + filename10); + MPI_File_set_size(file_handler, new_size); + MPI_File_close(&file_handler); + + std::string filename11 = path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + "/cpBC2.bin"; + int rc11 = + MPI_File_open(MPI_COMM_WORLD, filename11.c_str(), MPI_MODE_CREATE | MPI_MODE_WRONLY, info, &file_handler); + if (rc11 != MPI_SUCCESS) + throw UbException(UB_EXARGS, "couldn't open file " + filename11); + MPI_File_set_size(file_handler, new_size); + MPI_File_close(&file_handler); } void MPIIOMigrationBECoProcessor::writeBlocks(int step) { - grid->deleteBlockIDs(); - RenumberGridVisitor renumber(comm); - grid->accept(renumber); + grid->deleteBlockIDs(); + RenumberGridVisitor renumber(comm); + grid->accept(renumber); - MPIIOCoProcessor::writeBlocks(step); + MPIIOCoProcessor::writeBlocks(step); } void MPIIOMigrationBECoProcessor::writeDataSet(int step) { - int rank, size; - MPI_Comm_rank(MPI_COMM_WORLD, &rank); - MPI_Comm_size(MPI_COMM_WORLD, &size); - - int blocksCount = 0; // quantity of blocks, that belong to this process - - std::vector<SPtr<Block3D>> blocksVector[25]; - int minInitLevel = this->grid->getCoarsestInitializedLevel(); - int maxInitLevel = this->grid->getFinestInitializedLevel(); - for (int level = minInitLevel; level <= maxInitLevel; level++) - { - grid->getBlocks(level, rank, blocksVector[level]); - blocksCount += static_cast<int>(blocksVector[level].size()); - } - - dataSetParam dataSetParamStr1, dataSetParamStr2, dataSetParamStr3; - int firstGlobalID; - std::vector<double> doubleValuesArray; // double-values (arrays of f's) in all blocks - - if (comm->isRoot()) - { - UBLOG(logINFO, "MPIIOMigrationBECoProcessor::writeDataSet start collect data rank = " << rank); - UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); - } - - DSArraysPresence arrPresence; - bool firstBlock = true; - int doubleCountInBlock = 0; - int ic = 0; - SPtr< D3Q27EsoTwist3DSplittedVector > D3Q27EsoTwist3DSplittedVectorPtr; - CbArray4D<LBMReal, IndexerX4X3X2X1>::CbArray4DPtr localDistributions; - CbArray4D <LBMReal, IndexerX4X3X2X1>::CbArray4DPtr nonLocalDistributions; - CbArray3D<LBMReal, IndexerX3X2X1>::CbArray3DPtr zeroDistributions; - - for (int level = minInitLevel; level <= maxInitLevel; level++) - { - for (SPtr<Block3D> block : blocksVector[level]) // blocks of the current level - { - D3Q27EsoTwist3DSplittedVectorPtr = dynamicPointerCast<D3Q27EsoTwist3DSplittedVector>(block->getKernel()->getDataSet()->getFdistributions()); - localDistributions = D3Q27EsoTwist3DSplittedVectorPtr->getLocalDistributions(); - nonLocalDistributions = D3Q27EsoTwist3DSplittedVectorPtr->getNonLocalDistributions(); - zeroDistributions = D3Q27EsoTwist3DSplittedVectorPtr->getZeroDistributions(); - - if (firstBlock)// && block->getKernel()) // when first (any) valid block... - { - firstGlobalID = block->getGlobalID(); // id of the block needed to find it while regenerating the grid - - if (localDistributions) - { - dataSetParamStr1.nx[0] = static_cast<int>(localDistributions->getNX1()); - dataSetParamStr1.nx[1] = static_cast<int>(localDistributions->getNX2()); - dataSetParamStr1.nx[2] = static_cast<int>(localDistributions->getNX3()); - dataSetParamStr1.nx[3] = static_cast<int>(localDistributions->getNX4()); - } + int rank, size; + MPI_Comm_rank(MPI_COMM_WORLD, &rank); + MPI_Comm_size(MPI_COMM_WORLD, &size); + + int blocksCount = 0; // quantity of blocks, that belong to this process + + std::vector<SPtr<Block3D>> blocksVector[25]; + int minInitLevel = this->grid->getCoarsestInitializedLevel(); + int maxInitLevel = this->grid->getFinestInitializedLevel(); + for (int level = minInitLevel; level <= maxInitLevel; level++) { + grid->getBlocks(level, rank, blocksVector[level]); + blocksCount += static_cast<int>(blocksVector[level].size()); + } - if (nonLocalDistributions) - { - dataSetParamStr2.nx[0] = static_cast<int>(nonLocalDistributions->getNX1()); - dataSetParamStr2.nx[1] = static_cast<int>(nonLocalDistributions->getNX2()); - dataSetParamStr2.nx[2] = static_cast<int>(nonLocalDistributions->getNX3()); - dataSetParamStr2.nx[3] = static_cast<int>(nonLocalDistributions->getNX4()); - } - if (zeroDistributions) + dataSetParam dataSetParamStr1, dataSetParamStr2, dataSetParamStr3; + int firstGlobalID; + std::vector<double> doubleValuesArray; // double-values (arrays of f's) in all blocks + + if (comm->isRoot()) { + UBLOG(logINFO, "MPIIOMigrationBECoProcessor::writeDataSet start collect data rank = " << rank); + UBLOG(logINFO, "Physical Memory currently used by current process: " + << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); + } + + DSArraysPresence arrPresence; + bool firstBlock = true; + int doubleCountInBlock = 0; + int ic = 0; + SPtr<D3Q27EsoTwist3DSplittedVector> D3Q27EsoTwist3DSplittedVectorPtr; + CbArray4D<LBMReal, IndexerX4X3X2X1>::CbArray4DPtr localDistributions; + CbArray4D<LBMReal, IndexerX4X3X2X1>::CbArray4DPtr nonLocalDistributions; + CbArray3D<LBMReal, IndexerX3X2X1>::CbArray3DPtr zeroDistributions; + + for (int level = minInitLevel; level <= maxInitLevel; level++) { + for (SPtr<Block3D> block : blocksVector[level]) // blocks of the current level + { + D3Q27EsoTwist3DSplittedVectorPtr = dynamicPointerCast<D3Q27EsoTwist3DSplittedVector>( + block->getKernel()->getDataSet()->getFdistributions()); + localDistributions = D3Q27EsoTwist3DSplittedVectorPtr->getLocalDistributions(); + nonLocalDistributions = D3Q27EsoTwist3DSplittedVectorPtr->getNonLocalDistributions(); + zeroDistributions = D3Q27EsoTwist3DSplittedVectorPtr->getZeroDistributions(); + + if (firstBlock) // && block->getKernel()) // when first (any) valid block... { - dataSetParamStr3.nx[0] = static_cast<int>(zeroDistributions->getNX1()); - dataSetParamStr3.nx[1] = static_cast<int>(zeroDistributions->getNX2()); - dataSetParamStr3.nx[2] = static_cast<int>(zeroDistributions->getNX3()); - dataSetParamStr3.nx[3] = 1; + firstGlobalID = block->getGlobalID(); // id of the block needed to find it while regenerating the grid + + if (localDistributions) { + dataSetParamStr1.nx[0] = static_cast<int>(localDistributions->getNX1()); + dataSetParamStr1.nx[1] = static_cast<int>(localDistributions->getNX2()); + dataSetParamStr1.nx[2] = static_cast<int>(localDistributions->getNX3()); + dataSetParamStr1.nx[3] = static_cast<int>(localDistributions->getNX4()); + } + + if (nonLocalDistributions) { + dataSetParamStr2.nx[0] = static_cast<int>(nonLocalDistributions->getNX1()); + dataSetParamStr2.nx[1] = static_cast<int>(nonLocalDistributions->getNX2()); + dataSetParamStr2.nx[2] = static_cast<int>(nonLocalDistributions->getNX3()); + dataSetParamStr2.nx[3] = static_cast<int>(nonLocalDistributions->getNX4()); + } + if (zeroDistributions) { + dataSetParamStr3.nx[0] = static_cast<int>(zeroDistributions->getNX1()); + dataSetParamStr3.nx[1] = static_cast<int>(zeroDistributions->getNX2()); + dataSetParamStr3.nx[2] = static_cast<int>(zeroDistributions->getNX3()); + dataSetParamStr3.nx[3] = 1; + } + + // ... than save some parameters that are equal in all blocks + dataSetParamStr1.nx1 = dataSetParamStr2.nx1 = dataSetParamStr3.nx1 = + static_cast<int>(block->getKernel()->getDataSet()->getFdistributions()->getNX1()); + dataSetParamStr1.nx2 = dataSetParamStr2.nx2 = dataSetParamStr3.nx2 = + static_cast<int>(block->getKernel()->getDataSet()->getFdistributions()->getNX2()); + dataSetParamStr1.nx3 = dataSetParamStr2.nx3 = dataSetParamStr3.nx3 = + static_cast<int>(block->getKernel()->getDataSet()->getFdistributions()->getNX3()); + + doubleCountInBlock = + dataSetParamStr1.nx[0] * dataSetParamStr1.nx[1] * dataSetParamStr1.nx[2] * dataSetParamStr1.nx[3] + + dataSetParamStr2.nx[0] * dataSetParamStr2.nx[1] * dataSetParamStr2.nx[2] * dataSetParamStr2.nx[3] + + dataSetParamStr3.nx[0] * dataSetParamStr3.nx[1] * dataSetParamStr3.nx[2] * dataSetParamStr3.nx[3]; + + SPtr<CbArray4D<LBMReal, IndexerX4X3X2X1>> averageDensityArray = + block->getKernel()->getDataSet()->getAverageDensity(); + if (averageDensityArray) + arrPresence.isAverageDensityArrayPresent = true; + else + arrPresence.isAverageDensityArrayPresent = false; + + SPtr<CbArray4D<LBMReal, IndexerX4X3X2X1>> AverageVelocityArray3DPtr = + block->getKernel()->getDataSet()->getAverageVelocity(); + if (AverageVelocityArray3DPtr) + arrPresence.isAverageVelocityArrayPresent = true; + else + arrPresence.isAverageVelocityArrayPresent = false; + + SPtr<CbArray4D<LBMReal, IndexerX4X3X2X1>> AverageFluctArray3DPtr = + block->getKernel()->getDataSet()->getAverageFluctuations(); + if (AverageFluctArray3DPtr) + arrPresence.isAverageFluktuationsArrayPresent = true; + else + arrPresence.isAverageFluktuationsArrayPresent = false; + + SPtr<CbArray4D<LBMReal, IndexerX4X3X2X1>> AverageTripleArray3DPtr = + block->getKernel()->getDataSet()->getAverageTriplecorrelations(); + if (AverageTripleArray3DPtr) + arrPresence.isAverageTripleArrayPresent = true; + else + arrPresence.isAverageTripleArrayPresent = false; + + SPtr<CbArray4D<LBMReal, IndexerX4X3X2X1>> ShearStressValArray3DPtr = + block->getKernel()->getDataSet()->getShearStressValues(); + if (ShearStressValArray3DPtr) + arrPresence.isShearStressValArrayPresent = true; + else + arrPresence.isShearStressValArrayPresent = false; + + SPtr<CbArray3D<LBMReal, IndexerX3X2X1>> relaxationFactor3DPtr = + block->getKernel()->getDataSet()->getRelaxationFactor(); + if (relaxationFactor3DPtr) + arrPresence.isRelaxationFactorPresent = true; + else + arrPresence.isRelaxationFactorPresent = false; + + firstBlock = false; } - // ... than save some parameters that are equal in all blocks - dataSetParamStr1.nx1 = dataSetParamStr2.nx1 = dataSetParamStr3.nx1 = static_cast<int>(block->getKernel()->getDataSet()->getFdistributions()->getNX1()); - dataSetParamStr1.nx2 = dataSetParamStr2.nx2 = dataSetParamStr3.nx2 = static_cast<int>(block->getKernel()->getDataSet()->getFdistributions()->getNX2()); - dataSetParamStr1.nx3 = dataSetParamStr2.nx3 = dataSetParamStr3.nx3 = static_cast<int>(block->getKernel()->getDataSet()->getFdistributions()->getNX3()); - - doubleCountInBlock = dataSetParamStr1.nx[0] * dataSetParamStr1.nx[1] * dataSetParamStr1.nx[2] * dataSetParamStr1.nx[3] + - dataSetParamStr2.nx[0] * dataSetParamStr2.nx[1] * dataSetParamStr2.nx[2] * dataSetParamStr2.nx[3] + - dataSetParamStr3.nx[0] * dataSetParamStr3.nx[1] * dataSetParamStr3.nx[2] * dataSetParamStr3.nx[3]; - - SPtr< CbArray4D<LBMReal, IndexerX4X3X2X1> > averageDensityArray = block->getKernel()->getDataSet()->getAverageDensity(); - if (averageDensityArray) - arrPresence.isAverageDensityArrayPresent = true; - else - arrPresence.isAverageDensityArrayPresent = false; - - SPtr< CbArray4D<LBMReal, IndexerX4X3X2X1> > AverageVelocityArray3DPtr = block->getKernel()->getDataSet()->getAverageVelocity(); - if (AverageVelocityArray3DPtr) - arrPresence.isAverageVelocityArrayPresent = true; - else - arrPresence.isAverageVelocityArrayPresent = false; - - SPtr< CbArray4D<LBMReal, IndexerX4X3X2X1> > AverageFluctArray3DPtr = block->getKernel()->getDataSet()->getAverageFluctuations(); - if (AverageFluctArray3DPtr) - arrPresence.isAverageFluktuationsArrayPresent = true; - else - arrPresence.isAverageFluktuationsArrayPresent = false; - - SPtr< CbArray4D<LBMReal, IndexerX4X3X2X1> > AverageTripleArray3DPtr = block->getKernel()->getDataSet()->getAverageTriplecorrelations(); - if (AverageTripleArray3DPtr) - arrPresence.isAverageTripleArrayPresent = true; - else - arrPresence.isAverageTripleArrayPresent = false; - - SPtr< CbArray4D<LBMReal, IndexerX4X3X2X1> > ShearStressValArray3DPtr = block->getKernel()->getDataSet()->getShearStressValues(); - if (ShearStressValArray3DPtr) - arrPresence.isShearStressValArrayPresent = true; - else - arrPresence.isShearStressValArrayPresent = false; - - SPtr< CbArray3D<LBMReal, IndexerX3X2X1> > relaxationFactor3DPtr = block->getKernel()->getDataSet()->getRelaxationFactor(); - if (relaxationFactor3DPtr) - arrPresence.isRelaxationFactorPresent = true; - else - arrPresence.isRelaxationFactorPresent = false; - - firstBlock = false; - } - - if (localDistributions && (dataSetParamStr1.nx[0]>0) && (dataSetParamStr1.nx[1]>0) && (dataSetParamStr1.nx[2]>0) && (dataSetParamStr1.nx[3]>0)) - doubleValuesArray.insert(doubleValuesArray.end(), localDistributions->getDataVector().begin(), localDistributions->getDataVector().end()); - if (nonLocalDistributions && (dataSetParamStr2.nx[0]>0) && (dataSetParamStr2.nx[1]>0) && (dataSetParamStr2.nx[2]>0) && (dataSetParamStr2.nx[3]>0)) - doubleValuesArray.insert(doubleValuesArray.end(), nonLocalDistributions->getDataVector().begin(), nonLocalDistributions->getDataVector().end()); - if (zeroDistributions && (dataSetParamStr3.nx[0]>0) && (dataSetParamStr3.nx[1]>0) && (dataSetParamStr3.nx[2]>0)) - doubleValuesArray.insert(doubleValuesArray.end(), zeroDistributions->getDataVector().begin(), zeroDistributions->getDataVector().end()); - - ic++; - } - } - - MPI_Type_contiguous(doubleCountInBlock, MPI_DOUBLE, &dataSetDoubleType); - MPI_Type_commit(&dataSetDoubleType); - - if (comm->isRoot()) - { - UBLOG(logINFO, "MPIIOMigrationBECoProcessor::writeDataSet start MPI IO rank = " << rank); - UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); - } - - double start, finish; - if (comm->isRoot()) start = MPI_Wtime(); - - MPI_Info info = MPI_INFO_NULL; + if (localDistributions && (dataSetParamStr1.nx[0] > 0) && (dataSetParamStr1.nx[1] > 0) && + (dataSetParamStr1.nx[2] > 0) && (dataSetParamStr1.nx[3] > 0)) + doubleValuesArray.insert(doubleValuesArray.end(), localDistributions->getDataVector().begin(), + localDistributions->getDataVector().end()); + if (nonLocalDistributions && (dataSetParamStr2.nx[0] > 0) && (dataSetParamStr2.nx[1] > 0) && + (dataSetParamStr2.nx[2] > 0) && (dataSetParamStr2.nx[3] > 0)) + doubleValuesArray.insert(doubleValuesArray.end(), nonLocalDistributions->getDataVector().begin(), + nonLocalDistributions->getDataVector().end()); + if (zeroDistributions && (dataSetParamStr3.nx[0] > 0) && (dataSetParamStr3.nx[1] > 0) && + (dataSetParamStr3.nx[2] > 0)) + doubleValuesArray.insert(doubleValuesArray.end(), zeroDistributions->getDataVector().begin(), + zeroDistributions->getDataVector().end()); + + ic++; + } + } + + MPI_Type_contiguous(doubleCountInBlock, MPI_DOUBLE, &dataSetDoubleType); + MPI_Type_commit(&dataSetDoubleType); + + if (comm->isRoot()) { + UBLOG(logINFO, "MPIIOMigrationBECoProcessor::writeDataSet start MPI IO rank = " << rank); + UBLOG(logINFO, "Physical Memory currently used by current process: " + << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); + } + + double start, finish; + if (comm->isRoot()) + start = MPI_Wtime(); + + MPI_Info info = MPI_INFO_NULL; #ifdef HLRN_LUSTRE - MPI_Info_create(&info); - MPI_Info_set(info, "striping_factor", "40"); - MPI_Info_set(info, "striping_unit", "4M"); + MPI_Info_create(&info); + MPI_Info_set(info, "striping_factor", "40"); + MPI_Info_set(info, "striping_unit", "4M"); #endif - // write to the file - MPI_File file_handler; - std::string filename = path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + "/cpDataSet.bin"; - int rc = MPI_File_open(MPI_COMM_WORLD, filename.c_str(), MPI_MODE_CREATE | MPI_MODE_WRONLY, info, &file_handler); - if (rc != MPI_SUCCESS) throw UbException(UB_EXARGS, "couldn't open file " + filename); - - MPI_Offset write_offset = (MPI_Offset)(3 * sizeof(dataSetParam)) + (MPI_Offset)(firstGlobalID) * (MPI_Offset)(doubleCountInBlock) * (MPI_Offset)(sizeof(double)); - - MPI_File_write_at(file_handler, (MPI_Offset)0, &dataSetParamStr1, 1, dataSetParamType, MPI_STATUS_IGNORE); - MPI_File_write_at(file_handler, (MPI_Offset)(sizeof(dataSetParam)), &dataSetParamStr2, 1, dataSetParamType, MPI_STATUS_IGNORE); - MPI_File_write_at(file_handler, (MPI_Offset)(2 * sizeof(dataSetParam)), &dataSetParamStr3, 1, dataSetParamType, MPI_STATUS_IGNORE); - MPI_File_write_at(file_handler, write_offset, &doubleValuesArray[0], blocksCount, dataSetDoubleType, MPI_STATUS_IGNORE); - - MPI_File_sync(file_handler); - MPI_File_close(&file_handler); - MPI_Type_free(&dataSetDoubleType); - - if (comm->isRoot()) - { - finish = MPI_Wtime(); - UBLOG(logINFO, "MPIIOMigrationBECoProcessor::writeDataSet time: " << finish - start << " s"); - } - - MPI_File file_handler1; - std::string filename1 = path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + "/cpArrays.bin"; - rc = MPI_File_open(MPI_COMM_WORLD, filename1.c_str(), MPI_MODE_CREATE | MPI_MODE_WRONLY, info, &file_handler1); - if (rc != MPI_SUCCESS) throw UbException(UB_EXARGS, "couldn't open file " + filename1); - MPI_File_write_at(file_handler1, (MPI_Offset)0, &arrPresence, 1, arrayPresenceType, MPI_STATUS_IGNORE); - MPI_File_sync(file_handler1); - MPI_File_close(&file_handler1); - - if (arrPresence.isAverageDensityArrayPresent) - write4DArray(step, AverageDensity, std::string("/cpAverageDensityArray.bin")); - //writeAverageDensityArray(step); - - if (arrPresence.isAverageVelocityArrayPresent) - write4DArray(step, AverageVelocity, std::string("/cpAverageVelocityArray.bin")); - //writeAverageVelocityArray(step); - - if (arrPresence.isAverageFluktuationsArrayPresent) - write4DArray(step, AverageFluktuations, std::string("/cpAverageFluktuationsArray.bin")); - //writeAverageFluktuationsArray(step); - - if (arrPresence.isAverageTripleArrayPresent) - write4DArray(step, AverageTriple, std::string("/cpAverageTripleArray.bin")); - //writeAverageTripleArray(step); - - if (arrPresence.isShearStressValArrayPresent) - write4DArray(step, ShearStressVal, std::string("/cpShearStressValArray.bin")); - //writeShearStressValArray(step); - - if (arrPresence.isRelaxationFactorPresent) - write3DArray(step, RelaxationFactor, std::string("/cpRelaxationFactor.bin")); - //writeRelaxationFactor(step); + // write to the file + MPI_File file_handler; + std::string filename = path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + "/cpDataSet.bin"; + int rc = MPI_File_open(MPI_COMM_WORLD, filename.c_str(), MPI_MODE_CREATE | MPI_MODE_WRONLY, info, &file_handler); + if (rc != MPI_SUCCESS) + throw UbException(UB_EXARGS, "couldn't open file " + filename); + + MPI_Offset write_offset = (MPI_Offset)(3 * sizeof(dataSetParam)) + (MPI_Offset)(firstGlobalID) * + (MPI_Offset)(doubleCountInBlock) * + (MPI_Offset)(sizeof(double)); + + MPI_File_write_at(file_handler, (MPI_Offset)0, &dataSetParamStr1, 1, dataSetParamType, MPI_STATUS_IGNORE); + MPI_File_write_at(file_handler, (MPI_Offset)(sizeof(dataSetParam)), &dataSetParamStr2, 1, dataSetParamType, + MPI_STATUS_IGNORE); + MPI_File_write_at(file_handler, (MPI_Offset)(2 * sizeof(dataSetParam)), &dataSetParamStr3, 1, dataSetParamType, + MPI_STATUS_IGNORE); + MPI_File_write_at(file_handler, write_offset, &doubleValuesArray[0], blocksCount, dataSetDoubleType, + MPI_STATUS_IGNORE); + + MPI_File_sync(file_handler); + MPI_File_close(&file_handler); + MPI_Type_free(&dataSetDoubleType); + + if (comm->isRoot()) { + finish = MPI_Wtime(); + UBLOG(logINFO, "MPIIOMigrationBECoProcessor::writeDataSet time: " << finish - start << " s"); + } + MPI_File file_handler1; + std::string filename1 = path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + "/cpArrays.bin"; + rc = MPI_File_open(MPI_COMM_WORLD, filename1.c_str(), MPI_MODE_CREATE | MPI_MODE_WRONLY, info, &file_handler1); + if (rc != MPI_SUCCESS) + throw UbException(UB_EXARGS, "couldn't open file " + filename1); + MPI_File_write_at(file_handler1, (MPI_Offset)0, &arrPresence, 1, arrayPresenceType, MPI_STATUS_IGNORE); + MPI_File_sync(file_handler1); + MPI_File_close(&file_handler1); + + if (arrPresence.isAverageDensityArrayPresent) + write4DArray(step, AverageDensity, std::string("/cpAverageDensityArray.bin")); + // writeAverageDensityArray(step); + + if (arrPresence.isAverageVelocityArrayPresent) + write4DArray(step, AverageVelocity, std::string("/cpAverageVelocityArray.bin")); + // writeAverageVelocityArray(step); + + if (arrPresence.isAverageFluktuationsArrayPresent) + write4DArray(step, AverageFluktuations, std::string("/cpAverageFluktuationsArray.bin")); + // writeAverageFluktuationsArray(step); + + if (arrPresence.isAverageTripleArrayPresent) + write4DArray(step, AverageTriple, std::string("/cpAverageTripleArray.bin")); + // writeAverageTripleArray(step); + + if (arrPresence.isShearStressValArrayPresent) + write4DArray(step, ShearStressVal, std::string("/cpShearStressValArray.bin")); + // writeShearStressValArray(step); + + if (arrPresence.isRelaxationFactorPresent) + write3DArray(step, RelaxationFactor, std::string("/cpRelaxationFactor.bin")); + // writeRelaxationFactor(step); } void MPIIOMigrationBECoProcessor::write4DArray(int step, Arrays arrayType, std::string fname) { - int rank, size; - MPI_Comm_rank(MPI_COMM_WORLD, &rank); - MPI_Comm_size(MPI_COMM_WORLD, &size); - - int blocksCount = 0; // quantity of blocks in the grid, max 2147483648 blocks! - - std::vector<SPtr<Block3D>> blocksVector[25]; - int minInitLevel = this->grid->getCoarsestInitializedLevel(); - int maxInitLevel = this->grid->getFinestInitializedLevel(); - for (int level = minInitLevel; level <= maxInitLevel; level++) - { - grid->getBlocks(level, rank, blocksVector[level]); - blocksCount += static_cast<int>(blocksVector[level].size()); - } - - int firstGlobalID; - std::vector<double> doubleValuesArray; // double-values of the data array in all blocks - dataSetParam dataSetParamStr; - bool firstBlock = true; - int doubleCountInBlock = 0; - int ic = 0; - SPtr< CbArray4D<LBMReal, IndexerX4X3X2X1> > ___Array; - - if (comm->isRoot()) - { - UBLOG(logINFO, "MPIIOMigrationBECoProcessor::write4DArray start collect data rank = " << rank); - UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); - } - - for (int level = minInitLevel; level <= maxInitLevel; level++) - { - for (SPtr<Block3D> block : blocksVector[level]) // blocks of the current level - { - switch (arrayType) { - case AverageDensity: - ___Array = block->getKernel()->getDataSet()->getAverageDensity(); - break; - case AverageVelocity: - ___Array = block->getKernel()->getDataSet()->getAverageVelocity(); - break; - case AverageFluktuations: - ___Array = block->getKernel()->getDataSet()->getAverageFluctuations(); - break; - case AverageTriple: - ___Array = block->getKernel()->getDataSet()->getAverageTriplecorrelations(); - break; - case ShearStressVal: - ___Array = block->getKernel()->getDataSet()->getShearStressValues(); - break; - default: - UB_THROW(UbException(UB_EXARGS, "MPIIOMigrationBECoProcessor::write4DArray : 4D array type does not exist!")); - break; - } - - if (firstBlock) // when first (any) valid block... - { - firstGlobalID = block->getGlobalID(); - - dataSetParamStr.nx1 = dataSetParamStr.nx2 = dataSetParamStr.nx3 = 0; - dataSetParamStr.nx[0] = static_cast<int>(___Array->getNX1()); - dataSetParamStr.nx[1] = static_cast<int>(___Array->getNX2()); - dataSetParamStr.nx[2] = static_cast<int>(___Array->getNX3()); - dataSetParamStr.nx[3] = static_cast<int>(___Array->getNX4()); - doubleCountInBlock = dataSetParamStr.nx[0] * dataSetParamStr.nx[1] * dataSetParamStr.nx[2] * dataSetParamStr.nx[3]; - - firstBlock = false; - } - - if ((dataSetParamStr.nx[0] > 0) && (dataSetParamStr.nx[1] > 0) && (dataSetParamStr.nx[2] > 0) && (dataSetParamStr.nx[3] > 0)) - doubleValuesArray.insert(doubleValuesArray.end(), ___Array->getDataVector().begin(), ___Array->getDataVector().end()); - - ic++; - } - } - - if (comm->isRoot()) - { - UBLOG(logINFO, "MPIIOMigrationBECoProcessor::write4DArray start MPI IO rank = " << rank); - UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); - } - - // register new MPI-type depending on the block-specific information - MPI_Type_contiguous(doubleCountInBlock, MPI_DOUBLE, &dataSetDoubleType); - MPI_Type_commit(&dataSetDoubleType); - - double start, finish; - if (comm->isRoot()) start = MPI_Wtime(); - - MPI_Info info = MPI_INFO_NULL; - - MPI_File file_handler; - std::string filename = path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + fname; - int rc = MPI_File_open(MPI_COMM_WORLD, filename.c_str(), MPI_MODE_CREATE | MPI_MODE_WRONLY, info, &file_handler); - if (rc != MPI_SUCCESS) throw UbException(UB_EXARGS, "couldn't open file " + filename); - - MPI_Offset write_offset = (MPI_Offset)(sizeof(dataSetParam)) + (MPI_Offset)(firstGlobalID) * (MPI_Offset)(doubleCountInBlock) * (MPI_Offset)(sizeof(double)); - - // each process writes common parameters of a dataSet - MPI_File_write_at(file_handler, 0, &dataSetParamStr, 1, dataSetParamType, MPI_STATUS_IGNORE); - MPI_File_write_at(file_handler, write_offset, &doubleValuesArray[0], blocksCount, dataSetDoubleType, MPI_STATUS_IGNORE); - - MPI_File_sync(file_handler); - MPI_File_close(&file_handler); - MPI_Type_free(&dataSetDoubleType); - - if (comm->isRoot()) - { - finish = MPI_Wtime(); - UBLOG(logINFO, "MPIIOMigrationBECoProcessor::write4DArray time: " << finish - start << " s"); - } + int rank, size; + MPI_Comm_rank(MPI_COMM_WORLD, &rank); + MPI_Comm_size(MPI_COMM_WORLD, &size); + + int blocksCount = 0; // quantity of blocks in the grid, max 2147483648 blocks! + + std::vector<SPtr<Block3D>> blocksVector[25]; + int minInitLevel = this->grid->getCoarsestInitializedLevel(); + int maxInitLevel = this->grid->getFinestInitializedLevel(); + for (int level = minInitLevel; level <= maxInitLevel; level++) { + grid->getBlocks(level, rank, blocksVector[level]); + blocksCount += static_cast<int>(blocksVector[level].size()); + } + + int firstGlobalID; + std::vector<double> doubleValuesArray; // double-values of the data array in all blocks + dataSetParam dataSetParamStr; + bool firstBlock = true; + int doubleCountInBlock = 0; + int ic = 0; + SPtr<CbArray4D<LBMReal, IndexerX4X3X2X1>> ___Array; + + if (comm->isRoot()) { + UBLOG(logINFO, "MPIIOMigrationBECoProcessor::write4DArray start collect data rank = " << rank); + UBLOG(logINFO, "Physical Memory currently used by current process: " + << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); + } + + for (int level = minInitLevel; level <= maxInitLevel; level++) { + for (SPtr<Block3D> block : blocksVector[level]) // blocks of the current level + { + switch (arrayType) { + case AverageDensity: + ___Array = block->getKernel()->getDataSet()->getAverageDensity(); + break; + case AverageVelocity: + ___Array = block->getKernel()->getDataSet()->getAverageVelocity(); + break; + case AverageFluktuations: + ___Array = block->getKernel()->getDataSet()->getAverageFluctuations(); + break; + case AverageTriple: + ___Array = block->getKernel()->getDataSet()->getAverageTriplecorrelations(); + break; + case ShearStressVal: + ___Array = block->getKernel()->getDataSet()->getShearStressValues(); + break; + default: + UB_THROW(UbException(UB_EXARGS, + "MPIIOMigrationBECoProcessor::write4DArray : 4D array type does not exist!")); + break; + } + + if (firstBlock) // when first (any) valid block... + { + firstGlobalID = block->getGlobalID(); + + dataSetParamStr.nx1 = dataSetParamStr.nx2 = dataSetParamStr.nx3 = 0; + dataSetParamStr.nx[0] = static_cast<int>(___Array->getNX1()); + dataSetParamStr.nx[1] = static_cast<int>(___Array->getNX2()); + dataSetParamStr.nx[2] = static_cast<int>(___Array->getNX3()); + dataSetParamStr.nx[3] = static_cast<int>(___Array->getNX4()); + doubleCountInBlock = + dataSetParamStr.nx[0] * dataSetParamStr.nx[1] * dataSetParamStr.nx[2] * dataSetParamStr.nx[3]; + + firstBlock = false; + } + + if ((dataSetParamStr.nx[0] > 0) && (dataSetParamStr.nx[1] > 0) && (dataSetParamStr.nx[2] > 0) && + (dataSetParamStr.nx[3] > 0)) + doubleValuesArray.insert(doubleValuesArray.end(), ___Array->getDataVector().begin(), + ___Array->getDataVector().end()); + + ic++; + } + } + + if (comm->isRoot()) { + UBLOG(logINFO, "MPIIOMigrationBECoProcessor::write4DArray start MPI IO rank = " << rank); + UBLOG(logINFO, "Physical Memory currently used by current process: " + << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); + } + + // register new MPI-type depending on the block-specific information + MPI_Type_contiguous(doubleCountInBlock, MPI_DOUBLE, &dataSetDoubleType); + MPI_Type_commit(&dataSetDoubleType); + + double start, finish; + if (comm->isRoot()) + start = MPI_Wtime(); + + MPI_Info info = MPI_INFO_NULL; + + MPI_File file_handler; + std::string filename = path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + fname; + int rc = MPI_File_open(MPI_COMM_WORLD, filename.c_str(), MPI_MODE_CREATE | MPI_MODE_WRONLY, info, &file_handler); + if (rc != MPI_SUCCESS) + throw UbException(UB_EXARGS, "couldn't open file " + filename); + + MPI_Offset write_offset = (MPI_Offset)(sizeof(dataSetParam)) + (MPI_Offset)(firstGlobalID) * + (MPI_Offset)(doubleCountInBlock) * + (MPI_Offset)(sizeof(double)); + + // each process writes common parameters of a dataSet + MPI_File_write_at(file_handler, 0, &dataSetParamStr, 1, dataSetParamType, MPI_STATUS_IGNORE); + MPI_File_write_at(file_handler, write_offset, &doubleValuesArray[0], blocksCount, dataSetDoubleType, + MPI_STATUS_IGNORE); + + MPI_File_sync(file_handler); + MPI_File_close(&file_handler); + MPI_Type_free(&dataSetDoubleType); + + if (comm->isRoot()) { + finish = MPI_Wtime(); + UBLOG(logINFO, "MPIIOMigrationBECoProcessor::write4DArray time: " << finish - start << " s"); + } } void MPIIOMigrationBECoProcessor::write3DArray(int step, Arrays arrayType, std::string fname) { - int rank, size; - MPI_Comm_rank(MPI_COMM_WORLD, &rank); - MPI_Comm_size(MPI_COMM_WORLD, &size); - - int blocksCount = 0; // quantity of blocks in the grid, max 2147483648 blocks! - - std::vector<SPtr<Block3D>> blocksVector[25]; - int minInitLevel = this->grid->getCoarsestInitializedLevel(); - int maxInitLevel = this->grid->getFinestInitializedLevel(); - for (int level = minInitLevel; level <= maxInitLevel; level++) - { - grid->getBlocks(level, rank, blocksVector[level]); - blocksCount += static_cast<int>(blocksVector[level].size()); - } - - int firstGlobalID; - std::vector<double> doubleValuesArray; // double-values of the data array in all blocks - dataSetParam dataSetParamStr; - bool firstBlock = true; - int doubleCountInBlock = 0; - int ic = 0; - SPtr< CbArray3D<LBMReal, IndexerX3X2X1> > ___Array; - - if (comm->isRoot()) - { - UBLOG(logINFO, "MPIIOMigrationBECoProcessor::write3DArray start collect data rank = " << rank); - UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); - } - - for (int level = minInitLevel; level <= maxInitLevel; level++) - { - for (SPtr<Block3D> block : blocksVector[level]) // blocks of the current level - { - switch (arrayType) { - case RelaxationFactor: - ___Array = block->getKernel()->getDataSet()->getRelaxationFactor(); - break; - default: - UB_THROW(UbException(UB_EXARGS, "MPIIOMigrationBECoProcessor::write3DArray : 3D array type does not exist!")); - break; - } - - if (firstBlock) // when first (any) valid block... - { - firstGlobalID = block->getGlobalID(); - - dataSetParamStr.nx1 = dataSetParamStr.nx2 = dataSetParamStr.nx3 = 0; - dataSetParamStr.nx[0] = static_cast<int>(___Array->getNX1()); - dataSetParamStr.nx[1] = static_cast<int>(___Array->getNX2()); - dataSetParamStr.nx[2] = static_cast<int>(___Array->getNX3()); - dataSetParamStr.nx[3] = 1; - doubleCountInBlock = dataSetParamStr.nx[0] * dataSetParamStr.nx[1] * dataSetParamStr.nx[2] * dataSetParamStr.nx[3]; - - firstBlock = false; - } - - if ((dataSetParamStr.nx[0] > 0) && (dataSetParamStr.nx[1] > 0) && (dataSetParamStr.nx[2] > 0)) - doubleValuesArray.insert(doubleValuesArray.end(), ___Array->getDataVector().begin(), ___Array->getDataVector().end()); - - ic++; - } - } - - if (comm->isRoot()) - { - UBLOG(logINFO, "MPIIOMigrationBECoProcessor::write3DArray start MPI IO rank = " << rank); - UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); - } - - // register new MPI-type depending on the block-specific information - MPI_Type_contiguous(doubleCountInBlock, MPI_DOUBLE, &dataSetDoubleType); - MPI_Type_commit(&dataSetDoubleType); - - double start, finish; - if (comm->isRoot()) start = MPI_Wtime(); - - MPI_Info info = MPI_INFO_NULL; - - MPI_File file_handler; - std::string filename = path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + fname; - int rc = MPI_File_open(MPI_COMM_WORLD, filename.c_str(), MPI_MODE_CREATE | MPI_MODE_WRONLY, info, &file_handler); - if (rc != MPI_SUCCESS) throw UbException(UB_EXARGS, "couldn't open file " + filename); - - MPI_Offset write_offset = (MPI_Offset)(sizeof(dataSetParam)) + (MPI_Offset)(firstGlobalID) * (MPI_Offset)(doubleCountInBlock) * (MPI_Offset)(sizeof(double)); - - // each process writes common parameters of a dataSet - MPI_File_write_at(file_handler, 0, &dataSetParamStr, 1, dataSetParamType, MPI_STATUS_IGNORE); - MPI_File_write_at(file_handler, write_offset, &doubleValuesArray[0], blocksCount, dataSetDoubleType, MPI_STATUS_IGNORE); - - MPI_File_sync(file_handler); - MPI_File_close(&file_handler); - MPI_Type_free(&dataSetDoubleType); - - if (comm->isRoot()) - { - finish = MPI_Wtime(); - UBLOG(logINFO, "MPIIOMigrationBECoProcessor::write3DArray time: " << finish - start << " s"); - } -} + int rank, size; + MPI_Comm_rank(MPI_COMM_WORLD, &rank); + MPI_Comm_size(MPI_COMM_WORLD, &size); + + int blocksCount = 0; // quantity of blocks in the grid, max 2147483648 blocks! + + std::vector<SPtr<Block3D>> blocksVector[25]; + int minInitLevel = this->grid->getCoarsestInitializedLevel(); + int maxInitLevel = this->grid->getFinestInitializedLevel(); + for (int level = minInitLevel; level <= maxInitLevel; level++) { + grid->getBlocks(level, rank, blocksVector[level]); + blocksCount += static_cast<int>(blocksVector[level].size()); + } -//--------------------------------------------------------------------------------- + int firstGlobalID; + std::vector<double> doubleValuesArray; // double-values of the data array in all blocks + dataSetParam dataSetParamStr; + bool firstBlock = true; + int doubleCountInBlock = 0; + int ic = 0; + SPtr<CbArray3D<LBMReal, IndexerX3X2X1>> ___Array; + + if (comm->isRoot()) { + UBLOG(logINFO, "MPIIOMigrationBECoProcessor::write3DArray start collect data rank = " << rank); + UBLOG(logINFO, "Physical Memory currently used by current process: " + << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); + } -void MPIIOMigrationBECoProcessor::writeBoundaryConds(int step) -{ - int rank, size; - MPI_Comm_rank(MPI_COMM_WORLD, &rank); - MPI_Comm_size(MPI_COMM_WORLD, &size); - - if (comm->isRoot()) - { - UBLOG(logINFO, "MPIIOMigrationBECoProcessor::writeBoundaryConds start collect data rank = " << rank); - UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); - } - - int blocksCount = 0; // quantity of blocks, that belong to this process - size_t allBytesCount = 0; // quantity of bytes, that one process writes to the file - size_t count_boundCond = 0; // how many BoundaryConditions in all blocks - int count_indexContainer = 0; // how many indexContainer-values in all blocks - - std::vector<SPtr<Block3D>> blocksVector[25]; - int minInitLevel = this->grid->getCoarsestInitializedLevel(); - int maxInitLevel = this->grid->getFinestInitializedLevel(); - for (int level = minInitLevel; level <= maxInitLevel; level++) - { - grid->getBlocks(level, rank, blocksVector[level]); - blocksCount += static_cast<int>(blocksVector[level].size()); - } - - BCAddMigration* bcAddArray = new BCAddMigration[blocksCount]; - size_t* bytesCount = new size_t[blocksCount]; // quantity of bytes, that each block writes to the file - std::vector<BoundaryCondition>* bcVector = new std::vector<BoundaryCondition>[blocksCount]; - std::vector<int>* indexContainerVector = new std::vector<int>[blocksCount]; - std::vector<int> bcindexmatrixVector; - - bool bcindexmatrixCountNotInit = true; - int ic = 0; - SPtr<BCArray3D> bcArr; - - for (int level = minInitLevel; level <= maxInitLevel; level++) - { - for (SPtr<Block3D> block : blocksVector[level]) // all the blocks of the current level - { - bcArr = block->getKernel()->getBCProcessor()->getBCArray(); - - bcAddArray[ic].globalID = block->getGlobalID(); // id of the block needed to find it while regenerating the grid - bcAddArray[ic].boundCond_count = 0; // how many BoundaryConditions in this block - bcAddArray[ic].indexContainer_count = 0; // how many indexContainer-values in this block - bytesCount[ic] = sizeof(BCAddMigration); - bcVector[ic].resize(0); - indexContainerVector[ic].resize(0); - - for (int bc = 0; bc<bcArr->getBCVectorSize(); bc++) - { - BoundaryCondition* bouCond = new BoundaryCondition(); - if (bcArr->bcvector[bc] == NULL) - memset(bouCond, 0, sizeof(BoundaryCondition)); - else + for (int level = minInitLevel; level <= maxInitLevel; level++) { + for (SPtr<Block3D> block : blocksVector[level]) // blocks of the current level + { + switch (arrayType) { + case RelaxationFactor: + ___Array = block->getKernel()->getDataSet()->getRelaxationFactor(); + break; + default: + UB_THROW(UbException(UB_EXARGS, + "MPIIOMigrationBECoProcessor::write3DArray : 3D array type does not exist!")); + break; + } + + if (firstBlock) // when first (any) valid block... { - bouCond->noslipBoundaryFlags = bcArr->bcvector[bc]->getNoSlipBoundary(); - bouCond->slipBoundaryFlags = bcArr->bcvector[bc]->getSlipBoundary(); - bouCond->velocityBoundaryFlags = bcArr->bcvector[bc]->getVelocityBoundary(); - bouCond->densityBoundaryFlags = bcArr->bcvector[bc]->getDensityBoundary(); - bouCond->wallModelBoundaryFlags = bcArr->bcvector[bc]->getWallModelBoundary(); - bouCond->bcVelocityX1 = (float) bcArr->bcvector[bc]->getBoundaryVelocityX1(); - bouCond->bcVelocityX2 = (float) bcArr->bcvector[bc]->getBoundaryVelocityX2(); - bouCond->bcVelocityX3 = (float) bcArr->bcvector[bc]->getBoundaryVelocityX3(); - bouCond->bcDensity = (float) bcArr->bcvector[bc]->getBoundaryDensity(); - bouCond->bcLodiDensity = (float) bcArr->bcvector[bc]->getDensityLodiDensity(); - bouCond->bcLodiVelocityX1 = (float) bcArr->bcvector[bc]->getDensityLodiVelocityX1(); - bouCond->bcLodiVelocityX2 = (float) bcArr->bcvector[bc]->getDensityLodiVelocityX2(); - bouCond->bcLodiVelocityX3 = (float) bcArr->bcvector[bc]->getDensityLodiVelocityX3(); - bouCond->bcLodiLentgh = (float) bcArr->bcvector[bc]->getDensityLodiLength(); - bouCond->nx1 = (float) bcArr->bcvector[bc]->nx1; - bouCond->nx2 = (float) bcArr->bcvector[bc]->nx2; - bouCond->nx3 = (float) bcArr->bcvector[bc]->nx3; - for (int iq = 0; iq<26; iq++) - bouCond->q[iq] = (float) bcArr->bcvector[bc]->getQ(iq); - bouCond->algorithmType = bcArr->bcvector[bc]->getBcAlgorithmType(); + firstGlobalID = block->getGlobalID(); + + dataSetParamStr.nx1 = dataSetParamStr.nx2 = dataSetParamStr.nx3 = 0; + dataSetParamStr.nx[0] = static_cast<int>(___Array->getNX1()); + dataSetParamStr.nx[1] = static_cast<int>(___Array->getNX2()); + dataSetParamStr.nx[2] = static_cast<int>(___Array->getNX3()); + dataSetParamStr.nx[3] = 1; + doubleCountInBlock = + dataSetParamStr.nx[0] * dataSetParamStr.nx[1] * dataSetParamStr.nx[2] * dataSetParamStr.nx[3]; + + firstBlock = false; } - bcVector[ic].push_back(*bouCond); - bcAddArray[ic].boundCond_count++; - count_boundCond++; - bytesCount[ic] += sizeof(BoundaryCondition); - } - - if (bcindexmatrixCountNotInit) - { - boundCondParamStr.nx1 = static_cast<int>(bcArr->bcindexmatrix.getNX1()); - boundCondParamStr.nx2 = static_cast<int>(bcArr->bcindexmatrix.getNX2()); - boundCondParamStr.nx3 = static_cast<int>(bcArr->bcindexmatrix.getNX3()); - boundCondParamStr.bcindexmatrixCount = static_cast<int>(bcArr->bcindexmatrix.getDataVector().size()); - bcindexmatrixCountNotInit = false; - } - - bcindexmatrixVector.insert(bcindexmatrixVector.end(), bcArr->bcindexmatrix.getDataVector().begin(), bcArr->bcindexmatrix.getDataVector().end()); - - indexContainerVector[ic].insert(indexContainerVector[ic].begin(), bcArr->indexContainer.begin(), bcArr->indexContainer.end()); - bcAddArray[ic].indexContainer_count = static_cast<int>(bcArr->indexContainer.size()); - count_indexContainer += bcAddArray[ic].indexContainer_count; - bytesCount[ic] += bcAddArray[ic].indexContainer_count * sizeof(int); - - allBytesCount += bytesCount[ic]; - - ic++; - } - } - - MPI_Type_contiguous(boundCondParamStr.bcindexmatrixCount, MPI_INT, &bcindexmatrixType); - MPI_Type_commit(&bcindexmatrixType); - - if (comm->isRoot()) - { - UBLOG(logINFO, "MPIIOMigrationBECoProcessor::writeBoundaryConds start MPI IO rank = " << rank); - UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); - } - - double start, finish; - if (comm->isRoot()) start = MPI_Wtime(); - - MPI_Info info = MPI_INFO_NULL; - //MPI_Info_create (&info); - //MPI_Info_set(info,"romio_cb_write","enable"); - //MPI_Info_set(info,"cb_buffer_size","4194304"); - //MPI_Info_set(info,"striping_unit","4194304"); - -//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - MPI_File file_handler; - std::string filename = path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + "/cpBC1.bin"; - int rc = MPI_File_open(MPI_COMM_WORLD, filename.c_str(), MPI_MODE_CREATE | MPI_MODE_WRONLY, info, &file_handler); - if (rc != MPI_SUCCESS) throw UbException(UB_EXARGS, "couldn't open file " + filename); - - MPI_Offset write_offset = (MPI_Offset)(sizeof(int)) + (MPI_Offset)(bcAddArray[0].globalID) * (MPI_Offset)(boundCondParamStr.bcindexmatrixCount) * (MPI_Offset)(sizeof(int)); - - MPI_File_write_at(file_handler, 0, &boundCondParamStr.bcindexmatrixCount, 1, MPI_INT, MPI_STATUS_IGNORE); - MPI_File_write_at(file_handler, write_offset, &bcindexmatrixVector[0], blocksCount, bcindexmatrixType, MPI_STATUS_IGNORE); - - MPI_File_sync(file_handler); - MPI_File_close(&file_handler); - MPI_Type_free(&bcindexmatrixType); - -//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - filename = path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + "/cpBC2.bin"; - rc = MPI_File_open(MPI_COMM_WORLD, filename.c_str(), MPI_MODE_CREATE | MPI_MODE_WRONLY, info, &file_handler); - if (rc != MPI_SUCCESS) throw UbException(UB_EXARGS, "couldn't open file " + filename); - - MPI_File_write_at(file_handler, 0, &boundCondParamStr, 4, MPI_INT, MPI_STATUS_IGNORE); - - write_offset = (MPI_Offset)(sizeof(boundCondParam)) + (MPI_Offset)(grid->getNumberOfBlocks()) * (MPI_Offset)(sizeof(size_t)); - size_t next_file_offset = 0; - if (size > 1) - { - if (rank == 0) - { - next_file_offset = write_offset + allBytesCount; - MPI_Send(&next_file_offset, 1, MPI_LONG_LONG_INT, 1, 5, MPI_COMM_WORLD); - } - else - { - MPI_Recv(&write_offset, 1, MPI_LONG_LONG_INT, rank - 1, 5, MPI_COMM_WORLD, MPI_STATUS_IGNORE); - next_file_offset = write_offset + allBytesCount; - if (rank < size - 1) - MPI_Send(&next_file_offset, 1, MPI_LONG_LONG_INT, rank + 1, 5, MPI_COMM_WORLD); - } - } - - MPI_Offset write_offsetIndex; - - for (int nb = 0; nb < blocksCount; nb++) - { - write_offsetIndex = (MPI_Offset)(sizeof(boundCondParam)) + (MPI_Offset)(bcAddArray[nb].globalID) * (MPI_Offset)(sizeof(size_t)); - MPI_File_write_at(file_handler, write_offsetIndex, &write_offset, 1, MPI_LONG_LONG_INT, MPI_STATUS_IGNORE); - - MPI_File_write_at(file_handler, write_offset, &bcAddArray[nb], 3, MPI_INT, MPI_STATUS_IGNORE); - if (bcVector[nb].size() > 0) - MPI_File_write_at(file_handler, write_offset + (MPI_Offset)(sizeof(BCAddMigration)), &bcVector[nb][0], bcAddArray[nb].boundCond_count, boundCondType, MPI_STATUS_IGNORE); - - if (indexContainerVector[nb].size() > 0) - MPI_File_write_at(file_handler, write_offset + (MPI_Offset)(sizeof(BCAddMigration)) + (MPI_Offset)(bcAddArray[nb].boundCond_count) * (MPI_Offset)(sizeof(BoundaryCondition)), - &indexContainerVector[nb][0], bcAddArray[nb].indexContainer_count, MPI_INT, MPI_STATUS_IGNORE); - - write_offset += bytesCount[nb]; - } - - MPI_File_sync(file_handler); - MPI_File_close(&file_handler); - - if (comm->isRoot()) - { - finish = MPI_Wtime(); - UBLOG(logINFO, "MPIIOMigrationBECoProcessor::writeBoundaryConds time: " << finish - start << " s"); - } - - delete[] bcAddArray; - delete[] bytesCount; - delete[] bcVector; - delete[] indexContainerVector; + if ((dataSetParamStr.nx[0] > 0) && (dataSetParamStr.nx[1] > 0) && (dataSetParamStr.nx[2] > 0)) + doubleValuesArray.insert(doubleValuesArray.end(), ___Array->getDataVector().begin(), + ___Array->getDataVector().end()); + + ic++; + } + } + + if (comm->isRoot()) { + UBLOG(logINFO, "MPIIOMigrationBECoProcessor::write3DArray start MPI IO rank = " << rank); + UBLOG(logINFO, "Physical Memory currently used by current process: " + << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); + } + + // register new MPI-type depending on the block-specific information + MPI_Type_contiguous(doubleCountInBlock, MPI_DOUBLE, &dataSetDoubleType); + MPI_Type_commit(&dataSetDoubleType); + + double start, finish; + if (comm->isRoot()) + start = MPI_Wtime(); + + MPI_Info info = MPI_INFO_NULL; + + MPI_File file_handler; + std::string filename = path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + fname; + int rc = MPI_File_open(MPI_COMM_WORLD, filename.c_str(), MPI_MODE_CREATE | MPI_MODE_WRONLY, info, &file_handler); + if (rc != MPI_SUCCESS) + throw UbException(UB_EXARGS, "couldn't open file " + filename); + + MPI_Offset write_offset = (MPI_Offset)(sizeof(dataSetParam)) + (MPI_Offset)(firstGlobalID) * + (MPI_Offset)(doubleCountInBlock) * + (MPI_Offset)(sizeof(double)); + + // each process writes common parameters of a dataSet + MPI_File_write_at(file_handler, 0, &dataSetParamStr, 1, dataSetParamType, MPI_STATUS_IGNORE); + MPI_File_write_at(file_handler, write_offset, &doubleValuesArray[0], blocksCount, dataSetDoubleType, + MPI_STATUS_IGNORE); + + MPI_File_sync(file_handler); + MPI_File_close(&file_handler); + MPI_Type_free(&dataSetDoubleType); + + if (comm->isRoot()) { + finish = MPI_Wtime(); + UBLOG(logINFO, "MPIIOMigrationBECoProcessor::write3DArray time: " << finish - start << " s"); + } } -//------------------------------------------- READ ----------------------------------------------- -void MPIIOMigrationBECoProcessor::restart(int step) +//--------------------------------------------------------------------------------- + +void MPIIOMigrationBECoProcessor::writeBoundaryConds(int step) { - if (comm->isRoot()) UBLOG(logINFO, "MPIIOMigrationBECoProcessor restart step: " << step); - if (comm->isRoot()) UBLOG(logINFO, "Load check point - start"); + int rank, size; + MPI_Comm_rank(MPI_COMM_WORLD, &rank); + MPI_Comm_size(MPI_COMM_WORLD, &size); + + if (comm->isRoot()) { + UBLOG(logINFO, "MPIIOMigrationBECoProcessor::writeBoundaryConds start collect data rank = " << rank); + UBLOG(logINFO, "Physical Memory currently used by current process: " + << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); + } + + int blocksCount = 0; // quantity of blocks, that belong to this process + size_t allBytesCount = 0; // quantity of bytes, that one process writes to the file + size_t count_boundCond = 0; // how many BoundaryConditions in all blocks + int count_indexContainer = 0; // how many indexContainer-values in all blocks + + std::vector<SPtr<Block3D>> blocksVector[25]; + int minInitLevel = this->grid->getCoarsestInitializedLevel(); + int maxInitLevel = this->grid->getFinestInitializedLevel(); + for (int level = minInitLevel; level <= maxInitLevel; level++) { + grid->getBlocks(level, rank, blocksVector[level]); + blocksCount += static_cast<int>(blocksVector[level].size()); + } + + BCAddMigration *bcAddArray = new BCAddMigration[blocksCount]; + size_t *bytesCount = new size_t[blocksCount]; // quantity of bytes, that each block writes to the file + std::vector<BoundaryCondition> *bcVector = new std::vector<BoundaryCondition>[blocksCount]; + std::vector<int> *indexContainerVector = new std::vector<int>[blocksCount]; + std::vector<int> bcindexmatrixVector; + + bool bcindexmatrixCountNotInit = true; + int ic = 0; + SPtr<BCArray3D> bcArr; + + for (int level = minInitLevel; level <= maxInitLevel; level++) { + for (SPtr<Block3D> block : blocksVector[level]) // all the blocks of the current level + { + bcArr = block->getKernel()->getBCProcessor()->getBCArray(); + + bcAddArray[ic].globalID = + block->getGlobalID(); // id of the block needed to find it while regenerating the grid + bcAddArray[ic].boundCond_count = 0; // how many BoundaryConditions in this block + bcAddArray[ic].indexContainer_count = 0; // how many indexContainer-values in this block + bytesCount[ic] = sizeof(BCAddMigration); + bcVector[ic].resize(0); + indexContainerVector[ic].resize(0); + + for (int bc = 0; bc < bcArr->getBCVectorSize(); bc++) { + BoundaryCondition *bouCond = new BoundaryCondition(); + if (bcArr->bcvector[bc] == NULL) + memset(bouCond, 0, sizeof(BoundaryCondition)); + else { + bouCond->noslipBoundaryFlags = bcArr->bcvector[bc]->getNoSlipBoundary(); + bouCond->slipBoundaryFlags = bcArr->bcvector[bc]->getSlipBoundary(); + bouCond->velocityBoundaryFlags = bcArr->bcvector[bc]->getVelocityBoundary(); + bouCond->densityBoundaryFlags = bcArr->bcvector[bc]->getDensityBoundary(); + bouCond->wallModelBoundaryFlags = bcArr->bcvector[bc]->getWallModelBoundary(); + bouCond->bcVelocityX1 = (float)bcArr->bcvector[bc]->getBoundaryVelocityX1(); + bouCond->bcVelocityX2 = (float)bcArr->bcvector[bc]->getBoundaryVelocityX2(); + bouCond->bcVelocityX3 = (float)bcArr->bcvector[bc]->getBoundaryVelocityX3(); + bouCond->bcDensity = (float)bcArr->bcvector[bc]->getBoundaryDensity(); + bouCond->bcLodiDensity = (float)bcArr->bcvector[bc]->getDensityLodiDensity(); + bouCond->bcLodiVelocityX1 = (float)bcArr->bcvector[bc]->getDensityLodiVelocityX1(); + bouCond->bcLodiVelocityX2 = (float)bcArr->bcvector[bc]->getDensityLodiVelocityX2(); + bouCond->bcLodiVelocityX3 = (float)bcArr->bcvector[bc]->getDensityLodiVelocityX3(); + bouCond->bcLodiLentgh = (float)bcArr->bcvector[bc]->getDensityLodiLength(); + bouCond->nx1 = (float)bcArr->bcvector[bc]->nx1; + bouCond->nx2 = (float)bcArr->bcvector[bc]->nx2; + bouCond->nx3 = (float)bcArr->bcvector[bc]->nx3; + for (int iq = 0; iq < 26; iq++) + bouCond->q[iq] = (float)bcArr->bcvector[bc]->getQ(iq); + bouCond->algorithmType = bcArr->bcvector[bc]->getBcAlgorithmType(); + } + + bcVector[ic].push_back(*bouCond); + bcAddArray[ic].boundCond_count++; + count_boundCond++; + bytesCount[ic] += sizeof(BoundaryCondition); + } + + if (bcindexmatrixCountNotInit) { + boundCondParamStr.nx1 = static_cast<int>(bcArr->bcindexmatrix.getNX1()); + boundCondParamStr.nx2 = static_cast<int>(bcArr->bcindexmatrix.getNX2()); + boundCondParamStr.nx3 = static_cast<int>(bcArr->bcindexmatrix.getNX3()); + boundCondParamStr.bcindexmatrixCount = static_cast<int>(bcArr->bcindexmatrix.getDataVector().size()); + bcindexmatrixCountNotInit = false; + } + + bcindexmatrixVector.insert(bcindexmatrixVector.end(), bcArr->bcindexmatrix.getDataVector().begin(), + bcArr->bcindexmatrix.getDataVector().end()); + + indexContainerVector[ic].insert(indexContainerVector[ic].begin(), bcArr->indexContainer.begin(), + bcArr->indexContainer.end()); + bcAddArray[ic].indexContainer_count = static_cast<int>(bcArr->indexContainer.size()); + count_indexContainer += bcAddArray[ic].indexContainer_count; + bytesCount[ic] += bcAddArray[ic].indexContainer_count * sizeof(int); + + allBytesCount += bytesCount[ic]; + + ic++; + } + } + + MPI_Type_contiguous(boundCondParamStr.bcindexmatrixCount, MPI_INT, &bcindexmatrixType); + MPI_Type_commit(&bcindexmatrixType); - readBlocks(step); - SPtr<Grid3DVisitor> newMetisVisitor(new MetisPartitioningGridVisitor(comm, MetisPartitioningGridVisitor::LevelBased, D3Q27System::BSW, MetisPartitioner::KWAY)); - grid->accept(newMetisVisitor); + if (comm->isRoot()) { + UBLOG(logINFO, "MPIIOMigrationBECoProcessor::writeBoundaryConds start MPI IO rank = " << rank); + UBLOG(logINFO, "Physical Memory currently used by current process: " + << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); + } + + double start, finish; + if (comm->isRoot()) + start = MPI_Wtime(); + + MPI_Info info = MPI_INFO_NULL; + // MPI_Info_create (&info); + // MPI_Info_set(info,"romio_cb_write","enable"); + // MPI_Info_set(info,"cb_buffer_size","4194304"); + // MPI_Info_set(info,"striping_unit","4194304"); + + //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + MPI_File file_handler; + std::string filename = path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + "/cpBC1.bin"; + int rc = MPI_File_open(MPI_COMM_WORLD, filename.c_str(), MPI_MODE_CREATE | MPI_MODE_WRONLY, info, &file_handler); + if (rc != MPI_SUCCESS) + throw UbException(UB_EXARGS, "couldn't open file " + filename); + + MPI_Offset write_offset = (MPI_Offset)(sizeof(int)) + (MPI_Offset)(bcAddArray[0].globalID) * + (MPI_Offset)(boundCondParamStr.bcindexmatrixCount) * + (MPI_Offset)(sizeof(int)); + + MPI_File_write_at(file_handler, 0, &boundCondParamStr.bcindexmatrixCount, 1, MPI_INT, MPI_STATUS_IGNORE); + MPI_File_write_at(file_handler, write_offset, &bcindexmatrixVector[0], blocksCount, bcindexmatrixType, + MPI_STATUS_IGNORE); + + MPI_File_sync(file_handler); + MPI_File_close(&file_handler); + MPI_Type_free(&bcindexmatrixType); + + //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + filename = path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + "/cpBC2.bin"; + rc = MPI_File_open(MPI_COMM_WORLD, filename.c_str(), MPI_MODE_CREATE | MPI_MODE_WRONLY, info, &file_handler); + if (rc != MPI_SUCCESS) + throw UbException(UB_EXARGS, "couldn't open file " + filename); + + MPI_File_write_at(file_handler, 0, &boundCondParamStr, 4, MPI_INT, MPI_STATUS_IGNORE); + + write_offset = + (MPI_Offset)(sizeof(boundCondParam)) + (MPI_Offset)(grid->getNumberOfBlocks()) * (MPI_Offset)(sizeof(size_t)); + size_t next_file_offset = 0; + if (size > 1) { + if (rank == 0) { + next_file_offset = write_offset + allBytesCount; + MPI_Send(&next_file_offset, 1, MPI_LONG_LONG_INT, 1, 5, MPI_COMM_WORLD); + } else { + MPI_Recv(&write_offset, 1, MPI_LONG_LONG_INT, rank - 1, 5, MPI_COMM_WORLD, MPI_STATUS_IGNORE); + next_file_offset = write_offset + allBytesCount; + if (rank < size - 1) + MPI_Send(&next_file_offset, 1, MPI_LONG_LONG_INT, rank + 1, 5, MPI_COMM_WORLD); + } + } + + MPI_Offset write_offsetIndex; + + for (int nb = 0; nb < blocksCount; nb++) { + write_offsetIndex = + (MPI_Offset)(sizeof(boundCondParam)) + (MPI_Offset)(bcAddArray[nb].globalID) * (MPI_Offset)(sizeof(size_t)); + MPI_File_write_at(file_handler, write_offsetIndex, &write_offset, 1, MPI_LONG_LONG_INT, MPI_STATUS_IGNORE); + + MPI_File_write_at(file_handler, write_offset, &bcAddArray[nb], 3, MPI_INT, MPI_STATUS_IGNORE); + if (bcVector[nb].size() > 0) + MPI_File_write_at(file_handler, write_offset + (MPI_Offset)(sizeof(BCAddMigration)), &bcVector[nb][0], + bcAddArray[nb].boundCond_count, boundCondType, MPI_STATUS_IGNORE); + + if (indexContainerVector[nb].size() > 0) + MPI_File_write_at( + file_handler, + write_offset + (MPI_Offset)(sizeof(BCAddMigration)) + + (MPI_Offset)(bcAddArray[nb].boundCond_count) * (MPI_Offset)(sizeof(BoundaryCondition)), + &indexContainerVector[nb][0], bcAddArray[nb].indexContainer_count, MPI_INT, MPI_STATUS_IGNORE); - readDataSet(step); - readBoundaryConds(step); + write_offset += bytesCount[nb]; + } + + MPI_File_sync(file_handler); + MPI_File_close(&file_handler); + + if (comm->isRoot()) { + finish = MPI_Wtime(); + UBLOG(logINFO, "MPIIOMigrationBECoProcessor::writeBoundaryConds time: " << finish - start << " s"); + } - grid->setTimeStep(step); - if (comm->isRoot()) UBLOG(logINFO, "Load check point - end"); + delete[] bcAddArray; + delete[] bytesCount; + delete[] bcVector; + delete[] indexContainerVector; } -void MPIIOMigrationBECoProcessor::readBlocks(int step) +//------------------------------------------- READ ----------------------------------------------- +void MPIIOMigrationBECoProcessor::restart(int step) { - MPIIOCoProcessor::readBlocks(step); + if (comm->isRoot()) + UBLOG(logINFO, "MPIIOMigrationBECoProcessor restart step: " << step); + if (comm->isRoot()) + UBLOG(logINFO, "Load check point - start"); + + readBlocks(step); + SPtr<Grid3DVisitor> newMetisVisitor(new MetisPartitioningGridVisitor(comm, MetisPartitioningGridVisitor::LevelBased, + D3Q27System::BSW, MetisPartitioner::KWAY)); + grid->accept(newMetisVisitor); + + readDataSet(step); + readBoundaryConds(step); + + grid->setTimeStep(step); + if (comm->isRoot()) + UBLOG(logINFO, "Load check point - end"); } -void MPIIOMigrationBECoProcessor::blocksExchange(int tagN, int ind1, int ind2, int doubleCountInBlock, std::vector<double>& pV, std::vector<double>* rawDataReceive) +void MPIIOMigrationBECoProcessor::readBlocks(int step) { MPIIOCoProcessor::readBlocks(step); } + +void MPIIOMigrationBECoProcessor::blocksExchange(int tagN, int ind1, int ind2, int doubleCountInBlock, + std::vector<double> &pV, std::vector<double> *rawDataReceive) { - int rank, size; - MPI_Comm_rank(MPI_COMM_WORLD, &rank); - MPI_Comm_size(MPI_COMM_WORLD, &size); - - int indexB = ind1; - int indexE = ind2; -// int myBlocksCount = indexE - indexB; - - int* blocksCounterSend = new int[size]; - int* blocksCounterRec = new int[size]; - - std::vector<double>* rawDataSend = new std::vector<double>[size]; - for (int r = 0; r < size; r++) - { - rawDataSend[r].resize(0); - blocksCounterSend[r] = 0; - blocksCounterRec[r] = 0; - } - - SPtr<Block3D> tempBlock; - int tempRank; - - for(size_t ind = indexB - indexB; ind < indexE - indexB; ind++) // FIXME: both sides of operator are equivalent - { - tempBlock = grid->getBlock(indexB + int(ind)); - if(!tempBlock) throw UbException(UB_EXARGS,"MPIIOMigrationBECoProcessor::blocksExchange -- null block pointer!!!" ); - - tempRank = tempBlock->getRank(); - - if (tempRank == rank) // no need to send data, the process already has it - { - blocksCounterRec[tempRank]++; - rawDataReceive[tempRank].push_back(double(indexB + ind)); - rawDataReceive[tempRank].insert(rawDataReceive[tempRank].end(), pV.begin() + ind * size_t(doubleCountInBlock), pV.begin() + ind * size_t(doubleCountInBlock) + size_t(doubleCountInBlock)); - } - else // we must send data to other processes - { - blocksCounterSend[tempRank]++; - rawDataSend[tempRank].push_back(double(indexB + ind)); - rawDataSend[tempRank].insert(rawDataSend[tempRank].end(), pV.begin() + ind * size_t(doubleCountInBlock), pV.begin() + ind * size_t(doubleCountInBlock) + size_t(doubleCountInBlock)); - } - } - - MPI_Request* requests = new MPI_Request[size * 2]; // send + receive - int requestCount = 0; -// MPI_Status status; - - for (int r = 0; r < size; r++) - { - if (r != rank) - { - MPI_Irecv(&blocksCounterRec[r], 1, MPI_INT, r, tagN, MPI_COMM_WORLD, &requests[requestCount]); - requestCount++; - } - } - - for (int r = 0; r < size; r++) - { - if (r != rank) - { - MPI_Isend(&blocksCounterSend[r], 1, MPI_INT, r, tagN, MPI_COMM_WORLD, &requests[requestCount]); - requestCount++; - } - } - - MPI_Waitall(requestCount, &requests[0], MPI_STATUSES_IGNORE); - - MPI_Type_contiguous(doubleCountInBlock + 1, MPI_DOUBLE, &sendBlockDoubleType); - MPI_Type_commit(&sendBlockDoubleType); + int rank, size; + MPI_Comm_rank(MPI_COMM_WORLD, &rank); + MPI_Comm_size(MPI_COMM_WORLD, &size); + + int indexB = ind1; + int indexE = ind2; + // int myBlocksCount = indexE - indexB; + + int *blocksCounterSend = new int[size]; + int *blocksCounterRec = new int[size]; + + std::vector<double> *rawDataSend = new std::vector<double>[size]; + for (int r = 0; r < size; r++) { + rawDataSend[r].resize(0); + blocksCounterSend[r] = 0; + blocksCounterRec[r] = 0; + } - for (int r = 0; r < size; r++) + SPtr<Block3D> tempBlock; + int tempRank; + + for (size_t ind = indexB - indexB; ind < indexE - indexB; ind++) // FIXME: both sides of operator are equivalent { - if (r != rank) - rawDataReceive[r].resize(size_t(blocksCounterRec[r]) * size_t(doubleCountInBlock + 1)); + tempBlock = grid->getBlock(indexB + int(ind)); + if (!tempBlock) + throw UbException(UB_EXARGS, "MPIIOMigrationBECoProcessor::blocksExchange -- null block pointer!!!"); + + tempRank = tempBlock->getRank(); + + if (tempRank == rank) // no need to send data, the process already has it + { + blocksCounterRec[tempRank]++; + rawDataReceive[tempRank].push_back(double(indexB + ind)); + rawDataReceive[tempRank].insert(rawDataReceive[tempRank].end(), + pV.begin() + ind * size_t(doubleCountInBlock), + pV.begin() + ind * size_t(doubleCountInBlock) + size_t(doubleCountInBlock)); + } else // we must send data to other processes + { + blocksCounterSend[tempRank]++; + rawDataSend[tempRank].push_back(double(indexB + ind)); + rawDataSend[tempRank].insert(rawDataSend[tempRank].end(), pV.begin() + ind * size_t(doubleCountInBlock), + pV.begin() + ind * size_t(doubleCountInBlock) + size_t(doubleCountInBlock)); + } } - requestCount = 0; - int sendRecCount = 0; - size_t sendRecOffset = 0; - const int maxQuant = 400; - int restQuant; + MPI_Request *requests = new MPI_Request[size * 2]; // send + receive + int requestCount = 0; + // MPI_Status status; - for (int r = 0; r < size; r++) - { - if (r != rank) - { - sendRecCount = int(blocksCounterRec[r] / maxQuant); - if(sendRecCount * maxQuant < blocksCounterRec[r]) - sendRecCount++; - requests = (MPI_Request*)realloc(requests, (requestCount + sendRecCount) * sizeof(MPI_Request)); - - for(int sc = 0; sc < sendRecCount; sc++) - { - restQuant = (sc < sendRecCount - 1) ? maxQuant : blocksCounterRec[r] - sc * maxQuant; - sendRecOffset = size_t(sc) * size_t(maxQuant) * size_t((doubleCountInBlock + 1)); - MPI_Irecv(&rawDataReceive[r][sendRecOffset], restQuant, sendBlockDoubleType, r, tagN, MPI_COMM_WORLD, &requests[requestCount]); - requestCount++; - } - } + for (int r = 0; r < size; r++) { + if (r != rank) { + MPI_Irecv(&blocksCounterRec[r], 1, MPI_INT, r, tagN, MPI_COMM_WORLD, &requests[requestCount]); + requestCount++; + } } - for (int r = 0; r < size; r++) - { - if (r != rank) - { - sendRecCount = int(blocksCounterSend[r] / maxQuant); - if(sendRecCount * maxQuant < blocksCounterSend[r]) - sendRecCount++; - requests = (MPI_Request*)realloc(requests, (requestCount + sendRecCount) * sizeof(MPI_Request)); - - for(int sc = 0; sc < sendRecCount; sc++) - { - restQuant = (sc < sendRecCount - 1) ? maxQuant : blocksCounterSend[r] - sc * maxQuant; - sendRecOffset = size_t(sc) * size_t(maxQuant) * size_t((doubleCountInBlock + 1)); - MPI_Isend(&rawDataSend[r][sendRecOffset], restQuant, sendBlockDoubleType, r, tagN, MPI_COMM_WORLD, &requests[requestCount]); - requestCount++; - } - } + for (int r = 0; r < size; r++) { + if (r != rank) { + MPI_Isend(&blocksCounterSend[r], 1, MPI_INT, r, tagN, MPI_COMM_WORLD, &requests[requestCount]); + requestCount++; + } } - MPI_Waitall(requestCount, &requests[0], MPI_STATUSES_IGNORE); + MPI_Waitall(requestCount, &requests[0], MPI_STATUSES_IGNORE); - delete [] blocksCounterSend; - delete [] blocksCounterRec; - delete [] rawDataSend; - delete [] requests; + MPI_Type_contiguous(doubleCountInBlock + 1, MPI_DOUBLE, &sendBlockDoubleType); + MPI_Type_commit(&sendBlockDoubleType); + for (int r = 0; r < size; r++) { + if (r != rank) + rawDataReceive[r].resize(size_t(blocksCounterRec[r]) * size_t(doubleCountInBlock + 1)); + } + + requestCount = 0; + int sendRecCount = 0; + size_t sendRecOffset = 0; + const int maxQuant = 400; + int restQuant; + + for (int r = 0; r < size; r++) { + if (r != rank) { + sendRecCount = int(blocksCounterRec[r] / maxQuant); + if (sendRecCount * maxQuant < blocksCounterRec[r]) + sendRecCount++; + requests = (MPI_Request *)realloc(requests, (requestCount + sendRecCount) * sizeof(MPI_Request)); + + for (int sc = 0; sc < sendRecCount; sc++) { + restQuant = (sc < sendRecCount - 1) ? maxQuant : blocksCounterRec[r] - sc * maxQuant; + sendRecOffset = size_t(sc) * size_t(maxQuant) * size_t((doubleCountInBlock + 1)); + MPI_Irecv(&rawDataReceive[r][sendRecOffset], restQuant, sendBlockDoubleType, r, tagN, MPI_COMM_WORLD, + &requests[requestCount]); + requestCount++; + } + } + } + + for (int r = 0; r < size; r++) { + if (r != rank) { + sendRecCount = int(blocksCounterSend[r] / maxQuant); + if (sendRecCount * maxQuant < blocksCounterSend[r]) + sendRecCount++; + requests = (MPI_Request *)realloc(requests, (requestCount + sendRecCount) * sizeof(MPI_Request)); + + for (int sc = 0; sc < sendRecCount; sc++) { + restQuant = (sc < sendRecCount - 1) ? maxQuant : blocksCounterSend[r] - sc * maxQuant; + sendRecOffset = size_t(sc) * size_t(maxQuant) * size_t((doubleCountInBlock + 1)); + MPI_Isend(&rawDataSend[r][sendRecOffset], restQuant, sendBlockDoubleType, r, tagN, MPI_COMM_WORLD, + &requests[requestCount]); + requestCount++; + } + } + } + + MPI_Waitall(requestCount, &requests[0], MPI_STATUSES_IGNORE); + + delete[] blocksCounterSend; + delete[] blocksCounterRec; + delete[] rawDataSend; + delete[] requests; } void MPIIOMigrationBECoProcessor::readDataSet(int step) { - int rank, size; - MPI_Comm_rank(MPI_COMM_WORLD, &rank); - MPI_Comm_size(MPI_COMM_WORLD, &size); - - if (!lbmKernel) - UB_THROW(UbException(UB_EXARGS, "lbmKernel does not exist!")); - if (!bcProcessor) - UB_THROW(UbException(UB_EXARGS, "bcProcessor does not exist!")); - if (nue == -999.999) - UB_THROW(UbException(UB_EXARGS, "nue is not initialised!")); - - if (comm->isRoot()) - { - UBLOG(logINFO, "MPIIOMigrationBECoProcessor::readDataSet start MPI IO rank = " << rank); - UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); - } - - dataSetParam dataSetParamStr1, dataSetParamStr2, dataSetParamStr3; - - int blocksCountAll = grid->getNumberOfBlocks(); // quantity of all blocks in the grid - int blocksPerProcess = blocksCountAll / size; // how many blocks has each process - - size_t myBlocksCount; - if (rank < (size - 1)) - myBlocksCount = blocksPerProcess; - else - myBlocksCount = blocksPerProcess + (blocksCountAll - blocksPerProcess * size); - - int indexB = rank * blocksPerProcess; // the first "my" block - int indexE = indexB + int(myBlocksCount); // the latest "my" block - - double start, finish; - if (comm->isRoot()) start = MPI_Wtime(); - - MPI_File file_handler; - std::string filename = path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + "/cpDataSet.bin"; - int rc = MPI_File_open(MPI_COMM_WORLD, filename.c_str(), MPI_MODE_RDONLY, MPI_INFO_NULL, &file_handler); - if (rc != MPI_SUCCESS) throw UbException(UB_EXARGS, "couldn't open file " + filename); - - MPI_File_read_at(file_handler, (MPI_Offset)0, &dataSetParamStr1, 1, dataSetParamType, MPI_STATUS_IGNORE); - MPI_File_read_at(file_handler, (MPI_Offset)(sizeof(dataSetParam)), &dataSetParamStr2, 1, dataSetParamType, MPI_STATUS_IGNORE); - MPI_File_read_at(file_handler, (MPI_Offset)(2 * sizeof(dataSetParam)), &dataSetParamStr3, 1, dataSetParamType, MPI_STATUS_IGNORE); - - size_t doubleCountInBlock = dataSetParamStr1.nx[0] * dataSetParamStr1.nx[1] * dataSetParamStr1.nx[2] * dataSetParamStr1.nx[3] + - dataSetParamStr2.nx[0] * dataSetParamStr2.nx[1] * dataSetParamStr2.nx[2] * dataSetParamStr2.nx[3] + - dataSetParamStr3.nx[0] * dataSetParamStr3.nx[1] * dataSetParamStr3.nx[2] * dataSetParamStr3.nx[3]; - std::vector<double> doubleValuesArray(myBlocksCount * doubleCountInBlock); // double-values in all blocks - - MPI_Type_contiguous(int(doubleCountInBlock), MPI_DOUBLE, &dataSetDoubleType); - MPI_Type_commit(&dataSetDoubleType); - - MPI_Offset read_offset = (MPI_Offset)(3 * sizeof(dataSetParam)) + (MPI_Offset)(indexB * doubleCountInBlock * sizeof(double)); - MPI_File_read_at(file_handler, read_offset, &doubleValuesArray[0], int(myBlocksCount), dataSetDoubleType, MPI_STATUS_IGNORE); - - MPI_File_close(&file_handler); - MPI_Type_free(&dataSetDoubleType); - - if (comm->isRoot()) - { - finish = MPI_Wtime(); - UBLOG(logINFO, "MPIIOMigrationBECoProcessor::readDataSet time: " << finish - start << " s"); - UBLOG(logINFO, "MPIIOMigrationBECoProcessor::readDataSet start of exchange of data, rank = " << rank); - UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); - } - - std::vector<double>* rawDataReceive = new std::vector<double>[size]; - for (int r = 0; r < size; r++) - rawDataReceive[r].resize(0); - - blocksExchange(MESSAGE_TAG, indexB, indexE, int(doubleCountInBlock), doubleValuesArray, rawDataReceive); - - if (comm->isRoot()) - { - finish = MPI_Wtime(); - UBLOG(logINFO, "MPIIOMigrationBECoProcessor::readDataSet time: " << finish - start << " s"); - UBLOG(logINFO, "MPIIOMigrationBECoProcessor::readDataSet start of restore of data, rank = " << rank); - UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); - } - - //-------------------------------------- restore blocks --------------------------------- - int blockID; - std::vector<double> vectorsOfValues1, vectorsOfValues2, vectorsOfValues3; - - size_t vectorSize1 = dataSetParamStr1.nx[0] * dataSetParamStr1.nx[1] * dataSetParamStr1.nx[2] * dataSetParamStr1.nx[3]; - size_t vectorSize2 = dataSetParamStr2.nx[0] * dataSetParamStr2.nx[1] * dataSetParamStr2.nx[2] * dataSetParamStr2.nx[3]; - size_t vectorSize3 = dataSetParamStr3.nx[0] * dataSetParamStr3.nx[1] * dataSetParamStr3.nx[2] * dataSetParamStr3.nx[3]; - - size_t index; - for (int r = 0; r < size; r++) - { - index = 0; - for (int ii = 0; ii < int(rawDataReceive[r].size() / doubleCountInBlock); ii++) - { - blockID = (int)(rawDataReceive[r][index]); - index += 1; - - vectorsOfValues1.assign(rawDataReceive[r].data() + index, rawDataReceive[r].data() + index + vectorSize1); - index += vectorSize1; - - vectorsOfValues2.assign(rawDataReceive[r].data() + index, rawDataReceive[r].data() + index + vectorSize2); - index += vectorSize2; - - vectorsOfValues3.assign(rawDataReceive[r].data() + index, rawDataReceive[r].data() + index + vectorSize3); - index += vectorSize3; - - SPtr<DistributionArray3D> mFdistributions(new D3Q27EsoTwist3DSplittedVector()); - dynamicPointerCast<D3Q27EsoTwist3DSplittedVector>(mFdistributions)->setLocalDistributions(CbArray4D<LBMReal, IndexerX4X3X2X1>::CbArray4DPtr(new CbArray4D<LBMReal, IndexerX4X3X2X1>(vectorsOfValues1, dataSetParamStr1.nx[0], dataSetParamStr1.nx[1], dataSetParamStr1.nx[2], dataSetParamStr1.nx[3]))); - dynamicPointerCast<D3Q27EsoTwist3DSplittedVector>(mFdistributions)->setNonLocalDistributions(CbArray4D<LBMReal, IndexerX4X3X2X1>::CbArray4DPtr(new CbArray4D<LBMReal, IndexerX4X3X2X1>(vectorsOfValues2, dataSetParamStr2.nx[0], dataSetParamStr2.nx[1], dataSetParamStr2.nx[2], dataSetParamStr2.nx[3]))); - dynamicPointerCast<D3Q27EsoTwist3DSplittedVector>(mFdistributions)->setZeroDistributions(CbArray3D<LBMReal, IndexerX3X2X1>::CbArray3DPtr(new CbArray3D<LBMReal, IndexerX3X2X1>(vectorsOfValues3, dataSetParamStr3.nx[0], dataSetParamStr3.nx[1], dataSetParamStr3.nx[2]))); - - dynamicPointerCast<D3Q27EsoTwist3DSplittedVector>(mFdistributions)->setNX1(dataSetParamStr1.nx1); - dynamicPointerCast<D3Q27EsoTwist3DSplittedVector>(mFdistributions)->setNX2(dataSetParamStr1.nx2); - dynamicPointerCast<D3Q27EsoTwist3DSplittedVector>(mFdistributions)->setNX3(dataSetParamStr1.nx3); - - // find the nesessary block and fill it - SPtr<Block3D> block = grid->getBlock(blockID); - this->lbmKernel->setBlock(block); - SPtr<LBMKernel> kernel = this->lbmKernel->clone(); - LBMReal collFactor = LBMSystem::calcCollisionFactor(this->nue, block->getLevel()); - kernel->setCollisionFactor(collFactor); - kernel->setIndex(block->getX1(), block->getX2(), block->getX3()); - kernel->setDeltaT(LBMSystem::getDeltaT(block->getLevel())); - SPtr<DataSet3D> dataSetPtr = SPtr<DataSet3D>(new DataSet3D()); - dataSetPtr->setFdistributions(mFdistributions); - kernel->setDataSet(dataSetPtr); - block->setKernel(kernel); - } - } - if (comm->isRoot()) - { - UBLOG(logINFO, "MPIIOMigrationBECoProcessor::readDataSet end of restore of data, rank = " << rank); - UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); - } - - //------------------------------------------------------------- - - DSArraysPresence arrPresence; - MPI_File file_handler1; - std::string filename1 = path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + "/cpArrays.bin"; - rc = MPI_File_open(MPI_COMM_WORLD, filename1.c_str(), MPI_MODE_RDONLY, MPI_INFO_NULL, &file_handler1); - if (rc != MPI_SUCCESS) return;// throw UbException(UB_EXARGS, "couldn't open file " + filename1); - - MPI_File_read_at(file_handler1, (MPI_Offset)0, &arrPresence, 1, arrayPresenceType, MPI_STATUS_IGNORE); - MPI_File_close(&file_handler1); - - if (arrPresence.isAverageDensityArrayPresent) - readArray(step, AverageDensity, std::string("/cpAverageDensityArray.bin")); - //readAverageDensityArray(step); - - if (arrPresence.isAverageVelocityArrayPresent) - readArray(step, AverageVelocity, std::string("/cpAverageVelocityArray.bin")); - // readAverageVelocityArray(step); - - if (arrPresence.isAverageFluktuationsArrayPresent) - readArray(step, AverageFluktuations, std::string("/cpAverageFluktuationsArray.bin")); - // readAverageFluktuationsArray(step); - - if (arrPresence.isAverageTripleArrayPresent) - readArray(step, AverageTriple, std::string("/cpAverageTripleArray.bin")); - // readAverageTripleArray(step); - - if (arrPresence.isShearStressValArrayPresent) - readArray(step, ShearStressVal, std::string("/cpShearStressValArray.bin")); - // readShearStressValArray(step); - - if (arrPresence.isRelaxationFactorPresent) - readArray(step, RelaxationFactor, std::string("/cpRelaxationFactor.bin")); - // readRelaxationFactor(step); - - delete [] rawDataReceive; + int rank, size; + MPI_Comm_rank(MPI_COMM_WORLD, &rank); + MPI_Comm_size(MPI_COMM_WORLD, &size); + + if (!lbmKernel) + UB_THROW(UbException(UB_EXARGS, "lbmKernel does not exist!")); + if (!bcProcessor) + UB_THROW(UbException(UB_EXARGS, "bcProcessor does not exist!")); + if (nue == -999.999) + UB_THROW(UbException(UB_EXARGS, "nue is not initialised!")); + + if (comm->isRoot()) { + UBLOG(logINFO, "MPIIOMigrationBECoProcessor::readDataSet start MPI IO rank = " << rank); + UBLOG(logINFO, "Physical Memory currently used by current process: " + << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); + } + + dataSetParam dataSetParamStr1, dataSetParamStr2, dataSetParamStr3; + + int blocksCountAll = grid->getNumberOfBlocks(); // quantity of all blocks in the grid + int blocksPerProcess = blocksCountAll / size; // how many blocks has each process + + size_t myBlocksCount; + if (rank < (size - 1)) + myBlocksCount = blocksPerProcess; + else + myBlocksCount = blocksPerProcess + (blocksCountAll - blocksPerProcess * size); + + int indexB = rank * blocksPerProcess; // the first "my" block + int indexE = indexB + int(myBlocksCount); // the latest "my" block + + double start, finish; + if (comm->isRoot()) + start = MPI_Wtime(); + + MPI_File file_handler; + std::string filename = path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + "/cpDataSet.bin"; + int rc = MPI_File_open(MPI_COMM_WORLD, filename.c_str(), MPI_MODE_RDONLY, MPI_INFO_NULL, &file_handler); + if (rc != MPI_SUCCESS) + throw UbException(UB_EXARGS, "couldn't open file " + filename); + + MPI_File_read_at(file_handler, (MPI_Offset)0, &dataSetParamStr1, 1, dataSetParamType, MPI_STATUS_IGNORE); + MPI_File_read_at(file_handler, (MPI_Offset)(sizeof(dataSetParam)), &dataSetParamStr2, 1, dataSetParamType, + MPI_STATUS_IGNORE); + MPI_File_read_at(file_handler, (MPI_Offset)(2 * sizeof(dataSetParam)), &dataSetParamStr3, 1, dataSetParamType, + MPI_STATUS_IGNORE); + + size_t doubleCountInBlock = + dataSetParamStr1.nx[0] * dataSetParamStr1.nx[1] * dataSetParamStr1.nx[2] * dataSetParamStr1.nx[3] + + dataSetParamStr2.nx[0] * dataSetParamStr2.nx[1] * dataSetParamStr2.nx[2] * dataSetParamStr2.nx[3] + + dataSetParamStr3.nx[0] * dataSetParamStr3.nx[1] * dataSetParamStr3.nx[2] * dataSetParamStr3.nx[3]; + std::vector<double> doubleValuesArray(myBlocksCount * doubleCountInBlock); // double-values in all blocks + + MPI_Type_contiguous(int(doubleCountInBlock), MPI_DOUBLE, &dataSetDoubleType); + MPI_Type_commit(&dataSetDoubleType); + + MPI_Offset read_offset = + (MPI_Offset)(3 * sizeof(dataSetParam)) + (MPI_Offset)(indexB * doubleCountInBlock * sizeof(double)); + MPI_File_read_at(file_handler, read_offset, &doubleValuesArray[0], int(myBlocksCount), dataSetDoubleType, + MPI_STATUS_IGNORE); + + MPI_File_close(&file_handler); + MPI_Type_free(&dataSetDoubleType); + + if (comm->isRoot()) { + finish = MPI_Wtime(); + UBLOG(logINFO, "MPIIOMigrationBECoProcessor::readDataSet time: " << finish - start << " s"); + UBLOG(logINFO, "MPIIOMigrationBECoProcessor::readDataSet start of exchange of data, rank = " << rank); + UBLOG(logINFO, "Physical Memory currently used by current process: " + << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); + } + + std::vector<double> *rawDataReceive = new std::vector<double>[size]; + for (int r = 0; r < size; r++) + rawDataReceive[r].resize(0); + + blocksExchange(MESSAGE_TAG, indexB, indexE, int(doubleCountInBlock), doubleValuesArray, rawDataReceive); + + if (comm->isRoot()) { + finish = MPI_Wtime(); + UBLOG(logINFO, "MPIIOMigrationBECoProcessor::readDataSet time: " << finish - start << " s"); + UBLOG(logINFO, "MPIIOMigrationBECoProcessor::readDataSet start of restore of data, rank = " << rank); + UBLOG(logINFO, "Physical Memory currently used by current process: " + << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); + } + + //-------------------------------------- restore blocks --------------------------------- + int blockID; + std::vector<double> vectorsOfValues1, vectorsOfValues2, vectorsOfValues3; + + size_t vectorSize1 = + dataSetParamStr1.nx[0] * dataSetParamStr1.nx[1] * dataSetParamStr1.nx[2] * dataSetParamStr1.nx[3]; + size_t vectorSize2 = + dataSetParamStr2.nx[0] * dataSetParamStr2.nx[1] * dataSetParamStr2.nx[2] * dataSetParamStr2.nx[3]; + size_t vectorSize3 = + dataSetParamStr3.nx[0] * dataSetParamStr3.nx[1] * dataSetParamStr3.nx[2] * dataSetParamStr3.nx[3]; + + size_t index; + for (int r = 0; r < size; r++) { + index = 0; + for (int ii = 0; ii < int(rawDataReceive[r].size() / doubleCountInBlock); ii++) { + blockID = (int)(rawDataReceive[r][index]); + index += 1; + + vectorsOfValues1.assign(rawDataReceive[r].data() + index, rawDataReceive[r].data() + index + vectorSize1); + index += vectorSize1; + + vectorsOfValues2.assign(rawDataReceive[r].data() + index, rawDataReceive[r].data() + index + vectorSize2); + index += vectorSize2; + + vectorsOfValues3.assign(rawDataReceive[r].data() + index, rawDataReceive[r].data() + index + vectorSize3); + index += vectorSize3; + + SPtr<DistributionArray3D> mFdistributions(new D3Q27EsoTwist3DSplittedVector()); + dynamicPointerCast<D3Q27EsoTwist3DSplittedVector>(mFdistributions) + ->setLocalDistributions(CbArray4D<LBMReal, IndexerX4X3X2X1>::CbArray4DPtr( + new CbArray4D<LBMReal, IndexerX4X3X2X1>(vectorsOfValues1, dataSetParamStr1.nx[0], + dataSetParamStr1.nx[1], dataSetParamStr1.nx[2], + dataSetParamStr1.nx[3]))); + dynamicPointerCast<D3Q27EsoTwist3DSplittedVector>(mFdistributions) + ->setNonLocalDistributions(CbArray4D<LBMReal, IndexerX4X3X2X1>::CbArray4DPtr( + new CbArray4D<LBMReal, IndexerX4X3X2X1>(vectorsOfValues2, dataSetParamStr2.nx[0], + dataSetParamStr2.nx[1], dataSetParamStr2.nx[2], + dataSetParamStr2.nx[3]))); + dynamicPointerCast<D3Q27EsoTwist3DSplittedVector>(mFdistributions) + ->setZeroDistributions( + CbArray3D<LBMReal, IndexerX3X2X1>::CbArray3DPtr(new CbArray3D<LBMReal, IndexerX3X2X1>( + vectorsOfValues3, dataSetParamStr3.nx[0], dataSetParamStr3.nx[1], dataSetParamStr3.nx[2]))); + + dynamicPointerCast<D3Q27EsoTwist3DSplittedVector>(mFdistributions)->setNX1(dataSetParamStr1.nx1); + dynamicPointerCast<D3Q27EsoTwist3DSplittedVector>(mFdistributions)->setNX2(dataSetParamStr1.nx2); + dynamicPointerCast<D3Q27EsoTwist3DSplittedVector>(mFdistributions)->setNX3(dataSetParamStr1.nx3); + + // find the nesessary block and fill it + SPtr<Block3D> block = grid->getBlock(blockID); + this->lbmKernel->setBlock(block); + SPtr<LBMKernel> kernel = this->lbmKernel->clone(); + LBMReal collFactor = LBMSystem::calcCollisionFactor(this->nue, block->getLevel()); + kernel->setCollisionFactor(collFactor); + kernel->setIndex(block->getX1(), block->getX2(), block->getX3()); + kernel->setDeltaT(LBMSystem::getDeltaT(block->getLevel())); + SPtr<DataSet3D> dataSetPtr = SPtr<DataSet3D>(new DataSet3D()); + dataSetPtr->setFdistributions(mFdistributions); + kernel->setDataSet(dataSetPtr); + block->setKernel(kernel); + } + } + if (comm->isRoot()) { + UBLOG(logINFO, "MPIIOMigrationBECoProcessor::readDataSet end of restore of data, rank = " << rank); + UBLOG(logINFO, "Physical Memory currently used by current process: " + << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); + } + + //------------------------------------------------------------- + + DSArraysPresence arrPresence; + MPI_File file_handler1; + std::string filename1 = path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + "/cpArrays.bin"; + rc = MPI_File_open(MPI_COMM_WORLD, filename1.c_str(), MPI_MODE_RDONLY, MPI_INFO_NULL, &file_handler1); + if (rc != MPI_SUCCESS) + return; // throw UbException(UB_EXARGS, "couldn't open file " + filename1); + + MPI_File_read_at(file_handler1, (MPI_Offset)0, &arrPresence, 1, arrayPresenceType, MPI_STATUS_IGNORE); + MPI_File_close(&file_handler1); + + if (arrPresence.isAverageDensityArrayPresent) + readArray(step, AverageDensity, std::string("/cpAverageDensityArray.bin")); + // readAverageDensityArray(step); + + if (arrPresence.isAverageVelocityArrayPresent) + readArray(step, AverageVelocity, std::string("/cpAverageVelocityArray.bin")); + // readAverageVelocityArray(step); + + if (arrPresence.isAverageFluktuationsArrayPresent) + readArray(step, AverageFluktuations, std::string("/cpAverageFluktuationsArray.bin")); + // readAverageFluktuationsArray(step); + + if (arrPresence.isAverageTripleArrayPresent) + readArray(step, AverageTriple, std::string("/cpAverageTripleArray.bin")); + // readAverageTripleArray(step); + + if (arrPresence.isShearStressValArrayPresent) + readArray(step, ShearStressVal, std::string("/cpShearStressValArray.bin")); + // readShearStressValArray(step); + + if (arrPresence.isRelaxationFactorPresent) + readArray(step, RelaxationFactor, std::string("/cpRelaxationFactor.bin")); + // readRelaxationFactor(step); + + delete[] rawDataReceive; } void MPIIOMigrationBECoProcessor::readArray(int step, Arrays arrType, std::string fname) { - int rank, size; - MPI_Comm_rank(MPI_COMM_WORLD, &rank); - MPI_Comm_size(MPI_COMM_WORLD, &size); - - if (comm->isRoot()) - { - UBLOG(logINFO, "MPIIOMigrationBECoProcessor::readArray start MPI IO rank = " << rank); - UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); - } - double start, finish; - if (comm->isRoot()) start = MPI_Wtime(); - - dataSetParam dataSetParamStr; - memset(&dataSetParamStr, 0, sizeof(dataSetParam)); - - int blocksCountAll = grid->getNumberOfBlocks(); // quantity of all blocks in the grid - int blocksPerProcess = blocksCountAll / size; // how many blocks has each process - - size_t myBlocksCount; - if (rank < (size - 1)) - myBlocksCount = blocksPerProcess; - else - myBlocksCount = blocksPerProcess + (blocksCountAll - blocksPerProcess * size); - - int indexB = rank * blocksPerProcess; // the first "my" block - int indexE = indexB + int(myBlocksCount); // the latest "my" block - - MPI_File file_handler; - std::string filename = path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + fname; - int rc = MPI_File_open(MPI_COMM_WORLD, filename.c_str(), MPI_MODE_RDONLY, MPI_INFO_NULL, &file_handler); - if (rc != MPI_SUCCESS) throw UbException(UB_EXARGS, "couldn't open file " + filename); - - MPI_File_read_at(file_handler, (MPI_Offset)0, &dataSetParamStr, 1, dataSetParamType, MPI_STATUS_IGNORE); - - size_t doubleCountInBlock = dataSetParamStr.nx[0] * dataSetParamStr.nx[1] * dataSetParamStr.nx[2] * dataSetParamStr.nx[3]; - std::vector<double> doubleValuesArray(myBlocksCount * doubleCountInBlock); // double-values in all blocks - - MPI_Type_contiguous(int(doubleCountInBlock), MPI_DOUBLE, &dataSetDoubleType); - MPI_Type_commit(&dataSetDoubleType); - - MPI_Offset read_offset = (MPI_Offset)(sizeof(dataSetParam)) + (MPI_Offset)(indexB) * (MPI_Offset)(doubleCountInBlock) * (MPI_Offset)(sizeof(double)); - MPI_File_read_at(file_handler, read_offset, &doubleValuesArray[0], int(myBlocksCount), dataSetDoubleType, MPI_STATUS_IGNORE); - - MPI_File_close(&file_handler); - MPI_Type_free(&dataSetDoubleType); - - if (comm->isRoot()) - { - finish = MPI_Wtime(); - UBLOG(logINFO, "MPIIOMigrationBECoProcessor::readArray time: " << finish - start << " s"); - UBLOG(logINFO, "MPIIOMigrationBECoProcessor::readArray start of exchange of data, rank = " << rank); - UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); - } - - std::vector<double>* rawDataReceive = new std::vector<double>[size]; - for (int r = 0; r < size; r++) - rawDataReceive[r].resize(0); - - blocksExchange(MESSAGE_TAG + int(arrType), indexB, indexE, int(doubleCountInBlock), doubleValuesArray, rawDataReceive); - - if (comm->isRoot()) - { - finish = MPI_Wtime(); - UBLOG(logINFO, "MPIIOMigrationBECoProcessor::readArray end of exchange of data, rank = " << rank); - UBLOG(logINFO, "MPIIOMigrationBECoProcessor::readArray time: " << finish - start << " s"); - UBLOG(logINFO, "MPIIOMigrationBECoProcessor::readArray start of restore of data, rank = " << rank); - UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); - } - - //----------------------------- restore data --------------------------------- - int blockID; - std::vector<double> vectorsOfValues; - size_t index; - size_t nextVectorSize = dataSetParamStr.nx[0] * dataSetParamStr.nx[1] * dataSetParamStr.nx[2] * dataSetParamStr.nx[3]; - - for (int r = 0; r < size; r++) - { - index = 0; - for (int ii = 0; ii < int(rawDataReceive[r].size() / doubleCountInBlock); ii++) - { - blockID = (int)(rawDataReceive[r][index]); - SPtr<Block3D> block = grid->getBlock(blockID); - index += 1; - - vectorsOfValues.assign(rawDataReceive[r].data() + index, rawDataReceive[r].data() + index + nextVectorSize); - index += nextVectorSize; - - // fill arrays - SPtr<CbArray4D<LBMReal, IndexerX4X3X2X1>> ___4DArray; - SPtr<CbArray3D<LBMReal, IndexerX3X2X1>> ___3DArray; - - switch (arrType) { - case AverageDensity: - ___4DArray = CbArray4D<LBMReal, IndexerX4X3X2X1>::CbArray4DPtr(new CbArray4D<LBMReal, IndexerX4X3X2X1>(vectorsOfValues, dataSetParamStr.nx[0], dataSetParamStr.nx[1], dataSetParamStr.nx[2], dataSetParamStr.nx[3])); - block->getKernel()->getDataSet()->setAverageDensity(___4DArray); - break; - case AverageVelocity: - ___4DArray = CbArray4D<LBMReal, IndexerX4X3X2X1>::CbArray4DPtr(new CbArray4D<LBMReal, IndexerX4X3X2X1>(vectorsOfValues, dataSetParamStr.nx[0], dataSetParamStr.nx[1], dataSetParamStr.nx[2], dataSetParamStr.nx[3])); - block->getKernel()->getDataSet()->setAverageVelocity(___4DArray); - break; - case AverageFluktuations: - ___4DArray = CbArray4D<LBMReal, IndexerX4X3X2X1>::CbArray4DPtr(new CbArray4D<LBMReal, IndexerX4X3X2X1>(vectorsOfValues, dataSetParamStr.nx[0], dataSetParamStr.nx[1], dataSetParamStr.nx[2], dataSetParamStr.nx[3])); - block->getKernel()->getDataSet()->setAverageFluctuations(___4DArray); - break; - case AverageTriple: - ___4DArray = CbArray4D<LBMReal, IndexerX4X3X2X1>::CbArray4DPtr(new CbArray4D<LBMReal, IndexerX4X3X2X1>(vectorsOfValues, dataSetParamStr.nx[0], dataSetParamStr.nx[1], dataSetParamStr.nx[2], dataSetParamStr.nx[3])); - block->getKernel()->getDataSet()->setAverageTriplecorrelations(___4DArray); - break; - case ShearStressVal: - ___4DArray = CbArray4D<LBMReal, IndexerX4X3X2X1>::CbArray4DPtr(new CbArray4D<LBMReal, IndexerX4X3X2X1>(vectorsOfValues, dataSetParamStr.nx[0], dataSetParamStr.nx[1], dataSetParamStr.nx[2], dataSetParamStr.nx[3])); - block->getKernel()->getDataSet()->setShearStressValues(___4DArray); - break; - case RelaxationFactor: - ___3DArray = CbArray3D<LBMReal, IndexerX3X2X1>::CbArray3DPtr(new CbArray3D<LBMReal, IndexerX3X2X1>(vectorsOfValues, dataSetParamStr.nx[0], dataSetParamStr.nx[1], dataSetParamStr.nx[2])); - block->getKernel()->getDataSet()->setRelaxationFactor(___3DArray); - break; - default: - UB_THROW(UbException(UB_EXARGS, "MPIIOMigrationBECoProcessor::readArray : array type does not exist!")); - break; - } - } - } - - delete [] rawDataReceive; - - if (comm->isRoot()) - { - UBLOG(logINFO, "MPIIOMigrationBECoProcessor::readArray end of restore of data, rank = " << rank); - UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); - } + int rank, size; + MPI_Comm_rank(MPI_COMM_WORLD, &rank); + MPI_Comm_size(MPI_COMM_WORLD, &size); + + if (comm->isRoot()) { + UBLOG(logINFO, "MPIIOMigrationBECoProcessor::readArray start MPI IO rank = " << rank); + UBLOG(logINFO, "Physical Memory currently used by current process: " + << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); + } + double start, finish; + if (comm->isRoot()) + start = MPI_Wtime(); + + dataSetParam dataSetParamStr; + memset(&dataSetParamStr, 0, sizeof(dataSetParam)); + + int blocksCountAll = grid->getNumberOfBlocks(); // quantity of all blocks in the grid + int blocksPerProcess = blocksCountAll / size; // how many blocks has each process + + size_t myBlocksCount; + if (rank < (size - 1)) + myBlocksCount = blocksPerProcess; + else + myBlocksCount = blocksPerProcess + (blocksCountAll - blocksPerProcess * size); + + int indexB = rank * blocksPerProcess; // the first "my" block + int indexE = indexB + int(myBlocksCount); // the latest "my" block + + MPI_File file_handler; + std::string filename = path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + fname; + int rc = MPI_File_open(MPI_COMM_WORLD, filename.c_str(), MPI_MODE_RDONLY, MPI_INFO_NULL, &file_handler); + if (rc != MPI_SUCCESS) + throw UbException(UB_EXARGS, "couldn't open file " + filename); + + MPI_File_read_at(file_handler, (MPI_Offset)0, &dataSetParamStr, 1, dataSetParamType, MPI_STATUS_IGNORE); + + size_t doubleCountInBlock = + dataSetParamStr.nx[0] * dataSetParamStr.nx[1] * dataSetParamStr.nx[2] * dataSetParamStr.nx[3]; + std::vector<double> doubleValuesArray(myBlocksCount * doubleCountInBlock); // double-values in all blocks + + MPI_Type_contiguous(int(doubleCountInBlock), MPI_DOUBLE, &dataSetDoubleType); + MPI_Type_commit(&dataSetDoubleType); + + MPI_Offset read_offset = (MPI_Offset)(sizeof(dataSetParam)) + + (MPI_Offset)(indexB) * (MPI_Offset)(doubleCountInBlock) * (MPI_Offset)(sizeof(double)); + MPI_File_read_at(file_handler, read_offset, &doubleValuesArray[0], int(myBlocksCount), dataSetDoubleType, + MPI_STATUS_IGNORE); + + MPI_File_close(&file_handler); + MPI_Type_free(&dataSetDoubleType); + + if (comm->isRoot()) { + finish = MPI_Wtime(); + UBLOG(logINFO, "MPIIOMigrationBECoProcessor::readArray time: " << finish - start << " s"); + UBLOG(logINFO, "MPIIOMigrationBECoProcessor::readArray start of exchange of data, rank = " << rank); + UBLOG(logINFO, "Physical Memory currently used by current process: " + << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); + } + + std::vector<double> *rawDataReceive = new std::vector<double>[size]; + for (int r = 0; r < size; r++) + rawDataReceive[r].resize(0); + + blocksExchange(MESSAGE_TAG + int(arrType), indexB, indexE, int(doubleCountInBlock), doubleValuesArray, + rawDataReceive); + + if (comm->isRoot()) { + finish = MPI_Wtime(); + UBLOG(logINFO, "MPIIOMigrationBECoProcessor::readArray end of exchange of data, rank = " << rank); + UBLOG(logINFO, "MPIIOMigrationBECoProcessor::readArray time: " << finish - start << " s"); + UBLOG(logINFO, "MPIIOMigrationBECoProcessor::readArray start of restore of data, rank = " << rank); + UBLOG(logINFO, "Physical Memory currently used by current process: " + << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); + } + + //----------------------------- restore data --------------------------------- + int blockID; + std::vector<double> vectorsOfValues; + size_t index; + size_t nextVectorSize = + dataSetParamStr.nx[0] * dataSetParamStr.nx[1] * dataSetParamStr.nx[2] * dataSetParamStr.nx[3]; + + for (int r = 0; r < size; r++) { + index = 0; + for (int ii = 0; ii < int(rawDataReceive[r].size() / doubleCountInBlock); ii++) { + blockID = (int)(rawDataReceive[r][index]); + SPtr<Block3D> block = grid->getBlock(blockID); + index += 1; + + vectorsOfValues.assign(rawDataReceive[r].data() + index, rawDataReceive[r].data() + index + nextVectorSize); + index += nextVectorSize; + + // fill arrays + SPtr<CbArray4D<LBMReal, IndexerX4X3X2X1>> ___4DArray; + SPtr<CbArray3D<LBMReal, IndexerX3X2X1>> ___3DArray; + + switch (arrType) { + case AverageDensity: + ___4DArray = + CbArray4D<LBMReal, IndexerX4X3X2X1>::CbArray4DPtr(new CbArray4D<LBMReal, IndexerX4X3X2X1>( + vectorsOfValues, dataSetParamStr.nx[0], dataSetParamStr.nx[1], dataSetParamStr.nx[2], + dataSetParamStr.nx[3])); + block->getKernel()->getDataSet()->setAverageDensity(___4DArray); + break; + case AverageVelocity: + ___4DArray = + CbArray4D<LBMReal, IndexerX4X3X2X1>::CbArray4DPtr(new CbArray4D<LBMReal, IndexerX4X3X2X1>( + vectorsOfValues, dataSetParamStr.nx[0], dataSetParamStr.nx[1], dataSetParamStr.nx[2], + dataSetParamStr.nx[3])); + block->getKernel()->getDataSet()->setAverageVelocity(___4DArray); + break; + case AverageFluktuations: + ___4DArray = + CbArray4D<LBMReal, IndexerX4X3X2X1>::CbArray4DPtr(new CbArray4D<LBMReal, IndexerX4X3X2X1>( + vectorsOfValues, dataSetParamStr.nx[0], dataSetParamStr.nx[1], dataSetParamStr.nx[2], + dataSetParamStr.nx[3])); + block->getKernel()->getDataSet()->setAverageFluctuations(___4DArray); + break; + case AverageTriple: + ___4DArray = + CbArray4D<LBMReal, IndexerX4X3X2X1>::CbArray4DPtr(new CbArray4D<LBMReal, IndexerX4X3X2X1>( + vectorsOfValues, dataSetParamStr.nx[0], dataSetParamStr.nx[1], dataSetParamStr.nx[2], + dataSetParamStr.nx[3])); + block->getKernel()->getDataSet()->setAverageTriplecorrelations(___4DArray); + break; + case ShearStressVal: + ___4DArray = + CbArray4D<LBMReal, IndexerX4X3X2X1>::CbArray4DPtr(new CbArray4D<LBMReal, IndexerX4X3X2X1>( + vectorsOfValues, dataSetParamStr.nx[0], dataSetParamStr.nx[1], dataSetParamStr.nx[2], + dataSetParamStr.nx[3])); + block->getKernel()->getDataSet()->setShearStressValues(___4DArray); + break; + case RelaxationFactor: + ___3DArray = CbArray3D<LBMReal, IndexerX3X2X1>::CbArray3DPtr(new CbArray3D<LBMReal, IndexerX3X2X1>( + vectorsOfValues, dataSetParamStr.nx[0], dataSetParamStr.nx[1], dataSetParamStr.nx[2])); + block->getKernel()->getDataSet()->setRelaxationFactor(___3DArray); + break; + default: + UB_THROW( + UbException(UB_EXARGS, "MPIIOMigrationBECoProcessor::readArray : array type does not exist!")); + break; + } + } + } + + delete[] rawDataReceive; + + if (comm->isRoot()) { + UBLOG(logINFO, "MPIIOMigrationBECoProcessor::readArray end of restore of data, rank = " << rank); + UBLOG(logINFO, "Physical Memory currently used by current process: " + << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); + } } void MPIIOMigrationBECoProcessor::readBoundaryConds(int step) { - int rank, size; - MPI_Comm_rank(MPI_COMM_WORLD, &rank); - MPI_Comm_size(MPI_COMM_WORLD, &size); - - if (comm->isRoot()) - { - UBLOG(logINFO, "MPIIOMigrationBECoProcessor::readBoundaryConds start MPI IO rank = " << rank); - UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); - } - - double start, finish; - if (comm->isRoot()) start = MPI_Wtime(); - - int blocksCountAll = grid->getNumberOfBlocks(); // quantity of all blocks in the grid - size_t myBlocksCount; - int blocksPerProcess = blocksCountAll / size; // how many blocks has each process - - if (rank < (size - 1)) - myBlocksCount = blocksPerProcess; - else - myBlocksCount = blocksPerProcess + (blocksCountAll - blocksPerProcess * size); - - int indexB = rank * blocksPerProcess; // the first "my" block - int indexE = indexB + int(myBlocksCount); // the latest "my" block - - std::vector<int> bcindexmatrixVAll; - - MPI_File file_handler; - std::string filename = path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + "/cpBC1.bin"; - int rc = MPI_File_open(MPI_COMM_WORLD, filename.c_str(), MPI_MODE_RDONLY, MPI_INFO_NULL, &file_handler); - if (rc != MPI_SUCCESS) throw UbException(UB_EXARGS, "couldn't open file " + filename); - - int sizeOfBIM; - MPI_File_read_at(file_handler, (MPI_Offset)0, &sizeOfBIM, 1, MPI_INT, MPI_STATUS_IGNORE); - bcindexmatrixVAll.resize(myBlocksCount * sizeOfBIM); - - MPI_Type_contiguous(sizeOfBIM, MPI_INT, &bcindexmatrixType); - MPI_Type_commit(&bcindexmatrixType); - - MPI_Offset read_offset = (MPI_Offset)(sizeof(int)) + (MPI_Offset)(indexB) * (MPI_Offset)(sizeOfBIM) * (MPI_Offset)(sizeof(int)); - MPI_File_read_at(file_handler, read_offset, &bcindexmatrixVAll[0], int(myBlocksCount), bcindexmatrixType, MPI_STATUS_IGNORE); - - MPI_File_close(&file_handler); - MPI_Type_free(&bcindexmatrixType); - - if (comm->isRoot()) - { - finish = MPI_Wtime(); - UBLOG(logINFO, "MPIIOMigrationBECoProcessor::readBoundaryConds time: " << finish - start << " s"); - UBLOG(logINFO, "MPIIOMigrationBECoProcessor::readBoundaryConds start of exchange of data, rank = " << rank); - UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); - } - - std::vector<int>* rawDataReceive = new std::vector<int>[size]; - std::vector<int>* rawDataSend = new std::vector<int>[size]; - for (int r = 0; r < size; r++) - { - rawDataReceive[r].resize(0); - rawDataSend[r].resize(0); - rawDataReceive[r].push_back(0); - rawDataSend[r].push_back(0); - } - - SPtr<Block3D> tempBlock; - int tempRank; - for (int ind = indexB - indexB; ind < indexE - indexB; ind++) // FIXME: both sides of operator are equivalent - { - tempBlock = grid->getBlock(indexB + ind); - tempRank = tempBlock->getRank(); - - if (tempRank == rank) // no need to send data, the process already has it - { - rawDataReceive[tempRank][0]++; - rawDataReceive[tempRank].push_back(indexB + ind); - rawDataReceive[tempRank].insert(rawDataReceive[tempRank].end(), bcindexmatrixVAll.begin() + ind * sizeOfBIM, - bcindexmatrixVAll.begin() + ind * sizeOfBIM + sizeOfBIM); - } - else // we must send data to other processes - { - rawDataSend[tempRank][0]++; - rawDataSend[tempRank].push_back(indexB + ind); - rawDataSend[tempRank].insert(rawDataSend[tempRank].end(), bcindexmatrixVAll.begin() + ind * sizeOfBIM, - bcindexmatrixVAll.begin() + ind * sizeOfBIM + sizeOfBIM); - } - } - - MPI_Request* requests = new MPI_Request[size * 2]; // send + receive - int requestCount = 0; - MPI_Status status; - int quant; - int intBlockCount; - int rds; - - for (int r = 0; r < size; r++) - { - if (r != rank) - { - rds = int(rawDataSend[r].size()); - intBlockCount = (int)(rds / SEND_BLOCK_SIZE); - if (intBlockCount * SEND_BLOCK_SIZE < rds) - intBlockCount += 1; - - for (int i = rds; i < intBlockCount * SEND_BLOCK_SIZE; i++) - rawDataSend[r].push_back(0); - - MPI_Isend(&rawDataSend[r][0], intBlockCount, sendBlockIntType, r, MESSAGE_TAG + 7, MPI_COMM_WORLD, &requests[requestCount]); - //MPI_Isend(&rawDataSend[r][0], rawDataSend[r].size(), MPI_INT, r, MESSAGE_TAG + 7, MPI_COMM_WORLD, &requests[requestCount]); - requestCount++; - } - } - - for (int r = 0; r < size; r++) - { - if (r != rank) - { - MPI_Probe(r, MESSAGE_TAG + 7, MPI_COMM_WORLD, &status); - MPI_Get_count(&status, sendBlockIntType, &quant); - rawDataReceive[r].resize(quant * SEND_BLOCK_SIZE); - MPI_Irecv(&rawDataReceive[r][0], quant, sendBlockIntType, r, MESSAGE_TAG + 7, MPI_COMM_WORLD, &requests[requestCount]); - requestCount++; - } - } - - MPI_Waitall(requestCount, &requests[0], MPI_STATUSES_IGNORE); - -//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - if (comm->isRoot()) - { - finish = MPI_Wtime(); - UBLOG(logINFO, "MPIIOMigrationBECoProcessor::readBoundaryConds end of exchange of data, rank = " << rank); - UBLOG(logINFO, "MPIIOMigrationBECoProcessor::readBoundaryConds time: " << finish - start << " s"); - UBLOG(logINFO, "MPIIOMigrationBECoProcessor::readBoundaryConds start of restore of data, rank = " << rank); - UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); - } - - filename = path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + "/cpBC2.bin"; - rc = MPI_File_open(MPI_COMM_WORLD, filename.c_str(), MPI_MODE_RDONLY, MPI_INFO_NULL, &file_handler); - if (rc != MPI_SUCCESS) throw UbException(UB_EXARGS, "couldn't open file " + filename); - - MPI_File_read_at(file_handler, (MPI_Offset)0, &boundCondParamStr, 4, MPI_INT, MPI_STATUS_IGNORE); - - int blockID; - size_t index; - MPI_Offset read_offset1, read_offset2; - - BCAddMigration bcAddArray; - BoundaryCondition* nullBouCond = new BoundaryCondition(); - memset(nullBouCond, 0, sizeof(BoundaryCondition)); - BoundaryCondition* bcArray; - std::vector<SPtr<BoundaryConditions>> bcVector; - std::vector<int> indexContainerV; - std::vector<int> bcindexmatrixV; - - for (int r = 0; r < size; r++) - { - index = 1; - - for (int ii = 0; ii < rawDataReceive[r][0]; ii++) - { - blockID = (int)(rawDataReceive[r][index]); - index += 1; - - bcindexmatrixV.assign(rawDataReceive[r].data() + index, rawDataReceive[r].data() + index + sizeOfBIM); - index += sizeOfBIM; - - read_offset1 = (MPI_Offset)(sizeof(boundCondParam)) + (MPI_Offset)(blockID) * (MPI_Offset)(sizeof(size_t)); - - MPI_File_read_at(file_handler, read_offset1, &read_offset2, 1, MPI_LONG_LONG_INT, MPI_STATUS_IGNORE); - MPI_File_read_at(file_handler, read_offset2, &bcAddArray, 3, MPI_INT, MPI_STATUS_IGNORE); - - bcArray = new BoundaryCondition[bcAddArray.boundCond_count]; - indexContainerV.resize(bcAddArray.indexContainer_count); - - if (bcAddArray.boundCond_count > 0) - MPI_File_read_at(file_handler, read_offset2 + (MPI_Offset)(sizeof(BCAddMigration)), &bcArray[0], bcAddArray.boundCond_count, boundCondType, MPI_STATUS_IGNORE); - - if (bcAddArray.indexContainer_count > 0) - MPI_File_read_at(file_handler, read_offset2 + (MPI_Offset)(sizeof(BCAddMigration)) + (MPI_Offset)(bcAddArray.boundCond_count) * (MPI_Offset)(sizeof(BoundaryCondition)), - &indexContainerV[0], bcAddArray.indexContainer_count, MPI_INT, MPI_STATUS_IGNORE); - - bcVector.resize(0); - - for (size_t ibc = 0; ibc<bcAddArray.boundCond_count; ibc++) - { - SPtr<BoundaryConditions> bc; - if (memcmp(&bcArray[ibc], nullBouCond, sizeof(BoundaryCondition)) == 0) - bc = SPtr<BoundaryConditions>(); - else - { - bc = SPtr<BoundaryConditions>(new BoundaryConditions); - bc->noslipBoundaryFlags = bcArray[ibc].noslipBoundaryFlags; - bc->slipBoundaryFlags = bcArray[ibc].slipBoundaryFlags; - bc->densityBoundaryFlags = bcArray[ibc].densityBoundaryFlags; - bc->velocityBoundaryFlags = bcArray[ibc].velocityBoundaryFlags; - bc->wallModelBoundaryFlags = bcArray[ibc].wallModelBoundaryFlags; - bc->bcVelocityX1 = bcArray[ibc].bcVelocityX1; - bc->bcVelocityX2 = bcArray[ibc].bcVelocityX2; - bc->bcVelocityX3 = bcArray[ibc].bcVelocityX3; - bc->bcDensity = bcArray[ibc].bcDensity; - bc->bcLodiDensity = bcArray[ibc].bcLodiDensity; - bc->bcLodiVelocityX1 = bcArray[ibc].bcLodiVelocityX1; - bc->bcLodiVelocityX2 = bcArray[ibc].bcLodiVelocityX2; - bc->bcLodiVelocityX3 = bcArray[ibc].bcLodiVelocityX3; - bc->bcLodiLentgh = bcArray[ibc].bcLodiLentgh; - - bc->nx1 = bcArray[ibc].nx1; - bc->nx2 = bcArray[ibc].nx2; - bc->nx3 = bcArray[ibc].nx3; - for (int iq = 0; iq<26; iq++) - bc->setQ(bcArray[ibc].q[iq], iq); - bc->setBcAlgorithmType(bcArray[ibc].algorithmType); + int rank, size; + MPI_Comm_rank(MPI_COMM_WORLD, &rank); + MPI_Comm_size(MPI_COMM_WORLD, &size); + + if (comm->isRoot()) { + UBLOG(logINFO, "MPIIOMigrationBECoProcessor::readBoundaryConds start MPI IO rank = " << rank); + UBLOG(logINFO, "Physical Memory currently used by current process: " + << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); + } + + double start, finish; + if (comm->isRoot()) + start = MPI_Wtime(); + + int blocksCountAll = grid->getNumberOfBlocks(); // quantity of all blocks in the grid + size_t myBlocksCount; + int blocksPerProcess = blocksCountAll / size; // how many blocks has each process + + if (rank < (size - 1)) + myBlocksCount = blocksPerProcess; + else + myBlocksCount = blocksPerProcess + (blocksCountAll - blocksPerProcess * size); + + int indexB = rank * blocksPerProcess; // the first "my" block + int indexE = indexB + int(myBlocksCount); // the latest "my" block + + std::vector<int> bcindexmatrixVAll; + + MPI_File file_handler; + std::string filename = path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + "/cpBC1.bin"; + int rc = MPI_File_open(MPI_COMM_WORLD, filename.c_str(), MPI_MODE_RDONLY, MPI_INFO_NULL, &file_handler); + if (rc != MPI_SUCCESS) + throw UbException(UB_EXARGS, "couldn't open file " + filename); + + int sizeOfBIM; + MPI_File_read_at(file_handler, (MPI_Offset)0, &sizeOfBIM, 1, MPI_INT, MPI_STATUS_IGNORE); + bcindexmatrixVAll.resize(myBlocksCount * sizeOfBIM); + + MPI_Type_contiguous(sizeOfBIM, MPI_INT, &bcindexmatrixType); + MPI_Type_commit(&bcindexmatrixType); + + MPI_Offset read_offset = + (MPI_Offset)(sizeof(int)) + (MPI_Offset)(indexB) * (MPI_Offset)(sizeOfBIM) * (MPI_Offset)(sizeof(int)); + MPI_File_read_at(file_handler, read_offset, &bcindexmatrixVAll[0], int(myBlocksCount), bcindexmatrixType, + MPI_STATUS_IGNORE); + + MPI_File_close(&file_handler); + MPI_Type_free(&bcindexmatrixType); + + if (comm->isRoot()) { + finish = MPI_Wtime(); + UBLOG(logINFO, "MPIIOMigrationBECoProcessor::readBoundaryConds time: " << finish - start << " s"); + UBLOG(logINFO, "MPIIOMigrationBECoProcessor::readBoundaryConds start of exchange of data, rank = " << rank); + UBLOG(logINFO, "Physical Memory currently used by current process: " + << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); + } + + std::vector<int> *rawDataReceive = new std::vector<int>[size]; + std::vector<int> *rawDataSend = new std::vector<int>[size]; + for (int r = 0; r < size; r++) { + rawDataReceive[r].resize(0); + rawDataSend[r].resize(0); + rawDataReceive[r].push_back(0); + rawDataSend[r].push_back(0); + } + + SPtr<Block3D> tempBlock; + int tempRank; + for (int ind = indexB - indexB; ind < indexE - indexB; ind++) // FIXME: both sides of operator are equivalent + { + tempBlock = grid->getBlock(indexB + ind); + tempRank = tempBlock->getRank(); + + if (tempRank == rank) // no need to send data, the process already has it + { + rawDataReceive[tempRank][0]++; + rawDataReceive[tempRank].push_back(indexB + ind); + rawDataReceive[tempRank].insert(rawDataReceive[tempRank].end(), bcindexmatrixVAll.begin() + ind * sizeOfBIM, + bcindexmatrixVAll.begin() + ind * sizeOfBIM + sizeOfBIM); + } else // we must send data to other processes + { + rawDataSend[tempRank][0]++; + rawDataSend[tempRank].push_back(indexB + ind); + rawDataSend[tempRank].insert(rawDataSend[tempRank].end(), bcindexmatrixVAll.begin() + ind * sizeOfBIM, + bcindexmatrixVAll.begin() + ind * sizeOfBIM + sizeOfBIM); + } + } + + MPI_Request *requests = new MPI_Request[size * 2]; // send + receive + int requestCount = 0; + MPI_Status status; + int quant; + int intBlockCount; + int rds; + + for (int r = 0; r < size; r++) { + if (r != rank) { + rds = int(rawDataSend[r].size()); + intBlockCount = (int)(rds / SEND_BLOCK_SIZE); + if (intBlockCount * SEND_BLOCK_SIZE < rds) + intBlockCount += 1; + + for (int i = rds; i < intBlockCount * SEND_BLOCK_SIZE; i++) + rawDataSend[r].push_back(0); + + MPI_Isend(&rawDataSend[r][0], intBlockCount, sendBlockIntType, r, MESSAGE_TAG + 7, MPI_COMM_WORLD, + &requests[requestCount]); + // MPI_Isend(&rawDataSend[r][0], rawDataSend[r].size(), MPI_INT, r, MESSAGE_TAG + 7, MPI_COMM_WORLD, + // &requests[requestCount]); + requestCount++; + } + } + + for (int r = 0; r < size; r++) { + if (r != rank) { + MPI_Probe(r, MESSAGE_TAG + 7, MPI_COMM_WORLD, &status); + MPI_Get_count(&status, sendBlockIntType, &quant); + rawDataReceive[r].resize(quant * SEND_BLOCK_SIZE); + MPI_Irecv(&rawDataReceive[r][0], quant, sendBlockIntType, r, MESSAGE_TAG + 7, MPI_COMM_WORLD, + &requests[requestCount]); + requestCount++; + } + } + + MPI_Waitall(requestCount, &requests[0], MPI_STATUSES_IGNORE); + + //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + if (comm->isRoot()) { + finish = MPI_Wtime(); + UBLOG(logINFO, "MPIIOMigrationBECoProcessor::readBoundaryConds end of exchange of data, rank = " << rank); + UBLOG(logINFO, "MPIIOMigrationBECoProcessor::readBoundaryConds time: " << finish - start << " s"); + UBLOG(logINFO, "MPIIOMigrationBECoProcessor::readBoundaryConds start of restore of data, rank = " << rank); + UBLOG(logINFO, "Physical Memory currently used by current process: " + << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); + } + + filename = path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + "/cpBC2.bin"; + rc = MPI_File_open(MPI_COMM_WORLD, filename.c_str(), MPI_MODE_RDONLY, MPI_INFO_NULL, &file_handler); + if (rc != MPI_SUCCESS) + throw UbException(UB_EXARGS, "couldn't open file " + filename); + + MPI_File_read_at(file_handler, (MPI_Offset)0, &boundCondParamStr, 4, MPI_INT, MPI_STATUS_IGNORE); + + int blockID; + size_t index; + MPI_Offset read_offset1, read_offset2; + + BCAddMigration bcAddArray; + BoundaryCondition *nullBouCond = new BoundaryCondition(); + memset(nullBouCond, 0, sizeof(BoundaryCondition)); + BoundaryCondition *bcArray; + std::vector<SPtr<BoundaryConditions>> bcVector; + std::vector<int> indexContainerV; + std::vector<int> bcindexmatrixV; + + for (int r = 0; r < size; r++) { + index = 1; + + for (int ii = 0; ii < rawDataReceive[r][0]; ii++) { + blockID = (int)(rawDataReceive[r][index]); + index += 1; + + bcindexmatrixV.assign(rawDataReceive[r].data() + index, rawDataReceive[r].data() + index + sizeOfBIM); + index += sizeOfBIM; + + read_offset1 = (MPI_Offset)(sizeof(boundCondParam)) + (MPI_Offset)(blockID) * (MPI_Offset)(sizeof(size_t)); + + MPI_File_read_at(file_handler, read_offset1, &read_offset2, 1, MPI_LONG_LONG_INT, MPI_STATUS_IGNORE); + MPI_File_read_at(file_handler, read_offset2, &bcAddArray, 3, MPI_INT, MPI_STATUS_IGNORE); + + bcArray = new BoundaryCondition[bcAddArray.boundCond_count]; + indexContainerV.resize(bcAddArray.indexContainer_count); + + if (bcAddArray.boundCond_count > 0) + MPI_File_read_at(file_handler, read_offset2 + (MPI_Offset)(sizeof(BCAddMigration)), &bcArray[0], + bcAddArray.boundCond_count, boundCondType, MPI_STATUS_IGNORE); + + if (bcAddArray.indexContainer_count > 0) + MPI_File_read_at(file_handler, + read_offset2 + (MPI_Offset)(sizeof(BCAddMigration)) + + (MPI_Offset)(bcAddArray.boundCond_count) * (MPI_Offset)(sizeof(BoundaryCondition)), + &indexContainerV[0], bcAddArray.indexContainer_count, MPI_INT, MPI_STATUS_IGNORE); + + bcVector.resize(0); + + for (size_t ibc = 0; ibc < bcAddArray.boundCond_count; ibc++) { + SPtr<BoundaryConditions> bc; + if (memcmp(&bcArray[ibc], nullBouCond, sizeof(BoundaryCondition)) == 0) + bc = SPtr<BoundaryConditions>(); + else { + bc = SPtr<BoundaryConditions>(new BoundaryConditions); + bc->noslipBoundaryFlags = bcArray[ibc].noslipBoundaryFlags; + bc->slipBoundaryFlags = bcArray[ibc].slipBoundaryFlags; + bc->densityBoundaryFlags = bcArray[ibc].densityBoundaryFlags; + bc->velocityBoundaryFlags = bcArray[ibc].velocityBoundaryFlags; + bc->wallModelBoundaryFlags = bcArray[ibc].wallModelBoundaryFlags; + bc->bcVelocityX1 = bcArray[ibc].bcVelocityX1; + bc->bcVelocityX2 = bcArray[ibc].bcVelocityX2; + bc->bcVelocityX3 = bcArray[ibc].bcVelocityX3; + bc->bcDensity = bcArray[ibc].bcDensity; + bc->bcLodiDensity = bcArray[ibc].bcLodiDensity; + bc->bcLodiVelocityX1 = bcArray[ibc].bcLodiVelocityX1; + bc->bcLodiVelocityX2 = bcArray[ibc].bcLodiVelocityX2; + bc->bcLodiVelocityX3 = bcArray[ibc].bcLodiVelocityX3; + bc->bcLodiLentgh = bcArray[ibc].bcLodiLentgh; + + bc->nx1 = bcArray[ibc].nx1; + bc->nx2 = bcArray[ibc].nx2; + bc->nx3 = bcArray[ibc].nx3; + for (int iq = 0; iq < 26; iq++) + bc->setQ(bcArray[ibc].q[iq], iq); + bc->setBcAlgorithmType(bcArray[ibc].algorithmType); + } + + bcVector.push_back(bc); } - bcVector.push_back(bc); - } - - CbArray3D<int, IndexerX3X2X1> bcim(bcindexmatrixV, boundCondParamStr.nx1, boundCondParamStr.nx2, boundCondParamStr.nx3); - SPtr<Block3D> block1 = grid->getBlock(blockID); - - SPtr<BCProcessor> bcProc = bcProcessor->clone(block1->getKernel()); - SPtr<BCArray3D> bcArr(new BCArray3D()); - bcArr->bcindexmatrix = bcim; - bcArr->bcvector = bcVector; - bcArr->indexContainer = indexContainerV; - bcProc->setBCArray(bcArr); - - block1->getKernel()->setBCProcessor(bcProc); - } - } - -//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - MPI_File_close(&file_handler); - - delete nullBouCond; - if(bcArray) - delete bcArray; - delete [] rawDataReceive; - delete [] rawDataSend; - delete [] requests; - - if (comm->isRoot()) - { - finish = MPI_Wtime(); - UBLOG(logINFO, "MPIIOMigrationBECoProcessor::readBoundaryConds end of restore of data, rank = " << rank); - UBLOG(logINFO, "MPIIOMigrationBECoProcessor::readBoundaryConds time: " << finish - start << " s"); - UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); - } + CbArray3D<int, IndexerX3X2X1> bcim(bcindexmatrixV, boundCondParamStr.nx1, boundCondParamStr.nx2, + boundCondParamStr.nx3); + SPtr<Block3D> block1 = grid->getBlock(blockID); + + SPtr<BCProcessor> bcProc = bcProcessor->clone(block1->getKernel()); + SPtr<BCArray3D> bcArr(new BCArray3D()); + bcArr->bcindexmatrix = bcim; + bcArr->bcvector = bcVector; + bcArr->indexContainer = indexContainerV; + bcProc->setBCArray(bcArr); + + block1->getKernel()->setBCProcessor(bcProc); + } + } + + //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + MPI_File_close(&file_handler); + + delete nullBouCond; + if (bcArray) + delete bcArray; + delete[] rawDataReceive; + delete[] rawDataSend; + delete[] requests; + + if (comm->isRoot()) { + finish = MPI_Wtime(); + UBLOG(logINFO, "MPIIOMigrationBECoProcessor::readBoundaryConds end of restore of data, rank = " << rank); + UBLOG(logINFO, "MPIIOMigrationBECoProcessor::readBoundaryConds time: " << finish - start << " s"); + UBLOG(logINFO, "Physical Memory currently used by current process: " + << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); + } } ////////////////////////////////////////////////////////////////////////// -void MPIIOMigrationBECoProcessor::setLBMKernel(SPtr<LBMKernel> kernel) -{ - this->lbmKernel = kernel; -} +void MPIIOMigrationBECoProcessor::setLBMKernel(SPtr<LBMKernel> kernel) { this->lbmKernel = kernel; } ////////////////////////////////////////////////////////////////////////// -void MPIIOMigrationBECoProcessor::setBCProcessor(SPtr<BCProcessor> bcProcessor) -{ - this->bcProcessor = bcProcessor; -} +void MPIIOMigrationBECoProcessor::setBCProcessor(SPtr<BCProcessor> bcProcessor) { this->bcProcessor = bcProcessor; } ////////////////////////////////////////////////////////////////////////// -void MPIIOMigrationBECoProcessor::setNu(double nu) -{ - this->nue = nu; -} - +void MPIIOMigrationBECoProcessor::setNu(double nu) { this->nue = nu; } diff --git a/src/cpu/VirtualFluidsCore/CoProcessors/MPIIOMigrationBECoProcessor.h b/src/cpu/VirtualFluidsCore/CoProcessors/MPIIOMigrationBECoProcessor.h index 90ad1a928de9cf75f0845380944cb3898031d94c..5eb83b27aa49960501f5fd302a450f2b21f937d8 100644 --- a/src/cpu/VirtualFluidsCore/CoProcessors/MPIIOMigrationBECoProcessor.h +++ b/src/cpu/VirtualFluidsCore/CoProcessors/MPIIOMigrationBECoProcessor.h @@ -14,75 +14,82 @@ class Communicator; class BCProcessor; class LBMKernel; -//! \class MPIWriteBlocksBECoProcessor -//! \brief Writes the grid each timestep into the files and reads the grip from the files before regenerating +//! \class MPIWriteBlocksBECoProcessor +//! \brief Writes the grid each timestep into the files and reads the grip from the files before regenerating class MPIIOMigrationBECoProcessor : public MPIIOCoProcessor { - enum Arrays { AverageDensity = 1, AverageVelocity = 2, AverageFluktuations = 3, AverageTriple = 4, ShearStressVal = 5, RelaxationFactor = 6}; + enum Arrays { + AverageDensity = 1, + AverageVelocity = 2, + AverageFluktuations = 3, + AverageTriple = 4, + ShearStressVal = 5, + RelaxationFactor = 6 + }; public: + MPIIOMigrationBECoProcessor(SPtr<Grid3D> grid, SPtr<UbScheduler> s, const std::string &path, + SPtr<Communicator> comm); + ~MPIIOMigrationBECoProcessor() override; + //! Each timestep writes the grid into the files + void process(double step) override; + //! Reads the grid from the files before grid reconstruction + void restart(int step); + //! Writes the blocks of the grid into the file cpBlocks.bin + void writeBlocks(int step); + //! Writes the datasets of the blocks into the file cpDataSet.bin + void writeDataSet(int step); + void write4DArray(int step, Arrays arrType, std::string fname); + void write3DArray(int step, Arrays arrType, std::string fname); + // void writeAverageDensityArray(int step); + // void writeAverageVelocityArray(int step); + // void writeAverageFluktuationsArray(int step); + // void writeAverageTripleArray(int step); + // void writeShearStressValArray(int step); + // void writeRelaxationFactor(int step); + //! Writes the boundary conditions of the blocks into the file cpBC.bin + void writeBoundaryConds(int step); - MPIIOMigrationBECoProcessor(SPtr<Grid3D> grid, SPtr<UbScheduler> s, const std::string& path, SPtr<Communicator> comm); - ~MPIIOMigrationBECoProcessor() override; - //! Each timestep writes the grid into the files - void process(double step) override; - //! Reads the grid from the files before grid reconstruction - void restart(int step); - //! Writes the blocks of the grid into the file cpBlocks.bin - void writeBlocks(int step); - //! Writes the datasets of the blocks into the file cpDataSet.bin - void writeDataSet(int step); - void write4DArray(int step, Arrays arrType, std::string fname); - void write3DArray(int step, Arrays arrType, std::string fname); - // void writeAverageDensityArray(int step); - //void writeAverageVelocityArray(int step); - //void writeAverageFluktuationsArray(int step); - //void writeAverageTripleArray(int step); - //void writeShearStressValArray(int step); - //void writeRelaxationFactor(int step); - //! Writes the boundary conditions of the blocks into the file cpBC.bin - void writeBoundaryConds(int step); + //! Reads the blocks of the grid from the file cpBlocks.bin + void readBlocks(int step); + //! Reads the datasets of the blocks from the file cpDataSet.bin + void readDataSet(int step); + void readArray(int step, Arrays arrType, std::string fname); + // void readAverageDensityArray(int step); + // void readAverageVelocityArray(int step); + // void readAverageFluktuationsArray(int step); + // void readAverageTripleArray(int step); + // void readShearStressValArray(int step); + // void readRelaxationFactor(int step); + //! Reads the boundary conditions of the blocks from the file cpBC.bin + void readBoundaryConds(int step); + //! The function sets LBMKernel + void setLBMKernel(SPtr<LBMKernel> kernel); + //! The function sets BCProcessor + void setBCProcessor(SPtr<BCProcessor> bcProcessor); + //! The function truncates the data files + void clearAllFiles(int step); + void setNu(double nu); - //! Reads the blocks of the grid from the file cpBlocks.bin - void readBlocks(int step); - //! Reads the datasets of the blocks from the file cpDataSet.bin - void readDataSet(int step); - void readArray(int step, Arrays arrType, std::string fname); -// void readAverageDensityArray(int step); -// void readAverageVelocityArray(int step); -// void readAverageFluktuationsArray(int step); -// void readAverageTripleArray(int step); -// void readShearStressValArray(int step); -// void readRelaxationFactor(int step); - //! Reads the boundary conditions of the blocks from the file cpBC.bin - void readBoundaryConds(int step); - //! The function sets LBMKernel - void setLBMKernel(SPtr<LBMKernel> kernel); - //!The function sets BCProcessor - void setBCProcessor(SPtr<BCProcessor> bcProcessor); - //!The function truncates the data files - void clearAllFiles(int step); - void setNu(double nu); - - void blocksExchange(int tagN, int ind1, int ind2, int doubleCountInBlock, std::vector<double>& pV, std::vector<double>* rawDataReceive); + void blocksExchange(int tagN, int ind1, int ind2, int doubleCountInBlock, std::vector<double> &pV, + std::vector<double> *rawDataReceive); protected: - //std::string path; - //SPtr<Communicator> comm; + // std::string path; + // SPtr<Communicator> comm; private: - //MPI_Datatype gridParamType, block3dType; -// MPI_Datatype dataSetType, dataSetSmallType; - MPI_Datatype dataSetDoubleType; -// MPI_Datatype boundCondParamType, boundCondTypeAdd; - MPI_Datatype bcindexmatrixType; - MPI_Datatype sendBlockDoubleType, sendBlockIntType; - - MPIIODataStructures::boundCondParam boundCondParamStr; - SPtr<LBMKernel> lbmKernel; - SPtr<BCProcessor> bcProcessor; - double nue; + // MPI_Datatype gridParamType, block3dType; + // MPI_Datatype dataSetType, dataSetSmallType; + MPI_Datatype dataSetDoubleType; + // MPI_Datatype boundCondParamType, boundCondTypeAdd; + MPI_Datatype bcindexmatrixType; + MPI_Datatype sendBlockDoubleType, sendBlockIntType; + MPIIODataStructures::boundCondParam boundCondParamStr; + SPtr<LBMKernel> lbmKernel; + SPtr<BCProcessor> bcProcessor; + double nue; }; -#endif +#endif diff --git a/src/cpu/VirtualFluidsCore/CoProcessors/MPIIOMigrationCoProcessor.cpp b/src/cpu/VirtualFluidsCore/CoProcessors/MPIIOMigrationCoProcessor.cpp index e989bbf62cf01f5136613e3f218b12e90cd9cc75..94c33e5ba8109e2463da835b6bdcdd4c447c192b 100644 --- a/src/cpu/VirtualFluidsCore/CoProcessors/MPIIOMigrationCoProcessor.cpp +++ b/src/cpu/VirtualFluidsCore/CoProcessors/MPIIOMigrationCoProcessor.cpp @@ -1,336 +1,607 @@ #include "MPIIOMigrationCoProcessor.h" -#include "D3Q27System.h" -#include "LBMKernel.h" -#include "D3Q27EsoTwist3DSplittedVector.h" -#include <UbSystem.h> -#include <MemoryUtil.h> -#include "BoundaryConditions.h" +#include "BCArray3D.h" +#include "BCProcessor.h" #include "Block3D.h" +#include "BoundaryConditions.h" +#include "Communicator.h" #include "CoordinateTransformation3D.h" +#include "D3Q27EsoTwist3DSplittedVector.h" +#include "D3Q27System.h" #include "DataSet3D.h" #include "Grid3D.h" -#include "BCArray3D.h" -#include "Communicator.h" -#include "WbWriter.h" -#include "UbScheduler.h" #include "LBMKernel.h" -#include "BCProcessor.h" -#include "RenumberBlockVisitor.h" #include "MetisPartitioningGridVisitor.h" #include "PointerDefinitions.h" -#include "UbFileOutputASCII.h" +#include "RenumberBlockVisitor.h" #include "UbFileInputASCII.h" +#include "UbFileOutputASCII.h" +#include "UbScheduler.h" +#include "WbWriter.h" +#include <MemoryUtil.h> +#include <UbSystem.h> using namespace MPIIODataStructures; -MPIIOMigrationCoProcessor::MPIIOMigrationCoProcessor(SPtr<Grid3D> grid, SPtr<UbScheduler> s, const std::string& path, SPtr<Communicator> comm) : MPIIOCoProcessor(grid, s, path, comm) +MPIIOMigrationCoProcessor::MPIIOMigrationCoProcessor(SPtr<Grid3D> grid, SPtr<UbScheduler> s, const std::string &path, + SPtr<Communicator> comm) + : MPIIOCoProcessor(grid, s, path, comm) { - memset(&boundCondParamStr, 0, sizeof(boundCondParamStr)); - - //------------------------- define MPI types --------------------------------- + memset(&boundCondParamStr, 0, sizeof(boundCondParamStr)); - MPI_Datatype typesDataSet[3] = { MPI_DOUBLE, MPI_INT, MPI_CHAR }; - int blocksDataSet[3] = { 2, 2, 2 }; - MPI_Aint offsetsDatatSet[3], lbDataSet, extentDataSet; + //------------------------- define MPI types --------------------------------- - offsetsDatatSet[0] = 0; - MPI_Type_get_extent(MPI_DOUBLE, &lbDataSet, &extentDataSet); - offsetsDatatSet[1] = blocksDataSet[0] * extentDataSet; + MPI_Datatype typesDataSet[3] = { MPI_DOUBLE, MPI_INT, MPI_CHAR }; + int blocksDataSet[3] = { 2, 2, 2 }; + MPI_Aint offsetsDatatSet[3], lbDataSet, extentDataSet; - MPI_Type_get_extent(MPI_INT, &lbDataSet, &extentDataSet); - offsetsDatatSet[2] = offsetsDatatSet[1] + blocksDataSet[1] * extentDataSet; + offsetsDatatSet[0] = 0; + MPI_Type_get_extent(MPI_DOUBLE, &lbDataSet, &extentDataSet); + offsetsDatatSet[1] = blocksDataSet[0] * extentDataSet; - MPI_Type_create_struct(3, blocksDataSet, offsetsDatatSet, typesDataSet, &dataSetType); - MPI_Type_commit(&dataSetType); + MPI_Type_get_extent(MPI_INT, &lbDataSet, &extentDataSet); + offsetsDatatSet[2] = offsetsDatatSet[1] + blocksDataSet[1] * extentDataSet; - //----------------------------------------------------------------------- + MPI_Type_create_struct(3, blocksDataSet, offsetsDatatSet, typesDataSet, &dataSetType); + MPI_Type_commit(&dataSetType); - MPI_Type_contiguous(1, MPI_INT, &dataSetSmallType); - MPI_Type_commit(&dataSetSmallType); + //----------------------------------------------------------------------- - //----------------------------------------------------------------------- + MPI_Type_contiguous(1, MPI_INT, &dataSetSmallType); + MPI_Type_commit(&dataSetSmallType); - MPI_Type_contiguous(4, MPI_INT, &boundCondParamType); - MPI_Type_commit(&boundCondParamType); + //----------------------------------------------------------------------- - //--------------------------------------- + MPI_Type_contiguous(4, MPI_INT, &boundCondParamType); + MPI_Type_commit(&boundCondParamType); - MPI_Type_contiguous(3, MPI_INT, &boundCondTypeAdd); - MPI_Type_commit(&boundCondTypeAdd); + //--------------------------------------- + MPI_Type_contiguous(3, MPI_INT, &boundCondTypeAdd); + MPI_Type_commit(&boundCondTypeAdd); } ////////////////////////////////////////////////////////////////////////// MPIIOMigrationCoProcessor::~MPIIOMigrationCoProcessor() { - MPI_Type_free(&dataSetType); - MPI_Type_free(&dataSetSmallType); - MPI_Type_free(&boundCondParamType); - MPI_Type_free(&boundCondTypeAdd); + MPI_Type_free(&dataSetType); + MPI_Type_free(&dataSetSmallType); + MPI_Type_free(&boundCondParamType); + MPI_Type_free(&boundCondTypeAdd); } ////////////////////////////////////////////////////////////////////////// void MPIIOMigrationCoProcessor::process(double step) { - if (scheduler->isDue(step)) - { - if (comm->isRoot()) UBLOG(logINFO, "MPIIOMigrationCoProcessor save step: " << step); - if (comm->isRoot()) UBLOG(logINFO, "Save check point - start"); - /*if (comm->isRoot())*/ clearAllFiles((int)step); - - writeBlocks((int)step); - writeDataSet((int)step); - writeBoundaryConds((int)step); - - writeCpTimeStep((int)step); - - if (comm->isRoot()) UBLOG(logINFO, "Save check point - end"); - } + if (scheduler->isDue(step)) { + if (comm->isRoot()) + UBLOG(logINFO, "MPIIOMigrationCoProcessor save step: " << step); + if (comm->isRoot()) + UBLOG(logINFO, "Save check point - start"); + /*if (comm->isRoot())*/ clearAllFiles((int)step); + + writeBlocks((int)step); + writeDataSet((int)step); + writeBoundaryConds((int)step); + + writeCpTimeStep((int)step); + + if (comm->isRoot()) + UBLOG(logINFO, "Save check point - end"); + } } void MPIIOMigrationCoProcessor::clearAllFiles(int step) { - MPI_File file_handler; - MPI_Info info = MPI_INFO_NULL; - MPI_Offset new_size = 0; + MPI_File file_handler; + MPI_Info info = MPI_INFO_NULL; + MPI_Offset new_size = 0; - MPIIOCoProcessor::clearAllFiles(step); - - UbSystem::makeDirectory(path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step)); + MPIIOCoProcessor::clearAllFiles(step); - std::string filename10 = path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + "/cpBC.bin"; - int rc10 = MPI_File_open(MPI_COMM_WORLD, filename10.c_str(), MPI_MODE_CREATE | MPI_MODE_WRONLY, info, &file_handler); - if (rc10 != MPI_SUCCESS) throw UbException(UB_EXARGS, "couldn't open file " + filename10); - MPI_File_set_size(file_handler, new_size); - MPI_File_close(&file_handler); + UbSystem::makeDirectory(path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step)); + + std::string filename10 = path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + "/cpBC.bin"; + int rc10 = + MPI_File_open(MPI_COMM_WORLD, filename10.c_str(), MPI_MODE_CREATE | MPI_MODE_WRONLY, info, &file_handler); + if (rc10 != MPI_SUCCESS) + throw UbException(UB_EXARGS, "couldn't open file " + filename10); + MPI_File_set_size(file_handler, new_size); + MPI_File_close(&file_handler); } void MPIIOMigrationCoProcessor::writeBlocks(int step) { - grid->renumberBlockIDs(); - MPIIOCoProcessor::writeBlocks(step); + grid->renumberBlockIDs(); + MPIIOCoProcessor::writeBlocks(step); } void MPIIOMigrationCoProcessor::writeDataSet(int step) { - int rank, size; - MPI_Comm_rank(MPI_COMM_WORLD, &rank); - MPI_Comm_size(MPI_COMM_WORLD, &size); - - int blocksCount = 0; // quantity of blocks, that belong to this process - - std::vector<SPtr<Block3D>> blocksVector[25]; - int minInitLevel = this->grid->getCoarsestInitializedLevel(); - int maxInitLevel = this->grid->getFinestInitializedLevel(); - for (int level = minInitLevel; level <= maxInitLevel; level++) - { - grid->getBlocks(level, rank, blocksVector[level]); - blocksCount += static_cast<int>(blocksVector[level].size()); - } - - dataSetParam dataSetParamStr1, dataSetParamStr2, dataSetParamStr3; - DataSetMigration* dataSetArray = new DataSetMigration[blocksCount]; - std::vector<double> doubleValuesArray; // double-values (arrays of f's) in all blocks + int rank, size; + MPI_Comm_rank(MPI_COMM_WORLD, &rank); + MPI_Comm_size(MPI_COMM_WORLD, &size); + + int blocksCount = 0; // quantity of blocks, that belong to this process + + std::vector<SPtr<Block3D>> blocksVector[25]; + int minInitLevel = this->grid->getCoarsestInitializedLevel(); + int maxInitLevel = this->grid->getFinestInitializedLevel(); + for (int level = minInitLevel; level <= maxInitLevel; level++) { + grid->getBlocks(level, rank, blocksVector[level]); + blocksCount += static_cast<int>(blocksVector[level].size()); + } + + dataSetParam dataSetParamStr1, dataSetParamStr2, dataSetParamStr3; + DataSetMigration *dataSetArray = new DataSetMigration[blocksCount]; + std::vector<double> doubleValuesArray; // double-values (arrays of f's) in all blocks + + if (comm->isRoot()) { + UBLOG(logINFO, "MPIIOMigrationCoProcessor::writeDataSet start collect data rank = " << rank); + UBLOG(logINFO, "Physical Memory currently used by current process: " + << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); + } + + DSArraysPresence arrPresence; + bool firstBlock = true; + size_t doubleCountInBlock = 0; + int ic = 0; + SPtr<D3Q27EsoTwist3DSplittedVector> D3Q27EsoTwist3DSplittedVectorPtr; + CbArray4D<LBMReal, IndexerX4X3X2X1>::CbArray4DPtr localDistributions; + CbArray4D<LBMReal, IndexerX4X3X2X1>::CbArray4DPtr nonLocalDistributions; + CbArray3D<LBMReal, IndexerX3X2X1>::CbArray3DPtr zeroDistributions; + + for (int level = minInitLevel; level <= maxInitLevel; level++) { + for (SPtr<Block3D> block : blocksVector[level]) // blocks of the current level + { + dataSetArray[ic].globalID = + block->getGlobalID(); // id of the block needed to find it while regenerating the grid + dataSetArray[ic].ghostLayerWidth = block->getKernel()->getGhostLayerWidth(); + dataSetArray[ic].collFactor = block->getKernel()->getCollisionFactor(); + dataSetArray[ic].deltaT = block->getKernel()->getDeltaT(); + dataSetArray[ic].compressible = block->getKernel()->getCompressible(); + dataSetArray[ic].withForcing = block->getKernel()->getWithForcing(); + + D3Q27EsoTwist3DSplittedVectorPtr = dynamicPointerCast<D3Q27EsoTwist3DSplittedVector>( + block->getKernel()->getDataSet()->getFdistributions()); + localDistributions = D3Q27EsoTwist3DSplittedVectorPtr->getLocalDistributions(); + nonLocalDistributions = D3Q27EsoTwist3DSplittedVectorPtr->getNonLocalDistributions(); + zeroDistributions = D3Q27EsoTwist3DSplittedVectorPtr->getZeroDistributions(); + + if (firstBlock) // && block->getKernel()) // when first (any) valid block... + { + if (localDistributions) { + dataSetParamStr1.nx[0] = static_cast<int>(localDistributions->getNX1()); + dataSetParamStr1.nx[1] = static_cast<int>(localDistributions->getNX2()); + dataSetParamStr1.nx[2] = static_cast<int>(localDistributions->getNX3()); + dataSetParamStr1.nx[3] = static_cast<int>(localDistributions->getNX4()); + } + + if (nonLocalDistributions) { + dataSetParamStr2.nx[0] = static_cast<int>(nonLocalDistributions->getNX1()); + dataSetParamStr2.nx[1] = static_cast<int>(nonLocalDistributions->getNX2()); + dataSetParamStr2.nx[2] = static_cast<int>(nonLocalDistributions->getNX3()); + dataSetParamStr2.nx[3] = static_cast<int>(nonLocalDistributions->getNX4()); + } + if (zeroDistributions) { + dataSetParamStr3.nx[0] = static_cast<int>(zeroDistributions->getNX1()); + dataSetParamStr3.nx[1] = static_cast<int>(zeroDistributions->getNX2()); + dataSetParamStr3.nx[2] = static_cast<int>(zeroDistributions->getNX3()); + dataSetParamStr3.nx[3] = 1; + } + + // ... than save some parameters that are equal in all blocks + dataSetParamStr1.nx1 = dataSetParamStr2.nx1 = dataSetParamStr3.nx1 = + static_cast<int>(block->getKernel()->getDataSet()->getFdistributions()->getNX1()); + dataSetParamStr1.nx2 = dataSetParamStr2.nx2 = dataSetParamStr3.nx2 = + static_cast<int>(block->getKernel()->getDataSet()->getFdistributions()->getNX2()); + dataSetParamStr1.nx3 = dataSetParamStr2.nx3 = dataSetParamStr3.nx3 = + static_cast<int>(block->getKernel()->getDataSet()->getFdistributions()->getNX3()); + + doubleCountInBlock = + dataSetParamStr1.nx[0] * dataSetParamStr1.nx[1] * dataSetParamStr1.nx[2] * dataSetParamStr1.nx[3] + + dataSetParamStr2.nx[0] * dataSetParamStr2.nx[1] * dataSetParamStr2.nx[2] * dataSetParamStr2.nx[3] + + dataSetParamStr3.nx[0] * dataSetParamStr3.nx[1] * dataSetParamStr3.nx[2] * dataSetParamStr3.nx[3]; + + SPtr<CbArray4D<LBMReal, IndexerX4X3X2X1>> averageDensityArray = + block->getKernel()->getDataSet()->getAverageDensity(); + if (averageDensityArray) + arrPresence.isAverageDensityArrayPresent = true; + else + arrPresence.isAverageDensityArrayPresent = false; + + SPtr<CbArray4D<LBMReal, IndexerX4X3X2X1>> AverageVelocityArray3DPtr = + block->getKernel()->getDataSet()->getAverageVelocity(); + if (AverageVelocityArray3DPtr) + arrPresence.isAverageVelocityArrayPresent = true; + else + arrPresence.isAverageVelocityArrayPresent = false; + + SPtr<CbArray4D<LBMReal, IndexerX4X3X2X1>> AverageFluctArray3DPtr = + block->getKernel()->getDataSet()->getAverageFluctuations(); + if (AverageFluctArray3DPtr) + arrPresence.isAverageFluktuationsArrayPresent = true; + else + arrPresence.isAverageFluktuationsArrayPresent = false; + + SPtr<CbArray4D<LBMReal, IndexerX4X3X2X1>> AverageTripleArray3DPtr = + block->getKernel()->getDataSet()->getAverageTriplecorrelations(); + if (AverageTripleArray3DPtr) + arrPresence.isAverageTripleArrayPresent = true; + else + arrPresence.isAverageTripleArrayPresent = false; + + SPtr<CbArray4D<LBMReal, IndexerX4X3X2X1>> ShearStressValArray3DPtr = + block->getKernel()->getDataSet()->getShearStressValues(); + if (ShearStressValArray3DPtr) + arrPresence.isShearStressValArrayPresent = true; + else + arrPresence.isShearStressValArrayPresent = false; + + SPtr<CbArray3D<LBMReal, IndexerX3X2X1>> relaxationFactor3DPtr = + block->getKernel()->getDataSet()->getRelaxationFactor(); + if (relaxationFactor3DPtr) + arrPresence.isRelaxationFactorPresent = true; + else + arrPresence.isRelaxationFactorPresent = false; + + firstBlock = false; + } - if (comm->isRoot()) - { - UBLOG(logINFO, "MPIIOMigrationCoProcessor::writeDataSet start collect data rank = " << rank); - UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); - } + if (localDistributions && (dataSetParamStr1.nx[0] > 0) && (dataSetParamStr1.nx[1] > 0) && + (dataSetParamStr1.nx[2] > 0) && (dataSetParamStr1.nx[3] > 0)) + doubleValuesArray.insert(doubleValuesArray.end(), localDistributions->getDataVector().begin(), + localDistributions->getDataVector().end()); + if (nonLocalDistributions && (dataSetParamStr2.nx[0] > 0) && (dataSetParamStr2.nx[1] > 0) && + (dataSetParamStr2.nx[2] > 0) && (dataSetParamStr2.nx[3] > 0)) + doubleValuesArray.insert(doubleValuesArray.end(), nonLocalDistributions->getDataVector().begin(), + nonLocalDistributions->getDataVector().end()); + if (zeroDistributions && (dataSetParamStr3.nx[0] > 0) && (dataSetParamStr3.nx[1] > 0) && + (dataSetParamStr3.nx[2] > 0)) + doubleValuesArray.insert(doubleValuesArray.end(), zeroDistributions->getDataVector().begin(), + zeroDistributions->getDataVector().end()); + + ic++; + } + } + + // register new MPI-type depending on the block-specific information + MPI_Type_contiguous(int(doubleCountInBlock), MPI_DOUBLE, &dataSetDoubleType); + MPI_Type_commit(&dataSetDoubleType); + + if (comm->isRoot()) { + UBLOG(logINFO, "MPIIOMigrationCoProcessor::writeDataSet start MPI IO rank = " << rank); + UBLOG(logINFO, "Physical Memory currently used by current process: " + << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); + } + + double start, finish; + if (comm->isRoot()) + start = MPI_Wtime(); + + MPI_Info info = MPI_INFO_NULL; +#ifdef HLRN_LUSTRE + MPI_Info_create(&info); + MPI_Info_set(info, "striping_factor", "40"); + MPI_Info_set(info, "striping_unit", "4M"); +#endif - DSArraysPresence arrPresence; - bool firstBlock = true; - size_t doubleCountInBlock = 0; - int ic = 0; - SPtr< D3Q27EsoTwist3DSplittedVector > D3Q27EsoTwist3DSplittedVectorPtr; - CbArray4D<LBMReal, IndexerX4X3X2X1>::CbArray4DPtr localDistributions; - CbArray4D <LBMReal, IndexerX4X3X2X1>::CbArray4DPtr nonLocalDistributions; - CbArray3D<LBMReal, IndexerX3X2X1>::CbArray3DPtr zeroDistributions; + // write to the file + MPI_File file_handler; + std::string filename = path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + "/cpDataSet.bin"; + int rc = MPI_File_open(MPI_COMM_WORLD, filename.c_str(), MPI_MODE_CREATE | MPI_MODE_WRONLY, info, &file_handler); + if (rc != MPI_SUCCESS) + throw UbException(UB_EXARGS, "couldn't open file " + filename); + + MPI_File_write_at(file_handler, (MPI_Offset)0, &dataSetParamStr1, 1, dataSetParamType, MPI_STATUS_IGNORE); + MPI_File_write_at(file_handler, (MPI_Offset)(sizeof(dataSetParam)), &dataSetParamStr2, 1, dataSetParamType, + MPI_STATUS_IGNORE); + MPI_File_write_at(file_handler, (MPI_Offset)(2 * sizeof(dataSetParam)), &dataSetParamStr3, 1, dataSetParamType, + MPI_STATUS_IGNORE); + + MPI_Offset write_offset; + size_t sizeofOneDataSet = sizeof(DataSetMigration) + doubleCountInBlock * sizeof(double); + + for (size_t nb = 0; nb < blocksCount; nb++) { + write_offset = (MPI_Offset)(3 * sizeof(dataSetParam) + dataSetArray[nb].globalID * sizeofOneDataSet); + MPI_File_write_at(file_handler, write_offset, &dataSetArray[nb], 1, dataSetType, MPI_STATUS_IGNORE); + MPI_File_write_at(file_handler, (MPI_Offset)(write_offset + sizeof(DataSetMigration)), + &doubleValuesArray[nb * doubleCountInBlock], 1, dataSetDoubleType, MPI_STATUS_IGNORE); + } + + MPI_File_sync(file_handler); + MPI_File_close(&file_handler); + MPI_Type_free(&dataSetDoubleType); + + if (comm->isRoot()) { + finish = MPI_Wtime(); + UBLOG(logINFO, "MPIIOMigrationCoProcessor::writeDataSet time: " << finish - start << " s"); + } + + delete[] dataSetArray; + + MPI_File file_handler1; + std::string filename1 = path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + "/cpArrays.bin"; + rc = MPI_File_open(MPI_COMM_WORLD, filename1.c_str(), MPI_MODE_CREATE | MPI_MODE_WRONLY, info, &file_handler1); + if (rc != MPI_SUCCESS) + throw UbException(UB_EXARGS, "couldn't open file " + filename1); + MPI_File_write_at(file_handler1, (MPI_Offset)0, &arrPresence, 1, arrayPresenceType, MPI_STATUS_IGNORE); + MPI_File_sync(file_handler1); + MPI_File_close(&file_handler1); + + if (arrPresence.isAverageDensityArrayPresent) + write4DArray(step, AverageDensity, std::string("/cpAverageDensityArray.bin")); + // writeAverageDensityArray(step); + + if (arrPresence.isAverageVelocityArrayPresent) + write4DArray(step, AverageVelocity, std::string("/cpAverageVelocityArray.bin")); + // writeAverageVelocityArray(step); + + if (arrPresence.isAverageFluktuationsArrayPresent) + write4DArray(step, AverageFluktuations, std::string("/cpAverageFluktuationsArray.bin")); + // writeAverageFluktuationsArray(step); + + if (arrPresence.isAverageTripleArrayPresent) + write4DArray(step, AverageTriple, std::string("/cpAverageTripleArray.bin")); + // writeAverageTripleArray(step); + + if (arrPresence.isShearStressValArrayPresent) + write4DArray(step, ShearStressVal, std::string("/cpShearStressValArray.bin")); + // writeShearStressValArray(step); + + if (arrPresence.isRelaxationFactorPresent) + write3DArray(step, RelaxationFactor, std::string("/cpRelaxationFactor.bin")); +} - for (int level = minInitLevel; level <= maxInitLevel; level++) - { - for (SPtr<Block3D> block : blocksVector[level]) // blocks of the current level - { - dataSetArray[ic].globalID = block->getGlobalID(); // id of the block needed to find it while regenerating the grid - dataSetArray[ic].ghostLayerWidth = block->getKernel()->getGhostLayerWidth(); - dataSetArray[ic].collFactor = block->getKernel()->getCollisionFactor(); - dataSetArray[ic].deltaT = block->getKernel()->getDeltaT(); - dataSetArray[ic].compressible = block->getKernel()->getCompressible(); - dataSetArray[ic].withForcing = block->getKernel()->getWithForcing(); - - D3Q27EsoTwist3DSplittedVectorPtr = dynamicPointerCast<D3Q27EsoTwist3DSplittedVector>(block->getKernel()->getDataSet()->getFdistributions()); - localDistributions = D3Q27EsoTwist3DSplittedVectorPtr->getLocalDistributions(); - nonLocalDistributions = D3Q27EsoTwist3DSplittedVectorPtr->getNonLocalDistributions(); - zeroDistributions = D3Q27EsoTwist3DSplittedVectorPtr->getZeroDistributions(); - - if (firstBlock)// && block->getKernel()) // when first (any) valid block... - { - if (localDistributions) - { - dataSetParamStr1.nx[0] = static_cast<int>(localDistributions->getNX1()); - dataSetParamStr1.nx[1] = static_cast<int>(localDistributions->getNX2()); - dataSetParamStr1.nx[2] = static_cast<int>(localDistributions->getNX3()); - dataSetParamStr1.nx[3] = static_cast<int>(localDistributions->getNX4()); +void MPIIOMigrationCoProcessor::write4DArray(int step, Arrays arrayType, std::string fname) +{ + int rank, size; + MPI_Comm_rank(MPI_COMM_WORLD, &rank); + MPI_Comm_size(MPI_COMM_WORLD, &size); + + int blocksCount = 0; // quantity of blocks in the grid, max 2147483648 blocks! + + std::vector<SPtr<Block3D>> blocksVector[25]; + int minInitLevel = this->grid->getCoarsestInitializedLevel(); + int maxInitLevel = this->grid->getFinestInitializedLevel(); + for (int level = minInitLevel; level <= maxInitLevel; level++) { + grid->getBlocks(level, rank, blocksVector[level]); + blocksCount += static_cast<int>(blocksVector[level].size()); + } + + DataSetSmallMigration *dataSetSmallArray = new DataSetSmallMigration[blocksCount]; + std::vector<double> doubleValuesArray; // double-values of the AverageDensityArray in all blocks + dataSetParam dataSetParamStr; + + if (comm->isRoot()) { + UBLOG(logINFO, "MPIIOMigrationCoProcessor::writeAverageDensityArray start collect data rank = " << rank); + UBLOG(logINFO, "Physical Memory currently used by current process: " + << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); + } + + bool firstBlock = true; + size_t doubleCountInBlock = 0; + int ic = 0; + SPtr<CbArray4D<LBMReal, IndexerX4X3X2X1>> ___Array; + + for (int level = minInitLevel; level <= maxInitLevel; level++) { + for (SPtr<Block3D> block : blocksVector[level]) // blocks of the current level + { + dataSetSmallArray[ic].globalID = + block->getGlobalID(); // id of the block needed to find it while regenerating the grid + + switch (arrayType) { + case AverageDensity: + ___Array = block->getKernel()->getDataSet()->getAverageDensity(); + break; + case AverageVelocity: + ___Array = block->getKernel()->getDataSet()->getAverageVelocity(); + break; + case AverageFluktuations: + ___Array = block->getKernel()->getDataSet()->getAverageFluctuations(); + break; + case AverageTriple: + ___Array = block->getKernel()->getDataSet()->getAverageTriplecorrelations(); + break; + case ShearStressVal: + ___Array = block->getKernel()->getDataSet()->getShearStressValues(); + break; + default: + UB_THROW(UbException(UB_EXARGS, + "MPIIOMigrationCoProcessor::write4DArray : 4D array type does not exist!")); + break; } - if (nonLocalDistributions) - { - dataSetParamStr2.nx[0] = static_cast<int>(nonLocalDistributions->getNX1()); - dataSetParamStr2.nx[1] = static_cast<int>(nonLocalDistributions->getNX2()); - dataSetParamStr2.nx[2] = static_cast<int>(nonLocalDistributions->getNX3()); - dataSetParamStr2.nx[3] = static_cast<int>(nonLocalDistributions->getNX4()); - } - if (zeroDistributions) + if (firstBlock) // when first (any) valid block... { - dataSetParamStr3.nx[0] = static_cast<int>(zeroDistributions->getNX1()); - dataSetParamStr3.nx[1] = static_cast<int>(zeroDistributions->getNX2()); - dataSetParamStr3.nx[2] = static_cast<int>(zeroDistributions->getNX3()); - dataSetParamStr3.nx[3] = 1; + dataSetParamStr.nx1 = dataSetParamStr.nx2 = dataSetParamStr.nx3 = 0; + dataSetParamStr.nx[0] = static_cast<int>(___Array->getNX1()); + dataSetParamStr.nx[1] = static_cast<int>(___Array->getNX2()); + dataSetParamStr.nx[2] = static_cast<int>(___Array->getNX3()); + dataSetParamStr.nx[3] = static_cast<int>(___Array->getNX4()); + doubleCountInBlock = + dataSetParamStr.nx[0] * dataSetParamStr.nx[1] * dataSetParamStr.nx[2] * dataSetParamStr.nx[3]; + + firstBlock = false; } - // ... than save some parameters that are equal in all blocks - dataSetParamStr1.nx1 = dataSetParamStr2.nx1 = dataSetParamStr3.nx1 = static_cast<int>(block->getKernel()->getDataSet()->getFdistributions()->getNX1()); - dataSetParamStr1.nx2 = dataSetParamStr2.nx2 = dataSetParamStr3.nx2 = static_cast<int>(block->getKernel()->getDataSet()->getFdistributions()->getNX2()); - dataSetParamStr1.nx3 = dataSetParamStr2.nx3 = dataSetParamStr3.nx3 = static_cast<int>(block->getKernel()->getDataSet()->getFdistributions()->getNX3()); - - doubleCountInBlock = dataSetParamStr1.nx[0] * dataSetParamStr1.nx[1] * dataSetParamStr1.nx[2] * dataSetParamStr1.nx[3] + - dataSetParamStr2.nx[0] * dataSetParamStr2.nx[1] * dataSetParamStr2.nx[2] * dataSetParamStr2.nx[3] + - dataSetParamStr3.nx[0] * dataSetParamStr3.nx[1] * dataSetParamStr3.nx[2] * dataSetParamStr3.nx[3]; - - SPtr< CbArray4D<LBMReal, IndexerX4X3X2X1> > averageDensityArray = block->getKernel()->getDataSet()->getAverageDensity(); - if (averageDensityArray) - arrPresence.isAverageDensityArrayPresent = true; - else - arrPresence.isAverageDensityArrayPresent = false; - - SPtr< CbArray4D<LBMReal, IndexerX4X3X2X1> > AverageVelocityArray3DPtr = block->getKernel()->getDataSet()->getAverageVelocity(); - if (AverageVelocityArray3DPtr) - arrPresence.isAverageVelocityArrayPresent = true; - else - arrPresence.isAverageVelocityArrayPresent = false; - - SPtr< CbArray4D<LBMReal, IndexerX4X3X2X1> > AverageFluctArray3DPtr = block->getKernel()->getDataSet()->getAverageFluctuations(); - if (AverageFluctArray3DPtr) - arrPresence.isAverageFluktuationsArrayPresent = true; - else - arrPresence.isAverageFluktuationsArrayPresent = false; - - SPtr< CbArray4D<LBMReal, IndexerX4X3X2X1> > AverageTripleArray3DPtr = block->getKernel()->getDataSet()->getAverageTriplecorrelations(); - if (AverageTripleArray3DPtr) - arrPresence.isAverageTripleArrayPresent = true; - else - arrPresence.isAverageTripleArrayPresent = false; - - SPtr< CbArray4D<LBMReal, IndexerX4X3X2X1> > ShearStressValArray3DPtr = block->getKernel()->getDataSet()->getShearStressValues(); - if (ShearStressValArray3DPtr) - arrPresence.isShearStressValArrayPresent = true; - else - arrPresence.isShearStressValArrayPresent = false; - - SPtr< CbArray3D<LBMReal, IndexerX3X2X1> > relaxationFactor3DPtr = block->getKernel()->getDataSet()->getRelaxationFactor(); - if (relaxationFactor3DPtr) - arrPresence.isRelaxationFactorPresent = true; - else - arrPresence.isRelaxationFactorPresent = false; + if (___Array && (dataSetParamStr.nx[0] > 0) && (dataSetParamStr.nx[1] > 0) && (dataSetParamStr.nx[2] > 0) && + (dataSetParamStr.nx[3] > 0)) + doubleValuesArray.insert(doubleValuesArray.end(), ___Array->getDataVector().begin(), + ___Array->getDataVector().end()); - firstBlock = false; - } + ic++; + } + } - if (localDistributions && (dataSetParamStr1.nx[0]>0) && (dataSetParamStr1.nx[1]>0) && (dataSetParamStr1.nx[2]>0) && (dataSetParamStr1.nx[3]>0)) - doubleValuesArray.insert(doubleValuesArray.end(), localDistributions->getDataVector().begin(), localDistributions->getDataVector().end()); - if (nonLocalDistributions && (dataSetParamStr2.nx[0]>0) && (dataSetParamStr2.nx[1]>0) && (dataSetParamStr2.nx[2]>0) && (dataSetParamStr2.nx[3]>0)) - doubleValuesArray.insert(doubleValuesArray.end(), nonLocalDistributions->getDataVector().begin(), nonLocalDistributions->getDataVector().end()); - if (zeroDistributions && (dataSetParamStr3.nx[0]>0) && (dataSetParamStr3.nx[1]>0) && (dataSetParamStr3.nx[2]>0)) - doubleValuesArray.insert(doubleValuesArray.end(), zeroDistributions->getDataVector().begin(), zeroDistributions->getDataVector().end()); + // register new MPI-types depending on the block-specific information + MPI_Type_contiguous(int(doubleCountInBlock), MPI_DOUBLE, &dataSetDoubleType); + MPI_Type_commit(&dataSetDoubleType); - ic++; - } - } + if (comm->isRoot()) { + UBLOG(logINFO, "MPIIOMigrationCoProcessor::write4DArray start MPI IO rank = " << rank); + UBLOG(logINFO, "Physical Memory currently used by current process: " + << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); + } - // register new MPI-type depending on the block-specific information - MPI_Type_contiguous(int(doubleCountInBlock), MPI_DOUBLE, &dataSetDoubleType); - MPI_Type_commit(&dataSetDoubleType); + double start, finish; + if (comm->isRoot()) + start = MPI_Wtime(); - if (comm->isRoot()) - { - UBLOG(logINFO, "MPIIOMigrationCoProcessor::writeDataSet start MPI IO rank = " << rank); - UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); - } + MPI_Info info = MPI_INFO_NULL; - double start, finish; - if (comm->isRoot()) start = MPI_Wtime(); + MPI_File file_handler; + std::string filename = path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + fname; + int rc = MPI_File_open(MPI_COMM_WORLD, filename.c_str(), MPI_MODE_CREATE | MPI_MODE_WRONLY, info, &file_handler); + if (rc != MPI_SUCCESS) + throw UbException(UB_EXARGS, "couldn't open file " + filename); - MPI_Info info = MPI_INFO_NULL; -#ifdef HLRN_LUSTRE - MPI_Info_create(&info); - MPI_Info_set(info, "striping_factor", "40"); - MPI_Info_set(info, "striping_unit", "4M"); -#endif + // each process writes common parameters of a dataSet + MPI_File_write_at(file_handler, 0, &dataSetParamStr, 1, dataSetParamType, MPI_STATUS_IGNORE); - // write to the file - MPI_File file_handler; - std::string filename = path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + "/cpDataSet.bin"; - int rc = MPI_File_open(MPI_COMM_WORLD, filename.c_str(), MPI_MODE_CREATE | MPI_MODE_WRONLY, info, &file_handler); - if (rc != MPI_SUCCESS) throw UbException(UB_EXARGS, "couldn't open file " + filename); + MPI_Offset write_offset; + size_t sizeofOneDataSet = sizeof(DataSetSmallMigration) + doubleCountInBlock * sizeof(double); - MPI_File_write_at(file_handler, (MPI_Offset)0, &dataSetParamStr1, 1, dataSetParamType, MPI_STATUS_IGNORE); - MPI_File_write_at(file_handler, (MPI_Offset)(sizeof(dataSetParam)), &dataSetParamStr2, 1, dataSetParamType, MPI_STATUS_IGNORE); - MPI_File_write_at(file_handler, (MPI_Offset)(2 * sizeof(dataSetParam)), &dataSetParamStr3, 1, dataSetParamType, MPI_STATUS_IGNORE); + for (size_t nb = 0; nb < blocksCount; nb++) { + write_offset = (MPI_Offset)(sizeof(dataSetParam) + dataSetSmallArray[nb].globalID * sizeofOneDataSet); + MPI_File_write_at(file_handler, write_offset, &dataSetSmallArray[nb], 1, dataSetSmallType, MPI_STATUS_IGNORE); + MPI_File_write_at(file_handler, (MPI_Offset)(write_offset + sizeof(DataSetSmallMigration)), + &doubleValuesArray[nb * doubleCountInBlock], 1, dataSetDoubleType, MPI_STATUS_IGNORE); + } - MPI_Offset write_offset; - size_t sizeofOneDataSet = sizeof(DataSetMigration) + doubleCountInBlock * sizeof(double); + MPI_File_sync(file_handler); + MPI_File_close(&file_handler); + MPI_Type_free(&dataSetDoubleType); - for (size_t nb = 0; nb < blocksCount; nb++) - { - write_offset = (MPI_Offset)(3 * sizeof(dataSetParam) + dataSetArray[nb].globalID * sizeofOneDataSet); - MPI_File_write_at(file_handler, write_offset, &dataSetArray[nb], 1, dataSetType, MPI_STATUS_IGNORE); - MPI_File_write_at(file_handler, (MPI_Offset)(write_offset + sizeof(DataSetMigration)), &doubleValuesArray[nb * doubleCountInBlock], 1, dataSetDoubleType, MPI_STATUS_IGNORE); - } + if (comm->isRoot()) { + finish = MPI_Wtime(); + UBLOG(logINFO, "MPIIOMigrationCoProcessor::write4DArray time: " << finish - start << " s"); + } - MPI_File_sync(file_handler); - MPI_File_close(&file_handler); - MPI_Type_free(&dataSetDoubleType); + delete[] dataSetSmallArray; +} - if (comm->isRoot()) - { - finish = MPI_Wtime(); - UBLOG(logINFO, "MPIIOMigrationCoProcessor::writeDataSet time: " << finish - start << " s"); - } +void MPIIOMigrationCoProcessor::write3DArray(int step, Arrays arrayType, std::string fname) +{ + int rank, size; + MPI_Comm_rank(MPI_COMM_WORLD, &rank); + MPI_Comm_size(MPI_COMM_WORLD, &size); + + int blocksCount = 0; // quantity of blocks in the grid, max 2147483648 blocks! + + std::vector<SPtr<Block3D>> blocksVector[25]; + int minInitLevel = this->grid->getCoarsestInitializedLevel(); + int maxInitLevel = this->grid->getFinestInitializedLevel(); + for (int level = minInitLevel; level <= maxInitLevel; level++) { + grid->getBlocks(level, rank, blocksVector[level]); + blocksCount += static_cast<int>(blocksVector[level].size()); + } + + DataSetSmallMigration *dataSetSmallArray = new DataSetSmallMigration[blocksCount]; + std::vector<double> doubleValuesArray; // double-values (arrays of f's) in all blocks + dataSetParam dataSetParamStr; + + if (comm->isRoot()) { + UBLOG(logINFO, "MPIIOMigrationCoProcessor::write3DArray start collect data rank = " << rank); + UBLOG(logINFO, "Physical Memory currently used by current process: " + << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); + } + + bool firstBlock = true; + size_t doubleCountInBlock = 0; + int ic = 0; + SPtr<CbArray3D<LBMReal, IndexerX3X2X1>> ___Array; + + for (int level = minInitLevel; level <= maxInitLevel; level++) { + for (SPtr<Block3D> block : blocksVector[level]) // blocks of the current level + { + dataSetSmallArray[ic].globalID = + block->getGlobalID(); // id of the block needed to find it while regenerating the grid + + switch (arrayType) { + case RelaxationFactor: + ___Array = block->getKernel()->getDataSet()->getRelaxationFactor(); + break; + default: + UB_THROW(UbException(UB_EXARGS, + "MPIIOMigrationCoProcessor::write3DArray : 3D array type does not exist!")); + break; + } + + if (firstBlock) // when first (any) valid block... + { + dataSetParamStr.nx1 = dataSetParamStr.nx2 = dataSetParamStr.nx3 = 0; + dataSetParamStr.nx[0] = static_cast<int>(___Array->getNX1()); + dataSetParamStr.nx[1] = static_cast<int>(___Array->getNX2()); + dataSetParamStr.nx[2] = static_cast<int>(___Array->getNX3()); + dataSetParamStr.nx[3] = 1; + doubleCountInBlock = + dataSetParamStr.nx[0] * dataSetParamStr.nx[1] * dataSetParamStr.nx[2] * dataSetParamStr.nx[3]; + + firstBlock = false; + } + + if (___Array && (dataSetParamStr.nx[0] > 0) && (dataSetParamStr.nx[1] > 0) && (dataSetParamStr.nx[2] > 0)) + doubleValuesArray.insert(doubleValuesArray.end(), ___Array->getDataVector().begin(), + ___Array->getDataVector().end()); + + ic++; + } + } + + // register new MPI-types depending on the block-specific information + MPI_Type_contiguous(int(doubleCountInBlock), MPI_DOUBLE, &dataSetDoubleType); + MPI_Type_commit(&dataSetDoubleType); - delete[] dataSetArray; + if (comm->isRoot()) { + UBLOG(logINFO, "MPIIOMigrationCoProcessor::write3DArray start MPI IO rank = " << rank); + UBLOG(logINFO, "Physical Memory currently used by current process: " + << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); + } - MPI_File file_handler1; - std::string filename1 = path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + "/cpArrays.bin"; - rc = MPI_File_open(MPI_COMM_WORLD, filename1.c_str(), MPI_MODE_CREATE | MPI_MODE_WRONLY, info, &file_handler1); - if (rc != MPI_SUCCESS) throw UbException(UB_EXARGS, "couldn't open file " + filename1); - MPI_File_write_at(file_handler1, (MPI_Offset)0, &arrPresence, 1, arrayPresenceType, MPI_STATUS_IGNORE); - MPI_File_sync(file_handler1); - MPI_File_close(&file_handler1); + double start, finish; + if (comm->isRoot()) + start = MPI_Wtime(); - if (arrPresence.isAverageDensityArrayPresent) - write4DArray(step, AverageDensity, std::string("/cpAverageDensityArray.bin")); - //writeAverageDensityArray(step); + MPI_Info info = MPI_INFO_NULL; - if (arrPresence.isAverageVelocityArrayPresent) - write4DArray(step, AverageVelocity, std::string("/cpAverageVelocityArray.bin")); - //writeAverageVelocityArray(step); +#ifdef HLRN_LUSTRE + MPI_Info_create(&info); + MPI_Info_set(info, "striping_factor", "40"); + MPI_Info_set(info, "striping_unit", "4M"); +#endif + + MPI_File file_handler; + std::string filename = path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + fname; + int rc = MPI_File_open(MPI_COMM_WORLD, filename.c_str(), MPI_MODE_CREATE | MPI_MODE_WRONLY, info, &file_handler); + if (rc != MPI_SUCCESS) + throw UbException(UB_EXARGS, "couldn't open file " + filename); + + // each process writes common parameters of a dataSet + MPI_File_write_at(file_handler, 0, &dataSetParamStr, 1, dataSetParamType, MPI_STATUS_IGNORE); - if (arrPresence.isAverageFluktuationsArrayPresent) - write4DArray(step, AverageFluktuations, std::string("/cpAverageFluktuationsArray.bin")); - //writeAverageFluktuationsArray(step); + size_t sizeofOneDataSet = sizeof(DataSetSmallMigration) + doubleCountInBlock * sizeof(double); - if (arrPresence.isAverageTripleArrayPresent) - write4DArray(step, AverageTriple, std::string("/cpAverageTripleArray.bin")); - //writeAverageTripleArray(step); + MPI_Offset write_offset; + for (size_t nb = 0; nb < blocksCount; nb++) { + write_offset = (MPI_Offset)(sizeof(dataSetParam) + dataSetSmallArray[nb].globalID * sizeofOneDataSet); + MPI_File_write_at(file_handler, write_offset, &dataSetSmallArray[nb], 1, dataSetSmallType, MPI_STATUS_IGNORE); + MPI_File_write_at(file_handler, (MPI_Offset)(write_offset + sizeof(DataSetSmallMigration)), + &doubleValuesArray[nb * doubleCountInBlock], 1, dataSetDoubleType, MPI_STATUS_IGNORE); + } - if (arrPresence.isShearStressValArrayPresent) - write4DArray(step, ShearStressVal, std::string("/cpShearStressValArray.bin")); - //writeShearStressValArray(step); + MPI_File_sync(file_handler); + MPI_File_close(&file_handler); + MPI_Type_free(&dataSetDoubleType); - if (arrPresence.isRelaxationFactorPresent) - write3DArray(step, RelaxationFactor, std::string("/cpRelaxationFactor.bin")); + if (comm->isRoot()) { + finish = MPI_Wtime(); + UBLOG(logINFO, "MPIIOMigrationCoProcessor::write3DArray time: " << finish - start << " s"); + } + + delete[] dataSetSmallArray; } -void MPIIOMigrationCoProcessor::write4DArray(int step, Arrays arrayType, std::string fname) +/* +void MPIIOMigrationCoProcessor::writeAverageDensityArray(int step) { int rank, size; MPI_Comm_rank(MPI_COMM_WORLD, &rank); @@ -348,74 +619,64 @@ void MPIIOMigrationCoProcessor::write4DArray(int step, Arrays arrayType, std::st } DataSetSmallMigration* dataSetSmallArray = new DataSetSmallMigration[blocksCount]; - std::vector<double> doubleValuesArray; // double-values of the AverageDensityArray in all blocks + std::vector<double> doubleValuesArray; // double-values of the AverageDensityArray in all blocks dataSetParam dataSetParamStr; if (comm->isRoot()) { UBLOG(logINFO, "MPIIOMigrationCoProcessor::writeAverageDensityArray start collect data rank = " << rank); - UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); + UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / +1073741824.0 << " GB"); } bool firstBlock = true; size_t doubleCountInBlock = 0; int ic = 0; - SPtr< CbArray4D<LBMReal, IndexerX4X3X2X1> > ___Array; - for (int level = minInitLevel; level <= maxInitLevel; level++) { for (SPtr<Block3D> block : blocksVector[level]) // blocks of the current level { - dataSetSmallArray[ic].globalID = block->getGlobalID(); // id of the block needed to find it while regenerating the grid - - switch (arrayType) { - case AverageDensity: - ___Array = block->getKernel()->getDataSet()->getAverageDensity(); - break; - case AverageVelocity: - ___Array = block->getKernel()->getDataSet()->getAverageVelocity(); - break; - case AverageFluktuations: - ___Array = block->getKernel()->getDataSet()->getAverageFluctuations(); - break; - case AverageTriple: - ___Array = block->getKernel()->getDataSet()->getAverageTriplecorrelations(); - break; - case ShearStressVal: - ___Array = block->getKernel()->getDataSet()->getShearStressValues(); - break; - default: - UB_THROW(UbException(UB_EXARGS, "MPIIOMigrationCoProcessor::write4DArray : 4D array type does not exist!")); - break; - } + dataSetSmallArray[ic].globalID = block->getGlobalID(); // id of the block needed to find it while +regenerating the grid + + SPtr< CbArray4D<LBMReal, IndexerX4X3X2X1> > averageDensityArray = +block->getKernel()->getDataSet()->getAverageDensity(); if (firstBlock) // when first (any) valid block... { + //if (averageDensityArray) + //{ dataSetParamStr.nx1 = dataSetParamStr.nx2 = dataSetParamStr.nx3 = 0; - dataSetParamStr.nx[0] = static_cast<int>(___Array->getNX1()); - dataSetParamStr.nx[1] = static_cast<int>(___Array->getNX2()); - dataSetParamStr.nx[2] = static_cast<int>(___Array->getNX3()); - dataSetParamStr.nx[3] = static_cast<int>(___Array->getNX4()); - doubleCountInBlock = dataSetParamStr.nx[0] * dataSetParamStr.nx[1] * dataSetParamStr.nx[2] * dataSetParamStr.nx[3]; + dataSetParamStr.nx[0] = static_cast<int>(averageDensityArray->getNX1()); + dataSetParamStr.nx[1] = static_cast<int>(averageDensityArray->getNX2()); + dataSetParamStr.nx[2] = static_cast<int>(averageDensityArray->getNX3()); + dataSetParamStr.nx[3] = static_cast<int>(averageDensityArray->getNX4()); + doubleCountInBlock = dataSetParamStr.nx[0] * dataSetParamStr.nx[1] * dataSetParamStr.nx[2] * +dataSetParamStr.nx[3]; + //} + //else + // break; firstBlock = false; } - if (___Array && (dataSetParamStr.nx[0] > 0) && (dataSetParamStr.nx[1] > 0) && (dataSetParamStr.nx[2] > 0) && (dataSetParamStr.nx[3] > 0)) - doubleValuesArray.insert(doubleValuesArray.end(), ___Array->getDataVector().begin(), ___Array->getDataVector().end()); + if (averageDensityArray && (dataSetParamStr.nx[0] > 0) && (dataSetParamStr.nx[1] > 0) && (dataSetParamStr.nx[2] +> 0) && (dataSetParamStr.nx[3] > 0)) doubleValuesArray.insert(doubleValuesArray.end(), +averageDensityArray->getDataVector().begin(), averageDensityArray->getDataVector().end()); ic++; } } // register new MPI-types depending on the block-specific information - MPI_Type_contiguous(int(doubleCountInBlock), MPI_DOUBLE, &dataSetDoubleType); + MPI_Type_contiguous(doubleCountInBlock, MPI_DOUBLE, &dataSetDoubleType); MPI_Type_commit(&dataSetDoubleType); if (comm->isRoot()) { - UBLOG(logINFO, "MPIIOMigrationCoProcessor::write4DArray start MPI IO rank = " << rank); - UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); + UBLOG(logINFO, "MPIIOMigrationCoProcessor::writeAverageDensityArray start MPI IO rank = " << rank); + UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / +1073741824.0 << " GB"); } double start, finish; @@ -424,7 +685,7 @@ void MPIIOMigrationCoProcessor::write4DArray(int step, Arrays arrayType, std::st MPI_Info info = MPI_INFO_NULL; MPI_File file_handler; - std::string filename = path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + fname; + std::string filename = path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + "/cpAverageDensityArray.bin"; int rc = MPI_File_open(MPI_COMM_WORLD, filename.c_str(), MPI_MODE_CREATE | MPI_MODE_WRONLY, info, &file_handler); if (rc != MPI_SUCCESS) throw UbException(UB_EXARGS, "couldn't open file " + filename); @@ -438,7 +699,8 @@ void MPIIOMigrationCoProcessor::write4DArray(int step, Arrays arrayType, std::st { write_offset = (MPI_Offset)(sizeof(dataSetParam) + dataSetSmallArray[nb].globalID * sizeofOneDataSet); MPI_File_write_at(file_handler, write_offset, &dataSetSmallArray[nb], 1, dataSetSmallType, MPI_STATUS_IGNORE); - MPI_File_write_at(file_handler, (MPI_Offset)(write_offset + sizeof(DataSetSmallMigration)), &doubleValuesArray[nb * doubleCountInBlock], 1, dataSetDoubleType, MPI_STATUS_IGNORE); + MPI_File_write_at(file_handler, (MPI_Offset)(write_offset + sizeof(DataSetSmallMigration)), &doubleValuesArray[nb +* doubleCountInBlock], 1, dataSetDoubleType, MPI_STATUS_IGNORE); } MPI_File_sync(file_handler); @@ -448,13 +710,13 @@ void MPIIOMigrationCoProcessor::write4DArray(int step, Arrays arrayType, std::st if (comm->isRoot()) { finish = MPI_Wtime(); - UBLOG(logINFO, "MPIIOMigrationCoProcessor::write4DArray time: " << finish - start << " s"); + UBLOG(logINFO, "MPIIOMigrationCoProcessor::writeAverageDensityArray time: " << finish - start << " s"); } delete[] dataSetSmallArray; } -void MPIIOMigrationCoProcessor::write3DArray(int step, Arrays arrayType, std::string fname) +void MPIIOMigrationCoProcessor::writeAverageVelocityArray(int step) { int rank, size; MPI_Comm_rank(MPI_COMM_WORLD, &rank); @@ -472,62 +734,64 @@ void MPIIOMigrationCoProcessor::write3DArray(int step, Arrays arrayType, std::st } DataSetSmallMigration* dataSetSmallArray = new DataSetSmallMigration[blocksCount]; - std::vector<double> doubleValuesArray; // double-values (arrays of f's) in all blocks + std::vector<double> doubleValuesArray; // double-values (arrays of f's) in all blocks dataSetParam dataSetParamStr; if (comm->isRoot()) { - UBLOG(logINFO, "MPIIOMigrationCoProcessor::write3DArray start collect data rank = " << rank); - UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); + UBLOG(logINFO, "MPIIOMigrationCoProcessor::writeAverageVelocityArray start collect data rank = " << rank); + UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / +1073741824.0 << " GB"); } bool firstBlock = true; size_t doubleCountInBlock = 0; int ic = 0; - SPtr< CbArray3D<LBMReal, IndexerX3X2X1> > ___Array; - for (int level = minInitLevel; level <= maxInitLevel; level++) { for (SPtr<Block3D> block : blocksVector[level]) // blocks of the current level { - dataSetSmallArray[ic].globalID = block->getGlobalID(); // id of the block needed to find it while regenerating the grid - - switch (arrayType) { - case RelaxationFactor: - ___Array = block->getKernel()->getDataSet()->getRelaxationFactor(); - break; - default: - UB_THROW(UbException(UB_EXARGS, "MPIIOMigrationCoProcessor::write3DArray : 3D array type does not exist!")); - break; - } + dataSetSmallArray[ic].globalID = block->getGlobalID(); // id of the block needed to find it while +regenerating the grid + + SPtr< CbArray4D<LBMReal, IndexerX4X3X2X1> > AverageVelocityArray3DPtr = +block->getKernel()->getDataSet()->getAverageVelocity(); if (firstBlock) // when first (any) valid block... { + //if (AverageVelocityArray3DPtr) + //{ dataSetParamStr.nx1 = dataSetParamStr.nx2 = dataSetParamStr.nx3 = 0; - dataSetParamStr.nx[0] = static_cast<int>(___Array->getNX1()); - dataSetParamStr.nx[1] = static_cast<int>(___Array->getNX2()); - dataSetParamStr.nx[2] = static_cast<int>(___Array->getNX3()); - dataSetParamStr.nx[3] = 1; - doubleCountInBlock = dataSetParamStr.nx[0] * dataSetParamStr.nx[1] * dataSetParamStr.nx[2] * dataSetParamStr.nx[3]; + dataSetParamStr.nx[0] = static_cast<int>(AverageVelocityArray3DPtr->getNX1()); + dataSetParamStr.nx[1] = static_cast<int>(AverageVelocityArray3DPtr->getNX2()); + dataSetParamStr.nx[2] = static_cast<int>(AverageVelocityArray3DPtr->getNX3()); + dataSetParamStr.nx[3] = static_cast<int>(AverageVelocityArray3DPtr->getNX4()); + doubleCountInBlock = dataSetParamStr.nx[0] * dataSetParamStr.nx[1] * dataSetParamStr.nx[2] * +dataSetParamStr.nx[3]; + //} + //else + // break; firstBlock = false; } - if (___Array && (dataSetParamStr.nx[0]>0) && (dataSetParamStr.nx[1]>0) && (dataSetParamStr.nx[2]>0)) - doubleValuesArray.insert(doubleValuesArray.end(), ___Array->getDataVector().begin(), ___Array->getDataVector().end()); + if (AverageVelocityArray3DPtr && (dataSetParamStr.nx[0]>0) && (dataSetParamStr.nx[1]>0) && +(dataSetParamStr.nx[2]>0) && (dataSetParamStr.nx[3]>0)) doubleValuesArray.insert(doubleValuesArray.end(), +AverageVelocityArray3DPtr->getDataVector().begin(), AverageVelocityArray3DPtr->getDataVector().end()); ic++; } } // register new MPI-types depending on the block-specific information - MPI_Type_contiguous(int(doubleCountInBlock), MPI_DOUBLE, &dataSetDoubleType); + MPI_Type_contiguous(doubleCountInBlock, MPI_DOUBLE, &dataSetDoubleType); MPI_Type_commit(&dataSetDoubleType); if (comm->isRoot()) { - UBLOG(logINFO, "MPIIOMigrationCoProcessor::write3DArray start MPI IO rank = " << rank); - UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); + UBLOG(logINFO, "MPIIOMigrationCoProcessor::writeAverageVelocityArray start MPI IO rank = " << rank); + UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / +1073741824.0 << " GB"); } double start, finish; @@ -535,28 +799,23 @@ void MPIIOMigrationCoProcessor::write3DArray(int step, Arrays arrayType, std::st MPI_Info info = MPI_INFO_NULL; -#ifdef HLRN_LUSTRE - MPI_Info_create(&info); - MPI_Info_set(info, "striping_factor", "40"); - MPI_Info_set(info, "striping_unit", "4M"); -#endif - MPI_File file_handler; - std::string filename = path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + fname; + std::string filename = path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + "/cpAverageVelocityArray.bin"; int rc = MPI_File_open(MPI_COMM_WORLD, filename.c_str(), MPI_MODE_CREATE | MPI_MODE_WRONLY, info, &file_handler); if (rc != MPI_SUCCESS) throw UbException(UB_EXARGS, "couldn't open file " + filename); // each process writes common parameters of a dataSet MPI_File_write_at(file_handler, 0, &dataSetParamStr, 1, dataSetParamType, MPI_STATUS_IGNORE); + MPI_Offset write_offset; size_t sizeofOneDataSet = sizeof(DataSetSmallMigration) + doubleCountInBlock * sizeof(double); - MPI_Offset write_offset; for (size_t nb = 0; nb < blocksCount; nb++) { write_offset = (MPI_Offset)(sizeof(dataSetParam) + dataSetSmallArray[nb].globalID * sizeofOneDataSet); MPI_File_write_at(file_handler, write_offset, &dataSetSmallArray[nb], 1, dataSetSmallType, MPI_STATUS_IGNORE); - MPI_File_write_at(file_handler, (MPI_Offset)(write_offset + sizeof(DataSetSmallMigration)), &doubleValuesArray[nb * doubleCountInBlock], 1, dataSetDoubleType, MPI_STATUS_IGNORE); + MPI_File_write_at(file_handler, (MPI_Offset)(write_offset + sizeof(DataSetSmallMigration)), &doubleValuesArray[nb +* doubleCountInBlock], 1, dataSetDoubleType, MPI_STATUS_IGNORE); } MPI_File_sync(file_handler); @@ -566,14 +825,13 @@ void MPIIOMigrationCoProcessor::write3DArray(int step, Arrays arrayType, std::st if (comm->isRoot()) { finish = MPI_Wtime(); - UBLOG(logINFO, "MPIIOMigrationCoProcessor::write3DArray time: " << finish - start << " s"); + UBLOG(logINFO, "MPIIOMigrationCoProcessor::writeAverageVelocityArray time: " << finish - start << " s"); } delete[] dataSetSmallArray; } -/* -void MPIIOMigrationCoProcessor::writeAverageDensityArray(int step) +void MPIIOMigrationCoProcessor::writeAverageFluktuationsArray(int step) { int rank, size; MPI_Comm_rank(MPI_COMM_WORLD, &rank); @@ -591,13 +849,14 @@ void MPIIOMigrationCoProcessor::writeAverageDensityArray(int step) } DataSetSmallMigration* dataSetSmallArray = new DataSetSmallMigration[blocksCount]; - std::vector<double> doubleValuesArray; // double-values of the AverageDensityArray in all blocks + std::vector<double> doubleValuesArray; // double-values (arrays of f's) in all blocks dataSetParam dataSetParamStr; if (comm->isRoot()) { - UBLOG(logINFO, "MPIIOMigrationCoProcessor::writeAverageDensityArray start collect data rank = " << rank); - UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); + UBLOG(logINFO, "MPIIOMigrationCoProcessor::writeAverageFluktuationsArray start collect data rank = " << rank); + UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / +1073741824.0 << " GB"); } bool firstBlock = true; @@ -607,20 +866,23 @@ void MPIIOMigrationCoProcessor::writeAverageDensityArray(int step) { for (SPtr<Block3D> block : blocksVector[level]) // blocks of the current level { - dataSetSmallArray[ic].globalID = block->getGlobalID(); // id of the block needed to find it while regenerating the grid + dataSetSmallArray[ic].globalID = block->getGlobalID(); // id of the block needed to find it while +regenerating the grid - SPtr< CbArray4D<LBMReal, IndexerX4X3X2X1> > averageDensityArray = block->getKernel()->getDataSet()->getAverageDensity(); + SPtr< CbArray4D<LBMReal, IndexerX4X3X2X1> > AverageFluctArray3DPtr = +block->getKernel()->getDataSet()->getAverageFluctuations(); if (firstBlock) // when first (any) valid block... { - //if (averageDensityArray) + //if (AverageFluctArray3DPtr) //{ dataSetParamStr.nx1 = dataSetParamStr.nx2 = dataSetParamStr.nx3 = 0; - dataSetParamStr.nx[0] = static_cast<int>(averageDensityArray->getNX1()); - dataSetParamStr.nx[1] = static_cast<int>(averageDensityArray->getNX2()); - dataSetParamStr.nx[2] = static_cast<int>(averageDensityArray->getNX3()); - dataSetParamStr.nx[3] = static_cast<int>(averageDensityArray->getNX4()); - doubleCountInBlock = dataSetParamStr.nx[0] * dataSetParamStr.nx[1] * dataSetParamStr.nx[2] * dataSetParamStr.nx[3]; + dataSetParamStr.nx[0] = static_cast<int>(AverageFluctArray3DPtr->getNX1()); + dataSetParamStr.nx[1] = static_cast<int>(AverageFluctArray3DPtr->getNX2()); + dataSetParamStr.nx[2] = static_cast<int>(AverageFluctArray3DPtr->getNX3()); + dataSetParamStr.nx[3] = static_cast<int>(AverageFluctArray3DPtr->getNX4()); + doubleCountInBlock = dataSetParamStr.nx[0] * dataSetParamStr.nx[1] * dataSetParamStr.nx[2] * +dataSetParamStr.nx[3]; //} //else // break; @@ -628,8 +890,9 @@ void MPIIOMigrationCoProcessor::writeAverageDensityArray(int step) firstBlock = false; } - if (averageDensityArray && (dataSetParamStr.nx[0] > 0) && (dataSetParamStr.nx[1] > 0) && (dataSetParamStr.nx[2] > 0) && (dataSetParamStr.nx[3] > 0)) - doubleValuesArray.insert(doubleValuesArray.end(), averageDensityArray->getDataVector().begin(), averageDensityArray->getDataVector().end()); + if (AverageFluctArray3DPtr && (dataSetParamStr.nx[0]>0) && (dataSetParamStr.nx[1]>0) && +(dataSetParamStr.nx[2]>0) && (dataSetParamStr.nx[3]>0)) doubleValuesArray.insert(doubleValuesArray.end(), +AverageFluctArray3DPtr->getDataVector().begin(), AverageFluctArray3DPtr->getDataVector().end()); ic++; } @@ -641,17 +904,23 @@ void MPIIOMigrationCoProcessor::writeAverageDensityArray(int step) if (comm->isRoot()) { - UBLOG(logINFO, "MPIIOMigrationCoProcessor::writeAverageDensityArray start MPI IO rank = " << rank); - UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); + UBLOG(logINFO, "MPIIOMigrationCoProcessor::writeAverageFluktuationsArray start MPI IO rank = " << rank); + UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / +1073741824.0 << " GB"); } double start, finish; if (comm->isRoot()) start = MPI_Wtime(); MPI_Info info = MPI_INFO_NULL; +#ifdef HLRN_LUSTRE + MPI_Info_create(&info); + MPI_Info_set(info, "striping_factor", "40"); + MPI_Info_set(info, "striping_unit", "4M"); +#endif MPI_File file_handler; - std::string filename = path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + "/cpAverageDensityArray.bin"; + std::string filename = path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + "/cpAverageFluktuationsArray.bin"; int rc = MPI_File_open(MPI_COMM_WORLD, filename.c_str(), MPI_MODE_CREATE | MPI_MODE_WRONLY, info, &file_handler); if (rc != MPI_SUCCESS) throw UbException(UB_EXARGS, "couldn't open file " + filename); @@ -665,7 +934,8 @@ void MPIIOMigrationCoProcessor::writeAverageDensityArray(int step) { write_offset = (MPI_Offset)(sizeof(dataSetParam) + dataSetSmallArray[nb].globalID * sizeofOneDataSet); MPI_File_write_at(file_handler, write_offset, &dataSetSmallArray[nb], 1, dataSetSmallType, MPI_STATUS_IGNORE); - MPI_File_write_at(file_handler, (MPI_Offset)(write_offset + sizeof(DataSetSmallMigration)), &doubleValuesArray[nb * doubleCountInBlock], 1, dataSetDoubleType, MPI_STATUS_IGNORE); + MPI_File_write_at(file_handler, (MPI_Offset)(write_offset + sizeof(DataSetSmallMigration)), &doubleValuesArray[nb +* doubleCountInBlock], 1, dataSetDoubleType, MPI_STATUS_IGNORE); } MPI_File_sync(file_handler); @@ -675,13 +945,13 @@ void MPIIOMigrationCoProcessor::writeAverageDensityArray(int step) if (comm->isRoot()) { finish = MPI_Wtime(); - UBLOG(logINFO, "MPIIOMigrationCoProcessor::writeAverageDensityArray time: " << finish - start << " s"); + UBLOG(logINFO, "MPIIOMigrationCoProcessor::writeAverageFluktuationsArray time: " << finish - start << " s"); } delete[] dataSetSmallArray; } -void MPIIOMigrationCoProcessor::writeAverageVelocityArray(int step) +void MPIIOMigrationCoProcessor::writeAverageTripleArray(int step) { int rank, size; MPI_Comm_rank(MPI_COMM_WORLD, &rank); @@ -699,13 +969,14 @@ void MPIIOMigrationCoProcessor::writeAverageVelocityArray(int step) } DataSetSmallMigration* dataSetSmallArray = new DataSetSmallMigration[blocksCount]; - std::vector<double> doubleValuesArray; // double-values (arrays of f's) in all blocks + std::vector<double> doubleValuesArray; // double-values (arrays of f's) in all blocks dataSetParam dataSetParamStr; if (comm->isRoot()) { - UBLOG(logINFO, "MPIIOMigrationCoProcessor::writeAverageVelocityArray start collect data rank = " << rank); - UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); + UBLOG(logINFO, "MPIIOMigrationCoProcessor::writeAverageTripleArray start collect data rank = " << rank); + UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / +1073741824.0 << " GB"); } bool firstBlock = true; @@ -715,20 +986,23 @@ void MPIIOMigrationCoProcessor::writeAverageVelocityArray(int step) { for (SPtr<Block3D> block : blocksVector[level]) // blocks of the current level { - dataSetSmallArray[ic].globalID = block->getGlobalID(); // id of the block needed to find it while regenerating the grid + dataSetSmallArray[ic].globalID = block->getGlobalID(); // id of the block needed to find it while +regenerating the grid - SPtr< CbArray4D<LBMReal, IndexerX4X3X2X1> > AverageVelocityArray3DPtr = block->getKernel()->getDataSet()->getAverageVelocity(); + SPtr< CbArray4D<LBMReal, IndexerX4X3X2X1> > AverageTripleArray3DPtr = +block->getKernel()->getDataSet()->getAverageTriplecorrelations(); if (firstBlock) // when first (any) valid block... { - //if (AverageVelocityArray3DPtr) + //if (AverageTripleArray3DPtr) //{ dataSetParamStr.nx1 = dataSetParamStr.nx2 = dataSetParamStr.nx3 = 0; - dataSetParamStr.nx[0] = static_cast<int>(AverageVelocityArray3DPtr->getNX1()); - dataSetParamStr.nx[1] = static_cast<int>(AverageVelocityArray3DPtr->getNX2()); - dataSetParamStr.nx[2] = static_cast<int>(AverageVelocityArray3DPtr->getNX3()); - dataSetParamStr.nx[3] = static_cast<int>(AverageVelocityArray3DPtr->getNX4()); - doubleCountInBlock = dataSetParamStr.nx[0] * dataSetParamStr.nx[1] * dataSetParamStr.nx[2] * dataSetParamStr.nx[3]; + dataSetParamStr.nx[0] = static_cast<int>(AverageTripleArray3DPtr->getNX1()); + dataSetParamStr.nx[1] = static_cast<int>(AverageTripleArray3DPtr->getNX2()); + dataSetParamStr.nx[2] = static_cast<int>(AverageTripleArray3DPtr->getNX3()); + dataSetParamStr.nx[3] = static_cast<int>(AverageTripleArray3DPtr->getNX4()); + doubleCountInBlock = dataSetParamStr.nx[0] * dataSetParamStr.nx[1] * dataSetParamStr.nx[2] * +dataSetParamStr.nx[3]; //} //else // break; @@ -736,8 +1010,9 @@ void MPIIOMigrationCoProcessor::writeAverageVelocityArray(int step) firstBlock = false; } - if (AverageVelocityArray3DPtr && (dataSetParamStr.nx[0]>0) && (dataSetParamStr.nx[1]>0) && (dataSetParamStr.nx[2]>0) && (dataSetParamStr.nx[3]>0)) - doubleValuesArray.insert(doubleValuesArray.end(), AverageVelocityArray3DPtr->getDataVector().begin(), AverageVelocityArray3DPtr->getDataVector().end()); + if (AverageTripleArray3DPtr && (dataSetParamStr.nx[0]>0) && (dataSetParamStr.nx[1]>0) && +(dataSetParamStr.nx[2]>0) && (dataSetParamStr.nx[3]>0)) doubleValuesArray.insert(doubleValuesArray.end(), +AverageTripleArray3DPtr->getDataVector().begin(), AverageTripleArray3DPtr->getDataVector().end()); ic++; } @@ -749,8 +1024,9 @@ void MPIIOMigrationCoProcessor::writeAverageVelocityArray(int step) if (comm->isRoot()) { - UBLOG(logINFO, "MPIIOMigrationCoProcessor::writeAverageVelocityArray start MPI IO rank = " << rank); - UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); + UBLOG(logINFO, "MPIIOMigrationCoProcessor::writeAverageTripleArray start MPI IO rank = " << rank); + UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / +1073741824.0 << " GB"); } double start, finish; @@ -758,8 +1034,14 @@ void MPIIOMigrationCoProcessor::writeAverageVelocityArray(int step) MPI_Info info = MPI_INFO_NULL; +#ifdef HLRN_LUSTRE + MPI_Info_create(&info); + MPI_Info_set(info, "striping_factor", "40"); + MPI_Info_set(info, "striping_unit", "4M"); +#endif + MPI_File file_handler; - std::string filename = path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + "/cpAverageVelocityArray.bin"; + std::string filename = path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + "/cpAverageTripleArray.bin"; int rc = MPI_File_open(MPI_COMM_WORLD, filename.c_str(), MPI_MODE_CREATE | MPI_MODE_WRONLY, info, &file_handler); if (rc != MPI_SUCCESS) throw UbException(UB_EXARGS, "couldn't open file " + filename); @@ -773,7 +1055,8 @@ void MPIIOMigrationCoProcessor::writeAverageVelocityArray(int step) { write_offset = (MPI_Offset)(sizeof(dataSetParam) + dataSetSmallArray[nb].globalID * sizeofOneDataSet); MPI_File_write_at(file_handler, write_offset, &dataSetSmallArray[nb], 1, dataSetSmallType, MPI_STATUS_IGNORE); - MPI_File_write_at(file_handler, (MPI_Offset)(write_offset + sizeof(DataSetSmallMigration)), &doubleValuesArray[nb * doubleCountInBlock], 1, dataSetDoubleType, MPI_STATUS_IGNORE); + MPI_File_write_at(file_handler, (MPI_Offset)(write_offset + sizeof(DataSetSmallMigration)), &doubleValuesArray[nb +* doubleCountInBlock], 1, dataSetDoubleType, MPI_STATUS_IGNORE); } MPI_File_sync(file_handler); @@ -783,13 +1066,13 @@ void MPIIOMigrationCoProcessor::writeAverageVelocityArray(int step) if (comm->isRoot()) { finish = MPI_Wtime(); - UBLOG(logINFO, "MPIIOMigrationCoProcessor::writeAverageVelocityArray time: " << finish - start << " s"); + UBLOG(logINFO, "MPIIOMigrationCoProcessor::writeAverageTripleArray time: " << finish - start << " s"); } delete[] dataSetSmallArray; } -void MPIIOMigrationCoProcessor::writeAverageFluktuationsArray(int step) +void MPIIOMigrationCoProcessor::writeShearStressValArray(int step) { int rank, size; MPI_Comm_rank(MPI_COMM_WORLD, &rank); @@ -807,841 +1090,117 @@ void MPIIOMigrationCoProcessor::writeAverageFluktuationsArray(int step) } DataSetSmallMigration* dataSetSmallArray = new DataSetSmallMigration[blocksCount]; - std::vector<double> doubleValuesArray; // double-values (arrays of f's) in all blocks - dataSetParam dataSetParamStr; - - if (comm->isRoot()) - { - UBLOG(logINFO, "MPIIOMigrationCoProcessor::writeAverageFluktuationsArray start collect data rank = " << rank); - UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); - } - - bool firstBlock = true; - size_t doubleCountInBlock = 0; - int ic = 0; - for (int level = minInitLevel; level <= maxInitLevel; level++) - { - for (SPtr<Block3D> block : blocksVector[level]) // blocks of the current level - { - dataSetSmallArray[ic].globalID = block->getGlobalID(); // id of the block needed to find it while regenerating the grid - - SPtr< CbArray4D<LBMReal, IndexerX4X3X2X1> > AverageFluctArray3DPtr = block->getKernel()->getDataSet()->getAverageFluctuations(); - - if (firstBlock) // when first (any) valid block... - { - //if (AverageFluctArray3DPtr) - //{ - dataSetParamStr.nx1 = dataSetParamStr.nx2 = dataSetParamStr.nx3 = 0; - dataSetParamStr.nx[0] = static_cast<int>(AverageFluctArray3DPtr->getNX1()); - dataSetParamStr.nx[1] = static_cast<int>(AverageFluctArray3DPtr->getNX2()); - dataSetParamStr.nx[2] = static_cast<int>(AverageFluctArray3DPtr->getNX3()); - dataSetParamStr.nx[3] = static_cast<int>(AverageFluctArray3DPtr->getNX4()); - doubleCountInBlock = dataSetParamStr.nx[0] * dataSetParamStr.nx[1] * dataSetParamStr.nx[2] * dataSetParamStr.nx[3]; - //} - //else - // break; - - firstBlock = false; - } - - if (AverageFluctArray3DPtr && (dataSetParamStr.nx[0]>0) && (dataSetParamStr.nx[1]>0) && (dataSetParamStr.nx[2]>0) && (dataSetParamStr.nx[3]>0)) - doubleValuesArray.insert(doubleValuesArray.end(), AverageFluctArray3DPtr->getDataVector().begin(), AverageFluctArray3DPtr->getDataVector().end()); - - ic++; - } - } - - // register new MPI-types depending on the block-specific information - MPI_Type_contiguous(doubleCountInBlock, MPI_DOUBLE, &dataSetDoubleType); - MPI_Type_commit(&dataSetDoubleType); - - if (comm->isRoot()) - { - UBLOG(logINFO, "MPIIOMigrationCoProcessor::writeAverageFluktuationsArray start MPI IO rank = " << rank); - UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); - } - - double start, finish; - if (comm->isRoot()) start = MPI_Wtime(); - - MPI_Info info = MPI_INFO_NULL; -#ifdef HLRN_LUSTRE - MPI_Info_create(&info); - MPI_Info_set(info, "striping_factor", "40"); - MPI_Info_set(info, "striping_unit", "4M"); -#endif - - MPI_File file_handler; - std::string filename = path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + "/cpAverageFluktuationsArray.bin"; - int rc = MPI_File_open(MPI_COMM_WORLD, filename.c_str(), MPI_MODE_CREATE | MPI_MODE_WRONLY, info, &file_handler); - if (rc != MPI_SUCCESS) throw UbException(UB_EXARGS, "couldn't open file " + filename); - - // each process writes common parameters of a dataSet - MPI_File_write_at(file_handler, 0, &dataSetParamStr, 1, dataSetParamType, MPI_STATUS_IGNORE); - - MPI_Offset write_offset; - size_t sizeofOneDataSet = sizeof(DataSetSmallMigration) + doubleCountInBlock * sizeof(double); - - for (size_t nb = 0; nb < blocksCount; nb++) - { - write_offset = (MPI_Offset)(sizeof(dataSetParam) + dataSetSmallArray[nb].globalID * sizeofOneDataSet); - MPI_File_write_at(file_handler, write_offset, &dataSetSmallArray[nb], 1, dataSetSmallType, MPI_STATUS_IGNORE); - MPI_File_write_at(file_handler, (MPI_Offset)(write_offset + sizeof(DataSetSmallMigration)), &doubleValuesArray[nb * doubleCountInBlock], 1, dataSetDoubleType, MPI_STATUS_IGNORE); - } - - MPI_File_sync(file_handler); - MPI_File_close(&file_handler); - MPI_Type_free(&dataSetDoubleType); - - if (comm->isRoot()) - { - finish = MPI_Wtime(); - UBLOG(logINFO, "MPIIOMigrationCoProcessor::writeAverageFluktuationsArray time: " << finish - start << " s"); - } - - delete[] dataSetSmallArray; -} - -void MPIIOMigrationCoProcessor::writeAverageTripleArray(int step) -{ - int rank, size; - MPI_Comm_rank(MPI_COMM_WORLD, &rank); - MPI_Comm_size(MPI_COMM_WORLD, &size); - - int blocksCount = 0; // quantity of blocks in the grid, max 2147483648 blocks! - - std::vector<SPtr<Block3D>> blocksVector[25]; - int minInitLevel = this->grid->getCoarsestInitializedLevel(); - int maxInitLevel = this->grid->getFinestInitializedLevel(); - for (int level = minInitLevel; level <= maxInitLevel; level++) - { - grid->getBlocks(level, rank, blocksVector[level]); - blocksCount += static_cast<int>(blocksVector[level].size()); - } - - DataSetSmallMigration* dataSetSmallArray = new DataSetSmallMigration[blocksCount]; - std::vector<double> doubleValuesArray; // double-values (arrays of f's) in all blocks - dataSetParam dataSetParamStr; - - if (comm->isRoot()) - { - UBLOG(logINFO, "MPIIOMigrationCoProcessor::writeAverageTripleArray start collect data rank = " << rank); - UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); - } - - bool firstBlock = true; - size_t doubleCountInBlock = 0; - int ic = 0; - for (int level = minInitLevel; level <= maxInitLevel; level++) - { - for (SPtr<Block3D> block : blocksVector[level]) // blocks of the current level - { - dataSetSmallArray[ic].globalID = block->getGlobalID(); // id of the block needed to find it while regenerating the grid - - SPtr< CbArray4D<LBMReal, IndexerX4X3X2X1> > AverageTripleArray3DPtr = block->getKernel()->getDataSet()->getAverageTriplecorrelations(); - - if (firstBlock) // when first (any) valid block... - { - //if (AverageTripleArray3DPtr) - //{ - dataSetParamStr.nx1 = dataSetParamStr.nx2 = dataSetParamStr.nx3 = 0; - dataSetParamStr.nx[0] = static_cast<int>(AverageTripleArray3DPtr->getNX1()); - dataSetParamStr.nx[1] = static_cast<int>(AverageTripleArray3DPtr->getNX2()); - dataSetParamStr.nx[2] = static_cast<int>(AverageTripleArray3DPtr->getNX3()); - dataSetParamStr.nx[3] = static_cast<int>(AverageTripleArray3DPtr->getNX4()); - doubleCountInBlock = dataSetParamStr.nx[0] * dataSetParamStr.nx[1] * dataSetParamStr.nx[2] * dataSetParamStr.nx[3]; - //} - //else - // break; - - firstBlock = false; - } - - if (AverageTripleArray3DPtr && (dataSetParamStr.nx[0]>0) && (dataSetParamStr.nx[1]>0) && (dataSetParamStr.nx[2]>0) && (dataSetParamStr.nx[3]>0)) - doubleValuesArray.insert(doubleValuesArray.end(), AverageTripleArray3DPtr->getDataVector().begin(), AverageTripleArray3DPtr->getDataVector().end()); - - ic++; - } - } - - // register new MPI-types depending on the block-specific information - MPI_Type_contiguous(doubleCountInBlock, MPI_DOUBLE, &dataSetDoubleType); - MPI_Type_commit(&dataSetDoubleType); - - if (comm->isRoot()) - { - UBLOG(logINFO, "MPIIOMigrationCoProcessor::writeAverageTripleArray start MPI IO rank = " << rank); - UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); - } - - double start, finish; - if (comm->isRoot()) start = MPI_Wtime(); - - MPI_Info info = MPI_INFO_NULL; - -#ifdef HLRN_LUSTRE - MPI_Info_create(&info); - MPI_Info_set(info, "striping_factor", "40"); - MPI_Info_set(info, "striping_unit", "4M"); -#endif - - MPI_File file_handler; - std::string filename = path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + "/cpAverageTripleArray.bin"; - int rc = MPI_File_open(MPI_COMM_WORLD, filename.c_str(), MPI_MODE_CREATE | MPI_MODE_WRONLY, info, &file_handler); - if (rc != MPI_SUCCESS) throw UbException(UB_EXARGS, "couldn't open file " + filename); - - // each process writes common parameters of a dataSet - MPI_File_write_at(file_handler, 0, &dataSetParamStr, 1, dataSetParamType, MPI_STATUS_IGNORE); - - MPI_Offset write_offset; - size_t sizeofOneDataSet = sizeof(DataSetSmallMigration) + doubleCountInBlock * sizeof(double); - - for (size_t nb = 0; nb < blocksCount; nb++) - { - write_offset = (MPI_Offset)(sizeof(dataSetParam) + dataSetSmallArray[nb].globalID * sizeofOneDataSet); - MPI_File_write_at(file_handler, write_offset, &dataSetSmallArray[nb], 1, dataSetSmallType, MPI_STATUS_IGNORE); - MPI_File_write_at(file_handler, (MPI_Offset)(write_offset + sizeof(DataSetSmallMigration)), &doubleValuesArray[nb * doubleCountInBlock], 1, dataSetDoubleType, MPI_STATUS_IGNORE); - } - - MPI_File_sync(file_handler); - MPI_File_close(&file_handler); - MPI_Type_free(&dataSetDoubleType); - - if (comm->isRoot()) - { - finish = MPI_Wtime(); - UBLOG(logINFO, "MPIIOMigrationCoProcessor::writeAverageTripleArray time: " << finish - start << " s"); - } - - delete[] dataSetSmallArray; -} - -void MPIIOMigrationCoProcessor::writeShearStressValArray(int step) -{ - int rank, size; - MPI_Comm_rank(MPI_COMM_WORLD, &rank); - MPI_Comm_size(MPI_COMM_WORLD, &size); - - int blocksCount = 0; // quantity of blocks in the grid, max 2147483648 blocks! - - std::vector<SPtr<Block3D>> blocksVector[25]; - int minInitLevel = this->grid->getCoarsestInitializedLevel(); - int maxInitLevel = this->grid->getFinestInitializedLevel(); - for (int level = minInitLevel; level <= maxInitLevel; level++) - { - grid->getBlocks(level, rank, blocksVector[level]); - blocksCount += static_cast<int>(blocksVector[level].size()); - } - - DataSetSmallMigration* dataSetSmallArray = new DataSetSmallMigration[blocksCount]; - std::vector<double> doubleValuesArray; // double-values (arrays of f's) in all blocks - dataSetParam dataSetParamStr; - - if (comm->isRoot()) - { - UBLOG(logINFO, "MPIIOMigrationCoProcessor::writeShearStressValArray start collect data rank = " << rank); - UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); - } - - bool firstBlock = true; - size_t doubleCountInBlock = 0; - int ic = 0; - for (int level = minInitLevel; level <= maxInitLevel; level++) - { - for (SPtr<Block3D> block : blocksVector[level]) // blocks of the current level - { - dataSetSmallArray[ic].globalID = block->getGlobalID(); // id of the block needed to find it while regenerating the grid - - SPtr< CbArray4D<LBMReal, IndexerX4X3X2X1> > ShearStressValArray3DPtr = block->getKernel()->getDataSet()->getShearStressValues(); - - if (firstBlock) // when first (any) valid block... - { - //if (ShearStressValArray3DPtr) - //{ - dataSetParamStr.nx1 = dataSetParamStr.nx2 = dataSetParamStr.nx3 = 0; - dataSetParamStr.nx[0] = static_cast<int>(ShearStressValArray3DPtr->getNX1()); - dataSetParamStr.nx[1] = static_cast<int>(ShearStressValArray3DPtr->getNX2()); - dataSetParamStr.nx[2] = static_cast<int>(ShearStressValArray3DPtr->getNX3()); - dataSetParamStr.nx[3] = static_cast<int>(ShearStressValArray3DPtr->getNX4()); - doubleCountInBlock = dataSetParamStr.nx[0] * dataSetParamStr.nx[1] * dataSetParamStr.nx[2] * dataSetParamStr.nx[3]; - //} - //else - // break; - - firstBlock = false; - } - - if (ShearStressValArray3DPtr && (dataSetParamStr.nx[0]>0) && (dataSetParamStr.nx[1]>0) && (dataSetParamStr.nx[2]>0) && (dataSetParamStr.nx[3]>0)) - doubleValuesArray.insert(doubleValuesArray.end(), ShearStressValArray3DPtr->getDataVector().begin(), ShearStressValArray3DPtr->getDataVector().end()); - - ic++; - } - } - - // register new MPI-types depending on the block-specific information - MPI_Type_contiguous(doubleCountInBlock, MPI_DOUBLE, &dataSetDoubleType); - MPI_Type_commit(&dataSetDoubleType); - - if (comm->isRoot()) - { - UBLOG(logINFO, "MPIIOMigrationCoProcessor::writeShearStressValArray start MPI IO rank = " << rank); - UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); - } - - double start, finish; - if (comm->isRoot()) start = MPI_Wtime(); - - MPI_Info info = MPI_INFO_NULL; - -#ifdef HLRN_LUSTRE - MPI_Info_create(&info); - MPI_Info_set(info, "striping_factor", "40"); - MPI_Info_set(info, "striping_unit", "4M"); -#endif - - MPI_File file_handler; - std::string filename = path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + "/cpShearStressValArray.bin"; - int rc = MPI_File_open(MPI_COMM_WORLD, filename.c_str(), MPI_MODE_CREATE | MPI_MODE_WRONLY, info, &file_handler); - if (rc != MPI_SUCCESS) throw UbException(UB_EXARGS, "couldn't open file " + filename); - - // each process writes common parameters of a dataSet - MPI_File_write_at(file_handler, 0, &dataSetParamStr, 1, dataSetParamType, MPI_STATUS_IGNORE); - - MPI_Offset write_offset; - size_t sizeofOneDataSet = sizeof(DataSetSmallMigration) + doubleCountInBlock * sizeof(double); - - for (size_t nb = 0; nb < blocksCount; nb++) - { - write_offset = (MPI_Offset)(sizeof(dataSetParam) + dataSetSmallArray[nb].globalID * sizeofOneDataSet); - MPI_File_write_at(file_handler, write_offset, &dataSetSmallArray[nb], 1, dataSetSmallType, MPI_STATUS_IGNORE); - MPI_File_write_at(file_handler, (MPI_Offset)(write_offset + sizeof(DataSetSmallMigration)), &doubleValuesArray[nb * doubleCountInBlock], 1, dataSetDoubleType, MPI_STATUS_IGNORE); - } - - MPI_File_sync(file_handler); - MPI_File_close(&file_handler); - MPI_Type_free(&dataSetDoubleType); - - if (comm->isRoot()) - { - finish = MPI_Wtime(); - UBLOG(logINFO, "MPIIOMigrationCoProcessor::writeShearStressValArray time: " << finish - start << " s"); - } - - delete[] dataSetSmallArray; -} - -void MPIIOMigrationCoProcessor::writeRelaxationFactor(int step) -{ - int rank, size; - MPI_Comm_rank(MPI_COMM_WORLD, &rank); - MPI_Comm_size(MPI_COMM_WORLD, &size); - - int blocksCount = 0; // quantity of blocks in the grid, max 2147483648 blocks! - - std::vector<SPtr<Block3D>> blocksVector[25]; - int minInitLevel = this->grid->getCoarsestInitializedLevel(); - int maxInitLevel = this->grid->getFinestInitializedLevel(); - for (int level = minInitLevel; level <= maxInitLevel; level++) - { - grid->getBlocks(level, rank, blocksVector[level]); - blocksCount += static_cast<int>(blocksVector[level].size()); - } - - DataSetSmallMigration* dataSetSmallArray = new DataSetSmallMigration[blocksCount]; - std::vector<double> doubleValuesArray; // double-values (arrays of f's) in all blocks - dataSetParam dataSetParamStr; - - if (comm->isRoot()) - { - UBLOG(logINFO, "MPIIOMigrationCoProcessor::writeRelaxationFactor start collect data rank = " << rank); - UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); - } - - bool firstBlock = true; - size_t doubleCountInBlock = 0; - int ic = 0; - for (int level = minInitLevel; level <= maxInitLevel; level++) - { - for (SPtr<Block3D> block : blocksVector[level]) // blocks of the current level - { - dataSetSmallArray[ic].globalID = block->getGlobalID(); // id of the block needed to find it while regenerating the grid - - SPtr< CbArray3D<LBMReal, IndexerX3X2X1> > relaxationFactor3DPtr = block->getKernel()->getDataSet()->getRelaxationFactor(); - - if (firstBlock) // when first (any) valid block... - { - //if (relaxationFactor3DPtr) - //{ - dataSetParamStr.nx1 = dataSetParamStr.nx2 = dataSetParamStr.nx3 = 0; - dataSetParamStr.nx[0] = static_cast<int>(relaxationFactor3DPtr->getNX1()); - dataSetParamStr.nx[1] = static_cast<int>(relaxationFactor3DPtr->getNX2()); - dataSetParamStr.nx[2] = static_cast<int>(relaxationFactor3DPtr->getNX3()); - dataSetParamStr.nx[3] = 1; - doubleCountInBlock = dataSetParamStr.nx[0] * dataSetParamStr.nx[1] * dataSetParamStr.nx[2] * dataSetParamStr.nx[3]; - //} - //else - // break; - - firstBlock = false; - } - - if (relaxationFactor3DPtr && (dataSetParamStr.nx[0]>0) && (dataSetParamStr.nx[1]>0) && (dataSetParamStr.nx[2]>0)) - doubleValuesArray.insert(doubleValuesArray.end(), relaxationFactor3DPtr->getDataVector().begin(), relaxationFactor3DPtr->getDataVector().end()); - - ic++; - } - } - - // register new MPI-types depending on the block-specific information - MPI_Type_contiguous(doubleCountInBlock, MPI_DOUBLE, &dataSetDoubleType); - MPI_Type_commit(&dataSetDoubleType); - - if (comm->isRoot()) - { - UBLOG(logINFO, "MPIIOMigrationCoProcessor::writeRelaxationFactor start MPI IO rank = " << rank); - UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); - } - - double start, finish; - if (comm->isRoot()) start = MPI_Wtime(); - - MPI_Info info = MPI_INFO_NULL; - -#ifdef HLRN_LUSTRE - MPI_Info_create(&info); - MPI_Info_set(info, "striping_factor", "40"); - MPI_Info_set(info, "striping_unit", "4M"); -#endif - - MPI_File file_handler; - std::string filename = path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + "/cpRelaxationFactor.bin"; - int rc = MPI_File_open(MPI_COMM_WORLD, filename.c_str(), MPI_MODE_CREATE | MPI_MODE_WRONLY, info, &file_handler); - if (rc != MPI_SUCCESS) throw UbException(UB_EXARGS, "couldn't open file " + filename); - - // each process writes common parameters of a dataSet - MPI_File_write_at(file_handler, 0, &dataSetParamStr, 1, dataSetParamType, MPI_STATUS_IGNORE); - - MPI_Offset write_offset; - size_t sizeofOneDataSet = sizeof(DataSetSmallMigration) + doubleCountInBlock * sizeof(double); - - for (size_t nb = 0; nb < blocksCount; nb++) - { - write_offset = (MPI_Offset)(sizeof(dataSetParam) + dataSetSmallArray[nb].globalID * sizeofOneDataSet); - MPI_File_write_at(file_handler, write_offset, &dataSetSmallArray[nb], 1, dataSetSmallType, MPI_STATUS_IGNORE); - MPI_File_write_at(file_handler, (MPI_Offset)(write_offset + sizeof(DataSetSmallMigration)), &doubleValuesArray[nb * doubleCountInBlock], 1, dataSetDoubleType, MPI_STATUS_IGNORE); - } - - MPI_File_sync(file_handler); - MPI_File_close(&file_handler); - MPI_Type_free(&dataSetDoubleType); - - if (comm->isRoot()) - { - finish = MPI_Wtime(); - UBLOG(logINFO, "MPIIOMigrationCoProcessor::writeRelaxationFactor time: " << finish - start << " s"); - } - - delete[] dataSetSmallArray; -} -*/ -void MPIIOMigrationCoProcessor::writeBoundaryConds(int step) -{ - int rank, size; - MPI_Comm_rank(MPI_COMM_WORLD, &rank); - MPI_Comm_size(MPI_COMM_WORLD, &size); - - if (comm->isRoot()) - { - UBLOG(logINFO, "MPIIOMigrationCoProcessor::writeBoundaryConds start collect data rank = " << rank); - UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); - } - - int blocksCount = 0; // quantity of blocks, that belong to this process - size_t allBytesCount = 0; // quantity of bytes, that one process writes to the file - size_t count_boundCond = 0; // how many BoundaryConditions in all blocks - int count_indexContainer = 0; // how many indexContainer-values in all blocks - - std::vector<SPtr<Block3D>> blocksVector[25]; - int minInitLevel = this->grid->getCoarsestInitializedLevel(); - int maxInitLevel = this->grid->getFinestInitializedLevel(); - for (int level = minInitLevel; level <= maxInitLevel; level++) - { - grid->getBlocks(level, rank, blocksVector[level]); - blocksCount += static_cast<int>(blocksVector[level].size()); - } - - BCAddMigration* bcAddArray = new BCAddMigration[blocksCount]; - size_t* bytesCount = new size_t[blocksCount]; // quantity of bytes, that each block writes to the file - std::vector<BoundaryCondition>* bcVector = new std::vector<BoundaryCondition>[blocksCount]; - std::vector<int>* bcindexmatrixVector = new std::vector<int>[blocksCount]; - std::vector<int>* indexContainerVector = new std::vector<int>[blocksCount]; - - bool bcindexmatrixCountNotInit = true; - int ic = 0; - SPtr<BCArray3D> bcArr; - - for (int level = minInitLevel; level <= maxInitLevel; level++) - { - for (SPtr<Block3D> block : blocksVector[level]) // all the blocks of the current level - { - bcArr = block->getKernel()->getBCProcessor()->getBCArray(); - - bcAddArray[ic].globalID = block->getGlobalID(); // id of the block needed to find it while regenerating the grid - bcAddArray[ic].boundCond_count = 0; // how many BoundaryConditions in this block - bcAddArray[ic].indexContainer_count = 0; // how many indexContainer-values in this block - bytesCount[ic] = sizeof(BCAddMigration); - bcVector[ic].resize(0); - bcindexmatrixVector[ic].resize(0); - indexContainerVector[ic].resize(0); - - for (int bc = 0; bc<bcArr->getBCVectorSize(); bc++) - { - BoundaryCondition* bouCond = new BoundaryCondition(); - if (bcArr->bcvector[bc] == NULL) - { - memset(bouCond, 0, sizeof(BoundaryCondition)); - } - else - { - bouCond->noslipBoundaryFlags = bcArr->bcvector[bc]->getNoSlipBoundary(); - bouCond->slipBoundaryFlags = bcArr->bcvector[bc]->getSlipBoundary(); - bouCond->velocityBoundaryFlags = bcArr->bcvector[bc]->getVelocityBoundary(); - bouCond->densityBoundaryFlags = bcArr->bcvector[bc]->getDensityBoundary(); - bouCond->wallModelBoundaryFlags = bcArr->bcvector[bc]->getWallModelBoundary(); - bouCond->bcVelocityX1 = (float) bcArr->bcvector[bc]->getBoundaryVelocityX1(); - bouCond->bcVelocityX2 = (float) bcArr->bcvector[bc]->getBoundaryVelocityX2(); - bouCond->bcVelocityX3 = (float) bcArr->bcvector[bc]->getBoundaryVelocityX3(); - bouCond->bcDensity = (float) bcArr->bcvector[bc]->getBoundaryDensity(); - bouCond->bcLodiDensity = (float) bcArr->bcvector[bc]->getDensityLodiDensity(); - bouCond->bcLodiVelocityX1 = (float) bcArr->bcvector[bc]->getDensityLodiVelocityX1(); - bouCond->bcLodiVelocityX2 = (float) bcArr->bcvector[bc]->getDensityLodiVelocityX2(); - bouCond->bcLodiVelocityX3 = (float) bcArr->bcvector[bc]->getDensityLodiVelocityX3(); - bouCond->bcLodiLentgh = (float) bcArr->bcvector[bc]->getDensityLodiLength(); - bouCond->nx1 = (float) bcArr->bcvector[bc]->nx1; - bouCond->nx2 = (float) bcArr->bcvector[bc]->nx2; - bouCond->nx3 = (float) bcArr->bcvector[bc]->nx3; - for (int iq = 0; iq<26; iq++) - bouCond->q[iq] = (float) bcArr->bcvector[bc]->getQ(iq); - bouCond->algorithmType = bcArr->bcvector[bc]->getBcAlgorithmType(); - } - - bcVector[ic].push_back(*bouCond); - bcAddArray[ic].boundCond_count++; - count_boundCond++; - bytesCount[ic] += sizeof(BoundaryCondition); - } - - if (bcindexmatrixCountNotInit) - { - boundCondParamStr.nx1 = static_cast<int>(bcArr->bcindexmatrix.getNX1()); - boundCondParamStr.nx2 = static_cast<int>(bcArr->bcindexmatrix.getNX2()); - boundCondParamStr.nx3 = static_cast<int>(bcArr->bcindexmatrix.getNX3()); - boundCondParamStr.bcindexmatrixCount = static_cast<int>(bcArr->bcindexmatrix.getDataVector().size()); - bcindexmatrixCountNotInit = false; - } - bcindexmatrixVector[ic].insert(bcindexmatrixVector[ic].begin(), bcArr->bcindexmatrix.getDataVector().begin(), bcArr->bcindexmatrix.getDataVector().end()); - bytesCount[ic] += boundCondParamStr.bcindexmatrixCount * sizeof(int); - - indexContainerVector[ic].insert(indexContainerVector[ic].begin(), bcArr->indexContainer.begin(), bcArr->indexContainer.end()); - bcAddArray[ic].indexContainer_count = static_cast<int>(bcArr->indexContainer.size()); - count_indexContainer += bcAddArray[ic].indexContainer_count; - bytesCount[ic] += bcAddArray[ic].indexContainer_count * sizeof(int); - - allBytesCount += bytesCount[ic]; - - ic++; - } - } - - MPI_Type_contiguous(boundCondParamStr.bcindexmatrixCount, MPI_INT, &bcindexmatrixType); - MPI_Type_commit(&bcindexmatrixType); - - if (comm->isRoot()) - { - UBLOG(logINFO, "MPIIOMigrationCoProcessor::writeBoundaryConds start MPI IO rank = " << rank); - UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); - } - - double start, finish; - if (comm->isRoot()) start = MPI_Wtime(); - - MPI_Info info = MPI_INFO_NULL; - //MPI_Info_create (&info); - //MPI_Info_set(info,"romio_cb_write","enable"); - //MPI_Info_set(info,"cb_buffer_size","4194304"); - //MPI_Info_set(info,"striping_unit","4194304"); - - MPI_File file_handler; - std::string filename = path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + "/cpBC.bin"; - int rc = MPI_File_open(MPI_COMM_WORLD, filename.c_str(), MPI_MODE_CREATE | MPI_MODE_WRONLY, info, &file_handler); - if (rc != MPI_SUCCESS) throw UbException(UB_EXARGS, "couldn't open file " + filename); - - MPI_Offset write_offset = (MPI_Offset)(sizeof(boundCondParam) + grid->getNumberOfBlocks() * sizeof(size_t)); - size_t next_file_offset = 0; - if (size > 1) - { - if (rank == 0) - { - next_file_offset = write_offset + allBytesCount; - MPI_Send(&next_file_offset, 1, MPI_LONG_LONG_INT, 1, 5, MPI_COMM_WORLD); - } - else - { - MPI_Recv(&write_offset, 1, MPI_LONG_LONG_INT, rank - 1, 5, MPI_COMM_WORLD, MPI_STATUS_IGNORE); - next_file_offset = write_offset + allBytesCount; - if (rank < size - 1) - MPI_Send(&next_file_offset, 1, MPI_LONG_LONG_INT, rank + 1, 5, MPI_COMM_WORLD); - } - } - - MPI_File_write_at(file_handler, 0, &boundCondParamStr, 1, boundCondParamType, MPI_STATUS_IGNORE); - - MPI_Offset write_offsetIndex; - - for (int nb = 0; nb < blocksCount; nb++) - { - write_offsetIndex = (MPI_Offset)(sizeof(boundCondParam) + bcAddArray[nb].globalID * sizeof(size_t)); - MPI_File_write_at(file_handler, write_offsetIndex, &write_offset, 1, MPI_LONG_LONG_INT, MPI_STATUS_IGNORE); - - MPI_File_write_at(file_handler, write_offset, &bcAddArray[nb], 1, boundCondTypeAdd, MPI_STATUS_IGNORE); - if (bcVector[nb].size() > 0) - MPI_File_write_at(file_handler, (MPI_Offset)(write_offset + sizeof(BCAddMigration)), &bcVector[nb][0], bcAddArray[nb].boundCond_count, boundCondType, MPI_STATUS_IGNORE); - - if (bcindexmatrixVector[nb].size() > 0) - MPI_File_write_at(file_handler, (MPI_Offset)(write_offset + sizeof(BCAddMigration) + bcAddArray[nb].boundCond_count * sizeof(BoundaryCondition)), - &bcindexmatrixVector[nb][0], 1, bcindexmatrixType, MPI_STATUS_IGNORE); - - if (indexContainerVector[nb].size() > 0) - MPI_File_write_at(file_handler, (MPI_Offset)(write_offset + sizeof(BCAddMigration) + bcAddArray[nb].boundCond_count * sizeof(BoundaryCondition) + boundCondParamStr.bcindexmatrixCount * sizeof(int)), - &indexContainerVector[nb][0], bcAddArray[nb].indexContainer_count, MPI_INT, MPI_STATUS_IGNORE); - - write_offset += bytesCount[nb]; - } - - MPI_File_sync(file_handler); - MPI_File_close(&file_handler); - MPI_Type_free(&bcindexmatrixType); - - if (comm->isRoot()) - { - finish = MPI_Wtime(); - UBLOG(logINFO, "MPIIOMigrationCoProcessor::writeBoundaryConds time: " << finish - start << " s"); - } - - delete[] bcAddArray; - delete[] bytesCount; - delete[] bcVector; - delete[] bcindexmatrixVector; - delete[] indexContainerVector; -} - -//------------------------------------------- READ ----------------------------------------------- -void MPIIOMigrationCoProcessor::restart(int step) -{ - if (comm->isRoot()) UBLOG(logINFO, "MPIIOMigrationCoProcessor restart step: " << step); - if (comm->isRoot()) UBLOG(logINFO, "Load check point - start"); - - readBlocks(step); - - SPtr<Grid3DVisitor> metisVisitor(new MetisPartitioningGridVisitor(comm, MetisPartitioningGridVisitor::LevelBased, D3Q27System::BSW, MetisPartitioner::KWAY)); - grid->accept(metisVisitor); - - readDataSet(step); - readBoundaryConds(step); - - grid->setTimeStep(step); - - if (comm->isRoot()) UBLOG(logINFO, "Load check point - end"); -} - -void MPIIOMigrationCoProcessor::readBlocks(int step) -{ - MPIIOCoProcessor::readBlocks(step); -} - -void MPIIOMigrationCoProcessor::readDataSet(int step) -{ - int rank, size; - MPI_Comm_rank(MPI_COMM_WORLD, &rank); - MPI_Comm_size(MPI_COMM_WORLD, &size); - - if (comm->isRoot()) - { - UBLOG(logINFO, "MPIIOMigrationCoProcessor::readDataSet start MPI IO rank = " << rank); - UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); - } - double start, finish; - if (comm->isRoot()) start = MPI_Wtime(); - - size_t blocksCount = 0; // quantity of the blocks, that belong to this process - dataSetParam dataSetParamStr1, dataSetParamStr2, dataSetParamStr3; - - // read from the grid the blocks, that belong to this process - std::vector<SPtr<Block3D>> blocksVector[25]; - int minInitLevel = this->grid->getCoarsestInitializedLevel(); - int maxInitLevel = this->grid->getFinestInitializedLevel(); - for (int level = minInitLevel; level <= maxInitLevel; level++) - { - grid->getBlocks(level, rank, blocksVector[level]); - blocksCount += static_cast<int>(blocksVector[level].size()); - } - - DataSetMigration* dataSetArray = new DataSetMigration[blocksCount]; - - MPI_File file_handler; - std::string filename = path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + "/cpDataSet.bin"; - int rc = MPI_File_open(MPI_COMM_WORLD, filename.c_str(), MPI_MODE_RDONLY, MPI_INFO_NULL, &file_handler); - if (rc != MPI_SUCCESS) throw UbException(UB_EXARGS, "couldn't open file " + filename); - - MPI_File_read_at(file_handler, (MPI_Offset)0, &dataSetParamStr1, 1, dataSetParamType, MPI_STATUS_IGNORE); - MPI_File_read_at(file_handler, (MPI_Offset)(sizeof(dataSetParam)), &dataSetParamStr2, 1, dataSetParamType, MPI_STATUS_IGNORE); - MPI_File_read_at(file_handler, (MPI_Offset)(2 * sizeof(dataSetParam)), &dataSetParamStr3, 1, dataSetParamType, MPI_STATUS_IGNORE); - - size_t doubleCountInBlock = dataSetParamStr1.nx[0] * dataSetParamStr1.nx[1] * dataSetParamStr1.nx[2] * dataSetParamStr1.nx[3] + - dataSetParamStr2.nx[0] * dataSetParamStr2.nx[1] * dataSetParamStr2.nx[2] * dataSetParamStr2.nx[3] + - dataSetParamStr3.nx[0] * dataSetParamStr3.nx[1] * dataSetParamStr3.nx[2] * dataSetParamStr3.nx[3]; - std::vector<double> doubleValuesArray(blocksCount * doubleCountInBlock); // double-values in all blocks - - // define MPI_types depending on the block-specific information - MPI_Type_contiguous(int(doubleCountInBlock), MPI_DOUBLE, &dataSetDoubleType); - MPI_Type_commit(&dataSetDoubleType); - - size_t ic = 0; - MPI_Offset read_offset; - size_t sizeofOneDataSet = size_t(sizeof(DataSetMigration) + doubleCountInBlock * sizeof(double)); - - for (int level = minInitLevel; level <= maxInitLevel; level++) - { - for (SPtr<Block3D> block : blocksVector[level]) // blocks of the current level - { - read_offset = (MPI_Offset)(3 * sizeof(dataSetParam) + block->getGlobalID() * sizeofOneDataSet); - MPI_File_read_at(file_handler, read_offset, &dataSetArray[ic], 1, dataSetType, MPI_STATUS_IGNORE); - MPI_File_read_at(file_handler, (MPI_Offset)(read_offset + sizeof(DataSetMigration)), &doubleValuesArray[ic * doubleCountInBlock], 1, dataSetDoubleType, MPI_STATUS_IGNORE); - ic++; - } - } - - MPI_File_close(&file_handler); - MPI_Type_free(&dataSetDoubleType); + std::vector<double> doubleValuesArray; // double-values (arrays of f's) in all blocks + dataSetParam dataSetParamStr; if (comm->isRoot()) { - finish = MPI_Wtime(); - UBLOG(logINFO, "MPIIOMigrationCoProcessor::readDataSet time: " << finish - start << " s"); - UBLOG(logINFO, "MPIIOMigrationCoProcessor::readDataSet start of restore of data, rank = " << rank); - UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); + UBLOG(logINFO, "MPIIOMigrationCoProcessor::writeShearStressValArray start collect data rank = " << rank); + UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / +1073741824.0 << " GB"); } - size_t index = 0, vectorSize = 0; - std::vector<double> vectorsOfValues1, vectorsOfValues2, vectorsOfValues3; - - for (int n = 0; n < blocksCount; n++) + bool firstBlock = true; + size_t doubleCountInBlock = 0; + int ic = 0; + for (int level = minInitLevel; level <= maxInitLevel; level++) { - vectorSize = dataSetParamStr1.nx[0] * dataSetParamStr1.nx[1] * dataSetParamStr1.nx[2] * dataSetParamStr1.nx[3]; - vectorsOfValues1.assign(doubleValuesArray.data() + index, doubleValuesArray.data() + index + vectorSize); - index += vectorSize; - - vectorSize = dataSetParamStr2.nx[0] * dataSetParamStr2.nx[1] * dataSetParamStr2.nx[2] * dataSetParamStr2.nx[3]; - vectorsOfValues2.assign(doubleValuesArray.data() + index, doubleValuesArray.data() + index + vectorSize); - index += vectorSize; + for (SPtr<Block3D> block : blocksVector[level]) // blocks of the current level + { + dataSetSmallArray[ic].globalID = block->getGlobalID(); // id of the block needed to find it while +regenerating the grid - vectorSize = dataSetParamStr3.nx[0] * dataSetParamStr3.nx[1] * dataSetParamStr3.nx[2] * dataSetParamStr3.nx[3]; - vectorsOfValues3.assign(doubleValuesArray.data() + index, doubleValuesArray.data() + index + vectorSize); - index += vectorSize; + SPtr< CbArray4D<LBMReal, IndexerX4X3X2X1> > ShearStressValArray3DPtr = +block->getKernel()->getDataSet()->getShearStressValues(); - SPtr<DistributionArray3D> mFdistributions(new D3Q27EsoTwist3DSplittedVector()); + if (firstBlock) // when first (any) valid block... + { + //if (ShearStressValArray3DPtr) + //{ + dataSetParamStr.nx1 = dataSetParamStr.nx2 = dataSetParamStr.nx3 = 0; + dataSetParamStr.nx[0] = static_cast<int>(ShearStressValArray3DPtr->getNX1()); + dataSetParamStr.nx[1] = static_cast<int>(ShearStressValArray3DPtr->getNX2()); + dataSetParamStr.nx[2] = static_cast<int>(ShearStressValArray3DPtr->getNX3()); + dataSetParamStr.nx[3] = static_cast<int>(ShearStressValArray3DPtr->getNX4()); + doubleCountInBlock = dataSetParamStr.nx[0] * dataSetParamStr.nx[1] * dataSetParamStr.nx[2] * +dataSetParamStr.nx[3]; + //} + //else + // break; - dynamicPointerCast<D3Q27EsoTwist3DSplittedVector>(mFdistributions)->setLocalDistributions(CbArray4D<LBMReal, IndexerX4X3X2X1>::CbArray4DPtr(new CbArray4D<LBMReal, IndexerX4X3X2X1>(vectorsOfValues1, dataSetParamStr1.nx[0], dataSetParamStr1.nx[1], dataSetParamStr1.nx[2], dataSetParamStr1.nx[3]))); - dynamicPointerCast<D3Q27EsoTwist3DSplittedVector>(mFdistributions)->setNonLocalDistributions(CbArray4D<LBMReal, IndexerX4X3X2X1>::CbArray4DPtr(new CbArray4D<LBMReal, IndexerX4X3X2X1>(vectorsOfValues2, dataSetParamStr2.nx[0], dataSetParamStr2.nx[1], dataSetParamStr2.nx[2], dataSetParamStr2.nx[3]))); - dynamicPointerCast<D3Q27EsoTwist3DSplittedVector>(mFdistributions)->setZeroDistributions(CbArray3D<LBMReal, IndexerX3X2X1>::CbArray3DPtr(new CbArray3D<LBMReal, IndexerX3X2X1>(vectorsOfValues3, dataSetParamStr3.nx[0], dataSetParamStr3.nx[1], dataSetParamStr3.nx[2]))); + firstBlock = false; + } - dynamicPointerCast<D3Q27EsoTwist3DSplittedVector>(mFdistributions)->setNX1(dataSetParamStr1.nx1); - dynamicPointerCast<D3Q27EsoTwist3DSplittedVector>(mFdistributions)->setNX2(dataSetParamStr1.nx2); - dynamicPointerCast<D3Q27EsoTwist3DSplittedVector>(mFdistributions)->setNX3(dataSetParamStr1.nx3); + if (ShearStressValArray3DPtr && (dataSetParamStr.nx[0]>0) && (dataSetParamStr.nx[1]>0) && +(dataSetParamStr.nx[2]>0) && (dataSetParamStr.nx[3]>0)) doubleValuesArray.insert(doubleValuesArray.end(), +ShearStressValArray3DPtr->getDataVector().begin(), ShearStressValArray3DPtr->getDataVector().end()); - // find the nesessary block and fill it - SPtr<Block3D> block = grid->getBlock(dataSetArray[n].globalID); - this->lbmKernel->setBlock(block); - SPtr<LBMKernel> kernel = this->lbmKernel->clone(); - kernel->setGhostLayerWidth(dataSetArray[n].ghostLayerWidth); - kernel->setCollisionFactor(dataSetArray[n].collFactor); - kernel->setDeltaT(dataSetArray[n].deltaT); - kernel->setCompressible(dataSetArray[n].compressible); - kernel->setWithForcing(dataSetArray[n].withForcing); - SPtr<DataSet3D> dataSetPtr = SPtr<DataSet3D>(new DataSet3D()); - dataSetPtr->setFdistributions(mFdistributions); - kernel->setDataSet(dataSetPtr); - block->setKernel(kernel); + ic++; + } } + // register new MPI-types depending on the block-specific information + MPI_Type_contiguous(doubleCountInBlock, MPI_DOUBLE, &dataSetDoubleType); + MPI_Type_commit(&dataSetDoubleType); if (comm->isRoot()) { - UBLOG(logINFO, "MPIIOMigrationCoProcessor::readDataSet end of restore of data, rank = " << rank); - UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); + UBLOG(logINFO, "MPIIOMigrationCoProcessor::writeShearStressValArray start MPI IO rank = " << rank); + UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / +1073741824.0 << " GB"); } - delete[] dataSetArray; + double start, finish; + if (comm->isRoot()) start = MPI_Wtime(); + + MPI_Info info = MPI_INFO_NULL; - //------------------------------------------------------------- +#ifdef HLRN_LUSTRE + MPI_Info_create(&info); + MPI_Info_set(info, "striping_factor", "40"); + MPI_Info_set(info, "striping_unit", "4M"); +#endif - DSArraysPresence arrPresence; - MPI_File file_handler1; - std::string filename1 = path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + "/cpArrays.bin"; - rc = MPI_File_open(MPI_COMM_WORLD, filename1.c_str(), MPI_MODE_RDONLY, MPI_INFO_NULL, &file_handler1); - if (rc != MPI_SUCCESS) throw UbException(UB_EXARGS, "couldn't open file " + filename1); - MPI_File_read_at(file_handler1, (MPI_Offset)0, &arrPresence, 1, arrayPresenceType, MPI_STATUS_IGNORE); - MPI_File_close(&file_handler1); + MPI_File file_handler; + std::string filename = path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + "/cpShearStressValArray.bin"; + int rc = MPI_File_open(MPI_COMM_WORLD, filename.c_str(), MPI_MODE_CREATE | MPI_MODE_WRONLY, info, &file_handler); + if (rc != MPI_SUCCESS) throw UbException(UB_EXARGS, "couldn't open file " + filename); - if (arrPresence.isAverageDensityArrayPresent) - readArray(step, AverageDensity, std::string("/cpAverageDensityArray.bin")); - //readAverageDensityArray(step); + // each process writes common parameters of a dataSet + MPI_File_write_at(file_handler, 0, &dataSetParamStr, 1, dataSetParamType, MPI_STATUS_IGNORE); - if (arrPresence.isAverageVelocityArrayPresent) - readArray(step, AverageVelocity, std::string("/cpAverageVelocityArray.bin")); - // readAverageVelocityArray(step); + MPI_Offset write_offset; + size_t sizeofOneDataSet = sizeof(DataSetSmallMigration) + doubleCountInBlock * sizeof(double); - if (arrPresence.isAverageFluktuationsArrayPresent) - readArray(step, AverageFluktuations, std::string("/cpAverageFluktuationsArray.bin")); - // readAverageFluktuationsArray(step); + for (size_t nb = 0; nb < blocksCount; nb++) + { + write_offset = (MPI_Offset)(sizeof(dataSetParam) + dataSetSmallArray[nb].globalID * sizeofOneDataSet); + MPI_File_write_at(file_handler, write_offset, &dataSetSmallArray[nb], 1, dataSetSmallType, MPI_STATUS_IGNORE); + MPI_File_write_at(file_handler, (MPI_Offset)(write_offset + sizeof(DataSetSmallMigration)), &doubleValuesArray[nb +* doubleCountInBlock], 1, dataSetDoubleType, MPI_STATUS_IGNORE); + } - if (arrPresence.isAverageTripleArrayPresent) - readArray(step, AverageTriple, std::string("/cpAverageTripleArray.bin")); - // readAverageTripleArray(step); + MPI_File_sync(file_handler); + MPI_File_close(&file_handler); + MPI_Type_free(&dataSetDoubleType); - if (arrPresence.isShearStressValArrayPresent) - readArray(step, ShearStressVal, std::string("/cpShearStressValArray.bin")); - // readShearStressValArray(step); + if (comm->isRoot()) + { + finish = MPI_Wtime(); + UBLOG(logINFO, "MPIIOMigrationCoProcessor::writeShearStressValArray time: " << finish - start << " s"); + } - if (arrPresence.isRelaxationFactorPresent) - readArray(step, RelaxationFactor, std::string("/cpRelaxationFactor.bin")); - // readRelaxationFactor(step); + delete[] dataSetSmallArray; } -void MPIIOMigrationCoProcessor::readArray(int step, Arrays arrType, std::string fname) +void MPIIOMigrationCoProcessor::writeRelaxationFactor(int step) { int rank, size; MPI_Comm_rank(MPI_COMM_WORLD, &rank); MPI_Comm_size(MPI_COMM_WORLD, &size); - if (comm->isRoot()) - { - UBLOG(logINFO, "MPIIOMigrationCoProcessor::readArray start MPI IO rank = " << rank); - UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); - } - double start, finish; - if (comm->isRoot()) start = MPI_Wtime(); - - MPI_File file_handler; - std::string filename = path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + fname; - int rc = MPI_File_open(MPI_COMM_WORLD, filename.c_str(), MPI_MODE_RDONLY, MPI_INFO_NULL, &file_handler); - if (rc != MPI_SUCCESS) throw UbException(UB_EXARGS, "couldn't open file " + filename); - - size_t blocksCount = 0; - dataSetParam dataSetParamStr; - memset(&dataSetParamStr, 0, sizeof(dataSetParam)); + int blocksCount = 0; // quantity of blocks in the grid, max 2147483648 blocks! - // read from the grid the blocks, that belong to this process std::vector<SPtr<Block3D>> blocksVector[25]; int minInitLevel = this->grid->getCoarsestInitializedLevel(); int maxInitLevel = this->grid->getFinestInitializedLevel(); @@ -1651,96 +1210,635 @@ void MPIIOMigrationCoProcessor::readArray(int step, Arrays arrType, std::string blocksCount += static_cast<int>(blocksVector[level].size()); } - MPI_File_read_at(file_handler, (MPI_Offset)0, &dataSetParamStr, 1, dataSetParamType, MPI_STATUS_IGNORE); - DataSetSmallMigration* dataSetSmallArray = new DataSetSmallMigration[blocksCount]; - size_t doubleCountInBlock = dataSetParamStr.nx[0] * dataSetParamStr.nx[1] * dataSetParamStr.nx[2] * dataSetParamStr.nx[3]; - std::vector<double> doubleValuesArray(blocksCount * doubleCountInBlock); // double-values in all blocks - - // define MPI_types depending on the block-specific information - MPI_Type_contiguous(int(doubleCountInBlock), MPI_DOUBLE, &dataSetDoubleType); - MPI_Type_commit(&dataSetDoubleType); + std::vector<double> doubleValuesArray; // double-values (arrays of f's) in all blocks + dataSetParam dataSetParamStr; - size_t ic = 0; - MPI_Offset read_offset; - size_t sizeofOneDataSet = size_t(sizeof(DataSetSmallMigration) + doubleCountInBlock * sizeof(double)); + if (comm->isRoot()) + { + UBLOG(logINFO, "MPIIOMigrationCoProcessor::writeRelaxationFactor start collect data rank = " << rank); + UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / +1073741824.0 << " GB"); + } + bool firstBlock = true; + size_t doubleCountInBlock = 0; + int ic = 0; for (int level = minInitLevel; level <= maxInitLevel; level++) { for (SPtr<Block3D> block : blocksVector[level]) // blocks of the current level { - read_offset = (MPI_Offset)(sizeof(dataSetParam) + block->getGlobalID() * sizeofOneDataSet); - MPI_File_read_at(file_handler, read_offset, &dataSetSmallArray[ic], 1, dataSetSmallType, MPI_STATUS_IGNORE); - MPI_File_read_at(file_handler, (MPI_Offset)(read_offset + sizeof(DataSetSmallMigration)), &doubleValuesArray[ic * doubleCountInBlock], 1, dataSetDoubleType, MPI_STATUS_IGNORE); + dataSetSmallArray[ic].globalID = block->getGlobalID(); // id of the block needed to find it while +regenerating the grid + + SPtr< CbArray3D<LBMReal, IndexerX3X2X1> > relaxationFactor3DPtr = +block->getKernel()->getDataSet()->getRelaxationFactor(); + + if (firstBlock) // when first (any) valid block... + { + //if (relaxationFactor3DPtr) + //{ + dataSetParamStr.nx1 = dataSetParamStr.nx2 = dataSetParamStr.nx3 = 0; + dataSetParamStr.nx[0] = static_cast<int>(relaxationFactor3DPtr->getNX1()); + dataSetParamStr.nx[1] = static_cast<int>(relaxationFactor3DPtr->getNX2()); + dataSetParamStr.nx[2] = static_cast<int>(relaxationFactor3DPtr->getNX3()); + dataSetParamStr.nx[3] = 1; + doubleCountInBlock = dataSetParamStr.nx[0] * dataSetParamStr.nx[1] * dataSetParamStr.nx[2] * +dataSetParamStr.nx[3]; + //} + //else + // break; + + firstBlock = false; + } + + if (relaxationFactor3DPtr && (dataSetParamStr.nx[0]>0) && (dataSetParamStr.nx[1]>0) && +(dataSetParamStr.nx[2]>0)) doubleValuesArray.insert(doubleValuesArray.end(), +relaxationFactor3DPtr->getDataVector().begin(), relaxationFactor3DPtr->getDataVector().end()); + ic++; } } - MPI_File_close(&file_handler); - MPI_Type_free(&dataSetDoubleType); + // register new MPI-types depending on the block-specific information + MPI_Type_contiguous(doubleCountInBlock, MPI_DOUBLE, &dataSetDoubleType); + MPI_Type_commit(&dataSetDoubleType); if (comm->isRoot()) { - finish = MPI_Wtime(); - UBLOG(logINFO, "MPIIOMigrationCoProcessor::readArray readArray: " << finish - start << " s"); - UBLOG(logINFO, "MPIIOMigrationCoProcessor::readArray start of restore of data, rank = " << rank); - UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); + UBLOG(logINFO, "MPIIOMigrationCoProcessor::writeRelaxationFactor start MPI IO rank = " << rank); + UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / +1073741824.0 << " GB"); } - //----------------------------- restore data --------------------------------- - size_t index = 0; - size_t nextVectorSize = dataSetParamStr.nx[0] * dataSetParamStr.nx[1] * dataSetParamStr.nx[2] * dataSetParamStr.nx[3]; - std::vector<double> vectorsOfValues; - for (int n = 0; n < blocksCount; n++) - { - SPtr<Block3D> block = grid->getBlock(dataSetSmallArray[n].globalID); + double start, finish; + if (comm->isRoot()) start = MPI_Wtime(); - vectorsOfValues.assign(doubleValuesArray.data() + index, doubleValuesArray.data() + index + nextVectorSize); - index += nextVectorSize; + MPI_Info info = MPI_INFO_NULL; - // fill arrays - SPtr<CbArray4D<LBMReal, IndexerX4X3X2X1>> ___4DArray; - SPtr<CbArray3D<LBMReal, IndexerX3X2X1>> ___3DArray; - - switch (arrType) { - case AverageDensity: - ___4DArray = CbArray4D<LBMReal, IndexerX4X3X2X1>::CbArray4DPtr(new CbArray4D<LBMReal, IndexerX4X3X2X1>(vectorsOfValues, dataSetParamStr.nx[0], dataSetParamStr.nx[1], dataSetParamStr.nx[2], dataSetParamStr.nx[3])); - block->getKernel()->getDataSet()->setAverageDensity(___4DArray); - break; - case AverageVelocity: - ___4DArray = CbArray4D<LBMReal, IndexerX4X3X2X1>::CbArray4DPtr(new CbArray4D<LBMReal, IndexerX4X3X2X1>(vectorsOfValues, dataSetParamStr.nx[0], dataSetParamStr.nx[1], dataSetParamStr.nx[2], dataSetParamStr.nx[3])); - block->getKernel()->getDataSet()->setAverageVelocity(___4DArray); - break; - case AverageFluktuations: - ___4DArray = CbArray4D<LBMReal, IndexerX4X3X2X1>::CbArray4DPtr(new CbArray4D<LBMReal, IndexerX4X3X2X1>(vectorsOfValues, dataSetParamStr.nx[0], dataSetParamStr.nx[1], dataSetParamStr.nx[2], dataSetParamStr.nx[3])); - block->getKernel()->getDataSet()->setAverageFluctuations(___4DArray); - break; - case AverageTriple: - ___4DArray = CbArray4D<LBMReal, IndexerX4X3X2X1>::CbArray4DPtr(new CbArray4D<LBMReal, IndexerX4X3X2X1>(vectorsOfValues, dataSetParamStr.nx[0], dataSetParamStr.nx[1], dataSetParamStr.nx[2], dataSetParamStr.nx[3])); - block->getKernel()->getDataSet()->setAverageTriplecorrelations(___4DArray); - break; - case ShearStressVal: - ___4DArray = CbArray4D<LBMReal, IndexerX4X3X2X1>::CbArray4DPtr(new CbArray4D<LBMReal, IndexerX4X3X2X1>(vectorsOfValues, dataSetParamStr.nx[0], dataSetParamStr.nx[1], dataSetParamStr.nx[2], dataSetParamStr.nx[3])); - block->getKernel()->getDataSet()->setShearStressValues(___4DArray); - break; - case RelaxationFactor: - ___3DArray = CbArray3D<LBMReal, IndexerX3X2X1>::CbArray3DPtr(new CbArray3D<LBMReal, IndexerX3X2X1>(vectorsOfValues, dataSetParamStr.nx[0], dataSetParamStr.nx[1], dataSetParamStr.nx[2])); - block->getKernel()->getDataSet()->setRelaxationFactor(___3DArray); - break; - default: - UB_THROW(UbException(UB_EXARGS, "MPIIOMigrationCoProcessor::readArray : array type does not exist!")); - break; - } +#ifdef HLRN_LUSTRE + MPI_Info_create(&info); + MPI_Info_set(info, "striping_factor", "40"); + MPI_Info_set(info, "striping_unit", "4M"); +#endif + + MPI_File file_handler; + std::string filename = path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + "/cpRelaxationFactor.bin"; + int rc = MPI_File_open(MPI_COMM_WORLD, filename.c_str(), MPI_MODE_CREATE | MPI_MODE_WRONLY, info, &file_handler); + if (rc != MPI_SUCCESS) throw UbException(UB_EXARGS, "couldn't open file " + filename); + + // each process writes common parameters of a dataSet + MPI_File_write_at(file_handler, 0, &dataSetParamStr, 1, dataSetParamType, MPI_STATUS_IGNORE); + + MPI_Offset write_offset; + size_t sizeofOneDataSet = sizeof(DataSetSmallMigration) + doubleCountInBlock * sizeof(double); + + for (size_t nb = 0; nb < blocksCount; nb++) + { + write_offset = (MPI_Offset)(sizeof(dataSetParam) + dataSetSmallArray[nb].globalID * sizeofOneDataSet); + MPI_File_write_at(file_handler, write_offset, &dataSetSmallArray[nb], 1, dataSetSmallType, MPI_STATUS_IGNORE); + MPI_File_write_at(file_handler, (MPI_Offset)(write_offset + sizeof(DataSetSmallMigration)), &doubleValuesArray[nb +* doubleCountInBlock], 1, dataSetDoubleType, MPI_STATUS_IGNORE); } + MPI_File_sync(file_handler); + MPI_File_close(&file_handler); + MPI_Type_free(&dataSetDoubleType); + if (comm->isRoot()) { - UBLOG(logINFO, "MPIIOMigrationCoProcessor::readArray end of restore of data, rank = " << rank); - UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); + finish = MPI_Wtime(); + UBLOG(logINFO, "MPIIOMigrationCoProcessor::writeRelaxationFactor time: " << finish - start << " s"); } delete[] dataSetSmallArray; } +*/ +void MPIIOMigrationCoProcessor::writeBoundaryConds(int step) +{ + int rank, size; + MPI_Comm_rank(MPI_COMM_WORLD, &rank); + MPI_Comm_size(MPI_COMM_WORLD, &size); + + if (comm->isRoot()) { + UBLOG(logINFO, "MPIIOMigrationCoProcessor::writeBoundaryConds start collect data rank = " << rank); + UBLOG(logINFO, "Physical Memory currently used by current process: " + << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); + } + + int blocksCount = 0; // quantity of blocks, that belong to this process + size_t allBytesCount = 0; // quantity of bytes, that one process writes to the file + size_t count_boundCond = 0; // how many BoundaryConditions in all blocks + int count_indexContainer = 0; // how many indexContainer-values in all blocks + + std::vector<SPtr<Block3D>> blocksVector[25]; + int minInitLevel = this->grid->getCoarsestInitializedLevel(); + int maxInitLevel = this->grid->getFinestInitializedLevel(); + for (int level = minInitLevel; level <= maxInitLevel; level++) { + grid->getBlocks(level, rank, blocksVector[level]); + blocksCount += static_cast<int>(blocksVector[level].size()); + } + + BCAddMigration *bcAddArray = new BCAddMigration[blocksCount]; + size_t *bytesCount = new size_t[blocksCount]; // quantity of bytes, that each block writes to the file + std::vector<BoundaryCondition> *bcVector = new std::vector<BoundaryCondition>[blocksCount]; + std::vector<int> *bcindexmatrixVector = new std::vector<int>[blocksCount]; + std::vector<int> *indexContainerVector = new std::vector<int>[blocksCount]; + + bool bcindexmatrixCountNotInit = true; + int ic = 0; + SPtr<BCArray3D> bcArr; + + for (int level = minInitLevel; level <= maxInitLevel; level++) { + for (SPtr<Block3D> block : blocksVector[level]) // all the blocks of the current level + { + bcArr = block->getKernel()->getBCProcessor()->getBCArray(); + + bcAddArray[ic].globalID = + block->getGlobalID(); // id of the block needed to find it while regenerating the grid + bcAddArray[ic].boundCond_count = 0; // how many BoundaryConditions in this block + bcAddArray[ic].indexContainer_count = 0; // how many indexContainer-values in this block + bytesCount[ic] = sizeof(BCAddMigration); + bcVector[ic].resize(0); + bcindexmatrixVector[ic].resize(0); + indexContainerVector[ic].resize(0); + + for (int bc = 0; bc < bcArr->getBCVectorSize(); bc++) { + BoundaryCondition *bouCond = new BoundaryCondition(); + if (bcArr->bcvector[bc] == NULL) { + memset(bouCond, 0, sizeof(BoundaryCondition)); + } else { + bouCond->noslipBoundaryFlags = bcArr->bcvector[bc]->getNoSlipBoundary(); + bouCond->slipBoundaryFlags = bcArr->bcvector[bc]->getSlipBoundary(); + bouCond->velocityBoundaryFlags = bcArr->bcvector[bc]->getVelocityBoundary(); + bouCond->densityBoundaryFlags = bcArr->bcvector[bc]->getDensityBoundary(); + bouCond->wallModelBoundaryFlags = bcArr->bcvector[bc]->getWallModelBoundary(); + bouCond->bcVelocityX1 = (float)bcArr->bcvector[bc]->getBoundaryVelocityX1(); + bouCond->bcVelocityX2 = (float)bcArr->bcvector[bc]->getBoundaryVelocityX2(); + bouCond->bcVelocityX3 = (float)bcArr->bcvector[bc]->getBoundaryVelocityX3(); + bouCond->bcDensity = (float)bcArr->bcvector[bc]->getBoundaryDensity(); + bouCond->bcLodiDensity = (float)bcArr->bcvector[bc]->getDensityLodiDensity(); + bouCond->bcLodiVelocityX1 = (float)bcArr->bcvector[bc]->getDensityLodiVelocityX1(); + bouCond->bcLodiVelocityX2 = (float)bcArr->bcvector[bc]->getDensityLodiVelocityX2(); + bouCond->bcLodiVelocityX3 = (float)bcArr->bcvector[bc]->getDensityLodiVelocityX3(); + bouCond->bcLodiLentgh = (float)bcArr->bcvector[bc]->getDensityLodiLength(); + bouCond->nx1 = (float)bcArr->bcvector[bc]->nx1; + bouCond->nx2 = (float)bcArr->bcvector[bc]->nx2; + bouCond->nx3 = (float)bcArr->bcvector[bc]->nx3; + for (int iq = 0; iq < 26; iq++) + bouCond->q[iq] = (float)bcArr->bcvector[bc]->getQ(iq); + bouCond->algorithmType = bcArr->bcvector[bc]->getBcAlgorithmType(); + } + + bcVector[ic].push_back(*bouCond); + bcAddArray[ic].boundCond_count++; + count_boundCond++; + bytesCount[ic] += sizeof(BoundaryCondition); + } + + if (bcindexmatrixCountNotInit) { + boundCondParamStr.nx1 = static_cast<int>(bcArr->bcindexmatrix.getNX1()); + boundCondParamStr.nx2 = static_cast<int>(bcArr->bcindexmatrix.getNX2()); + boundCondParamStr.nx3 = static_cast<int>(bcArr->bcindexmatrix.getNX3()); + boundCondParamStr.bcindexmatrixCount = static_cast<int>(bcArr->bcindexmatrix.getDataVector().size()); + bcindexmatrixCountNotInit = false; + } + bcindexmatrixVector[ic].insert(bcindexmatrixVector[ic].begin(), + bcArr->bcindexmatrix.getDataVector().begin(), + bcArr->bcindexmatrix.getDataVector().end()); + bytesCount[ic] += boundCondParamStr.bcindexmatrixCount * sizeof(int); + + indexContainerVector[ic].insert(indexContainerVector[ic].begin(), bcArr->indexContainer.begin(), + bcArr->indexContainer.end()); + bcAddArray[ic].indexContainer_count = static_cast<int>(bcArr->indexContainer.size()); + count_indexContainer += bcAddArray[ic].indexContainer_count; + bytesCount[ic] += bcAddArray[ic].indexContainer_count * sizeof(int); + + allBytesCount += bytesCount[ic]; + + ic++; + } + } + + MPI_Type_contiguous(boundCondParamStr.bcindexmatrixCount, MPI_INT, &bcindexmatrixType); + MPI_Type_commit(&bcindexmatrixType); + + if (comm->isRoot()) { + UBLOG(logINFO, "MPIIOMigrationCoProcessor::writeBoundaryConds start MPI IO rank = " << rank); + UBLOG(logINFO, "Physical Memory currently used by current process: " + << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); + } + + double start, finish; + if (comm->isRoot()) + start = MPI_Wtime(); + + MPI_Info info = MPI_INFO_NULL; + // MPI_Info_create (&info); + // MPI_Info_set(info,"romio_cb_write","enable"); + // MPI_Info_set(info,"cb_buffer_size","4194304"); + // MPI_Info_set(info,"striping_unit","4194304"); + + MPI_File file_handler; + std::string filename = path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + "/cpBC.bin"; + int rc = MPI_File_open(MPI_COMM_WORLD, filename.c_str(), MPI_MODE_CREATE | MPI_MODE_WRONLY, info, &file_handler); + if (rc != MPI_SUCCESS) + throw UbException(UB_EXARGS, "couldn't open file " + filename); + + MPI_Offset write_offset = (MPI_Offset)(sizeof(boundCondParam) + grid->getNumberOfBlocks() * sizeof(size_t)); + size_t next_file_offset = 0; + if (size > 1) { + if (rank == 0) { + next_file_offset = write_offset + allBytesCount; + MPI_Send(&next_file_offset, 1, MPI_LONG_LONG_INT, 1, 5, MPI_COMM_WORLD); + } else { + MPI_Recv(&write_offset, 1, MPI_LONG_LONG_INT, rank - 1, 5, MPI_COMM_WORLD, MPI_STATUS_IGNORE); + next_file_offset = write_offset + allBytesCount; + if (rank < size - 1) + MPI_Send(&next_file_offset, 1, MPI_LONG_LONG_INT, rank + 1, 5, MPI_COMM_WORLD); + } + } + + MPI_File_write_at(file_handler, 0, &boundCondParamStr, 1, boundCondParamType, MPI_STATUS_IGNORE); + + MPI_Offset write_offsetIndex; + + for (int nb = 0; nb < blocksCount; nb++) { + write_offsetIndex = (MPI_Offset)(sizeof(boundCondParam) + bcAddArray[nb].globalID * sizeof(size_t)); + MPI_File_write_at(file_handler, write_offsetIndex, &write_offset, 1, MPI_LONG_LONG_INT, MPI_STATUS_IGNORE); + + MPI_File_write_at(file_handler, write_offset, &bcAddArray[nb], 1, boundCondTypeAdd, MPI_STATUS_IGNORE); + if (bcVector[nb].size() > 0) + MPI_File_write_at(file_handler, (MPI_Offset)(write_offset + sizeof(BCAddMigration)), &bcVector[nb][0], + bcAddArray[nb].boundCond_count, boundCondType, MPI_STATUS_IGNORE); + + if (bcindexmatrixVector[nb].size() > 0) + MPI_File_write_at(file_handler, + (MPI_Offset)(write_offset + sizeof(BCAddMigration) + + bcAddArray[nb].boundCond_count * sizeof(BoundaryCondition)), + &bcindexmatrixVector[nb][0], 1, bcindexmatrixType, MPI_STATUS_IGNORE); + + if (indexContainerVector[nb].size() > 0) + MPI_File_write_at(file_handler, + (MPI_Offset)(write_offset + sizeof(BCAddMigration) + + bcAddArray[nb].boundCond_count * sizeof(BoundaryCondition) + + boundCondParamStr.bcindexmatrixCount * sizeof(int)), + &indexContainerVector[nb][0], bcAddArray[nb].indexContainer_count, MPI_INT, + MPI_STATUS_IGNORE); + + write_offset += bytesCount[nb]; + } + + MPI_File_sync(file_handler); + MPI_File_close(&file_handler); + MPI_Type_free(&bcindexmatrixType); + + if (comm->isRoot()) { + finish = MPI_Wtime(); + UBLOG(logINFO, "MPIIOMigrationCoProcessor::writeBoundaryConds time: " << finish - start << " s"); + } + + delete[] bcAddArray; + delete[] bytesCount; + delete[] bcVector; + delete[] bcindexmatrixVector; + delete[] indexContainerVector; +} + +//------------------------------------------- READ ----------------------------------------------- +void MPIIOMigrationCoProcessor::restart(int step) +{ + if (comm->isRoot()) + UBLOG(logINFO, "MPIIOMigrationCoProcessor restart step: " << step); + if (comm->isRoot()) + UBLOG(logINFO, "Load check point - start"); + + readBlocks(step); + + SPtr<Grid3DVisitor> metisVisitor(new MetisPartitioningGridVisitor(comm, MetisPartitioningGridVisitor::LevelBased, + D3Q27System::BSW, MetisPartitioner::KWAY)); + grid->accept(metisVisitor); + + readDataSet(step); + readBoundaryConds(step); + + grid->setTimeStep(step); + + if (comm->isRoot()) + UBLOG(logINFO, "Load check point - end"); +} + +void MPIIOMigrationCoProcessor::readBlocks(int step) { MPIIOCoProcessor::readBlocks(step); } + +void MPIIOMigrationCoProcessor::readDataSet(int step) +{ + int rank, size; + MPI_Comm_rank(MPI_COMM_WORLD, &rank); + MPI_Comm_size(MPI_COMM_WORLD, &size); + + if (comm->isRoot()) { + UBLOG(logINFO, "MPIIOMigrationCoProcessor::readDataSet start MPI IO rank = " << rank); + UBLOG(logINFO, "Physical Memory currently used by current process: " + << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); + } + double start, finish; + if (comm->isRoot()) + start = MPI_Wtime(); + + size_t blocksCount = 0; // quantity of the blocks, that belong to this process + dataSetParam dataSetParamStr1, dataSetParamStr2, dataSetParamStr3; + + // read from the grid the blocks, that belong to this process + std::vector<SPtr<Block3D>> blocksVector[25]; + int minInitLevel = this->grid->getCoarsestInitializedLevel(); + int maxInitLevel = this->grid->getFinestInitializedLevel(); + for (int level = minInitLevel; level <= maxInitLevel; level++) { + grid->getBlocks(level, rank, blocksVector[level]); + blocksCount += static_cast<int>(blocksVector[level].size()); + } + + DataSetMigration *dataSetArray = new DataSetMigration[blocksCount]; + + MPI_File file_handler; + std::string filename = path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + "/cpDataSet.bin"; + int rc = MPI_File_open(MPI_COMM_WORLD, filename.c_str(), MPI_MODE_RDONLY, MPI_INFO_NULL, &file_handler); + if (rc != MPI_SUCCESS) + throw UbException(UB_EXARGS, "couldn't open file " + filename); + + MPI_File_read_at(file_handler, (MPI_Offset)0, &dataSetParamStr1, 1, dataSetParamType, MPI_STATUS_IGNORE); + MPI_File_read_at(file_handler, (MPI_Offset)(sizeof(dataSetParam)), &dataSetParamStr2, 1, dataSetParamType, + MPI_STATUS_IGNORE); + MPI_File_read_at(file_handler, (MPI_Offset)(2 * sizeof(dataSetParam)), &dataSetParamStr3, 1, dataSetParamType, + MPI_STATUS_IGNORE); + + size_t doubleCountInBlock = + dataSetParamStr1.nx[0] * dataSetParamStr1.nx[1] * dataSetParamStr1.nx[2] * dataSetParamStr1.nx[3] + + dataSetParamStr2.nx[0] * dataSetParamStr2.nx[1] * dataSetParamStr2.nx[2] * dataSetParamStr2.nx[3] + + dataSetParamStr3.nx[0] * dataSetParamStr3.nx[1] * dataSetParamStr3.nx[2] * dataSetParamStr3.nx[3]; + std::vector<double> doubleValuesArray(blocksCount * doubleCountInBlock); // double-values in all blocks + + // define MPI_types depending on the block-specific information + MPI_Type_contiguous(int(doubleCountInBlock), MPI_DOUBLE, &dataSetDoubleType); + MPI_Type_commit(&dataSetDoubleType); + + size_t ic = 0; + MPI_Offset read_offset; + size_t sizeofOneDataSet = size_t(sizeof(DataSetMigration) + doubleCountInBlock * sizeof(double)); + + for (int level = minInitLevel; level <= maxInitLevel; level++) { + for (SPtr<Block3D> block : blocksVector[level]) // blocks of the current level + { + read_offset = (MPI_Offset)(3 * sizeof(dataSetParam) + block->getGlobalID() * sizeofOneDataSet); + MPI_File_read_at(file_handler, read_offset, &dataSetArray[ic], 1, dataSetType, MPI_STATUS_IGNORE); + MPI_File_read_at(file_handler, (MPI_Offset)(read_offset + sizeof(DataSetMigration)), + &doubleValuesArray[ic * doubleCountInBlock], 1, dataSetDoubleType, MPI_STATUS_IGNORE); + ic++; + } + } + + MPI_File_close(&file_handler); + MPI_Type_free(&dataSetDoubleType); + + if (comm->isRoot()) { + finish = MPI_Wtime(); + UBLOG(logINFO, "MPIIOMigrationCoProcessor::readDataSet time: " << finish - start << " s"); + UBLOG(logINFO, "MPIIOMigrationCoProcessor::readDataSet start of restore of data, rank = " << rank); + UBLOG(logINFO, "Physical Memory currently used by current process: " + << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); + } + + size_t index = 0, vectorSize = 0; + std::vector<double> vectorsOfValues1, vectorsOfValues2, vectorsOfValues3; + + for (int n = 0; n < blocksCount; n++) { + vectorSize = dataSetParamStr1.nx[0] * dataSetParamStr1.nx[1] * dataSetParamStr1.nx[2] * dataSetParamStr1.nx[3]; + vectorsOfValues1.assign(doubleValuesArray.data() + index, doubleValuesArray.data() + index + vectorSize); + index += vectorSize; + + vectorSize = dataSetParamStr2.nx[0] * dataSetParamStr2.nx[1] * dataSetParamStr2.nx[2] * dataSetParamStr2.nx[3]; + vectorsOfValues2.assign(doubleValuesArray.data() + index, doubleValuesArray.data() + index + vectorSize); + index += vectorSize; + + vectorSize = dataSetParamStr3.nx[0] * dataSetParamStr3.nx[1] * dataSetParamStr3.nx[2] * dataSetParamStr3.nx[3]; + vectorsOfValues3.assign(doubleValuesArray.data() + index, doubleValuesArray.data() + index + vectorSize); + index += vectorSize; + + SPtr<DistributionArray3D> mFdistributions(new D3Q27EsoTwist3DSplittedVector()); + + dynamicPointerCast<D3Q27EsoTwist3DSplittedVector>(mFdistributions) + ->setLocalDistributions(CbArray4D<LBMReal, IndexerX4X3X2X1>::CbArray4DPtr( + new CbArray4D<LBMReal, IndexerX4X3X2X1>(vectorsOfValues1, dataSetParamStr1.nx[0], + dataSetParamStr1.nx[1], dataSetParamStr1.nx[2], + dataSetParamStr1.nx[3]))); + dynamicPointerCast<D3Q27EsoTwist3DSplittedVector>(mFdistributions) + ->setNonLocalDistributions(CbArray4D<LBMReal, IndexerX4X3X2X1>::CbArray4DPtr( + new CbArray4D<LBMReal, IndexerX4X3X2X1>(vectorsOfValues2, dataSetParamStr2.nx[0], + dataSetParamStr2.nx[1], dataSetParamStr2.nx[2], + dataSetParamStr2.nx[3]))); + dynamicPointerCast<D3Q27EsoTwist3DSplittedVector>(mFdistributions) + ->setZeroDistributions( + CbArray3D<LBMReal, IndexerX3X2X1>::CbArray3DPtr(new CbArray3D<LBMReal, IndexerX3X2X1>( + vectorsOfValues3, dataSetParamStr3.nx[0], dataSetParamStr3.nx[1], dataSetParamStr3.nx[2]))); + + dynamicPointerCast<D3Q27EsoTwist3DSplittedVector>(mFdistributions)->setNX1(dataSetParamStr1.nx1); + dynamicPointerCast<D3Q27EsoTwist3DSplittedVector>(mFdistributions)->setNX2(dataSetParamStr1.nx2); + dynamicPointerCast<D3Q27EsoTwist3DSplittedVector>(mFdistributions)->setNX3(dataSetParamStr1.nx3); + + // find the nesessary block and fill it + SPtr<Block3D> block = grid->getBlock(dataSetArray[n].globalID); + this->lbmKernel->setBlock(block); + SPtr<LBMKernel> kernel = this->lbmKernel->clone(); + kernel->setGhostLayerWidth(dataSetArray[n].ghostLayerWidth); + kernel->setCollisionFactor(dataSetArray[n].collFactor); + kernel->setDeltaT(dataSetArray[n].deltaT); + kernel->setCompressible(dataSetArray[n].compressible); + kernel->setWithForcing(dataSetArray[n].withForcing); + SPtr<DataSet3D> dataSetPtr = SPtr<DataSet3D>(new DataSet3D()); + dataSetPtr->setFdistributions(mFdistributions); + kernel->setDataSet(dataSetPtr); + block->setKernel(kernel); + } + + if (comm->isRoot()) { + UBLOG(logINFO, "MPIIOMigrationCoProcessor::readDataSet end of restore of data, rank = " << rank); + UBLOG(logINFO, "Physical Memory currently used by current process: " + << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); + } + + delete[] dataSetArray; + + //------------------------------------------------------------- + + DSArraysPresence arrPresence; + MPI_File file_handler1; + std::string filename1 = path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + "/cpArrays.bin"; + rc = MPI_File_open(MPI_COMM_WORLD, filename1.c_str(), MPI_MODE_RDONLY, MPI_INFO_NULL, &file_handler1); + if (rc != MPI_SUCCESS) + throw UbException(UB_EXARGS, "couldn't open file " + filename1); + MPI_File_read_at(file_handler1, (MPI_Offset)0, &arrPresence, 1, arrayPresenceType, MPI_STATUS_IGNORE); + MPI_File_close(&file_handler1); + + if (arrPresence.isAverageDensityArrayPresent) + readArray(step, AverageDensity, std::string("/cpAverageDensityArray.bin")); + // readAverageDensityArray(step); + + if (arrPresence.isAverageVelocityArrayPresent) + readArray(step, AverageVelocity, std::string("/cpAverageVelocityArray.bin")); + // readAverageVelocityArray(step); + + if (arrPresence.isAverageFluktuationsArrayPresent) + readArray(step, AverageFluktuations, std::string("/cpAverageFluktuationsArray.bin")); + // readAverageFluktuationsArray(step); + + if (arrPresence.isAverageTripleArrayPresent) + readArray(step, AverageTriple, std::string("/cpAverageTripleArray.bin")); + // readAverageTripleArray(step); + + if (arrPresence.isShearStressValArrayPresent) + readArray(step, ShearStressVal, std::string("/cpShearStressValArray.bin")); + // readShearStressValArray(step); + + if (arrPresence.isRelaxationFactorPresent) + readArray(step, RelaxationFactor, std::string("/cpRelaxationFactor.bin")); + // readRelaxationFactor(step); +} + +void MPIIOMigrationCoProcessor::readArray(int step, Arrays arrType, std::string fname) +{ + int rank, size; + MPI_Comm_rank(MPI_COMM_WORLD, &rank); + MPI_Comm_size(MPI_COMM_WORLD, &size); + + if (comm->isRoot()) { + UBLOG(logINFO, "MPIIOMigrationCoProcessor::readArray start MPI IO rank = " << rank); + UBLOG(logINFO, "Physical Memory currently used by current process: " + << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); + } + double start, finish; + if (comm->isRoot()) + start = MPI_Wtime(); + + MPI_File file_handler; + std::string filename = path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + fname; + int rc = MPI_File_open(MPI_COMM_WORLD, filename.c_str(), MPI_MODE_RDONLY, MPI_INFO_NULL, &file_handler); + if (rc != MPI_SUCCESS) + throw UbException(UB_EXARGS, "couldn't open file " + filename); + + size_t blocksCount = 0; + dataSetParam dataSetParamStr; + memset(&dataSetParamStr, 0, sizeof(dataSetParam)); + + // read from the grid the blocks, that belong to this process + std::vector<SPtr<Block3D>> blocksVector[25]; + int minInitLevel = this->grid->getCoarsestInitializedLevel(); + int maxInitLevel = this->grid->getFinestInitializedLevel(); + for (int level = minInitLevel; level <= maxInitLevel; level++) { + grid->getBlocks(level, rank, blocksVector[level]); + blocksCount += static_cast<int>(blocksVector[level].size()); + } + + MPI_File_read_at(file_handler, (MPI_Offset)0, &dataSetParamStr, 1, dataSetParamType, MPI_STATUS_IGNORE); + + DataSetSmallMigration *dataSetSmallArray = new DataSetSmallMigration[blocksCount]; + size_t doubleCountInBlock = + dataSetParamStr.nx[0] * dataSetParamStr.nx[1] * dataSetParamStr.nx[2] * dataSetParamStr.nx[3]; + std::vector<double> doubleValuesArray(blocksCount * doubleCountInBlock); // double-values in all blocks + + // define MPI_types depending on the block-specific information + MPI_Type_contiguous(int(doubleCountInBlock), MPI_DOUBLE, &dataSetDoubleType); + MPI_Type_commit(&dataSetDoubleType); + + size_t ic = 0; + MPI_Offset read_offset; + size_t sizeofOneDataSet = size_t(sizeof(DataSetSmallMigration) + doubleCountInBlock * sizeof(double)); + + for (int level = minInitLevel; level <= maxInitLevel; level++) { + for (SPtr<Block3D> block : blocksVector[level]) // blocks of the current level + { + read_offset = (MPI_Offset)(sizeof(dataSetParam) + block->getGlobalID() * sizeofOneDataSet); + MPI_File_read_at(file_handler, read_offset, &dataSetSmallArray[ic], 1, dataSetSmallType, MPI_STATUS_IGNORE); + MPI_File_read_at(file_handler, (MPI_Offset)(read_offset + sizeof(DataSetSmallMigration)), + &doubleValuesArray[ic * doubleCountInBlock], 1, dataSetDoubleType, MPI_STATUS_IGNORE); + ic++; + } + } + + MPI_File_close(&file_handler); + MPI_Type_free(&dataSetDoubleType); + + if (comm->isRoot()) { + finish = MPI_Wtime(); + UBLOG(logINFO, "MPIIOMigrationCoProcessor::readArray readArray: " << finish - start << " s"); + UBLOG(logINFO, "MPIIOMigrationCoProcessor::readArray start of restore of data, rank = " << rank); + UBLOG(logINFO, "Physical Memory currently used by current process: " + << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); + } + + //----------------------------- restore data --------------------------------- + size_t index = 0; + size_t nextVectorSize = + dataSetParamStr.nx[0] * dataSetParamStr.nx[1] * dataSetParamStr.nx[2] * dataSetParamStr.nx[3]; + std::vector<double> vectorsOfValues; + for (int n = 0; n < blocksCount; n++) { + SPtr<Block3D> block = grid->getBlock(dataSetSmallArray[n].globalID); + + vectorsOfValues.assign(doubleValuesArray.data() + index, doubleValuesArray.data() + index + nextVectorSize); + index += nextVectorSize; + + // fill arrays + SPtr<CbArray4D<LBMReal, IndexerX4X3X2X1>> ___4DArray; + SPtr<CbArray3D<LBMReal, IndexerX3X2X1>> ___3DArray; + + switch (arrType) { + case AverageDensity: + ___4DArray = CbArray4D<LBMReal, IndexerX4X3X2X1>::CbArray4DPtr(new CbArray4D<LBMReal, IndexerX4X3X2X1>( + vectorsOfValues, dataSetParamStr.nx[0], dataSetParamStr.nx[1], dataSetParamStr.nx[2], + dataSetParamStr.nx[3])); + block->getKernel()->getDataSet()->setAverageDensity(___4DArray); + break; + case AverageVelocity: + ___4DArray = CbArray4D<LBMReal, IndexerX4X3X2X1>::CbArray4DPtr(new CbArray4D<LBMReal, IndexerX4X3X2X1>( + vectorsOfValues, dataSetParamStr.nx[0], dataSetParamStr.nx[1], dataSetParamStr.nx[2], + dataSetParamStr.nx[3])); + block->getKernel()->getDataSet()->setAverageVelocity(___4DArray); + break; + case AverageFluktuations: + ___4DArray = CbArray4D<LBMReal, IndexerX4X3X2X1>::CbArray4DPtr(new CbArray4D<LBMReal, IndexerX4X3X2X1>( + vectorsOfValues, dataSetParamStr.nx[0], dataSetParamStr.nx[1], dataSetParamStr.nx[2], + dataSetParamStr.nx[3])); + block->getKernel()->getDataSet()->setAverageFluctuations(___4DArray); + break; + case AverageTriple: + ___4DArray = CbArray4D<LBMReal, IndexerX4X3X2X1>::CbArray4DPtr(new CbArray4D<LBMReal, IndexerX4X3X2X1>( + vectorsOfValues, dataSetParamStr.nx[0], dataSetParamStr.nx[1], dataSetParamStr.nx[2], + dataSetParamStr.nx[3])); + block->getKernel()->getDataSet()->setAverageTriplecorrelations(___4DArray); + break; + case ShearStressVal: + ___4DArray = CbArray4D<LBMReal, IndexerX4X3X2X1>::CbArray4DPtr(new CbArray4D<LBMReal, IndexerX4X3X2X1>( + vectorsOfValues, dataSetParamStr.nx[0], dataSetParamStr.nx[1], dataSetParamStr.nx[2], + dataSetParamStr.nx[3])); + block->getKernel()->getDataSet()->setShearStressValues(___4DArray); + break; + case RelaxationFactor: + ___3DArray = CbArray3D<LBMReal, IndexerX3X2X1>::CbArray3DPtr(new CbArray3D<LBMReal, IndexerX3X2X1>( + vectorsOfValues, dataSetParamStr.nx[0], dataSetParamStr.nx[1], dataSetParamStr.nx[2])); + block->getKernel()->getDataSet()->setRelaxationFactor(___3DArray); + break; + default: + UB_THROW(UbException(UB_EXARGS, "MPIIOMigrationCoProcessor::readArray : array type does not exist!")); + break; + } + } + + if (comm->isRoot()) { + UBLOG(logINFO, "MPIIOMigrationCoProcessor::readArray end of restore of data, rank = " << rank); + UBLOG(logINFO, "Physical Memory currently used by current process: " + << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); + } + + delete[] dataSetSmallArray; +} /*void MPIIOMigrationCoProcessor::readAverageDensityArray(int step) { @@ -1751,7 +1849,8 @@ void MPIIOMigrationCoProcessor::readArray(int step, Arrays arrType, std::string if (comm->isRoot()) { UBLOG(logINFO, "MPIIOMigrationCoProcessor::readAverageDensityArray start MPI IO rank = " << rank); - UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); + UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / +1073741824.0 << " GB"); } double start, finish; if (comm->isRoot()) start = MPI_Wtime(); @@ -1779,8 +1878,9 @@ void MPIIOMigrationCoProcessor::readArray(int step, Arrays arrType, std::string MPI_File_read_at(file_handler, (MPI_Offset)0, &dataSetParamStr, 1, dataSetParamType, MPI_STATUS_IGNORE); DataSetSmallMigration* dataSetSmallArray = new DataSetSmallMigration[blocksCount]; - size_t doubleCountInBlock = dataSetParamStr.nx[0] * dataSetParamStr.nx[1] * dataSetParamStr.nx[2] * dataSetParamStr.nx[3]; - std::vector<double> doubleValuesArray(blocksCount * doubleCountInBlock); // double-values in all blocks + size_t doubleCountInBlock = dataSetParamStr.nx[0] * dataSetParamStr.nx[1] * dataSetParamStr.nx[2] * +dataSetParamStr.nx[3]; std::vector<double> doubleValuesArray(blocksCount * doubleCountInBlock); // double-values in all +blocks // define MPI_types depending on the block-specific information MPI_Type_contiguous(doubleCountInBlock, MPI_DOUBLE, &dataSetDoubleType); @@ -1796,8 +1896,8 @@ void MPIIOMigrationCoProcessor::readArray(int step, Arrays arrType, std::string { read_offset = (MPI_Offset)(sizeof(dataSetParam) + block->getGlobalID() * sizeofOneDataSet); MPI_File_read_at(file_handler, read_offset, &dataSetSmallArray[ic], 1, dataSetSmallType, MPI_STATUS_IGNORE); - MPI_File_read_at(file_handler, (MPI_Offset)(read_offset + sizeof(DataSetSmallMigration)), &doubleValuesArray[ic * doubleCountInBlock], 1, dataSetDoubleType, MPI_STATUS_IGNORE); - ic++; + MPI_File_read_at(file_handler, (MPI_Offset)(read_offset + sizeof(DataSetSmallMigration)), &doubleValuesArray[ic +* doubleCountInBlock], 1, dataSetDoubleType, MPI_STATUS_IGNORE); ic++; } } @@ -1809,23 +1909,26 @@ void MPIIOMigrationCoProcessor::readArray(int step, Arrays arrType, std::string finish = MPI_Wtime(); UBLOG(logINFO, "MPIIOMigrationCoProcessor::readAverageDensityArray time: " << finish - start << " s"); UBLOG(logINFO, "MPIIOMigrationCoProcessor::readAverageDensityArray start of restore of data, rank = " << rank); - UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); + UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / +1073741824.0 << " GB"); } size_t index = 0; - size_t nextVectorSize = dataSetParamStr.nx[0] * dataSetParamStr.nx[1] * dataSetParamStr.nx[2] * dataSetParamStr.nx[3]; - std::vector<double> vectorsOfValues; - for (int n = 0; n < blocksCount; n++) + size_t nextVectorSize = dataSetParamStr.nx[0] * dataSetParamStr.nx[1] * dataSetParamStr.nx[2] * +dataSetParamStr.nx[3]; std::vector<double> vectorsOfValues; for (int n = 0; n < blocksCount; n++) { vectorsOfValues.assign(doubleValuesArray.data() + index, doubleValuesArray.data() + index + nextVectorSize); index += nextVectorSize; // fill mAverageDensity arrays SPtr<AverageValuesArray3D> mAverageDensity; - //if ((dataSetParamStr.nx[0]==0)&&(dataSetParamStr.nx[1]==0)&&(dataSetParamStr.nx[2]==0)&&(dataSetParamStr.nx[3]==0)) + //if +((dataSetParamStr.nx[0]==0)&&(dataSetParamStr.nx[1]==0)&&(dataSetParamStr.nx[2]==0)&&(dataSetParamStr.nx[3]==0)) // mAverageDensity = CbArray4D<LBMReal, IndexerX4X3X2X1>::CbArray4DPtr(); //else - mAverageDensity = CbArray4D<LBMReal, IndexerX4X3X2X1>::CbArray4DPtr(new CbArray4D<LBMReal, IndexerX4X3X2X1>(vectorsOfValues, dataSetParamStr.nx[0], dataSetParamStr.nx[1], dataSetParamStr.nx[2], dataSetParamStr.nx[3])); + mAverageDensity = CbArray4D<LBMReal, IndexerX4X3X2X1>::CbArray4DPtr(new CbArray4D<LBMReal, +IndexerX4X3X2X1>(vectorsOfValues, dataSetParamStr.nx[0], dataSetParamStr.nx[1], dataSetParamStr.nx[2], +dataSetParamStr.nx[3])); //std::cout << "rank=" << rank << ", dataSetArray[n].globalID=" << dataSetSmallArray[n].globalID << std::endl; // find the nesessary block and fill it @@ -1836,7 +1939,8 @@ void MPIIOMigrationCoProcessor::readArray(int step, Arrays arrType, std::string if (comm->isRoot()) { UBLOG(logINFO, "MPIIOMigrationCoProcessor::readAverageDensityArray end of restore of data, rank = " << rank); - UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); + UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / +1073741824.0 << " GB"); } delete[] dataSetSmallArray; @@ -1851,7 +1955,8 @@ void MPIIOMigrationCoProcessor::readAverageVelocityArray(int step) if (comm->isRoot()) { UBLOG(logINFO, "MPIIOMigrationCoProcessor::readAverageVelocityArray start MPI IO rank = " << rank); - UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); + UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / +1073741824.0 << " GB"); } double start, finish; if (comm->isRoot()) start = MPI_Wtime(); @@ -1879,8 +1984,9 @@ void MPIIOMigrationCoProcessor::readAverageVelocityArray(int step) MPI_File_read_at(file_handler, (MPI_Offset)0, &dataSetParamStr, 1, dataSetParamType, MPI_STATUS_IGNORE); DataSetSmallMigration* dataSetSmallArray = new DataSetSmallMigration[blocksCount]; - size_t doubleCountInBlock = dataSetParamStr.nx[0] * dataSetParamStr.nx[1] * dataSetParamStr.nx[2] * dataSetParamStr.nx[3]; - std::vector<double> doubleValuesArray(blocksCount * doubleCountInBlock); // double-values in all blocks + size_t doubleCountInBlock = dataSetParamStr.nx[0] * dataSetParamStr.nx[1] * dataSetParamStr.nx[2] * +dataSetParamStr.nx[3]; std::vector<double> doubleValuesArray(blocksCount * doubleCountInBlock); // double-values in all +blocks // define MPI_types depending on the block-specific information MPI_Type_contiguous(doubleCountInBlock, MPI_DOUBLE, &dataSetDoubleType); @@ -1896,8 +2002,8 @@ void MPIIOMigrationCoProcessor::readAverageVelocityArray(int step) { read_offset = (MPI_Offset)(sizeof(dataSetParam) + block->getGlobalID() * sizeofOneDataSet); MPI_File_read_at(file_handler, read_offset, &dataSetSmallArray[ic], 1, dataSetSmallType, MPI_STATUS_IGNORE); - MPI_File_read_at(file_handler, (MPI_Offset)(read_offset + sizeof(DataSetSmallMigration)), &doubleValuesArray[ic * doubleCountInBlock], 1, dataSetDoubleType, MPI_STATUS_IGNORE); - ic++; + MPI_File_read_at(file_handler, (MPI_Offset)(read_offset + sizeof(DataSetSmallMigration)), &doubleValuesArray[ic +* doubleCountInBlock], 1, dataSetDoubleType, MPI_STATUS_IGNORE); ic++; } } @@ -1909,23 +2015,26 @@ void MPIIOMigrationCoProcessor::readAverageVelocityArray(int step) finish = MPI_Wtime(); UBLOG(logINFO, "MPIIOMigrationCoProcessor::readAverageVelocityArray time: " << finish - start << " s"); UBLOG(logINFO, "MPIIOMigrationCoProcessor::readAverageVelocityArray start of restore of data, rank = " << rank); - UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); + UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / +1073741824.0 << " GB"); } size_t index = 0; - size_t nextVectorSize = dataSetParamStr.nx[0] * dataSetParamStr.nx[1] * dataSetParamStr.nx[2] * dataSetParamStr.nx[3]; - std::vector<double> vectorsOfValues; - for (int n = 0; n < blocksCount; n++) + size_t nextVectorSize = dataSetParamStr.nx[0] * dataSetParamStr.nx[1] * dataSetParamStr.nx[2] * +dataSetParamStr.nx[3]; std::vector<double> vectorsOfValues; for (int n = 0; n < blocksCount; n++) { vectorsOfValues.assign(doubleValuesArray.data() + index, doubleValuesArray.data() + index + nextVectorSize); index += nextVectorSize; // fill mAverageVelocity array SPtr<AverageValuesArray3D> mAverageVelocity; - //if ((dataSetParamStr.nx[0] == 0) && (dataSetParamStr.nx[1] == 0) && (dataSetParamStr.nx[2] == 0) && (dataSetParamStr.nx[3] == 0)) + //if ((dataSetParamStr.nx[0] == 0) && (dataSetParamStr.nx[1] == 0) && (dataSetParamStr.nx[2] == 0) && +(dataSetParamStr.nx[3] == 0)) // mAverageVelocity = CbArray4D<LBMReal, IndexerX4X3X2X1>::CbArray4DPtr(); //else - mAverageVelocity = CbArray4D<LBMReal, IndexerX4X3X2X1>::CbArray4DPtr(new CbArray4D<LBMReal, IndexerX4X3X2X1>(vectorsOfValues, dataSetParamStr.nx[0], dataSetParamStr.nx[1], dataSetParamStr.nx[2], dataSetParamStr.nx[3])); + mAverageVelocity = CbArray4D<LBMReal, IndexerX4X3X2X1>::CbArray4DPtr(new CbArray4D<LBMReal, +IndexerX4X3X2X1>(vectorsOfValues, dataSetParamStr.nx[0], dataSetParamStr.nx[1], dataSetParamStr.nx[2], +dataSetParamStr.nx[3])); // find the nesessary block and fill it SPtr<Block3D> block = grid->getBlock(dataSetSmallArray[n].globalID); @@ -1935,7 +2044,8 @@ void MPIIOMigrationCoProcessor::readAverageVelocityArray(int step) if (comm->isRoot()) { UBLOG(logINFO, "MPIIOMigrationCoProcessor::readAverageVelocityArray end of restore of data, rank = " << rank); - UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); + UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / +1073741824.0 << " GB"); } delete[] dataSetSmallArray; @@ -1950,7 +2060,8 @@ void MPIIOMigrationCoProcessor::readAverageFluktuationsArray(int step) if (comm->isRoot()) { UBLOG(logINFO, "MPIIOMigrationCoProcessor::readAverageFluktuationsArray start MPI IO rank = " << rank); - UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); + UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / +1073741824.0 << " GB"); } double start, finish; if (comm->isRoot()) start = MPI_Wtime(); @@ -1978,8 +2089,9 @@ void MPIIOMigrationCoProcessor::readAverageFluktuationsArray(int step) MPI_File_read_at(file_handler, (MPI_Offset)0, &dataSetParamStr, 1, dataSetParamType, MPI_STATUS_IGNORE); DataSetSmallMigration* dataSetSmallArray = new DataSetSmallMigration[blocksCount]; - int doubleCountInBlock = dataSetParamStr.nx[0] * dataSetParamStr.nx[1] * dataSetParamStr.nx[2] * dataSetParamStr.nx[3]; - std::vector<double> doubleValuesArray(blocksCount * doubleCountInBlock); // double-values in all blocks + int doubleCountInBlock = dataSetParamStr.nx[0] * dataSetParamStr.nx[1] * dataSetParamStr.nx[2] * +dataSetParamStr.nx[3]; std::vector<double> doubleValuesArray(blocksCount * doubleCountInBlock); // double-values in all +blocks // define MPI_types depending on the block-specific information MPI_Type_contiguous(doubleCountInBlock, MPI_DOUBLE, &dataSetDoubleType); @@ -1995,8 +2107,8 @@ void MPIIOMigrationCoProcessor::readAverageFluktuationsArray(int step) { read_offset = (MPI_Offset)(sizeof(dataSetParam) + block->getGlobalID() * sizeofOneDataSet); MPI_File_read_at(file_handler, read_offset, &dataSetSmallArray[ic], 1, dataSetSmallType, MPI_STATUS_IGNORE); - MPI_File_read_at(file_handler, (MPI_Offset)(read_offset + sizeof(DataSetSmallMigration)), &doubleValuesArray[ic * doubleCountInBlock], 1, dataSetDoubleType, MPI_STATUS_IGNORE); - ic++; + MPI_File_read_at(file_handler, (MPI_Offset)(read_offset + sizeof(DataSetSmallMigration)), &doubleValuesArray[ic +* doubleCountInBlock], 1, dataSetDoubleType, MPI_STATUS_IGNORE); ic++; } } @@ -2007,24 +2119,27 @@ void MPIIOMigrationCoProcessor::readAverageFluktuationsArray(int step) { finish = MPI_Wtime(); UBLOG(logINFO, "MPIIOMigrationCoProcessor::readAverageFluktuationsArray time: " << finish - start << " s"); - UBLOG(logINFO, "MPIIOMigrationCoProcessor::readAverageFluktuationsArray start of restore of data, rank = " << rank); - UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); + UBLOG(logINFO, "MPIIOMigrationCoProcessor::readAverageFluktuationsArray start of restore of data, rank = " << +rank); UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / +1073741824.0 << " GB"); } size_t index = 0; - size_t nextVectorSize = dataSetParamStr.nx[0] * dataSetParamStr.nx[1] * dataSetParamStr.nx[2] * dataSetParamStr.nx[3]; - std::vector<double> vectorsOfValues; - for (int n = 0; n < blocksCount; n++) + size_t nextVectorSize = dataSetParamStr.nx[0] * dataSetParamStr.nx[1] * dataSetParamStr.nx[2] * +dataSetParamStr.nx[3]; std::vector<double> vectorsOfValues; for (int n = 0; n < blocksCount; n++) { vectorsOfValues.assign(doubleValuesArray.data() + index, doubleValuesArray.data() + index + nextVectorSize); index += nextVectorSize; // fill AverageFluktuations array SPtr<AverageValuesArray3D> mAverageFluktuations; - //if ((dataSetParamStr.nx[0] == 0) && (dataSetParamStr.nx[1] == 0) && (dataSetParamStr.nx[2] == 0) && (dataSetParamStr.nx[3] == 0)) + //if ((dataSetParamStr.nx[0] == 0) && (dataSetParamStr.nx[1] == 0) && (dataSetParamStr.nx[2] == 0) && +(dataSetParamStr.nx[3] == 0)) // mAverageFluktuations = CbArray4D<LBMReal, IndexerX4X3X2X1>::CbArray4DPtr(); //else - mAverageFluktuations = CbArray4D<LBMReal, IndexerX4X3X2X1>::CbArray4DPtr(new CbArray4D<LBMReal, IndexerX4X3X2X1>(vectorsOfValues, dataSetParamStr.nx[0], dataSetParamStr.nx[1], dataSetParamStr.nx[2], dataSetParamStr.nx[3])); + mAverageFluktuations = CbArray4D<LBMReal, IndexerX4X3X2X1>::CbArray4DPtr(new CbArray4D<LBMReal, +IndexerX4X3X2X1>(vectorsOfValues, dataSetParamStr.nx[0], dataSetParamStr.nx[1], dataSetParamStr.nx[2], +dataSetParamStr.nx[3])); // find the nesessary block and fill it SPtr<Block3D> block = grid->getBlock(dataSetSmallArray[n].globalID); @@ -2034,7 +2149,8 @@ void MPIIOMigrationCoProcessor::readAverageFluktuationsArray(int step) if (comm->isRoot()) { UBLOG(logINFO, "MPIIOMigrationCoProcessor::readAverageFluktuationsArray end of restore of data, rank = " << rank); - UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); + UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / +1073741824.0 << " GB"); } delete[] dataSetSmallArray; @@ -2049,7 +2165,8 @@ void MPIIOMigrationCoProcessor::readAverageTripleArray(int step) if (comm->isRoot()) { UBLOG(logINFO, "MPIIOMigrationCoProcessor::readAverageTripleArray start MPI IO rank = " << rank); - UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); + UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / +1073741824.0 << " GB"); } double start, finish; if (comm->isRoot()) start = MPI_Wtime(); @@ -2077,8 +2194,9 @@ void MPIIOMigrationCoProcessor::readAverageTripleArray(int step) MPI_File_read_at(file_handler, (MPI_Offset)0, &dataSetParamStr, 1, dataSetParamType, MPI_STATUS_IGNORE); DataSetSmallMigration* dataSetSmallArray = new DataSetSmallMigration[blocksCount]; - size_t doubleCountInBlock = dataSetParamStr.nx[0] * dataSetParamStr.nx[1] * dataSetParamStr.nx[2] * dataSetParamStr.nx[3]; - std::vector<double> doubleValuesArray(blocksCount * doubleCountInBlock); // double-values in all blocks + size_t doubleCountInBlock = dataSetParamStr.nx[0] * dataSetParamStr.nx[1] * dataSetParamStr.nx[2] * +dataSetParamStr.nx[3]; std::vector<double> doubleValuesArray(blocksCount * doubleCountInBlock); // double-values in all +blocks // define MPI_types depending on the block-specific information MPI_Type_contiguous(doubleCountInBlock, MPI_DOUBLE, &dataSetDoubleType); @@ -2094,8 +2212,8 @@ void MPIIOMigrationCoProcessor::readAverageTripleArray(int step) { read_offset = (MPI_Offset)(sizeof(dataSetParam) + block->getGlobalID() * sizeofOneDataSet); MPI_File_read_at(file_handler, read_offset, &dataSetSmallArray[ic], 1, dataSetSmallType, MPI_STATUS_IGNORE); - MPI_File_read_at(file_handler, (MPI_Offset)(read_offset + sizeof(DataSetSmallMigration)), &doubleValuesArray[ic * doubleCountInBlock], 1, dataSetDoubleType, MPI_STATUS_IGNORE); - ic++; + MPI_File_read_at(file_handler, (MPI_Offset)(read_offset + sizeof(DataSetSmallMigration)), &doubleValuesArray[ic +* doubleCountInBlock], 1, dataSetDoubleType, MPI_STATUS_IGNORE); ic++; } } @@ -2107,23 +2225,26 @@ void MPIIOMigrationCoProcessor::readAverageTripleArray(int step) finish = MPI_Wtime(); UBLOG(logINFO, "MPIIOMigrationCoProcessor::readAverageTripleArray time: " << finish - start << " s"); UBLOG(logINFO, "MPIIOMigrationCoProcessor::readAverageTripleArray start of restore of data, rank = " << rank); - UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); + UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / +1073741824.0 << " GB"); } size_t index = 0; - size_t nextVectorSize = dataSetParamStr.nx[0] * dataSetParamStr.nx[1] * dataSetParamStr.nx[2] * dataSetParamStr.nx[3]; - std::vector<double> vectorsOfValues; - for (int n = 0; n < blocksCount; n++) + size_t nextVectorSize = dataSetParamStr.nx[0] * dataSetParamStr.nx[1] * dataSetParamStr.nx[2] * +dataSetParamStr.nx[3]; std::vector<double> vectorsOfValues; for (int n = 0; n < blocksCount; n++) { vectorsOfValues.assign(doubleValuesArray.data() + index, doubleValuesArray.data() + index + nextVectorSize); index += nextVectorSize; // fill AverageTriplecorrelations array SPtr<AverageValuesArray3D> mAverageTriplecorrelations; - //if ((dataSetParamStr.nx[0] == 0) && (dataSetParamStr.nx[1] == 0) && (dataSetParamStr.nx[2] == 0) && (dataSetParamStr.nx[3] == 0)) + //if ((dataSetParamStr.nx[0] == 0) && (dataSetParamStr.nx[1] == 0) && (dataSetParamStr.nx[2] == 0) && +(dataSetParamStr.nx[3] == 0)) // mAverageTriplecorrelations = CbArray4D<LBMReal, IndexerX4X3X2X1>::CbArray4DPtr(); //else - mAverageTriplecorrelations = CbArray4D<LBMReal, IndexerX4X3X2X1>::CbArray4DPtr(new CbArray4D<LBMReal, IndexerX4X3X2X1>(vectorsOfValues, dataSetParamStr.nx[0], dataSetParamStr.nx[1], dataSetParamStr.nx[2], dataSetParamStr.nx[3])); + mAverageTriplecorrelations = CbArray4D<LBMReal, IndexerX4X3X2X1>::CbArray4DPtr(new CbArray4D<LBMReal, +IndexerX4X3X2X1>(vectorsOfValues, dataSetParamStr.nx[0], dataSetParamStr.nx[1], dataSetParamStr.nx[2], +dataSetParamStr.nx[3])); // find the nesessary block and fill it SPtr<Block3D> block = grid->getBlock(dataSetSmallArray[n].globalID); @@ -2133,7 +2254,8 @@ void MPIIOMigrationCoProcessor::readAverageTripleArray(int step) if (comm->isRoot()) { UBLOG(logINFO, "MPIIOMigrationCoProcessor::readAverageTripleArray end of restore of data, rank = " << rank); - UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); + UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / +1073741824.0 << " GB"); } delete[] dataSetSmallArray; @@ -2148,7 +2270,8 @@ void MPIIOMigrationCoProcessor::readShearStressValArray(int step) if (comm->isRoot()) { UBLOG(logINFO, "MPIIOMigrationCoProcessor::readShearStressValArray start MPI IO rank = " << rank); - UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); + UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / +1073741824.0 << " GB"); } double start, finish; if (comm->isRoot()) start = MPI_Wtime(); @@ -2176,8 +2299,9 @@ void MPIIOMigrationCoProcessor::readShearStressValArray(int step) MPI_File_read_at(file_handler, (MPI_Offset)0, &dataSetParamStr, 1, dataSetParamType, MPI_STATUS_IGNORE); DataSetSmallMigration* dataSetSmallArray = new DataSetSmallMigration[blocksCount]; - size_t doubleCountInBlock = dataSetParamStr.nx[0] * dataSetParamStr.nx[1] * dataSetParamStr.nx[2] * dataSetParamStr.nx[3]; - std::vector<double> doubleValuesArray(blocksCount * doubleCountInBlock); // double-values in all blocks + size_t doubleCountInBlock = dataSetParamStr.nx[0] * dataSetParamStr.nx[1] * dataSetParamStr.nx[2] * +dataSetParamStr.nx[3]; std::vector<double> doubleValuesArray(blocksCount * doubleCountInBlock); // double-values in all +blocks // define MPI_types depending on the block-specific information MPI_Type_contiguous(doubleCountInBlock, MPI_DOUBLE, &dataSetDoubleType); @@ -2193,8 +2317,8 @@ void MPIIOMigrationCoProcessor::readShearStressValArray(int step) { read_offset = (MPI_Offset)(sizeof(dataSetParam) + block->getGlobalID() * sizeofOneDataSet); MPI_File_read_at(file_handler, read_offset, &dataSetSmallArray[ic], 1, dataSetSmallType, MPI_STATUS_IGNORE); - MPI_File_read_at(file_handler, (MPI_Offset)(read_offset + sizeof(DataSetSmallMigration)), &doubleValuesArray[ic * doubleCountInBlock], 1, dataSetDoubleType, MPI_STATUS_IGNORE); - ic++; + MPI_File_read_at(file_handler, (MPI_Offset)(read_offset + sizeof(DataSetSmallMigration)), &doubleValuesArray[ic +* doubleCountInBlock], 1, dataSetDoubleType, MPI_STATUS_IGNORE); ic++; } } @@ -2206,23 +2330,26 @@ void MPIIOMigrationCoProcessor::readShearStressValArray(int step) finish = MPI_Wtime(); UBLOG(logINFO, "MPIIOMigrationCoProcessor::readShearStressValArray time: " << finish - start << " s"); UBLOG(logINFO, "MPIIOMigrationCoProcessor::readShearStressValArray start of restore of data, rank = " << rank); - UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); + UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / +1073741824.0 << " GB"); } size_t index = 0; - size_t nextVectorSize = dataSetParamStr.nx[0] * dataSetParamStr.nx[1] * dataSetParamStr.nx[2] * dataSetParamStr.nx[3]; - std::vector<double> vectorsOfValues; - for (int n = 0; n < blocksCount; n++) + size_t nextVectorSize = dataSetParamStr.nx[0] * dataSetParamStr.nx[1] * dataSetParamStr.nx[2] * +dataSetParamStr.nx[3]; std::vector<double> vectorsOfValues; for (int n = 0; n < blocksCount; n++) { vectorsOfValues.assign(doubleValuesArray.data() + index, doubleValuesArray.data() + index + nextVectorSize); index += nextVectorSize; // fill ShearStressValuesArray array SPtr<ShearStressValuesArray3D> mShearStressValues; - //if ((dataSetParamStr.nx[0] == 0) && (dataSetParamStr.nx[1] == 0) && (dataSetParamStr.nx[2] == 0) && (dataSetParamStr.nx[3] == 0)) + //if ((dataSetParamStr.nx[0] == 0) && (dataSetParamStr.nx[1] == 0) && (dataSetParamStr.nx[2] == 0) && +(dataSetParamStr.nx[3] == 0)) // mShearStressValues = CbArray4D<LBMReal, IndexerX4X3X2X1>::CbArray4DPtr(); //else - mShearStressValues = CbArray4D<LBMReal, IndexerX4X3X2X1>::CbArray4DPtr(new CbArray4D<LBMReal, IndexerX4X3X2X1>(vectorsOfValues, dataSetParamStr.nx[0], dataSetParamStr.nx[1], dataSetParamStr.nx[2], dataSetParamStr.nx[3])); + mShearStressValues = CbArray4D<LBMReal, IndexerX4X3X2X1>::CbArray4DPtr(new CbArray4D<LBMReal, +IndexerX4X3X2X1>(vectorsOfValues, dataSetParamStr.nx[0], dataSetParamStr.nx[1], dataSetParamStr.nx[2], +dataSetParamStr.nx[3])); // find the nesessary block and fill it SPtr<Block3D> block = grid->getBlock(dataSetSmallArray[n].globalID); @@ -2232,7 +2359,8 @@ void MPIIOMigrationCoProcessor::readShearStressValArray(int step) if (comm->isRoot()) { UBLOG(logINFO, "MPIIOMigrationCoProcessor::readShearStressValArray end of restore of data, rank = " << rank); - UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); + UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / +1073741824.0 << " GB"); } delete[] dataSetSmallArray; @@ -2247,7 +2375,8 @@ void MPIIOMigrationCoProcessor::readRelaxationFactor(int step) if (comm->isRoot()) { UBLOG(logINFO, "MPIIOMigrationCoProcessor::readRelaxationFactor start MPI IO rank = " << rank); - UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); + UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / +1073741824.0 << " GB"); } double start, finish; if (comm->isRoot()) start = MPI_Wtime(); @@ -2275,8 +2404,9 @@ void MPIIOMigrationCoProcessor::readRelaxationFactor(int step) MPI_File_read_at(file_handler, (MPI_Offset)0, &dataSetParamStr, 1, dataSetParamType, MPI_STATUS_IGNORE); DataSetSmallMigration* dataSetSmallArray = new DataSetSmallMigration[blocksCount]; - size_t doubleCountInBlock = dataSetParamStr.nx[0] * dataSetParamStr.nx[1] * dataSetParamStr.nx[2] * dataSetParamStr.nx[3]; - std::vector<double> doubleValuesArray(blocksCount * doubleCountInBlock); // double-values in all blocks + size_t doubleCountInBlock = dataSetParamStr.nx[0] * dataSetParamStr.nx[1] * dataSetParamStr.nx[2] * +dataSetParamStr.nx[3]; std::vector<double> doubleValuesArray(blocksCount * doubleCountInBlock); // double-values in all +blocks // define MPI_types depending on the block-specific information MPI_Type_contiguous(doubleCountInBlock, MPI_DOUBLE, &dataSetDoubleType); @@ -2292,8 +2422,8 @@ void MPIIOMigrationCoProcessor::readRelaxationFactor(int step) { read_offset = (MPI_Offset)(sizeof(dataSetParam) + block->getGlobalID() * sizeofOneDataSet); MPI_File_read_at(file_handler, read_offset, &dataSetSmallArray[ic], 1, dataSetSmallType, MPI_STATUS_IGNORE); - MPI_File_read_at(file_handler, (MPI_Offset)(read_offset + sizeof(DataSetSmallMigration)), &doubleValuesArray[ic * doubleCountInBlock], 1, dataSetDoubleType, MPI_STATUS_IGNORE); - ic++; + MPI_File_read_at(file_handler, (MPI_Offset)(read_offset + sizeof(DataSetSmallMigration)), &doubleValuesArray[ic +* doubleCountInBlock], 1, dataSetDoubleType, MPI_STATUS_IGNORE); ic++; } } @@ -2305,13 +2435,13 @@ void MPIIOMigrationCoProcessor::readRelaxationFactor(int step) finish = MPI_Wtime(); UBLOG(logINFO, "MPIIOMigrationCoProcessor::readRelaxationFactor time: " << finish - start << " s"); UBLOG(logINFO, "MPIIOMigrationCoProcessor::readRelaxationFactor start of restore of data, rank = " << rank); - UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); + UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / +1073741824.0 << " GB"); } size_t index = 0; - size_t nextVectorSize = dataSetParamStr.nx[0] * dataSetParamStr.nx[1] * dataSetParamStr.nx[2] * dataSetParamStr.nx[3]; - std::vector<double> vectorsOfValues; - for (int n = 0; n < blocksCount; n++) + size_t nextVectorSize = dataSetParamStr.nx[0] * dataSetParamStr.nx[1] * dataSetParamStr.nx[2] * +dataSetParamStr.nx[3]; std::vector<double> vectorsOfValues; for (int n = 0; n < blocksCount; n++) { vectorsOfValues.assign(doubleValuesArray.data() + index, doubleValuesArray.data() + index + nextVectorSize); index += nextVectorSize; @@ -2321,7 +2451,8 @@ void MPIIOMigrationCoProcessor::readRelaxationFactor(int step) //if ((dataSetParamStr.nx[0] == 0) && (dataSetParamStr.nx[1] == 0) && (dataSetParamStr.nx[2] == 0)) // mRelaxationFactor = CbArray3D<LBMReal, IndexerX3X2X1>::CbArray3DPtr(); //else - mRelaxationFactor = CbArray3D<LBMReal, IndexerX3X2X1>::CbArray3DPtr(new CbArray3D<LBMReal, IndexerX3X2X1>(vectorsOfValues, dataSetParamStr.nx[0], dataSetParamStr.nx[1], dataSetParamStr.nx[2])); + mRelaxationFactor = CbArray3D<LBMReal, IndexerX3X2X1>::CbArray3DPtr(new CbArray3D<LBMReal, +IndexerX3X2X1>(vectorsOfValues, dataSetParamStr.nx[0], dataSetParamStr.nx[1], dataSetParamStr.nx[2])); // find the nesessary block and fill it SPtr<Block3D> block = grid->getBlock(dataSetSmallArray[n].globalID); @@ -2331,7 +2462,8 @@ void MPIIOMigrationCoProcessor::readRelaxationFactor(int step) if (comm->isRoot()) { UBLOG(logINFO, "MPIIOMigrationCoProcessor::readRelaxationFactor end of restore of data, rank = " << rank); - UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); + UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / +1073741824.0 << " GB"); } delete[] dataSetSmallArray; @@ -2340,168 +2472,164 @@ void MPIIOMigrationCoProcessor::readRelaxationFactor(int step) void MPIIOMigrationCoProcessor::readBoundaryConds(int step) { - int rank, size; - MPI_Comm_rank(MPI_COMM_WORLD, &rank); - MPI_Comm_size(MPI_COMM_WORLD, &size); - - if (comm->isRoot()) - { - UBLOG(logINFO, "MPIIOMigrationCoProcessor::readBoundaryConds start MPI IO rank = " << rank); - UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); - } - - double start, finish; - if (comm->isRoot()) start = MPI_Wtime(); - - MPI_File file_handler; - std::string filename = path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + "/cpBC.bin"; - int rc = MPI_File_open(MPI_COMM_WORLD, filename.c_str(), MPI_MODE_RDONLY, MPI_INFO_NULL, &file_handler); - if (rc != MPI_SUCCESS) throw UbException(UB_EXARGS, "couldn't open file " + filename); - - int blocksCount = 0; // quantity of the blocks, that belong to this process - - // read from the grid the blocks, that belong to this process - std::vector<SPtr<Block3D>> blocksVector[25]; - int minInitLevel = this->grid->getCoarsestInitializedLevel(); - int maxInitLevel = this->grid->getFinestInitializedLevel(); - for (int level = minInitLevel; level <= maxInitLevel; level++) - { - grid->getBlocks(level, rank, blocksVector[level]); - blocksCount += static_cast<int>(blocksVector[level].size()); - } - - BCAddMigration* bcAddArray = new BCAddMigration[blocksCount]; - BoundaryCondition* nullBouCond = new BoundaryCondition(); - memset(nullBouCond, 0, sizeof(BoundaryCondition)); - BoundaryCondition* bcArray; - int* intArray1; - int* intArray2; - std::vector<SPtr<BoundaryConditions>> bcVector; - std::vector<int> bcindexmatrixV; - std::vector<int> indexContainerV; - - if (comm->isRoot()) - { - finish = MPI_Wtime(); - UBLOG(logINFO, "MPIIOMigrationCoProcessor::readBoundaryConds time: " << finish - start << " s"); - UBLOG(logINFO, "MPIIOMigrationCoProcessor::readBoundaryConds start of restore of data, rank = " << rank); - UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); - } - - MPI_File_read_at(file_handler, (MPI_Offset)0, &boundCondParamStr, 1, boundCondParamType, MPI_STATUS_IGNORE); - MPI_Type_contiguous(boundCondParamStr.bcindexmatrixCount, MPI_INT, &bcindexmatrixType); - MPI_Type_commit(&bcindexmatrixType); - - int ic = 0; - MPI_Offset read_offset1, read_offset2; - for (int level = minInitLevel; level <= maxInitLevel; level++) - { - for (SPtr<Block3D> block : blocksVector[level]) // blocks of the current level - { - read_offset1 = (MPI_Offset)(sizeof(boundCondParam) + block->getGlobalID() * sizeof(size_t)); - - MPI_File_read_at(file_handler, read_offset1, &read_offset2, 1, MPI_LONG_LONG_INT, MPI_STATUS_IGNORE); - MPI_File_read_at(file_handler, read_offset2, &bcAddArray[ic], 1, boundCondTypeAdd, MPI_STATUS_IGNORE); - - bcArray = new BoundaryCondition[bcAddArray[ic].boundCond_count]; - intArray1 = new int[boundCondParamStr.bcindexmatrixCount]; - intArray2 = new int[bcAddArray[ic].indexContainer_count]; - - if (bcAddArray[ic].boundCond_count > 0) - { - MPI_File_read_at(file_handler, (MPI_Offset)(read_offset2 + sizeof(BCAddMigration)), &bcArray[0], bcAddArray[ic].boundCond_count, boundCondType, MPI_STATUS_IGNORE); - } - MPI_File_read_at(file_handler, (MPI_Offset)(read_offset2 + sizeof(BCAddMigration) + bcAddArray[ic].boundCond_count * sizeof(BoundaryCondition)), - &intArray1[0], 1, bcindexmatrixType, MPI_STATUS_IGNORE); - if (bcAddArray[ic].indexContainer_count > 0) - { - MPI_File_read_at(file_handler, (MPI_Offset)(read_offset2 + sizeof(BCAddMigration) + bcAddArray[ic].boundCond_count * sizeof(BoundaryCondition) + boundCondParamStr.bcindexmatrixCount * sizeof(int)), - &intArray2[0], bcAddArray[ic].indexContainer_count, MPI_INT, MPI_STATUS_IGNORE); - } - - bcindexmatrixV.resize(0); - indexContainerV.resize(0); - bcVector.resize(0); - - for (size_t ibc = 0; ibc<bcAddArray[ic].boundCond_count; ibc++) - { - SPtr<BoundaryConditions> bc; - if (memcmp(&bcArray[ibc], nullBouCond, sizeof(BoundaryCondition)) == 0) - bc = SPtr<BoundaryConditions>(); - else - { - bc = SPtr<BoundaryConditions>(new BoundaryConditions); - bc->noslipBoundaryFlags = bcArray[ibc].noslipBoundaryFlags; - bc->slipBoundaryFlags = bcArray[ibc].slipBoundaryFlags; - bc->densityBoundaryFlags = bcArray[ibc].densityBoundaryFlags; - bc->velocityBoundaryFlags = bcArray[ibc].velocityBoundaryFlags; - bc->wallModelBoundaryFlags = bcArray[ibc].wallModelBoundaryFlags; - bc->bcVelocityX1 = bcArray[ibc].bcVelocityX1; - bc->bcVelocityX2 = bcArray[ibc].bcVelocityX2; - bc->bcVelocityX3 = bcArray[ibc].bcVelocityX3; - bc->bcDensity = bcArray[ibc].bcDensity; - bc->bcLodiDensity = bcArray[ibc].bcLodiDensity; - bc->bcLodiVelocityX1 = bcArray[ibc].bcLodiVelocityX1; - bc->bcLodiVelocityX2 = bcArray[ibc].bcLodiVelocityX2; - bc->bcLodiVelocityX3 = bcArray[ibc].bcLodiVelocityX3; - bc->bcLodiLentgh = bcArray[ibc].bcLodiLentgh; - - bc->nx1 = bcArray[ibc].nx1; - bc->nx2 = bcArray[ibc].nx2; - bc->nx3 = bcArray[ibc].nx3; - for (int iq = 0; iq<26; iq++) - bc->setQ(bcArray[ibc].q[iq], iq); - bc->setBcAlgorithmType(bcArray[ibc].algorithmType); + int rank, size; + MPI_Comm_rank(MPI_COMM_WORLD, &rank); + MPI_Comm_size(MPI_COMM_WORLD, &size); + + if (comm->isRoot()) { + UBLOG(logINFO, "MPIIOMigrationCoProcessor::readBoundaryConds start MPI IO rank = " << rank); + UBLOG(logINFO, "Physical Memory currently used by current process: " + << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); + } + + double start, finish; + if (comm->isRoot()) + start = MPI_Wtime(); + + MPI_File file_handler; + std::string filename = path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + "/cpBC.bin"; + int rc = MPI_File_open(MPI_COMM_WORLD, filename.c_str(), MPI_MODE_RDONLY, MPI_INFO_NULL, &file_handler); + if (rc != MPI_SUCCESS) + throw UbException(UB_EXARGS, "couldn't open file " + filename); + + int blocksCount = 0; // quantity of the blocks, that belong to this process + + // read from the grid the blocks, that belong to this process + std::vector<SPtr<Block3D>> blocksVector[25]; + int minInitLevel = this->grid->getCoarsestInitializedLevel(); + int maxInitLevel = this->grid->getFinestInitializedLevel(); + for (int level = minInitLevel; level <= maxInitLevel; level++) { + grid->getBlocks(level, rank, blocksVector[level]); + blocksCount += static_cast<int>(blocksVector[level].size()); + } + + BCAddMigration *bcAddArray = new BCAddMigration[blocksCount]; + BoundaryCondition *nullBouCond = new BoundaryCondition(); + memset(nullBouCond, 0, sizeof(BoundaryCondition)); + BoundaryCondition *bcArray; + int *intArray1; + int *intArray2; + std::vector<SPtr<BoundaryConditions>> bcVector; + std::vector<int> bcindexmatrixV; + std::vector<int> indexContainerV; + + if (comm->isRoot()) { + finish = MPI_Wtime(); + UBLOG(logINFO, "MPIIOMigrationCoProcessor::readBoundaryConds time: " << finish - start << " s"); + UBLOG(logINFO, "MPIIOMigrationCoProcessor::readBoundaryConds start of restore of data, rank = " << rank); + UBLOG(logINFO, "Physical Memory currently used by current process: " + << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); + } + + MPI_File_read_at(file_handler, (MPI_Offset)0, &boundCondParamStr, 1, boundCondParamType, MPI_STATUS_IGNORE); + MPI_Type_contiguous(boundCondParamStr.bcindexmatrixCount, MPI_INT, &bcindexmatrixType); + MPI_Type_commit(&bcindexmatrixType); + + int ic = 0; + MPI_Offset read_offset1, read_offset2; + for (int level = minInitLevel; level <= maxInitLevel; level++) { + for (SPtr<Block3D> block : blocksVector[level]) // blocks of the current level + { + read_offset1 = (MPI_Offset)(sizeof(boundCondParam) + block->getGlobalID() * sizeof(size_t)); + + MPI_File_read_at(file_handler, read_offset1, &read_offset2, 1, MPI_LONG_LONG_INT, MPI_STATUS_IGNORE); + MPI_File_read_at(file_handler, read_offset2, &bcAddArray[ic], 1, boundCondTypeAdd, MPI_STATUS_IGNORE); + + bcArray = new BoundaryCondition[bcAddArray[ic].boundCond_count]; + intArray1 = new int[boundCondParamStr.bcindexmatrixCount]; + intArray2 = new int[bcAddArray[ic].indexContainer_count]; + + if (bcAddArray[ic].boundCond_count > 0) { + MPI_File_read_at(file_handler, (MPI_Offset)(read_offset2 + sizeof(BCAddMigration)), &bcArray[0], + bcAddArray[ic].boundCond_count, boundCondType, MPI_STATUS_IGNORE); + } + MPI_File_read_at(file_handler, + (MPI_Offset)(read_offset2 + sizeof(BCAddMigration) + + bcAddArray[ic].boundCond_count * sizeof(BoundaryCondition)), + &intArray1[0], 1, bcindexmatrixType, MPI_STATUS_IGNORE); + if (bcAddArray[ic].indexContainer_count > 0) { + MPI_File_read_at(file_handler, + (MPI_Offset)(read_offset2 + sizeof(BCAddMigration) + + bcAddArray[ic].boundCond_count * sizeof(BoundaryCondition) + + boundCondParamStr.bcindexmatrixCount * sizeof(int)), + &intArray2[0], bcAddArray[ic].indexContainer_count, MPI_INT, MPI_STATUS_IGNORE); } - bcVector.push_back(bc); - } + bcindexmatrixV.resize(0); + indexContainerV.resize(0); + bcVector.resize(0); + + for (size_t ibc = 0; ibc < bcAddArray[ic].boundCond_count; ibc++) { + SPtr<BoundaryConditions> bc; + if (memcmp(&bcArray[ibc], nullBouCond, sizeof(BoundaryCondition)) == 0) + bc = SPtr<BoundaryConditions>(); + else { + bc = SPtr<BoundaryConditions>(new BoundaryConditions); + bc->noslipBoundaryFlags = bcArray[ibc].noslipBoundaryFlags; + bc->slipBoundaryFlags = bcArray[ibc].slipBoundaryFlags; + bc->densityBoundaryFlags = bcArray[ibc].densityBoundaryFlags; + bc->velocityBoundaryFlags = bcArray[ibc].velocityBoundaryFlags; + bc->wallModelBoundaryFlags = bcArray[ibc].wallModelBoundaryFlags; + bc->bcVelocityX1 = bcArray[ibc].bcVelocityX1; + bc->bcVelocityX2 = bcArray[ibc].bcVelocityX2; + bc->bcVelocityX3 = bcArray[ibc].bcVelocityX3; + bc->bcDensity = bcArray[ibc].bcDensity; + bc->bcLodiDensity = bcArray[ibc].bcLodiDensity; + bc->bcLodiVelocityX1 = bcArray[ibc].bcLodiVelocityX1; + bc->bcLodiVelocityX2 = bcArray[ibc].bcLodiVelocityX2; + bc->bcLodiVelocityX3 = bcArray[ibc].bcLodiVelocityX3; + bc->bcLodiLentgh = bcArray[ibc].bcLodiLentgh; + + bc->nx1 = bcArray[ibc].nx1; + bc->nx2 = bcArray[ibc].nx2; + bc->nx3 = bcArray[ibc].nx3; + for (int iq = 0; iq < 26; iq++) + bc->setQ(bcArray[ibc].q[iq], iq); + bc->setBcAlgorithmType(bcArray[ibc].algorithmType); + } + + bcVector.push_back(bc); + } - for (int b1 = 0; b1 < boundCondParamStr.bcindexmatrixCount; b1++) - bcindexmatrixV.push_back(intArray1[b1]); + for (int b1 = 0; b1 < boundCondParamStr.bcindexmatrixCount; b1++) + bcindexmatrixV.push_back(intArray1[b1]); - for (int b2 = 0; b2 < bcAddArray[ic].indexContainer_count; b2++) - indexContainerV.push_back(intArray2[b2]); + for (int b2 = 0; b2 < bcAddArray[ic].indexContainer_count; b2++) + indexContainerV.push_back(intArray2[b2]); - CbArray3D<int, IndexerX3X2X1> bcim(bcindexmatrixV, boundCondParamStr.nx1, boundCondParamStr.nx2, boundCondParamStr.nx3); - SPtr<Block3D> block1 = grid->getBlock(bcAddArray[ic].globalID); + CbArray3D<int, IndexerX3X2X1> bcim(bcindexmatrixV, boundCondParamStr.nx1, boundCondParamStr.nx2, + boundCondParamStr.nx3); + SPtr<Block3D> block1 = grid->getBlock(bcAddArray[ic].globalID); - SPtr<BCProcessor> bcProc = bcProcessor->clone(block1->getKernel()); - SPtr<BCArray3D> bcArr(new BCArray3D()); - bcArr->bcindexmatrix = bcim; - bcArr->bcvector = bcVector; - bcArr->indexContainer = indexContainerV; - bcProc->setBCArray(bcArr); + SPtr<BCProcessor> bcProc = bcProcessor->clone(block1->getKernel()); + SPtr<BCArray3D> bcArr(new BCArray3D()); + bcArr->bcindexmatrix = bcim; + bcArr->bcvector = bcVector; + bcArr->indexContainer = indexContainerV; + bcProc->setBCArray(bcArr); - block1->getKernel()->setBCProcessor(bcProc); + block1->getKernel()->setBCProcessor(bcProc); - delete bcArray; - delete intArray1; + delete bcArray; + delete intArray1; - ic++; - } - } + ic++; + } + } - MPI_File_close(&file_handler); - MPI_Type_free(&bcindexmatrixType); + MPI_File_close(&file_handler); + MPI_Type_free(&bcindexmatrixType); - delete nullBouCond; + delete nullBouCond; - if (comm->isRoot()) - { - UBLOG(logINFO, "MPIIOMigrationCoProcessor::readBoundaryConds end of restore of data, rank = " << rank); - UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); - } + if (comm->isRoot()) { + UBLOG(logINFO, "MPIIOMigrationCoProcessor::readBoundaryConds end of restore of data, rank = " << rank); + UBLOG(logINFO, "Physical Memory currently used by current process: " + << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); + } } ////////////////////////////////////////////////////////////////////////// -void MPIIOMigrationCoProcessor::setLBMKernel(SPtr<LBMKernel> kernel) -{ - this->lbmKernel = kernel; -} +void MPIIOMigrationCoProcessor::setLBMKernel(SPtr<LBMKernel> kernel) { this->lbmKernel = kernel; } ////////////////////////////////////////////////////////////////////////// -void MPIIOMigrationCoProcessor::setBCProcessor(SPtr<BCProcessor> bcProcessor) -{ - this->bcProcessor = bcProcessor; -} - +void MPIIOMigrationCoProcessor::setBCProcessor(SPtr<BCProcessor> bcProcessor) { this->bcProcessor = bcProcessor; } diff --git a/src/cpu/VirtualFluidsCore/CoProcessors/MPIIOMigrationCoProcessor.h b/src/cpu/VirtualFluidsCore/CoProcessors/MPIIOMigrationCoProcessor.h index 1f09325694cf2439e324741cd06d6d5084974ed4..428407d37268043837d029fce6ae0ba2f365960b 100644 --- a/src/cpu/VirtualFluidsCore/CoProcessors/MPIIOMigrationCoProcessor.h +++ b/src/cpu/VirtualFluidsCore/CoProcessors/MPIIOMigrationCoProcessor.h @@ -13,69 +13,75 @@ class Communicator; class BCProcessor; class LBMKernel; - -//! \class MPIWriteBlocksCoProcessor -//! \brief Writes the grid each timestep into the files and reads the grip from the files before regenerating +//! \class MPIWriteBlocksCoProcessor +//! \brief Writes the grid each timestep into the files and reads the grip from the files before regenerating class MPIIOMigrationCoProcessor : public MPIIOCoProcessor { public: - enum Arrays { AverageDensity = 1, AverageVelocity = 2, AverageFluktuations = 3, AverageTriple = 4, ShearStressVal = 5, RelaxationFactor = 6 }; + enum Arrays { + AverageDensity = 1, + AverageVelocity = 2, + AverageFluktuations = 3, + AverageTriple = 4, + ShearStressVal = 5, + RelaxationFactor = 6 + }; - MPIIOMigrationCoProcessor(SPtr<Grid3D> grid, SPtr<UbScheduler> s, const std::string& path, SPtr<Communicator> comm); - ~MPIIOMigrationCoProcessor() override; - //! Each timestep writes the grid into the files - void process(double step) override; - //! Reads the grid from the files before grid reconstruction - void restart(int step); - //! Writes the blocks of the grid into the file cpBlocks.bin - void writeBlocks(int step); - //! Writes the datasets of the blocks into the file cpDataSet.bin - void writeDataSet(int step); - void write4DArray(int step, Arrays arrType, std::string fname); - void write3DArray(int step, Arrays arrType, std::string fname); -// void writeAverageDensityArray(int step); -// void writeAverageVelocityArray(int step); -// void writeAverageFluktuationsArray(int step); -// void writeAverageTripleArray(int step); -// void writeShearStressValArray(int step); -// void writeRelaxationFactor(int step); - //! Writes the boundary conditions of the blocks into the file cpBC.bin - void writeBoundaryConds(int step); + MPIIOMigrationCoProcessor(SPtr<Grid3D> grid, SPtr<UbScheduler> s, const std::string &path, SPtr<Communicator> comm); + ~MPIIOMigrationCoProcessor() override; + //! Each timestep writes the grid into the files + void process(double step) override; + //! Reads the grid from the files before grid reconstruction + void restart(int step); + //! Writes the blocks of the grid into the file cpBlocks.bin + void writeBlocks(int step); + //! Writes the datasets of the blocks into the file cpDataSet.bin + void writeDataSet(int step); + void write4DArray(int step, Arrays arrType, std::string fname); + void write3DArray(int step, Arrays arrType, std::string fname); + // void writeAverageDensityArray(int step); + // void writeAverageVelocityArray(int step); + // void writeAverageFluktuationsArray(int step); + // void writeAverageTripleArray(int step); + // void writeShearStressValArray(int step); + // void writeRelaxationFactor(int step); + //! Writes the boundary conditions of the blocks into the file cpBC.bin + void writeBoundaryConds(int step); - //! Reads the blocks of the grid from the file cpBlocks.bin - void readBlocks(int step); - //! Reads the datasets of the blocks from the file cpDataSet.bin - void readDataSet(int step); - void readArray(int step, Arrays arrType, std::string fname); -// void readAverageDensityArray(int step); -// void readAverageVelocityArray(int step); -// void readAverageFluktuationsArray(int step); -// void readAverageTripleArray(int step); -// void readShearStressValArray(int step); -// void readRelaxationFactor(int step); - //! Reads the boundary conditions of the blocks from the file cpBC.bin - void readBoundaryConds(int step); - //! The function sets LBMKernel - void setLBMKernel(SPtr<LBMKernel> kernel); - //!The function sets BCProcessor - void setBCProcessor(SPtr<BCProcessor> bcProcessor); - //!The function truncates the data files - void clearAllFiles(int step); - //void setNu(double nu); + //! Reads the blocks of the grid from the file cpBlocks.bin + void readBlocks(int step); + //! Reads the datasets of the blocks from the file cpDataSet.bin + void readDataSet(int step); + void readArray(int step, Arrays arrType, std::string fname); + // void readAverageDensityArray(int step); + // void readAverageVelocityArray(int step); + // void readAverageFluktuationsArray(int step); + // void readAverageTripleArray(int step); + // void readShearStressValArray(int step); + // void readRelaxationFactor(int step); + //! Reads the boundary conditions of the blocks from the file cpBC.bin + void readBoundaryConds(int step); + //! The function sets LBMKernel + void setLBMKernel(SPtr<LBMKernel> kernel); + //! The function sets BCProcessor + void setBCProcessor(SPtr<BCProcessor> bcProcessor); + //! The function truncates the data files + void clearAllFiles(int step); + // void setNu(double nu); protected: - //std::string path; - //SPtr<Communicator> comm; + // std::string path; + // SPtr<Communicator> comm; private: - //MPI_Datatype gridParamType, block3dType; - MPI_Datatype dataSetType, dataSetSmallType, dataSetDoubleType; - MPI_Datatype boundCondParamType, boundCondTypeAdd, bcindexmatrixType; + // MPI_Datatype gridParamType, block3dType; + MPI_Datatype dataSetType, dataSetSmallType, dataSetDoubleType; + MPI_Datatype boundCondParamType, boundCondTypeAdd, bcindexmatrixType; - MPIIODataStructures::boundCondParam boundCondParamStr; - SPtr<LBMKernel> lbmKernel; - SPtr<BCProcessor> bcProcessor; - //double nue; + MPIIODataStructures::boundCondParam boundCondParamStr; + SPtr<LBMKernel> lbmKernel; + SPtr<BCProcessor> bcProcessor; + // double nue; }; -#endif +#endif diff --git a/src/cpu/VirtualFluidsCore/CoProcessors/MPIIORestartCoProcessor.cpp b/src/cpu/VirtualFluidsCore/CoProcessors/MPIIORestartCoProcessor.cpp index b7bcb046449a1e3bc3963c5cbb7973cb68dbcfa2..abcf2bf7a932e03ea978265baa32f0872d767402 100644 --- a/src/cpu/VirtualFluidsCore/CoProcessors/MPIIORestartCoProcessor.cpp +++ b/src/cpu/VirtualFluidsCore/CoProcessors/MPIIORestartCoProcessor.cpp @@ -1,2254 +1,2370 @@ #include "MPIIORestartCoProcessor.h" -#include "D3Q27System.h" -#include "LBMKernel.h" -#include "D3Q27EsoTwist3DSplittedVector.h" -#include <UbSystem.h> -#include <MemoryUtil.h> -#include "BoundaryConditions.h" +#include "BCArray3D.h" +#include "BCProcessor.h" #include "Block3D.h" +#include "BoundaryConditions.h" +#include "Communicator.h" #include "CoordinateTransformation3D.h" +#include "D3Q27EsoTwist3DSplittedVector.h" +#include "D3Q27System.h" #include "DataSet3D.h" #include "Grid3D.h" #include "Grid3DSystem.h" -#include "BCArray3D.h" -#include "Communicator.h" -#include "WbWriter.h" -#include "UbScheduler.h" #include "LBMKernel.h" -#include "BCProcessor.h" -#include "UbFileOutputASCII.h" #include "UbFileInputASCII.h" +#include "UbFileOutputASCII.h" +#include "UbScheduler.h" +#include "WbWriter.h" +#include <MemoryUtil.h> +#include <UbSystem.h> //! BLOCK_SIZE defines the quantity of the BoundaryCondition-structures written as one block to the file -//! To avoid overflow in the parameter \a count of the function MPI_File_write_at +//! To avoid overflow in the parameter \a count of the function MPI_File_write_at //! structures BoundaryCondition are being written in blocks containing each of them BLOCK_SIZE structures #define BLOCK_SIZE 1024 using namespace MPIIODataStructures; -MPIIORestartCoProcessor::MPIIORestartCoProcessor(SPtr<Grid3D> grid, SPtr<UbScheduler> s, const std::string& path, SPtr<Communicator> comm) : MPIIOCoProcessor(grid, s, path, comm) +MPIIORestartCoProcessor::MPIIORestartCoProcessor(SPtr<Grid3D> grid, SPtr<UbScheduler> s, const std::string &path, + SPtr<Communicator> comm) + : MPIIOCoProcessor(grid, s, path, comm) { - memset(&boundCondParamStr, 0, sizeof(boundCondParamStr)); + memset(&boundCondParamStr, 0, sizeof(boundCondParamStr)); - //------------------------- define MPI types --------------------------------- + //------------------------- define MPI types --------------------------------- - MPI_Datatype typesDataSet[3] = { MPI_DOUBLE, MPI_INT, MPI_CHAR }; - int blocksDataSet[3] = { 2, 5, 2 }; - MPI_Aint offsetsDatatSet[3], lbDataSet, extentDataSet; + MPI_Datatype typesDataSet[3] = { MPI_DOUBLE, MPI_INT, MPI_CHAR }; + int blocksDataSet[3] = { 2, 5, 2 }; + MPI_Aint offsetsDatatSet[3], lbDataSet, extentDataSet; - offsetsDatatSet[0] = 0; - MPI_Type_get_extent(MPI_DOUBLE, &lbDataSet, &extentDataSet); - offsetsDatatSet[1] = blocksDataSet[0] * extentDataSet; + offsetsDatatSet[0] = 0; + MPI_Type_get_extent(MPI_DOUBLE, &lbDataSet, &extentDataSet); + offsetsDatatSet[1] = blocksDataSet[0] * extentDataSet; - MPI_Type_get_extent(MPI_INT, &lbDataSet, &extentDataSet); - offsetsDatatSet[2] = offsetsDatatSet[1] + blocksDataSet[1] * extentDataSet; + MPI_Type_get_extent(MPI_INT, &lbDataSet, &extentDataSet); + offsetsDatatSet[2] = offsetsDatatSet[1] + blocksDataSet[1] * extentDataSet; - MPI_Type_create_struct(3, blocksDataSet, offsetsDatatSet, typesDataSet, &dataSetType); - MPI_Type_commit(&dataSetType); + MPI_Type_create_struct(3, blocksDataSet, offsetsDatatSet, typesDataSet, &dataSetType); + MPI_Type_commit(&dataSetType); - //----------------------------------------------------------------------- + //----------------------------------------------------------------------- - MPI_Type_contiguous(4, MPI_INT, &dataSetSmallType); - MPI_Type_commit(&dataSetSmallType); + MPI_Type_contiguous(4, MPI_INT, &dataSetSmallType); + MPI_Type_commit(&dataSetSmallType); - //----------------------------------------------------------------------- + //----------------------------------------------------------------------- - MPI_Type_contiguous(4, MPI_INT, &boundCondParamType); - MPI_Type_commit(&boundCondParamType); + MPI_Type_contiguous(4, MPI_INT, &boundCondParamType); + MPI_Type_commit(&boundCondParamType); - //--------------------------------------- + //--------------------------------------- - MPI_Type_contiguous(BLOCK_SIZE, boundCondType, &boundCondType1000); - MPI_Type_commit(&boundCondType1000); + MPI_Type_contiguous(BLOCK_SIZE, boundCondType, &boundCondType1000); + MPI_Type_commit(&boundCondType1000); - //--------------------------------------- - - MPI_Type_contiguous(6, MPI_INT, &boundCondTypeAdd); - MPI_Type_commit(&boundCondTypeAdd); + //--------------------------------------- + MPI_Type_contiguous(6, MPI_INT, &boundCondTypeAdd); + MPI_Type_commit(&boundCondTypeAdd); } ////////////////////////////////////////////////////////////////////////// MPIIORestartCoProcessor::~MPIIORestartCoProcessor() { - MPI_Type_free(&dataSetType); - MPI_Type_free(&dataSetSmallType); - MPI_Type_free(&boundCondParamType); - MPI_Type_free(&boundCondType1000); - MPI_Type_free(&boundCondTypeAdd); + MPI_Type_free(&dataSetType); + MPI_Type_free(&dataSetSmallType); + MPI_Type_free(&boundCondParamType); + MPI_Type_free(&boundCondType1000); + MPI_Type_free(&boundCondTypeAdd); } ////////////////////////////////////////////////////////////////////////// void MPIIORestartCoProcessor::process(double step) { - if (scheduler->isDue(step)) - { - if (comm->isRoot()) UBLOG(logINFO, "MPIIORestartCoProcessor save step: " << step); - if (comm->isRoot()) UBLOG(logINFO, "Save check point - start"); - /*if (comm->isRoot())*/ clearAllFiles((int)step); - - writeBlocks((int)step); - writeDataSet((int)step); - writeBoundaryConds((int)step); - - writeCpTimeStep((int)step); - - if (comm->isRoot()) UBLOG(logINFO, "Save check point - end"); - } + if (scheduler->isDue(step)) { + if (comm->isRoot()) + UBLOG(logINFO, "MPIIORestartCoProcessor save step: " << step); + if (comm->isRoot()) + UBLOG(logINFO, "Save check point - start"); + /*if (comm->isRoot())*/ clearAllFiles((int)step); + + writeBlocks((int)step); + writeDataSet((int)step); + writeBoundaryConds((int)step); + + writeCpTimeStep((int)step); + + if (comm->isRoot()) + UBLOG(logINFO, "Save check point - end"); + } } ////////////////////////////////////////////////////////////////////////// void MPIIORestartCoProcessor::clearAllFiles(int step) { - MPI_File file_handler; - MPI_Info info = MPI_INFO_NULL; - MPI_Offset new_size = 0; + MPI_File file_handler; + MPI_Info info = MPI_INFO_NULL; + MPI_Offset new_size = 0; - UbSystem::makeDirectory(path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step)); + UbSystem::makeDirectory(path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step)); - MPIIOCoProcessor::clearAllFiles(step); + MPIIOCoProcessor::clearAllFiles(step); - std::string filename10 = path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + "/cpBC.bin"; - int rc10 = MPI_File_open(MPI_COMM_WORLD, filename10.c_str(), MPI_MODE_CREATE | MPI_MODE_WRONLY, info, &file_handler); - if (rc10 != MPI_SUCCESS) throw UbException(UB_EXARGS, "couldn't open file " + filename10); - MPI_File_set_size(file_handler, new_size); - MPI_File_close(&file_handler); + std::string filename10 = path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + "/cpBC.bin"; + int rc10 = + MPI_File_open(MPI_COMM_WORLD, filename10.c_str(), MPI_MODE_CREATE | MPI_MODE_WRONLY, info, &file_handler); + if (rc10 != MPI_SUCCESS) + throw UbException(UB_EXARGS, "couldn't open file " + filename10); + MPI_File_set_size(file_handler, new_size); + MPI_File_close(&file_handler); } ////////////////////////////////////////////////////////////////////////// -void MPIIORestartCoProcessor::writeBlocks(int step) -{ - MPIIOCoProcessor::writeBlocks(step); -} +void MPIIORestartCoProcessor::writeBlocks(int step) { MPIIOCoProcessor::writeBlocks(step); } void MPIIORestartCoProcessor::writeDataSet(int step) { - int rank, size; - MPI_Comm_rank(MPI_COMM_WORLD, &rank); - MPI_Comm_size(MPI_COMM_WORLD, &size); - - int blocksCount = 0; // quantity of blocks in the grid, max 2147483648 blocks! - - std::vector<SPtr<Block3D>> blocksVector[25]; - int minInitLevel = this->grid->getCoarsestInitializedLevel(); - int maxInitLevel = this->grid->getFinestInitializedLevel(); - for (int level = minInitLevel; level <= maxInitLevel; level++) - { - grid->getBlocks(level, rank, blocksVector[level]); - blocksCount += static_cast<int>(blocksVector[level].size()); - } - - dataSetParam dataSetParamStr1, dataSetParamStr2, dataSetParamStr3; - DataSetRestart* dataSetArray = new DataSetRestart[blocksCount]; - std::vector<double> doubleValuesArray; // double-values (arrays of f's) in all blocks - - if (comm->isRoot()) - { - UBLOG(logINFO, "MPIIORestartCoProcessor::writeDataSet start collect data rank = " << rank); - UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); - } - - DSArraysPresence arrPresence; - bool firstBlock = true; - int doubleCountInBlock = 0; - int ic = 0; - SPtr< D3Q27EsoTwist3DSplittedVector > D3Q27EsoTwist3DSplittedVectorPtr; - CbArray4D<LBMReal, IndexerX4X3X2X1>::CbArray4DPtr localDistributions; - CbArray4D <LBMReal, IndexerX4X3X2X1>::CbArray4DPtr nonLocalDistributions; - CbArray3D<LBMReal, IndexerX3X2X1>::CbArray3DPtr zeroDistributions; - - for (int level = minInitLevel; level <= maxInitLevel; level++) - { - for (SPtr<Block3D> block : blocksVector[level]) // blocks of the current level - { - dataSetArray[ic].x1 = block->getX1(); // coordinates of the block needed to find it while regenerating the grid - dataSetArray[ic].x2 = block->getX2(); - dataSetArray[ic].x3 = block->getX3(); - dataSetArray[ic].level = block->getLevel(); - dataSetArray[ic].ghostLayerWidth = block->getKernel()->getGhostLayerWidth(); - dataSetArray[ic].collFactor = block->getKernel()->getCollisionFactor(); - dataSetArray[ic].deltaT = block->getKernel()->getDeltaT(); - dataSetArray[ic].compressible = block->getKernel()->getCompressible(); - dataSetArray[ic].withForcing = block->getKernel()->getWithForcing(); - - D3Q27EsoTwist3DSplittedVectorPtr = dynamicPointerCast<D3Q27EsoTwist3DSplittedVector>(block->getKernel()->getDataSet()->getFdistributions()); - localDistributions = D3Q27EsoTwist3DSplittedVectorPtr->getLocalDistributions(); - nonLocalDistributions = D3Q27EsoTwist3DSplittedVectorPtr->getNonLocalDistributions(); - zeroDistributions = D3Q27EsoTwist3DSplittedVectorPtr->getZeroDistributions(); - - if (firstBlock) // when first (any) valid block... - { - if (localDistributions) + int rank, size; + MPI_Comm_rank(MPI_COMM_WORLD, &rank); + MPI_Comm_size(MPI_COMM_WORLD, &size); + + int blocksCount = 0; // quantity of blocks in the grid, max 2147483648 blocks! + + std::vector<SPtr<Block3D>> blocksVector[25]; + int minInitLevel = this->grid->getCoarsestInitializedLevel(); + int maxInitLevel = this->grid->getFinestInitializedLevel(); + for (int level = minInitLevel; level <= maxInitLevel; level++) { + grid->getBlocks(level, rank, blocksVector[level]); + blocksCount += static_cast<int>(blocksVector[level].size()); + } + + dataSetParam dataSetParamStr1, dataSetParamStr2, dataSetParamStr3; + DataSetRestart *dataSetArray = new DataSetRestart[blocksCount]; + std::vector<double> doubleValuesArray; // double-values (arrays of f's) in all blocks + + if (comm->isRoot()) { + UBLOG(logINFO, "MPIIORestartCoProcessor::writeDataSet start collect data rank = " << rank); + UBLOG(logINFO, "Physical Memory currently used by current process: " + << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); + } + + DSArraysPresence arrPresence; + bool firstBlock = true; + int doubleCountInBlock = 0; + int ic = 0; + SPtr<D3Q27EsoTwist3DSplittedVector> D3Q27EsoTwist3DSplittedVectorPtr; + CbArray4D<LBMReal, IndexerX4X3X2X1>::CbArray4DPtr localDistributions; + CbArray4D<LBMReal, IndexerX4X3X2X1>::CbArray4DPtr nonLocalDistributions; + CbArray3D<LBMReal, IndexerX3X2X1>::CbArray3DPtr zeroDistributions; + + for (int level = minInitLevel; level <= maxInitLevel; level++) { + for (SPtr<Block3D> block : blocksVector[level]) // blocks of the current level + { + dataSetArray[ic].x1 = + block->getX1(); // coordinates of the block needed to find it while regenerating the grid + dataSetArray[ic].x2 = block->getX2(); + dataSetArray[ic].x3 = block->getX3(); + dataSetArray[ic].level = block->getLevel(); + dataSetArray[ic].ghostLayerWidth = block->getKernel()->getGhostLayerWidth(); + dataSetArray[ic].collFactor = block->getKernel()->getCollisionFactor(); + dataSetArray[ic].deltaT = block->getKernel()->getDeltaT(); + dataSetArray[ic].compressible = block->getKernel()->getCompressible(); + dataSetArray[ic].withForcing = block->getKernel()->getWithForcing(); + + D3Q27EsoTwist3DSplittedVectorPtr = dynamicPointerCast<D3Q27EsoTwist3DSplittedVector>( + block->getKernel()->getDataSet()->getFdistributions()); + localDistributions = D3Q27EsoTwist3DSplittedVectorPtr->getLocalDistributions(); + nonLocalDistributions = D3Q27EsoTwist3DSplittedVectorPtr->getNonLocalDistributions(); + zeroDistributions = D3Q27EsoTwist3DSplittedVectorPtr->getZeroDistributions(); + + if (firstBlock) // when first (any) valid block... { - dataSetParamStr1.nx[0] = static_cast<int>(localDistributions->getNX1()); - dataSetParamStr1.nx[1] = static_cast<int>(localDistributions->getNX2()); - dataSetParamStr1.nx[2] = static_cast<int>(localDistributions->getNX3()); - dataSetParamStr1.nx[3] = static_cast<int>(localDistributions->getNX4()); - } - if (nonLocalDistributions) - { - dataSetParamStr2.nx[0] = static_cast<int>(nonLocalDistributions->getNX1()); - dataSetParamStr2.nx[1] = static_cast<int>(nonLocalDistributions->getNX2()); - dataSetParamStr2.nx[2] = static_cast<int>(nonLocalDistributions->getNX3()); - dataSetParamStr2.nx[3] = static_cast<int>(nonLocalDistributions->getNX4()); - } - if (zeroDistributions) - { - dataSetParamStr3.nx[0] = static_cast<int>(zeroDistributions->getNX1()); - dataSetParamStr3.nx[1] = static_cast<int>(zeroDistributions->getNX2()); - dataSetParamStr3.nx[2] = static_cast<int>(zeroDistributions->getNX3()); - dataSetParamStr3.nx[3] = 1; + if (localDistributions) { + dataSetParamStr1.nx[0] = static_cast<int>(localDistributions->getNX1()); + dataSetParamStr1.nx[1] = static_cast<int>(localDistributions->getNX2()); + dataSetParamStr1.nx[2] = static_cast<int>(localDistributions->getNX3()); + dataSetParamStr1.nx[3] = static_cast<int>(localDistributions->getNX4()); + } + if (nonLocalDistributions) { + dataSetParamStr2.nx[0] = static_cast<int>(nonLocalDistributions->getNX1()); + dataSetParamStr2.nx[1] = static_cast<int>(nonLocalDistributions->getNX2()); + dataSetParamStr2.nx[2] = static_cast<int>(nonLocalDistributions->getNX3()); + dataSetParamStr2.nx[3] = static_cast<int>(nonLocalDistributions->getNX4()); + } + if (zeroDistributions) { + dataSetParamStr3.nx[0] = static_cast<int>(zeroDistributions->getNX1()); + dataSetParamStr3.nx[1] = static_cast<int>(zeroDistributions->getNX2()); + dataSetParamStr3.nx[2] = static_cast<int>(zeroDistributions->getNX3()); + dataSetParamStr3.nx[3] = 1; + } + + // ... than save some parameters that are equal in all dataSets + dataSetParamStr1.nx1 = dataSetParamStr2.nx1 = dataSetParamStr3.nx1 = + static_cast<int>(block->getKernel()->getDataSet()->getFdistributions()->getNX1()); + dataSetParamStr1.nx2 = dataSetParamStr2.nx2 = dataSetParamStr3.nx2 = + static_cast<int>(block->getKernel()->getDataSet()->getFdistributions()->getNX2()); + dataSetParamStr1.nx3 = dataSetParamStr2.nx3 = dataSetParamStr3.nx3 = + static_cast<int>(block->getKernel()->getDataSet()->getFdistributions()->getNX3()); + + doubleCountInBlock = + dataSetParamStr1.nx[0] * dataSetParamStr1.nx[1] * dataSetParamStr1.nx[2] * dataSetParamStr1.nx[3] + + dataSetParamStr2.nx[0] * dataSetParamStr2.nx[1] * dataSetParamStr2.nx[2] * dataSetParamStr2.nx[3] + + dataSetParamStr3.nx[0] * dataSetParamStr3.nx[1] * dataSetParamStr3.nx[2] * dataSetParamStr3.nx[3]; + + SPtr<CbArray4D<LBMReal, IndexerX4X3X2X1>> averageDensityArray = + block->getKernel()->getDataSet()->getAverageDensity(); + if (averageDensityArray) + arrPresence.isAverageDensityArrayPresent = true; + else + arrPresence.isAverageDensityArrayPresent = false; + + SPtr<CbArray4D<LBMReal, IndexerX4X3X2X1>> AverageVelocityArray3DPtr = + block->getKernel()->getDataSet()->getAverageVelocity(); + if (AverageVelocityArray3DPtr) + arrPresence.isAverageVelocityArrayPresent = true; + else + arrPresence.isAverageVelocityArrayPresent = false; + + SPtr<CbArray4D<LBMReal, IndexerX4X3X2X1>> AverageFluctArray3DPtr = + block->getKernel()->getDataSet()->getAverageFluctuations(); + if (AverageFluctArray3DPtr) + arrPresence.isAverageFluktuationsArrayPresent = true; + else + arrPresence.isAverageFluktuationsArrayPresent = false; + + SPtr<CbArray4D<LBMReal, IndexerX4X3X2X1>> AverageTripleArray3DPtr = + block->getKernel()->getDataSet()->getAverageTriplecorrelations(); + if (AverageTripleArray3DPtr) + arrPresence.isAverageTripleArrayPresent = true; + else + arrPresence.isAverageTripleArrayPresent = false; + + SPtr<CbArray4D<LBMReal, IndexerX4X3X2X1>> ShearStressValArray3DPtr = + block->getKernel()->getDataSet()->getShearStressValues(); + if (ShearStressValArray3DPtr) + arrPresence.isShearStressValArrayPresent = true; + else + arrPresence.isShearStressValArrayPresent = false; + + SPtr<CbArray3D<LBMReal, IndexerX3X2X1>> relaxationFactor3DPtr = + block->getKernel()->getDataSet()->getRelaxationFactor(); + if (relaxationFactor3DPtr) + arrPresence.isRelaxationFactorPresent = true; + else + arrPresence.isRelaxationFactorPresent = false; + + firstBlock = false; } - // ... than save some parameters that are equal in all dataSets - dataSetParamStr1.nx1 = dataSetParamStr2.nx1 = dataSetParamStr3.nx1 = static_cast<int>(block->getKernel()->getDataSet()->getFdistributions()->getNX1()); - dataSetParamStr1.nx2 = dataSetParamStr2.nx2 = dataSetParamStr3.nx2 = static_cast<int>(block->getKernel()->getDataSet()->getFdistributions()->getNX2()); - dataSetParamStr1.nx3 = dataSetParamStr2.nx3 = dataSetParamStr3.nx3 = static_cast<int>(block->getKernel()->getDataSet()->getFdistributions()->getNX3()); - - doubleCountInBlock = dataSetParamStr1.nx[0] * dataSetParamStr1.nx[1] * dataSetParamStr1.nx[2] * dataSetParamStr1.nx[3] + - dataSetParamStr2.nx[0] * dataSetParamStr2.nx[1] * dataSetParamStr2.nx[2] * dataSetParamStr2.nx[3] + - dataSetParamStr3.nx[0] * dataSetParamStr3.nx[1] * dataSetParamStr3.nx[2] * dataSetParamStr3.nx[3]; - - SPtr< CbArray4D<LBMReal, IndexerX4X3X2X1> > averageDensityArray = block->getKernel()->getDataSet()->getAverageDensity(); - if (averageDensityArray) - arrPresence.isAverageDensityArrayPresent = true; - else - arrPresence.isAverageDensityArrayPresent = false; - - SPtr< CbArray4D<LBMReal, IndexerX4X3X2X1> > AverageVelocityArray3DPtr = block->getKernel()->getDataSet()->getAverageVelocity(); - if (AverageVelocityArray3DPtr) - arrPresence.isAverageVelocityArrayPresent = true; - else - arrPresence.isAverageVelocityArrayPresent = false; - - SPtr< CbArray4D<LBMReal, IndexerX4X3X2X1> > AverageFluctArray3DPtr = block->getKernel()->getDataSet()->getAverageFluctuations(); - if (AverageFluctArray3DPtr) - arrPresence.isAverageFluktuationsArrayPresent = true; - else - arrPresence.isAverageFluktuationsArrayPresent = false; - - SPtr< CbArray4D<LBMReal, IndexerX4X3X2X1> > AverageTripleArray3DPtr = block->getKernel()->getDataSet()->getAverageTriplecorrelations(); - if (AverageTripleArray3DPtr) - arrPresence.isAverageTripleArrayPresent = true; - else - arrPresence.isAverageTripleArrayPresent = false; - - SPtr< CbArray4D<LBMReal, IndexerX4X3X2X1> > ShearStressValArray3DPtr = block->getKernel()->getDataSet()->getShearStressValues(); - if (ShearStressValArray3DPtr) - arrPresence.isShearStressValArrayPresent = true; - else - arrPresence.isShearStressValArrayPresent = false; - - SPtr< CbArray3D<LBMReal, IndexerX3X2X1> > relaxationFactor3DPtr = block->getKernel()->getDataSet()->getRelaxationFactor(); - if (relaxationFactor3DPtr) - arrPresence.isRelaxationFactorPresent = true; - else - arrPresence.isRelaxationFactorPresent = false; - - firstBlock = false; - } - - if (localDistributions && (dataSetParamStr1.nx[0]>0) && (dataSetParamStr1.nx[1]>0) && (dataSetParamStr1.nx[2]>0) && (dataSetParamStr1.nx[3]>0)) - doubleValuesArray.insert(doubleValuesArray.end(), localDistributions->getDataVector().begin(), localDistributions->getDataVector().end()); - if (nonLocalDistributions && (dataSetParamStr2.nx[0]>0) && (dataSetParamStr2.nx[1]>0) && (dataSetParamStr2.nx[2]>0) && (dataSetParamStr2.nx[3]>0)) - doubleValuesArray.insert(doubleValuesArray.end(), nonLocalDistributions->getDataVector().begin(), nonLocalDistributions->getDataVector().end()); - if (zeroDistributions && (dataSetParamStr3.nx[0]>0) && (dataSetParamStr3.nx[1]>0) && (dataSetParamStr3.nx[2]>0)) - doubleValuesArray.insert(doubleValuesArray.end(), zeroDistributions->getDataVector().begin(), zeroDistributions->getDataVector().end()); - - ic++; - } - } - - // register new MPI-types depending on the block-specific information - MPI_Type_contiguous(doubleCountInBlock, MPI_DOUBLE, &dataSetDoubleType); - MPI_Type_commit(&dataSetDoubleType); - - if (comm->isRoot()) - { - UBLOG(logINFO, "MPIIORestartCoProcessor::writeDataSet start MPI IO rank = " << rank); - UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); - } - - // write to the file - // all processes calculate their offsets (quantity of bytes that the process is going to write) - // and notify the next process (with the rank = rank + 1) - MPI_Offset write_offset = (MPI_Offset)(size * sizeof(int)); - size_t next_write_offset = 0; - - if (size>1) - { - if (rank == 0) - { - next_write_offset = write_offset + 3 * sizeof(dataSetParam) + blocksCount * (sizeof(DataSetRestart) + doubleCountInBlock * sizeof(double)); - MPI_Send(&next_write_offset, 1, MPI_LONG_LONG_INT, 1, 5, MPI_COMM_WORLD); - } - else - { - MPI_Recv(&write_offset, 1, MPI_LONG_LONG_INT, rank - 1, 5, MPI_COMM_WORLD, MPI_STATUS_IGNORE); - next_write_offset = write_offset + 3 * sizeof(dataSetParam) + blocksCount * (sizeof(DataSetRestart) + doubleCountInBlock * sizeof(double)); - if (rank<size - 1) - MPI_Send(&next_write_offset, 1, MPI_LONG_LONG_INT, rank + 1, 5, MPI_COMM_WORLD); - } - } - - double start, finish; - if (comm->isRoot()) start = MPI_Wtime(); - - MPI_Info info = MPI_INFO_NULL; + if (localDistributions && (dataSetParamStr1.nx[0] > 0) && (dataSetParamStr1.nx[1] > 0) && + (dataSetParamStr1.nx[2] > 0) && (dataSetParamStr1.nx[3] > 0)) + doubleValuesArray.insert(doubleValuesArray.end(), localDistributions->getDataVector().begin(), + localDistributions->getDataVector().end()); + if (nonLocalDistributions && (dataSetParamStr2.nx[0] > 0) && (dataSetParamStr2.nx[1] > 0) && + (dataSetParamStr2.nx[2] > 0) && (dataSetParamStr2.nx[3] > 0)) + doubleValuesArray.insert(doubleValuesArray.end(), nonLocalDistributions->getDataVector().begin(), + nonLocalDistributions->getDataVector().end()); + if (zeroDistributions && (dataSetParamStr3.nx[0] > 0) && (dataSetParamStr3.nx[1] > 0) && + (dataSetParamStr3.nx[2] > 0)) + doubleValuesArray.insert(doubleValuesArray.end(), zeroDistributions->getDataVector().begin(), + zeroDistributions->getDataVector().end()); + + ic++; + } + } + + // register new MPI-types depending on the block-specific information + MPI_Type_contiguous(doubleCountInBlock, MPI_DOUBLE, &dataSetDoubleType); + MPI_Type_commit(&dataSetDoubleType); + + if (comm->isRoot()) { + UBLOG(logINFO, "MPIIORestartCoProcessor::writeDataSet start MPI IO rank = " << rank); + UBLOG(logINFO, "Physical Memory currently used by current process: " + << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); + } + + // write to the file + // all processes calculate their offsets (quantity of bytes that the process is going to write) + // and notify the next process (with the rank = rank + 1) + MPI_Offset write_offset = (MPI_Offset)(size * sizeof(int)); + size_t next_write_offset = 0; + + if (size > 1) { + if (rank == 0) { + next_write_offset = write_offset + 3 * sizeof(dataSetParam) + + blocksCount * (sizeof(DataSetRestart) + doubleCountInBlock * sizeof(double)); + MPI_Send(&next_write_offset, 1, MPI_LONG_LONG_INT, 1, 5, MPI_COMM_WORLD); + } else { + MPI_Recv(&write_offset, 1, MPI_LONG_LONG_INT, rank - 1, 5, MPI_COMM_WORLD, MPI_STATUS_IGNORE); + next_write_offset = write_offset + 3 * sizeof(dataSetParam) + + blocksCount * (sizeof(DataSetRestart) + doubleCountInBlock * sizeof(double)); + if (rank < size - 1) + MPI_Send(&next_write_offset, 1, MPI_LONG_LONG_INT, rank + 1, 5, MPI_COMM_WORLD); + } + } + + double start, finish; + if (comm->isRoot()) + start = MPI_Wtime(); + + MPI_Info info = MPI_INFO_NULL; #ifdef HLRN_LUSTRE - MPI_Info_create(&info); - MPI_Info_set(info, "striping_factor", "40"); - MPI_Info_set(info, "striping_unit", "4M"); + MPI_Info_create(&info); + MPI_Info_set(info, "striping_factor", "40"); + MPI_Info_set(info, "striping_unit", "4M"); #endif - MPI_File file_handler; - std::string filename = path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + "/cpDataSet.bin"; - int rc = MPI_File_open(MPI_COMM_WORLD, filename.c_str(), MPI_MODE_CREATE | MPI_MODE_WRONLY, info, &file_handler); - if (rc != MPI_SUCCESS) throw UbException(UB_EXARGS, "couldn't open file " + filename); - - // each process writes the quantity of it's blocks - MPI_File_write_at(file_handler, (MPI_Offset)(rank * sizeof(int)), &blocksCount, 1, MPI_INT, MPI_STATUS_IGNORE); - // each process writes common parameters of a dataSet - MPI_File_write_at(file_handler, write_offset, &dataSetParamStr1, 1, dataSetParamType, MPI_STATUS_IGNORE); - MPI_File_write_at(file_handler, (MPI_Offset)(write_offset + sizeof(dataSetParam)), &dataSetParamStr2, 1, dataSetParamType, MPI_STATUS_IGNORE); - MPI_File_write_at(file_handler, (MPI_Offset)(write_offset + 2 * sizeof(dataSetParam)), &dataSetParamStr3, 1, dataSetParamType, MPI_STATUS_IGNORE); - // each process writes data identifying blocks - MPI_File_write_at(file_handler, (MPI_Offset)(write_offset + 3 * sizeof(dataSetParam)), dataSetArray, blocksCount, dataSetType, MPI_STATUS_IGNORE); - // each process writes the dataSet arrays - if (doubleValuesArray.size() > 0) - MPI_File_write_at(file_handler, (MPI_Offset)(write_offset + 3 * sizeof(dataSetParam) + blocksCount * sizeof(DataSetRestart)), &doubleValuesArray[0], blocksCount, dataSetDoubleType, MPI_STATUS_IGNORE); - - MPI_File_sync(file_handler); - MPI_File_close(&file_handler); - - MPI_Type_free(&dataSetDoubleType); - - delete[] dataSetArray; - - if (comm->isRoot()) - { - finish = MPI_Wtime(); - UBLOG(logINFO, "MPIIORestartCoProcessor::writeDataSet time: " << finish - start << " s"); - } - - MPI_File file_handler1; - std::string filename1 = path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + "/cpArrays.bin"; - rc = MPI_File_open(MPI_COMM_WORLD, filename1.c_str(), MPI_MODE_CREATE | MPI_MODE_WRONLY, info, &file_handler1); - if (rc != MPI_SUCCESS) throw UbException(UB_EXARGS, "couldn't open file " + filename1); - MPI_File_write_at(file_handler1, (MPI_Offset)0, &arrPresence, 1, arrayPresenceType, MPI_STATUS_IGNORE); - MPI_File_sync(file_handler1); - MPI_File_close(&file_handler1); - - if (arrPresence.isAverageDensityArrayPresent) - writeAverageDensityArray(step); - - if (arrPresence.isAverageVelocityArrayPresent) - writeAverageVelocityArray(step); - - if (arrPresence.isAverageFluktuationsArrayPresent) - writeAverageFluktuationsArray(step); - - if (arrPresence.isAverageTripleArrayPresent) - writeAverageTripleArray(step); - - if (arrPresence.isShearStressValArrayPresent) - writeShearStressValArray(step); - - if (arrPresence.isRelaxationFactorPresent) - writeRelaxationFactor(step); - + MPI_File file_handler; + std::string filename = path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + "/cpDataSet.bin"; + int rc = MPI_File_open(MPI_COMM_WORLD, filename.c_str(), MPI_MODE_CREATE | MPI_MODE_WRONLY, info, &file_handler); + if (rc != MPI_SUCCESS) + throw UbException(UB_EXARGS, "couldn't open file " + filename); + + // each process writes the quantity of it's blocks + MPI_File_write_at(file_handler, (MPI_Offset)(rank * sizeof(int)), &blocksCount, 1, MPI_INT, MPI_STATUS_IGNORE); + // each process writes common parameters of a dataSet + MPI_File_write_at(file_handler, write_offset, &dataSetParamStr1, 1, dataSetParamType, MPI_STATUS_IGNORE); + MPI_File_write_at(file_handler, (MPI_Offset)(write_offset + sizeof(dataSetParam)), &dataSetParamStr2, 1, + dataSetParamType, MPI_STATUS_IGNORE); + MPI_File_write_at(file_handler, (MPI_Offset)(write_offset + 2 * sizeof(dataSetParam)), &dataSetParamStr3, 1, + dataSetParamType, MPI_STATUS_IGNORE); + // each process writes data identifying blocks + MPI_File_write_at(file_handler, (MPI_Offset)(write_offset + 3 * sizeof(dataSetParam)), dataSetArray, blocksCount, + dataSetType, MPI_STATUS_IGNORE); + // each process writes the dataSet arrays + if (doubleValuesArray.size() > 0) + MPI_File_write_at(file_handler, + (MPI_Offset)(write_offset + 3 * sizeof(dataSetParam) + blocksCount * sizeof(DataSetRestart)), + &doubleValuesArray[0], blocksCount, dataSetDoubleType, MPI_STATUS_IGNORE); + + MPI_File_sync(file_handler); + MPI_File_close(&file_handler); + + MPI_Type_free(&dataSetDoubleType); + + delete[] dataSetArray; + + if (comm->isRoot()) { + finish = MPI_Wtime(); + UBLOG(logINFO, "MPIIORestartCoProcessor::writeDataSet time: " << finish - start << " s"); + } + + MPI_File file_handler1; + std::string filename1 = path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + "/cpArrays.bin"; + rc = MPI_File_open(MPI_COMM_WORLD, filename1.c_str(), MPI_MODE_CREATE | MPI_MODE_WRONLY, info, &file_handler1); + if (rc != MPI_SUCCESS) + throw UbException(UB_EXARGS, "couldn't open file " + filename1); + MPI_File_write_at(file_handler1, (MPI_Offset)0, &arrPresence, 1, arrayPresenceType, MPI_STATUS_IGNORE); + MPI_File_sync(file_handler1); + MPI_File_close(&file_handler1); + + if (arrPresence.isAverageDensityArrayPresent) + writeAverageDensityArray(step); + + if (arrPresence.isAverageVelocityArrayPresent) + writeAverageVelocityArray(step); + + if (arrPresence.isAverageFluktuationsArrayPresent) + writeAverageFluktuationsArray(step); + + if (arrPresence.isAverageTripleArrayPresent) + writeAverageTripleArray(step); + + if (arrPresence.isShearStressValArrayPresent) + writeShearStressValArray(step); + + if (arrPresence.isRelaxationFactorPresent) + writeRelaxationFactor(step); } void MPIIORestartCoProcessor::writeAverageDensityArray(int step) { - int rank, size; - MPI_Comm_rank(MPI_COMM_WORLD, &rank); - MPI_Comm_size(MPI_COMM_WORLD, &size); - - int blocksCount = 0; // quantity of blocks in the grid, max 2147483648 blocks! - - std::vector<SPtr<Block3D>> blocksVector[25]; - int minInitLevel = this->grid->getCoarsestInitializedLevel(); - int maxInitLevel = this->grid->getFinestInitializedLevel(); - for (int level = minInitLevel; level <= maxInitLevel; level++) - { - grid->getBlocks(level, rank, blocksVector[level]); - blocksCount += static_cast<int>(blocksVector[level].size()); - } - - DataSetSmallRestart* dataSetSmallArray = new DataSetSmallRestart[blocksCount]; - std::vector<double> doubleValuesArray; // double-values of the AverageDensityArray in all blocks - dataSetParam dataSetParamStr; - - if (comm->isRoot()) - { - UBLOG(logINFO, "MPIIORestartCoProcessor::writeAverageDensityArray start collect data rank = " << rank); - UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); - } - - bool firstBlock = true; - int doubleCountInBlock = 0; - int ic = 0; - SPtr< CbArray4D<LBMReal, IndexerX4X3X2X1> > averageDensityArray; - - for (int level = minInitLevel; level <= maxInitLevel; level++) - { - for (SPtr<Block3D> block : blocksVector[level]) // blocks of the current level - { - dataSetSmallArray[ic].x1 = block->getX1(); // coordinates of the block needed to find it while regenerating the grid - dataSetSmallArray[ic].x2 = block->getX2(); - dataSetSmallArray[ic].x3 = block->getX3(); - dataSetSmallArray[ic].level = block->getLevel(); - - averageDensityArray = block->getKernel()->getDataSet()->getAverageDensity(); - - if (firstBlock) // when first (any) valid block... - { - dataSetParamStr.nx1 = dataSetParamStr.nx2 = dataSetParamStr.nx3 = 0; - dataSetParamStr.nx[0] = static_cast<int>(averageDensityArray->getNX1()); - dataSetParamStr.nx[1] = static_cast<int>(averageDensityArray->getNX2()); - dataSetParamStr.nx[2] = static_cast<int>(averageDensityArray->getNX3()); - dataSetParamStr.nx[3] = static_cast<int>(averageDensityArray->getNX4()); - doubleCountInBlock = dataSetParamStr.nx[0] * dataSetParamStr.nx[1] * dataSetParamStr.nx[2] * dataSetParamStr.nx[3]; - - firstBlock = false; - } - - if ((dataSetParamStr.nx[0] > 0) && (dataSetParamStr.nx[1] > 0) && (dataSetParamStr.nx[2] > 0) && (dataSetParamStr.nx[3] > 0)) - doubleValuesArray.insert(doubleValuesArray.end(), averageDensityArray->getDataVector().begin(), averageDensityArray->getDataVector().end()); - - ic++; - } - } - - // register new MPI-types depending on the block-specific information - MPI_Type_contiguous(doubleCountInBlock, MPI_DOUBLE, &dataSetDoubleType); - MPI_Type_commit(&dataSetDoubleType); - - if (comm->isRoot()) - { - UBLOG(logINFO, "MPIIORestartCoProcessor::writeAverageDensityArray start MPI IO rank = " << rank); - UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); - } - - // write to the file - // all processes calculate their offsets (quantity of bytes that the process is going to write) - // and notify the next process (with the rank = rank + 1) - MPI_Offset write_offset = (MPI_Offset)(size * sizeof(int)); - size_t next_write_offset = 0; - - if (size > 1) - { - if (rank == 0) - { - next_write_offset = write_offset + sizeof(dataSetParam) + blocksCount*(sizeof(DataSetSmallRestart) + doubleCountInBlock * sizeof(double)); - MPI_Send(&next_write_offset, 1, MPI_LONG_LONG_INT, 1, 5, MPI_COMM_WORLD); - } - else - { - MPI_Recv(&write_offset, 1, MPI_LONG_LONG_INT, rank - 1, 5, MPI_COMM_WORLD, MPI_STATUS_IGNORE); - next_write_offset = write_offset + sizeof(dataSetParam) + blocksCount*(sizeof(DataSetSmallRestart) + doubleCountInBlock * sizeof(double)); - if (rank<size - 1) - MPI_Send(&next_write_offset, 1, MPI_LONG_LONG_INT, rank + 1, 5, MPI_COMM_WORLD); - } - } - - double start, finish; - if (comm->isRoot()) start = MPI_Wtime(); - - MPI_Info info = MPI_INFO_NULL; + int rank, size; + MPI_Comm_rank(MPI_COMM_WORLD, &rank); + MPI_Comm_size(MPI_COMM_WORLD, &size); + + int blocksCount = 0; // quantity of blocks in the grid, max 2147483648 blocks! + + std::vector<SPtr<Block3D>> blocksVector[25]; + int minInitLevel = this->grid->getCoarsestInitializedLevel(); + int maxInitLevel = this->grid->getFinestInitializedLevel(); + for (int level = minInitLevel; level <= maxInitLevel; level++) { + grid->getBlocks(level, rank, blocksVector[level]); + blocksCount += static_cast<int>(blocksVector[level].size()); + } + + DataSetSmallRestart *dataSetSmallArray = new DataSetSmallRestart[blocksCount]; + std::vector<double> doubleValuesArray; // double-values of the AverageDensityArray in all blocks + dataSetParam dataSetParamStr; + + if (comm->isRoot()) { + UBLOG(logINFO, "MPIIORestartCoProcessor::writeAverageDensityArray start collect data rank = " << rank); + UBLOG(logINFO, "Physical Memory currently used by current process: " + << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); + } + + bool firstBlock = true; + int doubleCountInBlock = 0; + int ic = 0; + SPtr<CbArray4D<LBMReal, IndexerX4X3X2X1>> averageDensityArray; + + for (int level = minInitLevel; level <= maxInitLevel; level++) { + for (SPtr<Block3D> block : blocksVector[level]) // blocks of the current level + { + dataSetSmallArray[ic].x1 = + block->getX1(); // coordinates of the block needed to find it while regenerating the grid + dataSetSmallArray[ic].x2 = block->getX2(); + dataSetSmallArray[ic].x3 = block->getX3(); + dataSetSmallArray[ic].level = block->getLevel(); + + averageDensityArray = block->getKernel()->getDataSet()->getAverageDensity(); + + if (firstBlock) // when first (any) valid block... + { + dataSetParamStr.nx1 = dataSetParamStr.nx2 = dataSetParamStr.nx3 = 0; + dataSetParamStr.nx[0] = static_cast<int>(averageDensityArray->getNX1()); + dataSetParamStr.nx[1] = static_cast<int>(averageDensityArray->getNX2()); + dataSetParamStr.nx[2] = static_cast<int>(averageDensityArray->getNX3()); + dataSetParamStr.nx[3] = static_cast<int>(averageDensityArray->getNX4()); + doubleCountInBlock = + dataSetParamStr.nx[0] * dataSetParamStr.nx[1] * dataSetParamStr.nx[2] * dataSetParamStr.nx[3]; + + firstBlock = false; + } + + if ((dataSetParamStr.nx[0] > 0) && (dataSetParamStr.nx[1] > 0) && (dataSetParamStr.nx[2] > 0) && + (dataSetParamStr.nx[3] > 0)) + doubleValuesArray.insert(doubleValuesArray.end(), averageDensityArray->getDataVector().begin(), + averageDensityArray->getDataVector().end()); + + ic++; + } + } + + // register new MPI-types depending on the block-specific information + MPI_Type_contiguous(doubleCountInBlock, MPI_DOUBLE, &dataSetDoubleType); + MPI_Type_commit(&dataSetDoubleType); + + if (comm->isRoot()) { + UBLOG(logINFO, "MPIIORestartCoProcessor::writeAverageDensityArray start MPI IO rank = " << rank); + UBLOG(logINFO, "Physical Memory currently used by current process: " + << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); + } + + // write to the file + // all processes calculate their offsets (quantity of bytes that the process is going to write) + // and notify the next process (with the rank = rank + 1) + MPI_Offset write_offset = (MPI_Offset)(size * sizeof(int)); + size_t next_write_offset = 0; + + if (size > 1) { + if (rank == 0) { + next_write_offset = write_offset + sizeof(dataSetParam) + + blocksCount * (sizeof(DataSetSmallRestart) + doubleCountInBlock * sizeof(double)); + MPI_Send(&next_write_offset, 1, MPI_LONG_LONG_INT, 1, 5, MPI_COMM_WORLD); + } else { + MPI_Recv(&write_offset, 1, MPI_LONG_LONG_INT, rank - 1, 5, MPI_COMM_WORLD, MPI_STATUS_IGNORE); + next_write_offset = write_offset + sizeof(dataSetParam) + + blocksCount * (sizeof(DataSetSmallRestart) + doubleCountInBlock * sizeof(double)); + if (rank < size - 1) + MPI_Send(&next_write_offset, 1, MPI_LONG_LONG_INT, rank + 1, 5, MPI_COMM_WORLD); + } + } + + double start, finish; + if (comm->isRoot()) + start = MPI_Wtime(); + + MPI_Info info = MPI_INFO_NULL; #ifdef HLRN_LUSTRE - MPI_Info_create(&info); - MPI_Info_set(info, "striping_factor", "40"); - MPI_Info_set(info, "striping_unit", "4M"); + MPI_Info_create(&info); + MPI_Info_set(info, "striping_factor", "40"); + MPI_Info_set(info, "striping_unit", "4M"); #endif - MPI_File file_handler; - std::string filename = path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + "/cpAverageDensityArray.bin"; - int rc = MPI_File_open(MPI_COMM_WORLD, filename.c_str(), MPI_MODE_CREATE | MPI_MODE_WRONLY, info, &file_handler); - if (rc != MPI_SUCCESS) throw UbException(UB_EXARGS, "couldn't open file " + filename); - - // each process writes the quantity of it's blocks - MPI_File_write_at(file_handler, (MPI_Offset)(rank * sizeof(int)), &blocksCount, 1, MPI_INT, MPI_STATUS_IGNORE); - // each process writes common parameters of a dataSet - MPI_File_write_at(file_handler, write_offset, &dataSetParamStr, 1, dataSetParamType, MPI_STATUS_IGNORE); - // each process writes data identifying blocks - MPI_File_write_at(file_handler, (MPI_Offset)(write_offset + sizeof(dataSetParam)), dataSetSmallArray, blocksCount, dataSetSmallType, MPI_STATUS_IGNORE); - // each process writes the dataSet arrays - if (doubleValuesArray.size() > 0) - MPI_File_write_at(file_handler, (MPI_Offset)(write_offset + sizeof(dataSetParam) + blocksCount * sizeof(DataSetSmallRestart)), &doubleValuesArray[0], blocksCount, dataSetDoubleType, MPI_STATUS_IGNORE); - - MPI_File_sync(file_handler); - MPI_File_close(&file_handler); - MPI_Type_free(&dataSetDoubleType); - - if (comm->isRoot()) - { - finish = MPI_Wtime(); - UBLOG(logINFO, "MPIIORestartCoProcessor::writeAverageDensityArray time: " << finish - start << " s"); - } - - delete[] dataSetSmallArray; + MPI_File file_handler; + std::string filename = path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + "/cpAverageDensityArray.bin"; + int rc = MPI_File_open(MPI_COMM_WORLD, filename.c_str(), MPI_MODE_CREATE | MPI_MODE_WRONLY, info, &file_handler); + if (rc != MPI_SUCCESS) + throw UbException(UB_EXARGS, "couldn't open file " + filename); + + // each process writes the quantity of it's blocks + MPI_File_write_at(file_handler, (MPI_Offset)(rank * sizeof(int)), &blocksCount, 1, MPI_INT, MPI_STATUS_IGNORE); + // each process writes common parameters of a dataSet + MPI_File_write_at(file_handler, write_offset, &dataSetParamStr, 1, dataSetParamType, MPI_STATUS_IGNORE); + // each process writes data identifying blocks + MPI_File_write_at(file_handler, (MPI_Offset)(write_offset + sizeof(dataSetParam)), dataSetSmallArray, blocksCount, + dataSetSmallType, MPI_STATUS_IGNORE); + // each process writes the dataSet arrays + if (doubleValuesArray.size() > 0) + MPI_File_write_at(file_handler, + (MPI_Offset)(write_offset + sizeof(dataSetParam) + blocksCount * sizeof(DataSetSmallRestart)), + &doubleValuesArray[0], blocksCount, dataSetDoubleType, MPI_STATUS_IGNORE); + + MPI_File_sync(file_handler); + MPI_File_close(&file_handler); + MPI_Type_free(&dataSetDoubleType); + + if (comm->isRoot()) { + finish = MPI_Wtime(); + UBLOG(logINFO, "MPIIORestartCoProcessor::writeAverageDensityArray time: " << finish - start << " s"); + } + + delete[] dataSetSmallArray; } void MPIIORestartCoProcessor::writeAverageVelocityArray(int step) { - int rank, size; - MPI_Comm_rank(MPI_COMM_WORLD, &rank); - MPI_Comm_size(MPI_COMM_WORLD, &size); - - int blocksCount = 0; // quantity of blocks in the grid, max 2147483648 blocks! - - std::vector<SPtr<Block3D>> blocksVector[25]; - int minInitLevel = this->grid->getCoarsestInitializedLevel(); - int maxInitLevel = this->grid->getFinestInitializedLevel(); - for (int level = minInitLevel; level <= maxInitLevel; level++) - { - grid->getBlocks(level, rank, blocksVector[level]); - blocksCount += static_cast<int>(blocksVector[level].size()); - } - - DataSetSmallRestart* dataSetSmallArray = new DataSetSmallRestart[blocksCount]; - std::vector<double> doubleValuesArray; // double-values (arrays of f's) in all blocks - dataSetParam dataSetParamStr; - - if (comm->isRoot()) - { - UBLOG(logINFO, "MPIIORestartCoProcessor::writeAverageVelocityArray start collect data rank = " << rank); - UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); - } - - bool firstBlock = true; - int doubleCountInBlock = 0; - int ic = 0; - SPtr< CbArray4D<LBMReal, IndexerX4X3X2X1> > AverageVelocityArray3DPtr; - - for (int level = minInitLevel; level <= maxInitLevel; level++) - { - for (SPtr<Block3D> block : blocksVector[level]) // blocks of the current level - { - dataSetSmallArray[ic].x1 = block->getX1(); // coordinates of the block needed to find it while regenerating the grid - dataSetSmallArray[ic].x2 = block->getX2(); - dataSetSmallArray[ic].x3 = block->getX3(); - dataSetSmallArray[ic].level = block->getLevel(); - - AverageVelocityArray3DPtr = block->getKernel()->getDataSet()->getAverageVelocity(); - - if (firstBlock) // when first (any) valid block... - { - dataSetParamStr.nx1 = dataSetParamStr.nx2 = dataSetParamStr.nx3 = 0; - dataSetParamStr.nx[0] = static_cast<int>(AverageVelocityArray3DPtr->getNX1()); - dataSetParamStr.nx[1] = static_cast<int>(AverageVelocityArray3DPtr->getNX2()); - dataSetParamStr.nx[2] = static_cast<int>(AverageVelocityArray3DPtr->getNX3()); - dataSetParamStr.nx[3] = static_cast<int>(AverageVelocityArray3DPtr->getNX4()); - doubleCountInBlock = dataSetParamStr.nx[0] * dataSetParamStr.nx[1] * dataSetParamStr.nx[2] * dataSetParamStr.nx[3]; - - firstBlock = false; - } - - if ((dataSetParamStr.nx[0]>0) && (dataSetParamStr.nx[1]>0) && (dataSetParamStr.nx[2]>0) && (dataSetParamStr.nx[3]>0)) - doubleValuesArray.insert(doubleValuesArray.end(), AverageVelocityArray3DPtr->getDataVector().begin(), AverageVelocityArray3DPtr->getDataVector().end()); - - ic++; - } - } - - // register new MPI-types depending on the block-specific information - MPI_Type_contiguous(doubleCountInBlock, MPI_DOUBLE, &dataSetDoubleType); - MPI_Type_commit(&dataSetDoubleType); - - if (comm->isRoot()) - { - UBLOG(logINFO, "MPIIORestartCoProcessor::writeAverageVelocityArray start MPI IO rank = " << rank); - UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); - } - - // write to the file - // all processes calculate their offsets (quantity of bytes that the process is going to write) - // and notify the next process (with the rank = rank + 1) - MPI_Offset write_offset = (MPI_Offset)(size * sizeof(int)); - size_t next_write_offset = 0; - - if (size > 1) - { - if (rank == 0) - { - next_write_offset = write_offset + sizeof(dataSetParam) + blocksCount*(sizeof(DataSetSmallRestart) + doubleCountInBlock * sizeof(double)); - MPI_Send(&next_write_offset, 1, MPI_LONG_LONG_INT, 1, 5, MPI_COMM_WORLD); - } - else - { - MPI_Recv(&write_offset, 1, MPI_LONG_LONG_INT, rank - 1, 5, MPI_COMM_WORLD, MPI_STATUS_IGNORE); - next_write_offset = write_offset + sizeof(dataSetParam) + blocksCount*(sizeof(DataSetSmallRestart) + doubleCountInBlock * sizeof(double)); - if (rank<size - 1) - MPI_Send(&next_write_offset, 1, MPI_LONG_LONG_INT, rank + 1, 5, MPI_COMM_WORLD); - } - } - - double start, finish; - if (comm->isRoot()) start = MPI_Wtime(); - - MPI_Info info = MPI_INFO_NULL; + int rank, size; + MPI_Comm_rank(MPI_COMM_WORLD, &rank); + MPI_Comm_size(MPI_COMM_WORLD, &size); + + int blocksCount = 0; // quantity of blocks in the grid, max 2147483648 blocks! + + std::vector<SPtr<Block3D>> blocksVector[25]; + int minInitLevel = this->grid->getCoarsestInitializedLevel(); + int maxInitLevel = this->grid->getFinestInitializedLevel(); + for (int level = minInitLevel; level <= maxInitLevel; level++) { + grid->getBlocks(level, rank, blocksVector[level]); + blocksCount += static_cast<int>(blocksVector[level].size()); + } + + DataSetSmallRestart *dataSetSmallArray = new DataSetSmallRestart[blocksCount]; + std::vector<double> doubleValuesArray; // double-values (arrays of f's) in all blocks + dataSetParam dataSetParamStr; + + if (comm->isRoot()) { + UBLOG(logINFO, "MPIIORestartCoProcessor::writeAverageVelocityArray start collect data rank = " << rank); + UBLOG(logINFO, "Physical Memory currently used by current process: " + << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); + } + + bool firstBlock = true; + int doubleCountInBlock = 0; + int ic = 0; + SPtr<CbArray4D<LBMReal, IndexerX4X3X2X1>> AverageVelocityArray3DPtr; + + for (int level = minInitLevel; level <= maxInitLevel; level++) { + for (SPtr<Block3D> block : blocksVector[level]) // blocks of the current level + { + dataSetSmallArray[ic].x1 = + block->getX1(); // coordinates of the block needed to find it while regenerating the grid + dataSetSmallArray[ic].x2 = block->getX2(); + dataSetSmallArray[ic].x3 = block->getX3(); + dataSetSmallArray[ic].level = block->getLevel(); + + AverageVelocityArray3DPtr = block->getKernel()->getDataSet()->getAverageVelocity(); + + if (firstBlock) // when first (any) valid block... + { + dataSetParamStr.nx1 = dataSetParamStr.nx2 = dataSetParamStr.nx3 = 0; + dataSetParamStr.nx[0] = static_cast<int>(AverageVelocityArray3DPtr->getNX1()); + dataSetParamStr.nx[1] = static_cast<int>(AverageVelocityArray3DPtr->getNX2()); + dataSetParamStr.nx[2] = static_cast<int>(AverageVelocityArray3DPtr->getNX3()); + dataSetParamStr.nx[3] = static_cast<int>(AverageVelocityArray3DPtr->getNX4()); + doubleCountInBlock = + dataSetParamStr.nx[0] * dataSetParamStr.nx[1] * dataSetParamStr.nx[2] * dataSetParamStr.nx[3]; + + firstBlock = false; + } + + if ((dataSetParamStr.nx[0] > 0) && (dataSetParamStr.nx[1] > 0) && (dataSetParamStr.nx[2] > 0) && + (dataSetParamStr.nx[3] > 0)) + doubleValuesArray.insert(doubleValuesArray.end(), AverageVelocityArray3DPtr->getDataVector().begin(), + AverageVelocityArray3DPtr->getDataVector().end()); + + ic++; + } + } + + // register new MPI-types depending on the block-specific information + MPI_Type_contiguous(doubleCountInBlock, MPI_DOUBLE, &dataSetDoubleType); + MPI_Type_commit(&dataSetDoubleType); + + if (comm->isRoot()) { + UBLOG(logINFO, "MPIIORestartCoProcessor::writeAverageVelocityArray start MPI IO rank = " << rank); + UBLOG(logINFO, "Physical Memory currently used by current process: " + << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); + } + + // write to the file + // all processes calculate their offsets (quantity of bytes that the process is going to write) + // and notify the next process (with the rank = rank + 1) + MPI_Offset write_offset = (MPI_Offset)(size * sizeof(int)); + size_t next_write_offset = 0; + + if (size > 1) { + if (rank == 0) { + next_write_offset = write_offset + sizeof(dataSetParam) + + blocksCount * (sizeof(DataSetSmallRestart) + doubleCountInBlock * sizeof(double)); + MPI_Send(&next_write_offset, 1, MPI_LONG_LONG_INT, 1, 5, MPI_COMM_WORLD); + } else { + MPI_Recv(&write_offset, 1, MPI_LONG_LONG_INT, rank - 1, 5, MPI_COMM_WORLD, MPI_STATUS_IGNORE); + next_write_offset = write_offset + sizeof(dataSetParam) + + blocksCount * (sizeof(DataSetSmallRestart) + doubleCountInBlock * sizeof(double)); + if (rank < size - 1) + MPI_Send(&next_write_offset, 1, MPI_LONG_LONG_INT, rank + 1, 5, MPI_COMM_WORLD); + } + } + + double start, finish; + if (comm->isRoot()) + start = MPI_Wtime(); + + MPI_Info info = MPI_INFO_NULL; #ifdef HLRN_LUSTRE - MPI_Info_create(&info); - MPI_Info_set(info, "striping_factor", "40"); - MPI_Info_set(info, "striping_unit", "4M"); + MPI_Info_create(&info); + MPI_Info_set(info, "striping_factor", "40"); + MPI_Info_set(info, "striping_unit", "4M"); #endif - MPI_File file_handler; - std::string filename = path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + "/cpAverageVelocityArray.bin"; - int rc = MPI_File_open(MPI_COMM_WORLD, filename.c_str(), MPI_MODE_CREATE | MPI_MODE_WRONLY, info, &file_handler); - if (rc != MPI_SUCCESS) throw UbException(UB_EXARGS, "couldn't open file " + filename); - - // each process writes the quantity of it's blocks - MPI_File_write_at(file_handler, (MPI_Offset)(rank * sizeof(int)), &blocksCount, 1, MPI_INT, MPI_STATUS_IGNORE); - // each process writes common parameters of a dataSet - MPI_File_write_at(file_handler, write_offset, &dataSetParamStr, 1, dataSetParamType, MPI_STATUS_IGNORE); - // each process writes data identifying blocks - MPI_File_write_at(file_handler, (MPI_Offset)(write_offset + sizeof(dataSetParam)), dataSetSmallArray, blocksCount, dataSetSmallType, MPI_STATUS_IGNORE); - // each process writes the dataSet arrays - if (doubleValuesArray.size() > 0) - MPI_File_write_at(file_handler, (MPI_Offset)(write_offset + sizeof(dataSetParam) + blocksCount * sizeof(DataSetSmallRestart)), &doubleValuesArray[0], blocksCount, dataSetDoubleType, MPI_STATUS_IGNORE); - - MPI_File_sync(file_handler); - MPI_File_close(&file_handler); - - MPI_Type_free(&dataSetDoubleType); - if (comm->isRoot()) - { - finish = MPI_Wtime(); - UBLOG(logINFO, "MPIIORestartCoProcessor::writeAverageVelocityArray time: " << finish - start << " s"); - } - - delete[] dataSetSmallArray; + MPI_File file_handler; + std::string filename = path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + "/cpAverageVelocityArray.bin"; + int rc = MPI_File_open(MPI_COMM_WORLD, filename.c_str(), MPI_MODE_CREATE | MPI_MODE_WRONLY, info, &file_handler); + if (rc != MPI_SUCCESS) + throw UbException(UB_EXARGS, "couldn't open file " + filename); + + // each process writes the quantity of it's blocks + MPI_File_write_at(file_handler, (MPI_Offset)(rank * sizeof(int)), &blocksCount, 1, MPI_INT, MPI_STATUS_IGNORE); + // each process writes common parameters of a dataSet + MPI_File_write_at(file_handler, write_offset, &dataSetParamStr, 1, dataSetParamType, MPI_STATUS_IGNORE); + // each process writes data identifying blocks + MPI_File_write_at(file_handler, (MPI_Offset)(write_offset + sizeof(dataSetParam)), dataSetSmallArray, blocksCount, + dataSetSmallType, MPI_STATUS_IGNORE); + // each process writes the dataSet arrays + if (doubleValuesArray.size() > 0) + MPI_File_write_at(file_handler, + (MPI_Offset)(write_offset + sizeof(dataSetParam) + blocksCount * sizeof(DataSetSmallRestart)), + &doubleValuesArray[0], blocksCount, dataSetDoubleType, MPI_STATUS_IGNORE); + + MPI_File_sync(file_handler); + MPI_File_close(&file_handler); + + MPI_Type_free(&dataSetDoubleType); + if (comm->isRoot()) { + finish = MPI_Wtime(); + UBLOG(logINFO, "MPIIORestartCoProcessor::writeAverageVelocityArray time: " << finish - start << " s"); + } + + delete[] dataSetSmallArray; } void MPIIORestartCoProcessor::writeAverageFluktuationsArray(int step) { - int rank, size; - MPI_Comm_rank(MPI_COMM_WORLD, &rank); - MPI_Comm_size(MPI_COMM_WORLD, &size); - - int blocksCount = 0; // quantity of blocks in the grid, max 2147483648 blocks! - - std::vector<SPtr<Block3D>> blocksVector[25]; - int minInitLevel = this->grid->getCoarsestInitializedLevel(); - int maxInitLevel = this->grid->getFinestInitializedLevel(); - for (int level = minInitLevel; level <= maxInitLevel; level++) - { - grid->getBlocks(level, rank, blocksVector[level]); - blocksCount += static_cast<int>(blocksVector[level].size()); - } - - DataSetSmallRestart* dataSetSmallArray = new DataSetSmallRestart[blocksCount]; - std::vector<double> doubleValuesArray; // double-values (arrays of f's) in all blocks - dataSetParam dataSetParamStr; - - if (comm->isRoot()) - { - UBLOG(logINFO, "MPIIORestartCoProcessor::writeAverageFluktuationsArray start collect data rank = " << rank); - UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); - } - - bool firstBlock = true; - int doubleCountInBlock = 0; - int ic = 0; - SPtr< CbArray4D<LBMReal, IndexerX4X3X2X1> > AverageFluctArray3DPtr; - - for (int level = minInitLevel; level <= maxInitLevel; level++) - { - for (SPtr<Block3D> block : blocksVector[level]) // blocks of the current level - { - dataSetSmallArray[ic].x1 = block->getX1(); // coordinates of the block needed to find it while regenerating the grid - dataSetSmallArray[ic].x2 = block->getX2(); - dataSetSmallArray[ic].x3 = block->getX3(); - dataSetSmallArray[ic].level = block->getLevel(); - - AverageFluctArray3DPtr = block->getKernel()->getDataSet()->getAverageFluctuations(); - - if (firstBlock) // when first (any) valid block... - { - dataSetParamStr.nx1 = dataSetParamStr.nx2 = dataSetParamStr.nx3 = 0; - dataSetParamStr.nx[0] = static_cast<int>(AverageFluctArray3DPtr->getNX1()); - dataSetParamStr.nx[1] = static_cast<int>(AverageFluctArray3DPtr->getNX2()); - dataSetParamStr.nx[2] = static_cast<int>(AverageFluctArray3DPtr->getNX3()); - dataSetParamStr.nx[3] = static_cast<int>(AverageFluctArray3DPtr->getNX4()); - doubleCountInBlock = dataSetParamStr.nx[0] * dataSetParamStr.nx[1] * dataSetParamStr.nx[2] * dataSetParamStr.nx[3]; - - firstBlock = false; - } - - if ((dataSetParamStr.nx[0]>0) && (dataSetParamStr.nx[1]>0) && (dataSetParamStr.nx[2]>0) && (dataSetParamStr.nx[3]>0)) - doubleValuesArray.insert(doubleValuesArray.end(), AverageFluctArray3DPtr->getDataVector().begin(), AverageFluctArray3DPtr->getDataVector().end()); - - ic++; - } - } - - // register new MPI-types depending on the block-specific information - MPI_Type_contiguous(doubleCountInBlock, MPI_DOUBLE, &dataSetDoubleType); - MPI_Type_commit(&dataSetDoubleType); - - if (comm->isRoot()) - { - UBLOG(logINFO, "MPIIORestartCoProcessor::writeAverageFluktuationsArray start MPI IO rank = " << rank); - UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); - } - - // write to the file - // all processes calculate their offsets (quantity of bytes that the process is going to write) - // and notify the next process (with the rank = rank + 1) - MPI_Offset write_offset = (MPI_Offset)(size * sizeof(int)); - size_t next_write_offset = 0; - - if (size > 1) - { - if (rank == 0) - { - next_write_offset = write_offset + sizeof(dataSetParam) + blocksCount*(sizeof(DataSetSmallRestart) + doubleCountInBlock * sizeof(double)); - MPI_Send(&next_write_offset, 1, MPI_LONG_LONG_INT, 1, 5, MPI_COMM_WORLD); - } - else - { - MPI_Recv(&write_offset, 1, MPI_LONG_LONG_INT, rank - 1, 5, MPI_COMM_WORLD, MPI_STATUS_IGNORE); - next_write_offset = write_offset + sizeof(dataSetParam) + blocksCount*(sizeof(DataSetSmallRestart) + doubleCountInBlock * sizeof(double)); - if (rank<size - 1) - MPI_Send(&next_write_offset, 1, MPI_LONG_LONG_INT, rank + 1, 5, MPI_COMM_WORLD); - } - } - - double start, finish; - if (comm->isRoot()) start = MPI_Wtime(); - - MPI_Info info = MPI_INFO_NULL; + int rank, size; + MPI_Comm_rank(MPI_COMM_WORLD, &rank); + MPI_Comm_size(MPI_COMM_WORLD, &size); + + int blocksCount = 0; // quantity of blocks in the grid, max 2147483648 blocks! + + std::vector<SPtr<Block3D>> blocksVector[25]; + int minInitLevel = this->grid->getCoarsestInitializedLevel(); + int maxInitLevel = this->grid->getFinestInitializedLevel(); + for (int level = minInitLevel; level <= maxInitLevel; level++) { + grid->getBlocks(level, rank, blocksVector[level]); + blocksCount += static_cast<int>(blocksVector[level].size()); + } + + DataSetSmallRestart *dataSetSmallArray = new DataSetSmallRestart[blocksCount]; + std::vector<double> doubleValuesArray; // double-values (arrays of f's) in all blocks + dataSetParam dataSetParamStr; + + if (comm->isRoot()) { + UBLOG(logINFO, "MPIIORestartCoProcessor::writeAverageFluktuationsArray start collect data rank = " << rank); + UBLOG(logINFO, "Physical Memory currently used by current process: " + << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); + } + + bool firstBlock = true; + int doubleCountInBlock = 0; + int ic = 0; + SPtr<CbArray4D<LBMReal, IndexerX4X3X2X1>> AverageFluctArray3DPtr; + + for (int level = minInitLevel; level <= maxInitLevel; level++) { + for (SPtr<Block3D> block : blocksVector[level]) // blocks of the current level + { + dataSetSmallArray[ic].x1 = + block->getX1(); // coordinates of the block needed to find it while regenerating the grid + dataSetSmallArray[ic].x2 = block->getX2(); + dataSetSmallArray[ic].x3 = block->getX3(); + dataSetSmallArray[ic].level = block->getLevel(); + + AverageFluctArray3DPtr = block->getKernel()->getDataSet()->getAverageFluctuations(); + + if (firstBlock) // when first (any) valid block... + { + dataSetParamStr.nx1 = dataSetParamStr.nx2 = dataSetParamStr.nx3 = 0; + dataSetParamStr.nx[0] = static_cast<int>(AverageFluctArray3DPtr->getNX1()); + dataSetParamStr.nx[1] = static_cast<int>(AverageFluctArray3DPtr->getNX2()); + dataSetParamStr.nx[2] = static_cast<int>(AverageFluctArray3DPtr->getNX3()); + dataSetParamStr.nx[3] = static_cast<int>(AverageFluctArray3DPtr->getNX4()); + doubleCountInBlock = + dataSetParamStr.nx[0] * dataSetParamStr.nx[1] * dataSetParamStr.nx[2] * dataSetParamStr.nx[3]; + + firstBlock = false; + } + + if ((dataSetParamStr.nx[0] > 0) && (dataSetParamStr.nx[1] > 0) && (dataSetParamStr.nx[2] > 0) && + (dataSetParamStr.nx[3] > 0)) + doubleValuesArray.insert(doubleValuesArray.end(), AverageFluctArray3DPtr->getDataVector().begin(), + AverageFluctArray3DPtr->getDataVector().end()); + + ic++; + } + } + + // register new MPI-types depending on the block-specific information + MPI_Type_contiguous(doubleCountInBlock, MPI_DOUBLE, &dataSetDoubleType); + MPI_Type_commit(&dataSetDoubleType); + + if (comm->isRoot()) { + UBLOG(logINFO, "MPIIORestartCoProcessor::writeAverageFluktuationsArray start MPI IO rank = " << rank); + UBLOG(logINFO, "Physical Memory currently used by current process: " + << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); + } + + // write to the file + // all processes calculate their offsets (quantity of bytes that the process is going to write) + // and notify the next process (with the rank = rank + 1) + MPI_Offset write_offset = (MPI_Offset)(size * sizeof(int)); + size_t next_write_offset = 0; + + if (size > 1) { + if (rank == 0) { + next_write_offset = write_offset + sizeof(dataSetParam) + + blocksCount * (sizeof(DataSetSmallRestart) + doubleCountInBlock * sizeof(double)); + MPI_Send(&next_write_offset, 1, MPI_LONG_LONG_INT, 1, 5, MPI_COMM_WORLD); + } else { + MPI_Recv(&write_offset, 1, MPI_LONG_LONG_INT, rank - 1, 5, MPI_COMM_WORLD, MPI_STATUS_IGNORE); + next_write_offset = write_offset + sizeof(dataSetParam) + + blocksCount * (sizeof(DataSetSmallRestart) + doubleCountInBlock * sizeof(double)); + if (rank < size - 1) + MPI_Send(&next_write_offset, 1, MPI_LONG_LONG_INT, rank + 1, 5, MPI_COMM_WORLD); + } + } + + double start, finish; + if (comm->isRoot()) + start = MPI_Wtime(); + + MPI_Info info = MPI_INFO_NULL; #ifdef HLRN_LUSTRE - MPI_Info_create(&info); - MPI_Info_set(info, "striping_factor", "40"); - MPI_Info_set(info, "striping_unit", "4M"); + MPI_Info_create(&info); + MPI_Info_set(info, "striping_factor", "40"); + MPI_Info_set(info, "striping_unit", "4M"); #endif - MPI_File file_handler; - std::string filename = path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + "/cpAverageFluktuationsArray.bin"; - int rc = MPI_File_open(MPI_COMM_WORLD, filename.c_str(), MPI_MODE_CREATE | MPI_MODE_WRONLY, info, &file_handler); - if (rc != MPI_SUCCESS) throw UbException(UB_EXARGS, "couldn't open file " + filename); - - // each process writes the quantity of it's blocks - MPI_File_write_at(file_handler, (MPI_Offset)(rank * sizeof(int)), &blocksCount, 1, MPI_INT, MPI_STATUS_IGNORE); - // each process writes common parameters of a dataSet - MPI_File_write_at(file_handler, write_offset, &dataSetParamStr, 1, dataSetParamType, MPI_STATUS_IGNORE); - // each process writes data identifying blocks - MPI_File_write_at(file_handler, (MPI_Offset)(write_offset + sizeof(dataSetParam)), dataSetSmallArray, blocksCount, dataSetSmallType, MPI_STATUS_IGNORE); - // each process writes the dataSet arrays - if (doubleValuesArray.size() > 0) - MPI_File_write_at(file_handler, (MPI_Offset)(write_offset + sizeof(dataSetParam) + blocksCount * sizeof(DataSetSmallRestart)), &doubleValuesArray[0], blocksCount, dataSetDoubleType, MPI_STATUS_IGNORE); - - MPI_File_sync(file_handler); - MPI_File_close(&file_handler); - MPI_Type_free(&dataSetDoubleType); - - if (comm->isRoot()) - { - finish = MPI_Wtime(); - UBLOG(logINFO, "MPIIORestartCoProcessor::writeAverageFluktuationsArray time: " << finish - start << " s"); - } - - delete[] dataSetSmallArray; + MPI_File file_handler; + std::string filename = + path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + "/cpAverageFluktuationsArray.bin"; + int rc = MPI_File_open(MPI_COMM_WORLD, filename.c_str(), MPI_MODE_CREATE | MPI_MODE_WRONLY, info, &file_handler); + if (rc != MPI_SUCCESS) + throw UbException(UB_EXARGS, "couldn't open file " + filename); + + // each process writes the quantity of it's blocks + MPI_File_write_at(file_handler, (MPI_Offset)(rank * sizeof(int)), &blocksCount, 1, MPI_INT, MPI_STATUS_IGNORE); + // each process writes common parameters of a dataSet + MPI_File_write_at(file_handler, write_offset, &dataSetParamStr, 1, dataSetParamType, MPI_STATUS_IGNORE); + // each process writes data identifying blocks + MPI_File_write_at(file_handler, (MPI_Offset)(write_offset + sizeof(dataSetParam)), dataSetSmallArray, blocksCount, + dataSetSmallType, MPI_STATUS_IGNORE); + // each process writes the dataSet arrays + if (doubleValuesArray.size() > 0) + MPI_File_write_at(file_handler, + (MPI_Offset)(write_offset + sizeof(dataSetParam) + blocksCount * sizeof(DataSetSmallRestart)), + &doubleValuesArray[0], blocksCount, dataSetDoubleType, MPI_STATUS_IGNORE); + + MPI_File_sync(file_handler); + MPI_File_close(&file_handler); + MPI_Type_free(&dataSetDoubleType); + + if (comm->isRoot()) { + finish = MPI_Wtime(); + UBLOG(logINFO, "MPIIORestartCoProcessor::writeAverageFluktuationsArray time: " << finish - start << " s"); + } + + delete[] dataSetSmallArray; } void MPIIORestartCoProcessor::writeAverageTripleArray(int step) { - int rank, size; - MPI_Comm_rank(MPI_COMM_WORLD, &rank); - MPI_Comm_size(MPI_COMM_WORLD, &size); - - int blocksCount = 0; // quantity of blocks in the grid, max 2147483648 blocks! - - std::vector<SPtr<Block3D>> blocksVector[25]; - int minInitLevel = this->grid->getCoarsestInitializedLevel(); - int maxInitLevel = this->grid->getFinestInitializedLevel(); - for (int level = minInitLevel; level <= maxInitLevel; level++) - { - grid->getBlocks(level, rank, blocksVector[level]); - blocksCount += static_cast<int>(blocksVector[level].size()); - } - - DataSetSmallRestart* dataSetSmallArray = new DataSetSmallRestart[blocksCount]; - std::vector<double> doubleValuesArray; // double-values (arrays of f's) in all blocks - dataSetParam dataSetParamStr; - - if (comm->isRoot()) - { - UBLOG(logINFO, "MPIIORestartCoProcessor::writeAverageTripleArray start collect data rank = " << rank); - UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); - } - - bool firstBlock = true; - int doubleCountInBlock = 0; - int ic = 0; - SPtr< CbArray4D<LBMReal, IndexerX4X3X2X1> > AverageTripleArray3DPtr; - - for (int level = minInitLevel; level <= maxInitLevel; level++) - { - for (SPtr<Block3D> block : blocksVector[level]) // blocks of the current level - { - dataSetSmallArray[ic].x1 = block->getX1(); // coordinates of the block needed to find it while regenerating the grid - dataSetSmallArray[ic].x2 = block->getX2(); - dataSetSmallArray[ic].x3 = block->getX3(); - dataSetSmallArray[ic].level = block->getLevel(); - - AverageTripleArray3DPtr = block->getKernel()->getDataSet()->getAverageTriplecorrelations(); - - if (firstBlock) // when first (any) valid block... - { - dataSetParamStr.nx1 = dataSetParamStr.nx2 = dataSetParamStr.nx3 = 0; - dataSetParamStr.nx[0] = static_cast<int>(AverageTripleArray3DPtr->getNX1()); - dataSetParamStr.nx[1] = static_cast<int>(AverageTripleArray3DPtr->getNX2()); - dataSetParamStr.nx[2] = static_cast<int>(AverageTripleArray3DPtr->getNX3()); - dataSetParamStr.nx[3] = static_cast<int>(AverageTripleArray3DPtr->getNX4()); - doubleCountInBlock = dataSetParamStr.nx[0] * dataSetParamStr.nx[1] * dataSetParamStr.nx[2] * dataSetParamStr.nx[3]; - - firstBlock = false; - } - - if ((dataSetParamStr.nx[0]>0) && (dataSetParamStr.nx[1]>0) && (dataSetParamStr.nx[2]>0) && (dataSetParamStr.nx[3]>0)) - doubleValuesArray.insert(doubleValuesArray.end(), AverageTripleArray3DPtr->getDataVector().begin(), AverageTripleArray3DPtr->getDataVector().end()); - - ic++; - } - } - - // register new MPI-types depending on the block-specific information - MPI_Type_contiguous(doubleCountInBlock, MPI_DOUBLE, &dataSetDoubleType); - MPI_Type_commit(&dataSetDoubleType); - - if (comm->isRoot()) - { - UBLOG(logINFO, "MPIIORestartCoProcessor::writeAverageTripleArray start MPI IO rank = " << rank); - UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); - } - - // write to the file - // all processes calculate their offsets (quantity of bytes that the process is going to write) - // and notify the next process (with the rank = rank + 1) - MPI_Offset write_offset = (MPI_Offset)(size * sizeof(int)); - size_t next_write_offset = 0; - - if (size > 1) - { - if (rank == 0) - { - next_write_offset = write_offset + sizeof(dataSetParam) + blocksCount*(sizeof(DataSetSmallRestart) + doubleCountInBlock * sizeof(double)); - MPI_Send(&next_write_offset, 1, MPI_LONG_LONG_INT, 1, 5, MPI_COMM_WORLD); - } - else - { - MPI_Recv(&write_offset, 1, MPI_LONG_LONG_INT, rank - 1, 5, MPI_COMM_WORLD, MPI_STATUS_IGNORE); - next_write_offset = write_offset + sizeof(dataSetParam) + blocksCount*(sizeof(DataSetSmallRestart) + doubleCountInBlock * sizeof(double)); - if (rank<size - 1) - MPI_Send(&next_write_offset, 1, MPI_LONG_LONG_INT, rank + 1, 5, MPI_COMM_WORLD); - } - } - - double start, finish; - if (comm->isRoot()) start = MPI_Wtime(); - - MPI_Info info = MPI_INFO_NULL; + int rank, size; + MPI_Comm_rank(MPI_COMM_WORLD, &rank); + MPI_Comm_size(MPI_COMM_WORLD, &size); + + int blocksCount = 0; // quantity of blocks in the grid, max 2147483648 blocks! + + std::vector<SPtr<Block3D>> blocksVector[25]; + int minInitLevel = this->grid->getCoarsestInitializedLevel(); + int maxInitLevel = this->grid->getFinestInitializedLevel(); + for (int level = minInitLevel; level <= maxInitLevel; level++) { + grid->getBlocks(level, rank, blocksVector[level]); + blocksCount += static_cast<int>(blocksVector[level].size()); + } + + DataSetSmallRestart *dataSetSmallArray = new DataSetSmallRestart[blocksCount]; + std::vector<double> doubleValuesArray; // double-values (arrays of f's) in all blocks + dataSetParam dataSetParamStr; + + if (comm->isRoot()) { + UBLOG(logINFO, "MPIIORestartCoProcessor::writeAverageTripleArray start collect data rank = " << rank); + UBLOG(logINFO, "Physical Memory currently used by current process: " + << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); + } + + bool firstBlock = true; + int doubleCountInBlock = 0; + int ic = 0; + SPtr<CbArray4D<LBMReal, IndexerX4X3X2X1>> AverageTripleArray3DPtr; + + for (int level = minInitLevel; level <= maxInitLevel; level++) { + for (SPtr<Block3D> block : blocksVector[level]) // blocks of the current level + { + dataSetSmallArray[ic].x1 = + block->getX1(); // coordinates of the block needed to find it while regenerating the grid + dataSetSmallArray[ic].x2 = block->getX2(); + dataSetSmallArray[ic].x3 = block->getX3(); + dataSetSmallArray[ic].level = block->getLevel(); + + AverageTripleArray3DPtr = block->getKernel()->getDataSet()->getAverageTriplecorrelations(); + + if (firstBlock) // when first (any) valid block... + { + dataSetParamStr.nx1 = dataSetParamStr.nx2 = dataSetParamStr.nx3 = 0; + dataSetParamStr.nx[0] = static_cast<int>(AverageTripleArray3DPtr->getNX1()); + dataSetParamStr.nx[1] = static_cast<int>(AverageTripleArray3DPtr->getNX2()); + dataSetParamStr.nx[2] = static_cast<int>(AverageTripleArray3DPtr->getNX3()); + dataSetParamStr.nx[3] = static_cast<int>(AverageTripleArray3DPtr->getNX4()); + doubleCountInBlock = + dataSetParamStr.nx[0] * dataSetParamStr.nx[1] * dataSetParamStr.nx[2] * dataSetParamStr.nx[3]; + + firstBlock = false; + } + + if ((dataSetParamStr.nx[0] > 0) && (dataSetParamStr.nx[1] > 0) && (dataSetParamStr.nx[2] > 0) && + (dataSetParamStr.nx[3] > 0)) + doubleValuesArray.insert(doubleValuesArray.end(), AverageTripleArray3DPtr->getDataVector().begin(), + AverageTripleArray3DPtr->getDataVector().end()); + + ic++; + } + } + + // register new MPI-types depending on the block-specific information + MPI_Type_contiguous(doubleCountInBlock, MPI_DOUBLE, &dataSetDoubleType); + MPI_Type_commit(&dataSetDoubleType); + + if (comm->isRoot()) { + UBLOG(logINFO, "MPIIORestartCoProcessor::writeAverageTripleArray start MPI IO rank = " << rank); + UBLOG(logINFO, "Physical Memory currently used by current process: " + << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); + } + + // write to the file + // all processes calculate their offsets (quantity of bytes that the process is going to write) + // and notify the next process (with the rank = rank + 1) + MPI_Offset write_offset = (MPI_Offset)(size * sizeof(int)); + size_t next_write_offset = 0; + + if (size > 1) { + if (rank == 0) { + next_write_offset = write_offset + sizeof(dataSetParam) + + blocksCount * (sizeof(DataSetSmallRestart) + doubleCountInBlock * sizeof(double)); + MPI_Send(&next_write_offset, 1, MPI_LONG_LONG_INT, 1, 5, MPI_COMM_WORLD); + } else { + MPI_Recv(&write_offset, 1, MPI_LONG_LONG_INT, rank - 1, 5, MPI_COMM_WORLD, MPI_STATUS_IGNORE); + next_write_offset = write_offset + sizeof(dataSetParam) + + blocksCount * (sizeof(DataSetSmallRestart) + doubleCountInBlock * sizeof(double)); + if (rank < size - 1) + MPI_Send(&next_write_offset, 1, MPI_LONG_LONG_INT, rank + 1, 5, MPI_COMM_WORLD); + } + } + + double start, finish; + if (comm->isRoot()) + start = MPI_Wtime(); + + MPI_Info info = MPI_INFO_NULL; #ifdef HLRN_LUSTRE - MPI_Info_create(&info); - MPI_Info_set(info, "striping_factor", "40"); - MPI_Info_set(info, "striping_unit", "4M"); + MPI_Info_create(&info); + MPI_Info_set(info, "striping_factor", "40"); + MPI_Info_set(info, "striping_unit", "4M"); #endif - MPI_File file_handler; - std::string filename = path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + "/cpAverageTripleArray.bin"; - int rc = MPI_File_open(MPI_COMM_WORLD, filename.c_str(), MPI_MODE_CREATE | MPI_MODE_WRONLY, info, &file_handler); - if (rc != MPI_SUCCESS) throw UbException(UB_EXARGS, "couldn't open file " + filename); - - // each process writes the quantity of it's blocks - MPI_File_write_at(file_handler, (MPI_Offset)(rank * sizeof(int)), &blocksCount, 1, MPI_INT, MPI_STATUS_IGNORE); - // each process writes common parameters of a dataSet - MPI_File_write_at(file_handler, write_offset, &dataSetParamStr, 1, dataSetParamType, MPI_STATUS_IGNORE); - // each process writes data identifying blocks - MPI_File_write_at(file_handler, (MPI_Offset)(write_offset + sizeof(dataSetParam)), dataSetSmallArray, blocksCount, dataSetSmallType, MPI_STATUS_IGNORE); - // each process writes the dataSet arrays - if (doubleValuesArray.size() > 0) - MPI_File_write_at(file_handler, (MPI_Offset)(write_offset + sizeof(dataSetParam) + blocksCount * sizeof(DataSetSmallRestart)), &doubleValuesArray[0], blocksCount, dataSetDoubleType, MPI_STATUS_IGNORE); - - MPI_File_sync(file_handler); - MPI_File_close(&file_handler); - MPI_Type_free(&dataSetDoubleType); - - if (comm->isRoot()) - { - finish = MPI_Wtime(); - UBLOG(logINFO, "MPIIORestartCoProcessor::writeAverageTripleArray time: " << finish - start << " s"); - } - - delete[] dataSetSmallArray; + MPI_File file_handler; + std::string filename = path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + "/cpAverageTripleArray.bin"; + int rc = MPI_File_open(MPI_COMM_WORLD, filename.c_str(), MPI_MODE_CREATE | MPI_MODE_WRONLY, info, &file_handler); + if (rc != MPI_SUCCESS) + throw UbException(UB_EXARGS, "couldn't open file " + filename); + + // each process writes the quantity of it's blocks + MPI_File_write_at(file_handler, (MPI_Offset)(rank * sizeof(int)), &blocksCount, 1, MPI_INT, MPI_STATUS_IGNORE); + // each process writes common parameters of a dataSet + MPI_File_write_at(file_handler, write_offset, &dataSetParamStr, 1, dataSetParamType, MPI_STATUS_IGNORE); + // each process writes data identifying blocks + MPI_File_write_at(file_handler, (MPI_Offset)(write_offset + sizeof(dataSetParam)), dataSetSmallArray, blocksCount, + dataSetSmallType, MPI_STATUS_IGNORE); + // each process writes the dataSet arrays + if (doubleValuesArray.size() > 0) + MPI_File_write_at(file_handler, + (MPI_Offset)(write_offset + sizeof(dataSetParam) + blocksCount * sizeof(DataSetSmallRestart)), + &doubleValuesArray[0], blocksCount, dataSetDoubleType, MPI_STATUS_IGNORE); + + MPI_File_sync(file_handler); + MPI_File_close(&file_handler); + MPI_Type_free(&dataSetDoubleType); + + if (comm->isRoot()) { + finish = MPI_Wtime(); + UBLOG(logINFO, "MPIIORestartCoProcessor::writeAverageTripleArray time: " << finish - start << " s"); + } + + delete[] dataSetSmallArray; } void MPIIORestartCoProcessor::writeShearStressValArray(int step) { - int rank, size; - MPI_Comm_rank(MPI_COMM_WORLD, &rank); - MPI_Comm_size(MPI_COMM_WORLD, &size); - - int blocksCount = 0; // quantity of blocks in the grid, max 2147483648 blocks! - - std::vector<SPtr<Block3D>> blocksVector[25]; - int minInitLevel = this->grid->getCoarsestInitializedLevel(); - int maxInitLevel = this->grid->getFinestInitializedLevel(); - for (int level = minInitLevel; level <= maxInitLevel; level++) - { - grid->getBlocks(level, rank, blocksVector[level]); - blocksCount += static_cast<int>(blocksVector[level].size()); - } - - DataSetSmallRestart* dataSetSmallArray = new DataSetSmallRestart[blocksCount]; - std::vector<double> doubleValuesArray; // double-values (arrays of f's) in all blocks - dataSetParam dataSetParamStr; - - if (comm->isRoot()) - { - UBLOG(logINFO, "MPIIORestartCoProcessor::writeShearStressValArray start collect data rank = " << rank); - UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); - } - - bool firstBlock = true; - int doubleCountInBlock = 0; - int ic = 0; - SPtr< CbArray4D<LBMReal, IndexerX4X3X2X1> > ShearStressValArray3DPtr; - - for (int level = minInitLevel; level <= maxInitLevel; level++) - { - for (SPtr<Block3D> block : blocksVector[level]) // blocks of the current level - { - dataSetSmallArray[ic].x1 = block->getX1(); // coordinates of the block needed to find it while regenerating the grid - dataSetSmallArray[ic].x2 = block->getX2(); - dataSetSmallArray[ic].x3 = block->getX3(); - dataSetSmallArray[ic].level = block->getLevel(); - - ShearStressValArray3DPtr = block->getKernel()->getDataSet()->getShearStressValues(); - - if (firstBlock) // when first (any) valid block... - { - dataSetParamStr.nx1 = dataSetParamStr.nx2 = dataSetParamStr.nx3 = 0; - dataSetParamStr.nx[0] = static_cast<int>(ShearStressValArray3DPtr->getNX1()); - dataSetParamStr.nx[1] = static_cast<int>(ShearStressValArray3DPtr->getNX2()); - dataSetParamStr.nx[2] = static_cast<int>(ShearStressValArray3DPtr->getNX3()); - dataSetParamStr.nx[3] = static_cast<int>(ShearStressValArray3DPtr->getNX4()); - doubleCountInBlock = dataSetParamStr.nx[0] * dataSetParamStr.nx[1] * dataSetParamStr.nx[2] * dataSetParamStr.nx[3]; - - firstBlock = false; - } - - if ((dataSetParamStr.nx[0]>0) && (dataSetParamStr.nx[1]>0) && (dataSetParamStr.nx[2]>0) && (dataSetParamStr.nx[3]>0)) - doubleValuesArray.insert(doubleValuesArray.end(), ShearStressValArray3DPtr->getDataVector().begin(), ShearStressValArray3DPtr->getDataVector().end()); - - ic++; - } - } - - // register new MPI-types depending on the block-specific information - MPI_Type_contiguous(doubleCountInBlock, MPI_DOUBLE, &dataSetDoubleType); - MPI_Type_commit(&dataSetDoubleType); - - if (comm->isRoot()) - { - UBLOG(logINFO, "MPIIORestartCoProcessor::writeShearStressValArray start MPI IO rank = " << rank); - UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); - } - - // write to the file - // all processes calculate their offsets (quantity of bytes that the process is going to write) - // and notify the next process (with the rank = rank + 1) - MPI_Offset write_offset = (MPI_Offset)(size * sizeof(int)); - size_t next_write_offset = 0; - - if (size > 1) - { - if (rank == 0) - { - next_write_offset = write_offset + sizeof(dataSetParam) + blocksCount*(sizeof(DataSetSmallRestart) + doubleCountInBlock * sizeof(double)); - MPI_Send(&next_write_offset, 1, MPI_LONG_LONG_INT, 1, 5, MPI_COMM_WORLD); - } - else - { - MPI_Recv(&write_offset, 1, MPI_LONG_LONG_INT, rank - 1, 5, MPI_COMM_WORLD, MPI_STATUS_IGNORE); - next_write_offset = write_offset + sizeof(dataSetParam) + blocksCount*(sizeof(DataSetSmallRestart) + doubleCountInBlock * sizeof(double)); - if (rank<size - 1) - MPI_Send(&next_write_offset, 1, MPI_LONG_LONG_INT, rank + 1, 5, MPI_COMM_WORLD); - } - } - - double start, finish; - if (comm->isRoot()) start = MPI_Wtime(); - - MPI_Info info = MPI_INFO_NULL; + int rank, size; + MPI_Comm_rank(MPI_COMM_WORLD, &rank); + MPI_Comm_size(MPI_COMM_WORLD, &size); + + int blocksCount = 0; // quantity of blocks in the grid, max 2147483648 blocks! + + std::vector<SPtr<Block3D>> blocksVector[25]; + int minInitLevel = this->grid->getCoarsestInitializedLevel(); + int maxInitLevel = this->grid->getFinestInitializedLevel(); + for (int level = minInitLevel; level <= maxInitLevel; level++) { + grid->getBlocks(level, rank, blocksVector[level]); + blocksCount += static_cast<int>(blocksVector[level].size()); + } + + DataSetSmallRestart *dataSetSmallArray = new DataSetSmallRestart[blocksCount]; + std::vector<double> doubleValuesArray; // double-values (arrays of f's) in all blocks + dataSetParam dataSetParamStr; + + if (comm->isRoot()) { + UBLOG(logINFO, "MPIIORestartCoProcessor::writeShearStressValArray start collect data rank = " << rank); + UBLOG(logINFO, "Physical Memory currently used by current process: " + << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); + } + + bool firstBlock = true; + int doubleCountInBlock = 0; + int ic = 0; + SPtr<CbArray4D<LBMReal, IndexerX4X3X2X1>> ShearStressValArray3DPtr; + + for (int level = minInitLevel; level <= maxInitLevel; level++) { + for (SPtr<Block3D> block : blocksVector[level]) // blocks of the current level + { + dataSetSmallArray[ic].x1 = + block->getX1(); // coordinates of the block needed to find it while regenerating the grid + dataSetSmallArray[ic].x2 = block->getX2(); + dataSetSmallArray[ic].x3 = block->getX3(); + dataSetSmallArray[ic].level = block->getLevel(); + + ShearStressValArray3DPtr = block->getKernel()->getDataSet()->getShearStressValues(); + + if (firstBlock) // when first (any) valid block... + { + dataSetParamStr.nx1 = dataSetParamStr.nx2 = dataSetParamStr.nx3 = 0; + dataSetParamStr.nx[0] = static_cast<int>(ShearStressValArray3DPtr->getNX1()); + dataSetParamStr.nx[1] = static_cast<int>(ShearStressValArray3DPtr->getNX2()); + dataSetParamStr.nx[2] = static_cast<int>(ShearStressValArray3DPtr->getNX3()); + dataSetParamStr.nx[3] = static_cast<int>(ShearStressValArray3DPtr->getNX4()); + doubleCountInBlock = + dataSetParamStr.nx[0] * dataSetParamStr.nx[1] * dataSetParamStr.nx[2] * dataSetParamStr.nx[3]; + + firstBlock = false; + } + + if ((dataSetParamStr.nx[0] > 0) && (dataSetParamStr.nx[1] > 0) && (dataSetParamStr.nx[2] > 0) && + (dataSetParamStr.nx[3] > 0)) + doubleValuesArray.insert(doubleValuesArray.end(), ShearStressValArray3DPtr->getDataVector().begin(), + ShearStressValArray3DPtr->getDataVector().end()); + + ic++; + } + } + + // register new MPI-types depending on the block-specific information + MPI_Type_contiguous(doubleCountInBlock, MPI_DOUBLE, &dataSetDoubleType); + MPI_Type_commit(&dataSetDoubleType); + + if (comm->isRoot()) { + UBLOG(logINFO, "MPIIORestartCoProcessor::writeShearStressValArray start MPI IO rank = " << rank); + UBLOG(logINFO, "Physical Memory currently used by current process: " + << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); + } + + // write to the file + // all processes calculate their offsets (quantity of bytes that the process is going to write) + // and notify the next process (with the rank = rank + 1) + MPI_Offset write_offset = (MPI_Offset)(size * sizeof(int)); + size_t next_write_offset = 0; + + if (size > 1) { + if (rank == 0) { + next_write_offset = write_offset + sizeof(dataSetParam) + + blocksCount * (sizeof(DataSetSmallRestart) + doubleCountInBlock * sizeof(double)); + MPI_Send(&next_write_offset, 1, MPI_LONG_LONG_INT, 1, 5, MPI_COMM_WORLD); + } else { + MPI_Recv(&write_offset, 1, MPI_LONG_LONG_INT, rank - 1, 5, MPI_COMM_WORLD, MPI_STATUS_IGNORE); + next_write_offset = write_offset + sizeof(dataSetParam) + + blocksCount * (sizeof(DataSetSmallRestart) + doubleCountInBlock * sizeof(double)); + if (rank < size - 1) + MPI_Send(&next_write_offset, 1, MPI_LONG_LONG_INT, rank + 1, 5, MPI_COMM_WORLD); + } + } + + double start, finish; + if (comm->isRoot()) + start = MPI_Wtime(); + + MPI_Info info = MPI_INFO_NULL; #ifdef HLRN_LUSTRE - MPI_Info_create(&info); - MPI_Info_set(info, "striping_factor", "40"); - MPI_Info_set(info, "striping_unit", "4M"); + MPI_Info_create(&info); + MPI_Info_set(info, "striping_factor", "40"); + MPI_Info_set(info, "striping_unit", "4M"); #endif - MPI_File file_handler; - std::string filename = path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + "/cpShearStressValArray.bin"; - int rc = MPI_File_open(MPI_COMM_WORLD, filename.c_str(), MPI_MODE_CREATE | MPI_MODE_WRONLY, info, &file_handler); - if (rc != MPI_SUCCESS) throw UbException(UB_EXARGS, "couldn't open file " + filename); - - // each process writes the quantity of it's blocks - MPI_File_write_at(file_handler, (MPI_Offset)(rank * sizeof(int)), &blocksCount, 1, MPI_INT, MPI_STATUS_IGNORE); - // each process writes common parameters of a dataSet - MPI_File_write_at(file_handler, write_offset, &dataSetParamStr, 1, dataSetParamType, MPI_STATUS_IGNORE); - // each process writes data identifying blocks - MPI_File_write_at(file_handler, (MPI_Offset)(write_offset + sizeof(dataSetParam)), dataSetSmallArray, blocksCount, dataSetSmallType, MPI_STATUS_IGNORE); - // each process writes the dataSet arrays - if (doubleValuesArray.size() > 0) - MPI_File_write_at(file_handler, (MPI_Offset)(write_offset + sizeof(dataSetParam) + blocksCount * sizeof(DataSetSmallRestart)), &doubleValuesArray[0], blocksCount, dataSetDoubleType, MPI_STATUS_IGNORE); - - MPI_File_sync(file_handler); - MPI_File_close(&file_handler); - MPI_Type_free(&dataSetDoubleType); - - if (comm->isRoot()) - { - finish = MPI_Wtime(); - UBLOG(logINFO, "MPIIORestartCoProcessor::writeShearStressValArray time: " << finish - start << " s"); - } - - delete[] dataSetSmallArray; + MPI_File file_handler; + std::string filename = path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + "/cpShearStressValArray.bin"; + int rc = MPI_File_open(MPI_COMM_WORLD, filename.c_str(), MPI_MODE_CREATE | MPI_MODE_WRONLY, info, &file_handler); + if (rc != MPI_SUCCESS) + throw UbException(UB_EXARGS, "couldn't open file " + filename); + + // each process writes the quantity of it's blocks + MPI_File_write_at(file_handler, (MPI_Offset)(rank * sizeof(int)), &blocksCount, 1, MPI_INT, MPI_STATUS_IGNORE); + // each process writes common parameters of a dataSet + MPI_File_write_at(file_handler, write_offset, &dataSetParamStr, 1, dataSetParamType, MPI_STATUS_IGNORE); + // each process writes data identifying blocks + MPI_File_write_at(file_handler, (MPI_Offset)(write_offset + sizeof(dataSetParam)), dataSetSmallArray, blocksCount, + dataSetSmallType, MPI_STATUS_IGNORE); + // each process writes the dataSet arrays + if (doubleValuesArray.size() > 0) + MPI_File_write_at(file_handler, + (MPI_Offset)(write_offset + sizeof(dataSetParam) + blocksCount * sizeof(DataSetSmallRestart)), + &doubleValuesArray[0], blocksCount, dataSetDoubleType, MPI_STATUS_IGNORE); + + MPI_File_sync(file_handler); + MPI_File_close(&file_handler); + MPI_Type_free(&dataSetDoubleType); + + if (comm->isRoot()) { + finish = MPI_Wtime(); + UBLOG(logINFO, "MPIIORestartCoProcessor::writeShearStressValArray time: " << finish - start << " s"); + } + + delete[] dataSetSmallArray; } void MPIIORestartCoProcessor::writeRelaxationFactor(int step) { - int rank, size; - MPI_Comm_rank(MPI_COMM_WORLD, &rank); - MPI_Comm_size(MPI_COMM_WORLD, &size); - - int blocksCount = 0; // quantity of blocks in the grid, max 2147483648 blocks! - - std::vector<SPtr<Block3D>> blocksVector[25]; - int minInitLevel = this->grid->getCoarsestInitializedLevel(); - int maxInitLevel = this->grid->getFinestInitializedLevel(); - for (int level = minInitLevel; level <= maxInitLevel; level++) - { - grid->getBlocks(level, rank, blocksVector[level]); - blocksCount += static_cast<int>(blocksVector[level].size()); - } - - DataSetSmallRestart* dataSetSmallArray = new DataSetSmallRestart[blocksCount]; - std::vector<double> doubleValuesArray; // double-values (arrays of f's) in all blocks - dataSetParam dataSetParamStr; - - if (comm->isRoot()) - { - UBLOG(logINFO, "MPIIORestartCoProcessor::writeRelaxationFactor start collect data rank = " << rank); - UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); - } - - bool firstBlock = true; - int doubleCountInBlock = 0; - int ic = 0; - SPtr< CbArray3D<LBMReal, IndexerX3X2X1> > RelaxationFactor3DPtr; - - for (int level = minInitLevel; level <= maxInitLevel; level++) - { - for (SPtr<Block3D> block : blocksVector[level]) // blocks of the current level - { - dataSetSmallArray[ic].x1 = block->getX1(); // coordinates of the block needed to find it while regenerating the grid - dataSetSmallArray[ic].x2 = block->getX2(); - dataSetSmallArray[ic].x3 = block->getX3(); - dataSetSmallArray[ic].level = block->getLevel(); - - RelaxationFactor3DPtr = block->getKernel()->getDataSet()->getRelaxationFactor(); - - if (firstBlock) // when first (any) valid block... - { - dataSetParamStr.nx1 = dataSetParamStr.nx2 = dataSetParamStr.nx3 = 0; - dataSetParamStr.nx[0] = static_cast<int>(RelaxationFactor3DPtr->getNX1()); - dataSetParamStr.nx[1] = static_cast<int>(RelaxationFactor3DPtr->getNX2()); - dataSetParamStr.nx[2] = static_cast<int>(RelaxationFactor3DPtr->getNX3()); - dataSetParamStr.nx[3] = 1; - doubleCountInBlock = dataSetParamStr.nx[0] * dataSetParamStr.nx[1] * dataSetParamStr.nx[2] * dataSetParamStr.nx[3]; - - firstBlock = false; - } - - if ((dataSetParamStr.nx[0]>0) && (dataSetParamStr.nx[1]>0) && (dataSetParamStr.nx[2]>0)) - doubleValuesArray.insert(doubleValuesArray.end(), RelaxationFactor3DPtr->getDataVector().begin(), RelaxationFactor3DPtr->getDataVector().end()); - - ic++; - } - } - - // register new MPI-types depending on the block-specific information - MPI_Type_contiguous(doubleCountInBlock, MPI_DOUBLE, &dataSetDoubleType); - MPI_Type_commit(&dataSetDoubleType); - - if (comm->isRoot()) - { - UBLOG(logINFO, "MPIIORestartCoProcessor::writeRelaxationFactor start MPI IO rank = " << rank); - UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); - } - - // write to the file - // all processes calculate their offsets (quantity of bytes that the process is going to write) - // and notify the next process (with the rank = rank + 1) - MPI_Offset write_offset = (MPI_Offset)(size * sizeof(int)); - size_t next_write_offset = 0; - - if (size > 1) - { - if (rank == 0) - { - next_write_offset = write_offset + sizeof(dataSetParam) + blocksCount*(sizeof(DataSetSmallRestart) + doubleCountInBlock * sizeof(double)); - MPI_Send(&next_write_offset, 1, MPI_LONG_LONG_INT, 1, 5, MPI_COMM_WORLD); - } - else - { - MPI_Recv(&write_offset, 1, MPI_LONG_LONG_INT, rank - 1, 5, MPI_COMM_WORLD, MPI_STATUS_IGNORE); - next_write_offset = write_offset + sizeof(dataSetParam) + blocksCount*(sizeof(DataSetSmallRestart) + doubleCountInBlock * sizeof(double)); - if (rank<size - 1) - MPI_Send(&next_write_offset, 1, MPI_LONG_LONG_INT, rank + 1, 5, MPI_COMM_WORLD); - } - } - - double start, finish; - if (comm->isRoot()) start = MPI_Wtime(); - - MPI_Info info = MPI_INFO_NULL; + int rank, size; + MPI_Comm_rank(MPI_COMM_WORLD, &rank); + MPI_Comm_size(MPI_COMM_WORLD, &size); + + int blocksCount = 0; // quantity of blocks in the grid, max 2147483648 blocks! + + std::vector<SPtr<Block3D>> blocksVector[25]; + int minInitLevel = this->grid->getCoarsestInitializedLevel(); + int maxInitLevel = this->grid->getFinestInitializedLevel(); + for (int level = minInitLevel; level <= maxInitLevel; level++) { + grid->getBlocks(level, rank, blocksVector[level]); + blocksCount += static_cast<int>(blocksVector[level].size()); + } + + DataSetSmallRestart *dataSetSmallArray = new DataSetSmallRestart[blocksCount]; + std::vector<double> doubleValuesArray; // double-values (arrays of f's) in all blocks + dataSetParam dataSetParamStr; + + if (comm->isRoot()) { + UBLOG(logINFO, "MPIIORestartCoProcessor::writeRelaxationFactor start collect data rank = " << rank); + UBLOG(logINFO, "Physical Memory currently used by current process: " + << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); + } + + bool firstBlock = true; + int doubleCountInBlock = 0; + int ic = 0; + SPtr<CbArray3D<LBMReal, IndexerX3X2X1>> RelaxationFactor3DPtr; + + for (int level = minInitLevel; level <= maxInitLevel; level++) { + for (SPtr<Block3D> block : blocksVector[level]) // blocks of the current level + { + dataSetSmallArray[ic].x1 = + block->getX1(); // coordinates of the block needed to find it while regenerating the grid + dataSetSmallArray[ic].x2 = block->getX2(); + dataSetSmallArray[ic].x3 = block->getX3(); + dataSetSmallArray[ic].level = block->getLevel(); + + RelaxationFactor3DPtr = block->getKernel()->getDataSet()->getRelaxationFactor(); + + if (firstBlock) // when first (any) valid block... + { + dataSetParamStr.nx1 = dataSetParamStr.nx2 = dataSetParamStr.nx3 = 0; + dataSetParamStr.nx[0] = static_cast<int>(RelaxationFactor3DPtr->getNX1()); + dataSetParamStr.nx[1] = static_cast<int>(RelaxationFactor3DPtr->getNX2()); + dataSetParamStr.nx[2] = static_cast<int>(RelaxationFactor3DPtr->getNX3()); + dataSetParamStr.nx[3] = 1; + doubleCountInBlock = + dataSetParamStr.nx[0] * dataSetParamStr.nx[1] * dataSetParamStr.nx[2] * dataSetParamStr.nx[3]; + + firstBlock = false; + } + + if ((dataSetParamStr.nx[0] > 0) && (dataSetParamStr.nx[1] > 0) && (dataSetParamStr.nx[2] > 0)) + doubleValuesArray.insert(doubleValuesArray.end(), RelaxationFactor3DPtr->getDataVector().begin(), + RelaxationFactor3DPtr->getDataVector().end()); + + ic++; + } + } + + // register new MPI-types depending on the block-specific information + MPI_Type_contiguous(doubleCountInBlock, MPI_DOUBLE, &dataSetDoubleType); + MPI_Type_commit(&dataSetDoubleType); + + if (comm->isRoot()) { + UBLOG(logINFO, "MPIIORestartCoProcessor::writeRelaxationFactor start MPI IO rank = " << rank); + UBLOG(logINFO, "Physical Memory currently used by current process: " + << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); + } + + // write to the file + // all processes calculate their offsets (quantity of bytes that the process is going to write) + // and notify the next process (with the rank = rank + 1) + MPI_Offset write_offset = (MPI_Offset)(size * sizeof(int)); + size_t next_write_offset = 0; + + if (size > 1) { + if (rank == 0) { + next_write_offset = write_offset + sizeof(dataSetParam) + + blocksCount * (sizeof(DataSetSmallRestart) + doubleCountInBlock * sizeof(double)); + MPI_Send(&next_write_offset, 1, MPI_LONG_LONG_INT, 1, 5, MPI_COMM_WORLD); + } else { + MPI_Recv(&write_offset, 1, MPI_LONG_LONG_INT, rank - 1, 5, MPI_COMM_WORLD, MPI_STATUS_IGNORE); + next_write_offset = write_offset + sizeof(dataSetParam) + + blocksCount * (sizeof(DataSetSmallRestart) + doubleCountInBlock * sizeof(double)); + if (rank < size - 1) + MPI_Send(&next_write_offset, 1, MPI_LONG_LONG_INT, rank + 1, 5, MPI_COMM_WORLD); + } + } + + double start, finish; + if (comm->isRoot()) + start = MPI_Wtime(); + + MPI_Info info = MPI_INFO_NULL; #ifdef HLRN_LUSTRE - MPI_Info_create(&info); - MPI_Info_set(info, "striping_factor", "40"); - MPI_Info_set(info, "striping_unit", "4M"); + MPI_Info_create(&info); + MPI_Info_set(info, "striping_factor", "40"); + MPI_Info_set(info, "striping_unit", "4M"); #endif - MPI_File file_handler; - std::string filename = path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + "/cpRelaxationFactor.bin"; - int rc = MPI_File_open(MPI_COMM_WORLD, filename.c_str(), MPI_MODE_CREATE | MPI_MODE_WRONLY, info, &file_handler); - if (rc != MPI_SUCCESS) throw UbException(UB_EXARGS, "couldn't open file " + filename); - - // each process writes the quantity of it's blocks - MPI_File_write_at(file_handler, (MPI_Offset)(rank * sizeof(int)), &blocksCount, 1, MPI_INT, MPI_STATUS_IGNORE); - // each process writes common parameters of a dataSet - MPI_File_write_at(file_handler, write_offset, &dataSetParamStr, 1, dataSetParamType, MPI_STATUS_IGNORE); - // each process writes data identifying blocks - MPI_File_write_at(file_handler, (MPI_Offset)(write_offset + sizeof(dataSetParam)), dataSetSmallArray, blocksCount, dataSetSmallType, MPI_STATUS_IGNORE); - // each process writes the dataSet arrays - if (doubleValuesArray.size() > 0) - MPI_File_write_at(file_handler, (MPI_Offset)(write_offset + sizeof(dataSetParam) + blocksCount * sizeof(DataSetSmallRestart)), &doubleValuesArray[0], blocksCount, dataSetDoubleType, MPI_STATUS_IGNORE); - - MPI_File_sync(file_handler); - MPI_File_close(&file_handler); - MPI_Type_free(&dataSetDoubleType); - - if (comm->isRoot()) - { - finish = MPI_Wtime(); - UBLOG(logINFO, "MPIIORestartCoProcessor::writeRelaxationFactor time: " << finish - start << " s"); - } - - delete[] dataSetSmallArray; + MPI_File file_handler; + std::string filename = path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + "/cpRelaxationFactor.bin"; + int rc = MPI_File_open(MPI_COMM_WORLD, filename.c_str(), MPI_MODE_CREATE | MPI_MODE_WRONLY, info, &file_handler); + if (rc != MPI_SUCCESS) + throw UbException(UB_EXARGS, "couldn't open file " + filename); + + // each process writes the quantity of it's blocks + MPI_File_write_at(file_handler, (MPI_Offset)(rank * sizeof(int)), &blocksCount, 1, MPI_INT, MPI_STATUS_IGNORE); + // each process writes common parameters of a dataSet + MPI_File_write_at(file_handler, write_offset, &dataSetParamStr, 1, dataSetParamType, MPI_STATUS_IGNORE); + // each process writes data identifying blocks + MPI_File_write_at(file_handler, (MPI_Offset)(write_offset + sizeof(dataSetParam)), dataSetSmallArray, blocksCount, + dataSetSmallType, MPI_STATUS_IGNORE); + // each process writes the dataSet arrays + if (doubleValuesArray.size() > 0) + MPI_File_write_at(file_handler, + (MPI_Offset)(write_offset + sizeof(dataSetParam) + blocksCount * sizeof(DataSetSmallRestart)), + &doubleValuesArray[0], blocksCount, dataSetDoubleType, MPI_STATUS_IGNORE); + + MPI_File_sync(file_handler); + MPI_File_close(&file_handler); + MPI_Type_free(&dataSetDoubleType); + + if (comm->isRoot()) { + finish = MPI_Wtime(); + UBLOG(logINFO, "MPIIORestartCoProcessor::writeRelaxationFactor time: " << finish - start << " s"); + } + + delete[] dataSetSmallArray; } void MPIIORestartCoProcessor::writeBoundaryConds(int step) { - int rank, size; - MPI_Comm_rank(MPI_COMM_WORLD, &rank); - MPI_Comm_size(MPI_COMM_WORLD, &size); - - if (comm->isRoot()) - { - UBLOG(logINFO, "MPIIORestartCoProcessor::writeBoundaryConds start collect data rank = " << rank); - UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); - } - - int blocksCount = 0; // quantity of blocks in the grid, max 2147483648 blocks! - size_t count_boundCond = 0; // how many BoundaryConditions in all blocks - int count_indexContainer = 0; // how many indexContainer-values in all blocks - size_t byteCount = 0; // how many bytes writes this process in the file - - std::vector<SPtr<Block3D>> blocksVector[25]; - int minInitLevel = this->grid->getCoarsestInitializedLevel(); - int maxInitLevel = this->grid->getFinestInitializedLevel(); - for (int level = minInitLevel; level <= maxInitLevel; level++) - { - grid->getBlocks(level, rank, blocksVector[level]); - blocksCount += static_cast<int>(blocksVector[level].size()); - } - - BCAddRestart* bcAddArray = new BCAddRestart[blocksCount]; - std::vector<BoundaryCondition> bcVector; - std::vector<int> bcindexmatrixV; - std::vector<int> indexContainerV; - bool bcindexmatrixCountNotInit = true; - int ic = 0; - SPtr<BCArray3D> bcArr; - - for (int level = minInitLevel; level <= maxInitLevel; level++) - { - for (SPtr<Block3D> block : blocksVector[level]) // all the blocks of the current level - { - bcArr = block->getKernel()->getBCProcessor()->getBCArray(); - - bcAddArray[ic].x1 = block->getX1(); // coordinates of the block needed to find it while regenerating the grid - bcAddArray[ic].x2 = block->getX2(); - bcAddArray[ic].x3 = block->getX3(); - bcAddArray[ic].level = block->getLevel(); - bcAddArray[ic].boundCond_count = 0; // how many BoundaryConditions in this block - bcAddArray[ic].indexContainer_count = 0; // how many indexContainer-values in this block - - for (int bc = 0; bc<bcArr->getBCVectorSize(); bc++) - { - BoundaryCondition* bouCond = new BoundaryCondition(); - if (bcArr->bcvector[bc] == NULL) - { - memset(bouCond, 0, sizeof(BoundaryCondition)); - } - else - { - bouCond->noslipBoundaryFlags = bcArr->bcvector[bc]->getNoSlipBoundary(); - bouCond->slipBoundaryFlags = bcArr->bcvector[bc]->getSlipBoundary(); - bouCond->velocityBoundaryFlags = bcArr->bcvector[bc]->getVelocityBoundary(); - bouCond->densityBoundaryFlags = bcArr->bcvector[bc]->getDensityBoundary(); - bouCond->wallModelBoundaryFlags = bcArr->bcvector[bc]->getWallModelBoundary(); - bouCond->bcVelocityX1 = (float) bcArr->bcvector[bc]->getBoundaryVelocityX1(); - bouCond->bcVelocityX2 = (float) bcArr->bcvector[bc]->getBoundaryVelocityX2(); - bouCond->bcVelocityX3 = (float) bcArr->bcvector[bc]->getBoundaryVelocityX3(); - bouCond->bcDensity = (float) bcArr->bcvector[bc]->getBoundaryDensity(); - bouCond->bcLodiDensity = (float) bcArr->bcvector[bc]->getDensityLodiDensity(); - bouCond->bcLodiVelocityX1 = (float) bcArr->bcvector[bc]->getDensityLodiVelocityX1(); - bouCond->bcLodiVelocityX2 = (float) bcArr->bcvector[bc]->getDensityLodiVelocityX2(); - bouCond->bcLodiVelocityX3 = (float) bcArr->bcvector[bc]->getDensityLodiVelocityX3(); - bouCond->bcLodiLentgh = (float) bcArr->bcvector[bc]->getDensityLodiLength(); - bouCond->nx1 = (float) bcArr->bcvector[bc]->nx1; - bouCond->nx2 = (float) bcArr->bcvector[bc]->nx2; - bouCond->nx3 = (float) bcArr->bcvector[bc]->nx3; - for (int iq = 0; iq<26; iq++) - bouCond->q[iq] = (float) bcArr->bcvector[bc]->getQ(iq); - bouCond->algorithmType = bcArr->bcvector[bc]->getBcAlgorithmType(); + int rank, size; + MPI_Comm_rank(MPI_COMM_WORLD, &rank); + MPI_Comm_size(MPI_COMM_WORLD, &size); + + if (comm->isRoot()) { + UBLOG(logINFO, "MPIIORestartCoProcessor::writeBoundaryConds start collect data rank = " << rank); + UBLOG(logINFO, "Physical Memory currently used by current process: " + << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); + } + + int blocksCount = 0; // quantity of blocks in the grid, max 2147483648 blocks! + size_t count_boundCond = 0; // how many BoundaryConditions in all blocks + int count_indexContainer = 0; // how many indexContainer-values in all blocks + size_t byteCount = 0; // how many bytes writes this process in the file + + std::vector<SPtr<Block3D>> blocksVector[25]; + int minInitLevel = this->grid->getCoarsestInitializedLevel(); + int maxInitLevel = this->grid->getFinestInitializedLevel(); + for (int level = minInitLevel; level <= maxInitLevel; level++) { + grid->getBlocks(level, rank, blocksVector[level]); + blocksCount += static_cast<int>(blocksVector[level].size()); + } + + BCAddRestart *bcAddArray = new BCAddRestart[blocksCount]; + std::vector<BoundaryCondition> bcVector; + std::vector<int> bcindexmatrixV; + std::vector<int> indexContainerV; + bool bcindexmatrixCountNotInit = true; + int ic = 0; + SPtr<BCArray3D> bcArr; + + for (int level = minInitLevel; level <= maxInitLevel; level++) { + for (SPtr<Block3D> block : blocksVector[level]) // all the blocks of the current level + { + bcArr = block->getKernel()->getBCProcessor()->getBCArray(); + + bcAddArray[ic].x1 = + block->getX1(); // coordinates of the block needed to find it while regenerating the grid + bcAddArray[ic].x2 = block->getX2(); + bcAddArray[ic].x3 = block->getX3(); + bcAddArray[ic].level = block->getLevel(); + bcAddArray[ic].boundCond_count = 0; // how many BoundaryConditions in this block + bcAddArray[ic].indexContainer_count = 0; // how many indexContainer-values in this block + + for (int bc = 0; bc < bcArr->getBCVectorSize(); bc++) { + BoundaryCondition *bouCond = new BoundaryCondition(); + if (bcArr->bcvector[bc] == NULL) { + memset(bouCond, 0, sizeof(BoundaryCondition)); + } else { + bouCond->noslipBoundaryFlags = bcArr->bcvector[bc]->getNoSlipBoundary(); + bouCond->slipBoundaryFlags = bcArr->bcvector[bc]->getSlipBoundary(); + bouCond->velocityBoundaryFlags = bcArr->bcvector[bc]->getVelocityBoundary(); + bouCond->densityBoundaryFlags = bcArr->bcvector[bc]->getDensityBoundary(); + bouCond->wallModelBoundaryFlags = bcArr->bcvector[bc]->getWallModelBoundary(); + bouCond->bcVelocityX1 = (float)bcArr->bcvector[bc]->getBoundaryVelocityX1(); + bouCond->bcVelocityX2 = (float)bcArr->bcvector[bc]->getBoundaryVelocityX2(); + bouCond->bcVelocityX3 = (float)bcArr->bcvector[bc]->getBoundaryVelocityX3(); + bouCond->bcDensity = (float)bcArr->bcvector[bc]->getBoundaryDensity(); + bouCond->bcLodiDensity = (float)bcArr->bcvector[bc]->getDensityLodiDensity(); + bouCond->bcLodiVelocityX1 = (float)bcArr->bcvector[bc]->getDensityLodiVelocityX1(); + bouCond->bcLodiVelocityX2 = (float)bcArr->bcvector[bc]->getDensityLodiVelocityX2(); + bouCond->bcLodiVelocityX3 = (float)bcArr->bcvector[bc]->getDensityLodiVelocityX3(); + bouCond->bcLodiLentgh = (float)bcArr->bcvector[bc]->getDensityLodiLength(); + bouCond->nx1 = (float)bcArr->bcvector[bc]->nx1; + bouCond->nx2 = (float)bcArr->bcvector[bc]->nx2; + bouCond->nx3 = (float)bcArr->bcvector[bc]->nx3; + for (int iq = 0; iq < 26; iq++) + bouCond->q[iq] = (float)bcArr->bcvector[bc]->getQ(iq); + bouCond->algorithmType = bcArr->bcvector[bc]->getBcAlgorithmType(); + } + + bcVector.push_back(*bouCond); + bcAddArray[ic].boundCond_count++; + count_boundCond++; } - bcVector.push_back(*bouCond); - bcAddArray[ic].boundCond_count++; - count_boundCond++; - } - - // the quantity of elements in the bcindexmatrix array (CbArray3D<int, IndexerX3X2X1>) in bcArray(BCArray3D) is always equal, - // this will be the size of the "write-read-block" in MPI_write_.../MPI_read-functions when writing/reading BoundConds - if (bcindexmatrixCountNotInit) - { - boundCondParamStr.nx1 = static_cast<int>(bcArr->bcindexmatrix.getNX1()); - boundCondParamStr.nx2 = static_cast<int>(bcArr->bcindexmatrix.getNX2()); - boundCondParamStr.nx3 = static_cast<int>(bcArr->bcindexmatrix.getNX3()); - boundCondParamStr.bcindexmatrixCount = static_cast<int>(bcArr->bcindexmatrix.getDataVector().size()); - bcindexmatrixCountNotInit = false; - } - bcindexmatrixV.insert(bcindexmatrixV.end(), bcArr->bcindexmatrix.getDataVector().begin(), bcArr->bcindexmatrix.getDataVector().end()); - - indexContainerV.insert(indexContainerV.end(), bcArr->indexContainer.begin(), bcArr->indexContainer.end()); - bcAddArray[ic].indexContainer_count = static_cast<int>(bcArr->indexContainer.size()); - count_indexContainer += bcAddArray[ic].indexContainer_count; - - ic++; - } - } - - MPI_Type_contiguous(boundCondParamStr.bcindexmatrixCount, MPI_INT, &bcindexmatrixType); - MPI_Type_commit(&bcindexmatrixType); - - //how many "big blocks" of BLOCK_SIZE size can by formed - int bcBlockCount = (int)(count_boundCond / BLOCK_SIZE); - if (bcBlockCount * BLOCK_SIZE<count_boundCond) - bcBlockCount += 1; - for (int i = (int)count_boundCond; i<bcBlockCount * BLOCK_SIZE; i++) - { - BoundaryCondition* bouCond = new BoundaryCondition(); - memset(bouCond, 0, sizeof(BoundaryCondition)); - bcVector.push_back(*bouCond); - } - - byteCount = bcBlockCount * BLOCK_SIZE * sizeof(BoundaryCondition) + blocksCount * sizeof(BCAddRestart) + sizeof(int) * (blocksCount * boundCondParamStr.bcindexmatrixCount + count_indexContainer); - - // write to the file - // all processes calculate their offsets (quantity of bytes that the process is going to write) - // and notify the next process (with the rank = rank + 1) - MPI_Offset write_offset = (MPI_Offset)(size * (3 * sizeof(int) + sizeof(boundCondParam))); - size_t next_write_offset = 0; - - if (size>1) - { - if (rank == 0) - { - next_write_offset = write_offset + byteCount; - MPI_Send(&next_write_offset, 1, MPI_LONG_LONG_INT, 1, 5, MPI_COMM_WORLD); - } - else - { - MPI_Recv(&write_offset, 1, MPI_LONG_LONG_INT, rank - 1, 5, MPI_COMM_WORLD, MPI_STATUS_IGNORE); - next_write_offset = write_offset + byteCount; - if (rank<size - 1) - MPI_Send(&next_write_offset, 1, MPI_LONG_LONG_INT, rank + 1, 5, MPI_COMM_WORLD); - } - } - - if (comm->isRoot()) - { - UBLOG(logINFO, "MPIIORestartCoProcessor::writeBoundaryConds start MPI IO rank = " << rank); - UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); - } - - double start, finish; - if (comm->isRoot()) start = MPI_Wtime(); - - MPI_Info info = MPI_INFO_NULL; + // the quantity of elements in the bcindexmatrix array (CbArray3D<int, IndexerX3X2X1>) in bcArray(BCArray3D) + // is always equal, this will be the size of the "write-read-block" in MPI_write_.../MPI_read-functions when + // writing/reading BoundConds + if (bcindexmatrixCountNotInit) { + boundCondParamStr.nx1 = static_cast<int>(bcArr->bcindexmatrix.getNX1()); + boundCondParamStr.nx2 = static_cast<int>(bcArr->bcindexmatrix.getNX2()); + boundCondParamStr.nx3 = static_cast<int>(bcArr->bcindexmatrix.getNX3()); + boundCondParamStr.bcindexmatrixCount = static_cast<int>(bcArr->bcindexmatrix.getDataVector().size()); + bcindexmatrixCountNotInit = false; + } + bcindexmatrixV.insert(bcindexmatrixV.end(), bcArr->bcindexmatrix.getDataVector().begin(), + bcArr->bcindexmatrix.getDataVector().end()); + + indexContainerV.insert(indexContainerV.end(), bcArr->indexContainer.begin(), bcArr->indexContainer.end()); + bcAddArray[ic].indexContainer_count = static_cast<int>(bcArr->indexContainer.size()); + count_indexContainer += bcAddArray[ic].indexContainer_count; + + ic++; + } + } + + MPI_Type_contiguous(boundCondParamStr.bcindexmatrixCount, MPI_INT, &bcindexmatrixType); + MPI_Type_commit(&bcindexmatrixType); + + // how many "big blocks" of BLOCK_SIZE size can by formed + int bcBlockCount = (int)(count_boundCond / BLOCK_SIZE); + if (bcBlockCount * BLOCK_SIZE < count_boundCond) + bcBlockCount += 1; + for (int i = (int)count_boundCond; i < bcBlockCount * BLOCK_SIZE; i++) { + BoundaryCondition *bouCond = new BoundaryCondition(); + memset(bouCond, 0, sizeof(BoundaryCondition)); + bcVector.push_back(*bouCond); + } + + byteCount = bcBlockCount * BLOCK_SIZE * sizeof(BoundaryCondition) + blocksCount * sizeof(BCAddRestart) + + sizeof(int) * (blocksCount * boundCondParamStr.bcindexmatrixCount + count_indexContainer); + + // write to the file + // all processes calculate their offsets (quantity of bytes that the process is going to write) + // and notify the next process (with the rank = rank + 1) + MPI_Offset write_offset = (MPI_Offset)(size * (3 * sizeof(int) + sizeof(boundCondParam))); + size_t next_write_offset = 0; + + if (size > 1) { + if (rank == 0) { + next_write_offset = write_offset + byteCount; + MPI_Send(&next_write_offset, 1, MPI_LONG_LONG_INT, 1, 5, MPI_COMM_WORLD); + } else { + MPI_Recv(&write_offset, 1, MPI_LONG_LONG_INT, rank - 1, 5, MPI_COMM_WORLD, MPI_STATUS_IGNORE); + next_write_offset = write_offset + byteCount; + if (rank < size - 1) + MPI_Send(&next_write_offset, 1, MPI_LONG_LONG_INT, rank + 1, 5, MPI_COMM_WORLD); + } + } + + if (comm->isRoot()) { + UBLOG(logINFO, "MPIIORestartCoProcessor::writeBoundaryConds start MPI IO rank = " << rank); + UBLOG(logINFO, "Physical Memory currently used by current process: " + << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); + } + + double start, finish; + if (comm->isRoot()) + start = MPI_Wtime(); + + MPI_Info info = MPI_INFO_NULL; #ifdef HLRN_LUSTRE - MPI_Info_create(&info); - MPI_Info_set(info, "striping_factor", "40"); - MPI_Info_set(info, "striping_unit", "4M"); + MPI_Info_create(&info); + MPI_Info_set(info, "striping_factor", "40"); + MPI_Info_set(info, "striping_unit", "4M"); #endif - MPI_File file_handler; - std::string filename = path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + "/cpBC.bin"; - int rc = MPI_File_open(MPI_COMM_WORLD, filename.c_str(), MPI_MODE_CREATE | MPI_MODE_WRONLY, info, &file_handler); - if (rc != MPI_SUCCESS) throw UbException(UB_EXARGS, "couldn't open file " + filename); - - MPI_Offset write_offset1 = (MPI_Offset)(rank * (3 * sizeof(int) + sizeof(boundCondParam))); - - // each process writes the quantity of it's blocks - MPI_File_write_at(file_handler, write_offset1, &blocksCount, 1, MPI_INT, MPI_STATUS_IGNORE); - // each process writes the quantity of "big blocks" of BLOCK_SIZE of boundary conditions - MPI_File_write_at(file_handler, (MPI_Offset)(write_offset1 + sizeof(int)), &bcBlockCount, 1, MPI_INT, MPI_STATUS_IGNORE); - // each process writes the quantity of indexContainer elements in all blocks - MPI_File_write_at(file_handler, (MPI_Offset)(write_offset1 + 2 * sizeof(int)), &count_indexContainer, 1, MPI_INT, MPI_STATUS_IGNORE); - // each process writes the quantity of bcindexmatrix elements in every block - MPI_File_write_at(file_handler, (MPI_Offset)(write_offset1 + 3 * sizeof(int)), &boundCondParamStr, 1, boundCondParamType, MPI_STATUS_IGNORE); - - // each process writes data identifying the blocks - MPI_File_write_at(file_handler, write_offset, bcAddArray, blocksCount, boundCondTypeAdd, MPI_STATUS_IGNORE); - // each process writes boundary conditions - if (bcVector.size()>0) - MPI_File_write_at(file_handler, (MPI_Offset)(write_offset + blocksCount * sizeof(BCAddRestart)), &bcVector[0], bcBlockCount, boundCondType1000, MPI_STATUS_IGNORE); - // each process writes bcindexmatrix values - if (bcindexmatrixV.size()>0) - MPI_File_write_at(file_handler, (MPI_Offset)(write_offset + blocksCount * sizeof(BCAddRestart) + bcBlockCount*BLOCK_SIZE * sizeof(BoundaryCondition)), &bcindexmatrixV[0], blocksCount, bcindexmatrixType, MPI_STATUS_IGNORE); - // each process writes indexContainer values - if (indexContainerV.size()>0) - MPI_File_write_at(file_handler, (MPI_Offset)(write_offset + blocksCount * sizeof(BCAddRestart) + bcBlockCount*BLOCK_SIZE * sizeof(BoundaryCondition) + blocksCount*boundCondParamStr.bcindexmatrixCount * sizeof(int)), &indexContainerV[0], count_indexContainer, MPI_INT, MPI_STATUS_IGNORE); - - MPI_File_sync(file_handler); - MPI_File_close(&file_handler); - MPI_Type_free(&bcindexmatrixType); - - if (comm->isRoot()) - { - finish = MPI_Wtime(); - UBLOG(logINFO, "MPIIORestartCoProcessor::writeBoundaryConds time: " << finish - start << " s"); - } - - delete[] bcAddArray; + MPI_File file_handler; + std::string filename = path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + "/cpBC.bin"; + int rc = MPI_File_open(MPI_COMM_WORLD, filename.c_str(), MPI_MODE_CREATE | MPI_MODE_WRONLY, info, &file_handler); + if (rc != MPI_SUCCESS) + throw UbException(UB_EXARGS, "couldn't open file " + filename); + + MPI_Offset write_offset1 = (MPI_Offset)(rank * (3 * sizeof(int) + sizeof(boundCondParam))); + + // each process writes the quantity of it's blocks + MPI_File_write_at(file_handler, write_offset1, &blocksCount, 1, MPI_INT, MPI_STATUS_IGNORE); + // each process writes the quantity of "big blocks" of BLOCK_SIZE of boundary conditions + MPI_File_write_at(file_handler, (MPI_Offset)(write_offset1 + sizeof(int)), &bcBlockCount, 1, MPI_INT, + MPI_STATUS_IGNORE); + // each process writes the quantity of indexContainer elements in all blocks + MPI_File_write_at(file_handler, (MPI_Offset)(write_offset1 + 2 * sizeof(int)), &count_indexContainer, 1, MPI_INT, + MPI_STATUS_IGNORE); + // each process writes the quantity of bcindexmatrix elements in every block + MPI_File_write_at(file_handler, (MPI_Offset)(write_offset1 + 3 * sizeof(int)), &boundCondParamStr, 1, + boundCondParamType, MPI_STATUS_IGNORE); + + // each process writes data identifying the blocks + MPI_File_write_at(file_handler, write_offset, bcAddArray, blocksCount, boundCondTypeAdd, MPI_STATUS_IGNORE); + // each process writes boundary conditions + if (bcVector.size() > 0) + MPI_File_write_at(file_handler, (MPI_Offset)(write_offset + blocksCount * sizeof(BCAddRestart)), &bcVector[0], + bcBlockCount, boundCondType1000, MPI_STATUS_IGNORE); + // each process writes bcindexmatrix values + if (bcindexmatrixV.size() > 0) + MPI_File_write_at(file_handler, + (MPI_Offset)(write_offset + blocksCount * sizeof(BCAddRestart) + + bcBlockCount * BLOCK_SIZE * sizeof(BoundaryCondition)), + &bcindexmatrixV[0], blocksCount, bcindexmatrixType, MPI_STATUS_IGNORE); + // each process writes indexContainer values + if (indexContainerV.size() > 0) + MPI_File_write_at(file_handler, + (MPI_Offset)(write_offset + blocksCount * sizeof(BCAddRestart) + + bcBlockCount * BLOCK_SIZE * sizeof(BoundaryCondition) + + blocksCount * boundCondParamStr.bcindexmatrixCount * sizeof(int)), + &indexContainerV[0], count_indexContainer, MPI_INT, MPI_STATUS_IGNORE); + + MPI_File_sync(file_handler); + MPI_File_close(&file_handler); + MPI_Type_free(&bcindexmatrixType); + + if (comm->isRoot()) { + finish = MPI_Wtime(); + UBLOG(logINFO, "MPIIORestartCoProcessor::writeBoundaryConds time: " << finish - start << " s"); + } + + delete[] bcAddArray; } //------------------------------------------- READ ----------------------------------------------- void MPIIORestartCoProcessor::restart(int step) { - if (comm->isRoot()) UBLOG(logINFO, "MPIIORestartCoProcessor restart step: " << step); - if (comm->isRoot()) UBLOG(logINFO, "Load check point - start"); + if (comm->isRoot()) + UBLOG(logINFO, "MPIIORestartCoProcessor restart step: " << step); + if (comm->isRoot()) + UBLOG(logINFO, "Load check point - start"); - readBlocks(step); - readDataSet(step); - readBoundaryConds(step); + readBlocks(step); + readDataSet(step); + readBoundaryConds(step); - grid->setTimeStep(step); + grid->setTimeStep(step); - if (comm->isRoot()) UBLOG(logINFO, "Load check point - end"); + if (comm->isRoot()) + UBLOG(logINFO, "Load check point - end"); } -void MPIIORestartCoProcessor::readBlocks(int step) -{ - MPIIOCoProcessor::readBlocks(step); -} +void MPIIORestartCoProcessor::readBlocks(int step) { MPIIOCoProcessor::readBlocks(step); } void MPIIORestartCoProcessor::readDataSet(int step) { - int rank, size; - MPI_Comm_rank(MPI_COMM_WORLD, &rank); - MPI_Comm_size(MPI_COMM_WORLD, &size); - - if (comm->isRoot()) - { - UBLOG(logINFO, "MPIIORestartCoProcessor::readDataSet start MPI IO rank = " << rank); - UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); - } - double start, finish; - if (comm->isRoot()) start = MPI_Wtime(); - - MPI_File file_handler; - std::string filename = path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + "/cpDataSet.bin"; - int rc = MPI_File_open(MPI_COMM_WORLD, filename.c_str(), MPI_MODE_RDONLY, MPI_INFO_NULL, &file_handler); - if (rc != MPI_SUCCESS) throw UbException(UB_EXARGS, "couldn't open file " + filename); - - // calculate the read offset - MPI_Offset read_offset = (MPI_Offset)(size * sizeof(int)); - size_t next_read_offset = 0; - - // read count of blocks - int blocksCount = 0; - dataSetParam dataSetParamStr1, dataSetParamStr2, dataSetParamStr3; - - MPI_File_read_at(file_handler, (MPI_Offset)(rank * sizeof(int)), &blocksCount, 1, MPI_INT, MPI_STATUS_IGNORE); - MPI_File_read_at(file_handler, read_offset, &dataSetParamStr1, 1, dataSetParamType, MPI_STATUS_IGNORE); - MPI_File_read_at(file_handler, (MPI_Offset)(read_offset + sizeof(dataSetParam)), &dataSetParamStr2, 1, dataSetParamType, MPI_STATUS_IGNORE); - MPI_File_read_at(file_handler, (MPI_Offset)(read_offset + 2 * sizeof(dataSetParam)), &dataSetParamStr3, 1, dataSetParamType, MPI_STATUS_IGNORE); - - DataSetRestart* dataSetArray = new DataSetRestart[blocksCount]; - double doubleCountInBlock = dataSetParamStr1.nx[0] * dataSetParamStr1.nx[1] * dataSetParamStr1.nx[2] * dataSetParamStr1.nx[3] + - dataSetParamStr2.nx[0] * dataSetParamStr2.nx[1] * dataSetParamStr2.nx[2] * dataSetParamStr2.nx[3] + - dataSetParamStr3.nx[0] * dataSetParamStr3.nx[1] * dataSetParamStr3.nx[2] * dataSetParamStr3.nx[3]; - std::vector<double> doubleValuesArray(size_t(blocksCount * doubleCountInBlock)); // double-values in all blocks - - // define MPI_types depending on the block-specific information - MPI_Type_contiguous(int(doubleCountInBlock), MPI_DOUBLE, &dataSetDoubleType); - MPI_Type_commit(&dataSetDoubleType); - - if (size > 1) - { - if (rank == 0) - { - next_read_offset = read_offset + 3 * sizeof(dataSetParam) + blocksCount * (sizeof(DataSetRestart) + size_t(doubleCountInBlock) * sizeof(double)); - MPI_Send(&next_read_offset, 1, MPI_LONG_LONG_INT, 1, 5, MPI_COMM_WORLD); - } - else - { - MPI_Recv(&read_offset, 1, MPI_LONG_LONG_INT, rank - 1, 5, MPI_COMM_WORLD, MPI_STATUS_IGNORE); - next_read_offset = read_offset + 3 * sizeof(dataSetParam) + blocksCount * (sizeof(DataSetRestart) + size_t(doubleCountInBlock) * sizeof(double)); - if (rank < size - 1) - MPI_Send(&next_read_offset, 1, MPI_LONG_LONG_INT, rank + 1, 5, MPI_COMM_WORLD); - } - } - - MPI_File_read_at(file_handler, (MPI_Offset)(read_offset + 3 * sizeof(dataSetParam)), dataSetArray, blocksCount, dataSetType, MPI_STATUS_IGNORE); - MPI_File_read_at(file_handler, (MPI_Offset)(read_offset + 3 * sizeof(dataSetParam) + blocksCount * sizeof(DataSetRestart)), &doubleValuesArray[0], blocksCount, dataSetDoubleType, MPI_STATUS_IGNORE); - MPI_File_close(&file_handler); - MPI_Type_free(&dataSetDoubleType); - - if (comm->isRoot()) - { - finish = MPI_Wtime(); - UBLOG(logINFO, "MPIIORestartCoProcessor::readDataSet time: " << finish - start << " s"); - UBLOG(logINFO, "MPIIORestartCoProcessor::readDataSet start of restore of data, rank = " << rank); - UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); - } - - size_t index = 0, vectorSize = 0; - std::vector<double> vectorsOfValues1, vectorsOfValues2, vectorsOfValues3; - - for (int n = 0; n < blocksCount; n++) - { - vectorSize = dataSetParamStr1.nx[0] * dataSetParamStr1.nx[1] * dataSetParamStr1.nx[2] * dataSetParamStr1.nx[3]; - vectorsOfValues1.assign(doubleValuesArray.data() + index, doubleValuesArray.data() + index + vectorSize); - index += vectorSize; - - vectorSize = dataSetParamStr2.nx[0] * dataSetParamStr2.nx[1] * dataSetParamStr2.nx[2] * dataSetParamStr2.nx[3]; - vectorsOfValues2.assign(doubleValuesArray.data() + index, doubleValuesArray.data() + index + vectorSize); - index += vectorSize; - - vectorSize = dataSetParamStr3.nx[0] * dataSetParamStr3.nx[1] * dataSetParamStr3.nx[2] * dataSetParamStr3.nx[3]; - vectorsOfValues3.assign(doubleValuesArray.data() + index, doubleValuesArray.data() + index + vectorSize); - index += vectorSize; - - SPtr<DistributionArray3D> mFdistributions(new D3Q27EsoTwist3DSplittedVector()); - - dynamicPointerCast<D3Q27EsoTwist3DSplittedVector>(mFdistributions)->setLocalDistributions(CbArray4D<LBMReal, IndexerX4X3X2X1>::CbArray4DPtr(new CbArray4D<LBMReal, IndexerX4X3X2X1>(vectorsOfValues1, dataSetParamStr1.nx[0], dataSetParamStr1.nx[1], dataSetParamStr1.nx[2], dataSetParamStr1.nx[3]))); - dynamicPointerCast<D3Q27EsoTwist3DSplittedVector>(mFdistributions)->setNonLocalDistributions(CbArray4D<LBMReal, IndexerX4X3X2X1>::CbArray4DPtr(new CbArray4D<LBMReal, IndexerX4X3X2X1>(vectorsOfValues2, dataSetParamStr2.nx[0], dataSetParamStr2.nx[1], dataSetParamStr2.nx[2], dataSetParamStr2.nx[3]))); - dynamicPointerCast<D3Q27EsoTwist3DSplittedVector>(mFdistributions)->setZeroDistributions(CbArray3D<LBMReal, IndexerX3X2X1>::CbArray3DPtr(new CbArray3D<LBMReal, IndexerX3X2X1>(vectorsOfValues3, dataSetParamStr3.nx[0], dataSetParamStr3.nx[1], dataSetParamStr3.nx[2]))); - - dynamicPointerCast<D3Q27EsoTwist3DSplittedVector>(mFdistributions)->setNX1(dataSetParamStr1.nx1); - dynamicPointerCast<D3Q27EsoTwist3DSplittedVector>(mFdistributions)->setNX2(dataSetParamStr1.nx2); - dynamicPointerCast<D3Q27EsoTwist3DSplittedVector>(mFdistributions)->setNX3(dataSetParamStr1.nx3); - - // find the nesessary block and fill it - SPtr<Block3D> block = grid->getBlock(dataSetArray[n].x1, dataSetArray[n].x2, dataSetArray[n].x3, dataSetArray[n].level); - this->lbmKernel->setBlock(block); - SPtr<LBMKernel> kernel = this->lbmKernel->clone(); - kernel->setGhostLayerWidth(dataSetArray[n].ghostLayerWidth); - kernel->setCollisionFactor(dataSetArray[n].collFactor); - kernel->setDeltaT(dataSetArray[n].deltaT); - kernel->setCompressible(dataSetArray[n].compressible); - kernel->setWithForcing(dataSetArray[n].withForcing); - SPtr<DataSet3D> dataSetPtr = SPtr<DataSet3D>(new DataSet3D()); - dataSetPtr->setFdistributions(mFdistributions); - kernel->setDataSet(dataSetPtr); - block->setKernel(kernel); - } - - if (comm->isRoot()) - { - UBLOG(logINFO, "MPIIORestartCoProcessor::readDataSet end of restore of data, rank = " << rank); - UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); - } - - delete[] dataSetArray; - - //------------------------------------------------------------- - - DSArraysPresence arrPresence; - MPI_File file_handler1; - std::string filename1 = path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + "/cpArrays.bin"; - rc = MPI_File_open(MPI_COMM_WORLD, filename1.c_str(), MPI_MODE_RDONLY, MPI_INFO_NULL, &file_handler1); - if (rc != MPI_SUCCESS) throw UbException(UB_EXARGS, "couldn't open file " + filename1); - MPI_File_read_at(file_handler1, (MPI_Offset)0, &arrPresence, 1, arrayPresenceType, MPI_STATUS_IGNORE); - MPI_File_close(&file_handler1); - - if (arrPresence.isAverageDensityArrayPresent) - readAverageDensityArray(step); - - if (arrPresence.isAverageVelocityArrayPresent) - readAverageVelocityArray(step); - - if (arrPresence.isAverageFluktuationsArrayPresent) - readAverageFluktuationsArray(step); - - if (arrPresence.isAverageTripleArrayPresent) - readAverageTripleArray(step); - - if (arrPresence.isShearStressValArrayPresent) - readShearStressValArray(step); - - if (arrPresence.isRelaxationFactorPresent) - readRelaxationFactor(step); - + int rank, size; + MPI_Comm_rank(MPI_COMM_WORLD, &rank); + MPI_Comm_size(MPI_COMM_WORLD, &size); + + if (comm->isRoot()) { + UBLOG(logINFO, "MPIIORestartCoProcessor::readDataSet start MPI IO rank = " << rank); + UBLOG(logINFO, "Physical Memory currently used by current process: " + << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); + } + double start, finish; + if (comm->isRoot()) + start = MPI_Wtime(); + + MPI_File file_handler; + std::string filename = path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + "/cpDataSet.bin"; + int rc = MPI_File_open(MPI_COMM_WORLD, filename.c_str(), MPI_MODE_RDONLY, MPI_INFO_NULL, &file_handler); + if (rc != MPI_SUCCESS) + throw UbException(UB_EXARGS, "couldn't open file " + filename); + + // calculate the read offset + MPI_Offset read_offset = (MPI_Offset)(size * sizeof(int)); + size_t next_read_offset = 0; + + // read count of blocks + int blocksCount = 0; + dataSetParam dataSetParamStr1, dataSetParamStr2, dataSetParamStr3; + + MPI_File_read_at(file_handler, (MPI_Offset)(rank * sizeof(int)), &blocksCount, 1, MPI_INT, MPI_STATUS_IGNORE); + MPI_File_read_at(file_handler, read_offset, &dataSetParamStr1, 1, dataSetParamType, MPI_STATUS_IGNORE); + MPI_File_read_at(file_handler, (MPI_Offset)(read_offset + sizeof(dataSetParam)), &dataSetParamStr2, 1, + dataSetParamType, MPI_STATUS_IGNORE); + MPI_File_read_at(file_handler, (MPI_Offset)(read_offset + 2 * sizeof(dataSetParam)), &dataSetParamStr3, 1, + dataSetParamType, MPI_STATUS_IGNORE); + + DataSetRestart *dataSetArray = new DataSetRestart[blocksCount]; + double doubleCountInBlock = + dataSetParamStr1.nx[0] * dataSetParamStr1.nx[1] * dataSetParamStr1.nx[2] * dataSetParamStr1.nx[3] + + dataSetParamStr2.nx[0] * dataSetParamStr2.nx[1] * dataSetParamStr2.nx[2] * dataSetParamStr2.nx[3] + + dataSetParamStr3.nx[0] * dataSetParamStr3.nx[1] * dataSetParamStr3.nx[2] * dataSetParamStr3.nx[3]; + std::vector<double> doubleValuesArray(size_t(blocksCount * doubleCountInBlock)); // double-values in all blocks + + // define MPI_types depending on the block-specific information + MPI_Type_contiguous(int(doubleCountInBlock), MPI_DOUBLE, &dataSetDoubleType); + MPI_Type_commit(&dataSetDoubleType); + + if (size > 1) { + if (rank == 0) { + next_read_offset = read_offset + 3 * sizeof(dataSetParam) + + blocksCount * (sizeof(DataSetRestart) + size_t(doubleCountInBlock) * sizeof(double)); + MPI_Send(&next_read_offset, 1, MPI_LONG_LONG_INT, 1, 5, MPI_COMM_WORLD); + } else { + MPI_Recv(&read_offset, 1, MPI_LONG_LONG_INT, rank - 1, 5, MPI_COMM_WORLD, MPI_STATUS_IGNORE); + next_read_offset = read_offset + 3 * sizeof(dataSetParam) + + blocksCount * (sizeof(DataSetRestart) + size_t(doubleCountInBlock) * sizeof(double)); + if (rank < size - 1) + MPI_Send(&next_read_offset, 1, MPI_LONG_LONG_INT, rank + 1, 5, MPI_COMM_WORLD); + } + } + + MPI_File_read_at(file_handler, (MPI_Offset)(read_offset + 3 * sizeof(dataSetParam)), dataSetArray, blocksCount, + dataSetType, MPI_STATUS_IGNORE); + MPI_File_read_at(file_handler, + (MPI_Offset)(read_offset + 3 * sizeof(dataSetParam) + blocksCount * sizeof(DataSetRestart)), + &doubleValuesArray[0], blocksCount, dataSetDoubleType, MPI_STATUS_IGNORE); + MPI_File_close(&file_handler); + MPI_Type_free(&dataSetDoubleType); + + if (comm->isRoot()) { + finish = MPI_Wtime(); + UBLOG(logINFO, "MPIIORestartCoProcessor::readDataSet time: " << finish - start << " s"); + UBLOG(logINFO, "MPIIORestartCoProcessor::readDataSet start of restore of data, rank = " << rank); + UBLOG(logINFO, "Physical Memory currently used by current process: " + << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); + } + + size_t index = 0, vectorSize = 0; + std::vector<double> vectorsOfValues1, vectorsOfValues2, vectorsOfValues3; + + for (int n = 0; n < blocksCount; n++) { + vectorSize = dataSetParamStr1.nx[0] * dataSetParamStr1.nx[1] * dataSetParamStr1.nx[2] * dataSetParamStr1.nx[3]; + vectorsOfValues1.assign(doubleValuesArray.data() + index, doubleValuesArray.data() + index + vectorSize); + index += vectorSize; + + vectorSize = dataSetParamStr2.nx[0] * dataSetParamStr2.nx[1] * dataSetParamStr2.nx[2] * dataSetParamStr2.nx[3]; + vectorsOfValues2.assign(doubleValuesArray.data() + index, doubleValuesArray.data() + index + vectorSize); + index += vectorSize; + + vectorSize = dataSetParamStr3.nx[0] * dataSetParamStr3.nx[1] * dataSetParamStr3.nx[2] * dataSetParamStr3.nx[3]; + vectorsOfValues3.assign(doubleValuesArray.data() + index, doubleValuesArray.data() + index + vectorSize); + index += vectorSize; + + SPtr<DistributionArray3D> mFdistributions(new D3Q27EsoTwist3DSplittedVector()); + + dynamicPointerCast<D3Q27EsoTwist3DSplittedVector>(mFdistributions) + ->setLocalDistributions(CbArray4D<LBMReal, IndexerX4X3X2X1>::CbArray4DPtr( + new CbArray4D<LBMReal, IndexerX4X3X2X1>(vectorsOfValues1, dataSetParamStr1.nx[0], + dataSetParamStr1.nx[1], dataSetParamStr1.nx[2], + dataSetParamStr1.nx[3]))); + dynamicPointerCast<D3Q27EsoTwist3DSplittedVector>(mFdistributions) + ->setNonLocalDistributions(CbArray4D<LBMReal, IndexerX4X3X2X1>::CbArray4DPtr( + new CbArray4D<LBMReal, IndexerX4X3X2X1>(vectorsOfValues2, dataSetParamStr2.nx[0], + dataSetParamStr2.nx[1], dataSetParamStr2.nx[2], + dataSetParamStr2.nx[3]))); + dynamicPointerCast<D3Q27EsoTwist3DSplittedVector>(mFdistributions) + ->setZeroDistributions( + CbArray3D<LBMReal, IndexerX3X2X1>::CbArray3DPtr(new CbArray3D<LBMReal, IndexerX3X2X1>( + vectorsOfValues3, dataSetParamStr3.nx[0], dataSetParamStr3.nx[1], dataSetParamStr3.nx[2]))); + + dynamicPointerCast<D3Q27EsoTwist3DSplittedVector>(mFdistributions)->setNX1(dataSetParamStr1.nx1); + dynamicPointerCast<D3Q27EsoTwist3DSplittedVector>(mFdistributions)->setNX2(dataSetParamStr1.nx2); + dynamicPointerCast<D3Q27EsoTwist3DSplittedVector>(mFdistributions)->setNX3(dataSetParamStr1.nx3); + + // find the nesessary block and fill it + SPtr<Block3D> block = + grid->getBlock(dataSetArray[n].x1, dataSetArray[n].x2, dataSetArray[n].x3, dataSetArray[n].level); + this->lbmKernel->setBlock(block); + SPtr<LBMKernel> kernel = this->lbmKernel->clone(); + kernel->setGhostLayerWidth(dataSetArray[n].ghostLayerWidth); + kernel->setCollisionFactor(dataSetArray[n].collFactor); + kernel->setDeltaT(dataSetArray[n].deltaT); + kernel->setCompressible(dataSetArray[n].compressible); + kernel->setWithForcing(dataSetArray[n].withForcing); + SPtr<DataSet3D> dataSetPtr = SPtr<DataSet3D>(new DataSet3D()); + dataSetPtr->setFdistributions(mFdistributions); + kernel->setDataSet(dataSetPtr); + block->setKernel(kernel); + } + + if (comm->isRoot()) { + UBLOG(logINFO, "MPIIORestartCoProcessor::readDataSet end of restore of data, rank = " << rank); + UBLOG(logINFO, "Physical Memory currently used by current process: " + << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); + } + + delete[] dataSetArray; + + //------------------------------------------------------------- + + DSArraysPresence arrPresence; + MPI_File file_handler1; + std::string filename1 = path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + "/cpArrays.bin"; + rc = MPI_File_open(MPI_COMM_WORLD, filename1.c_str(), MPI_MODE_RDONLY, MPI_INFO_NULL, &file_handler1); + if (rc != MPI_SUCCESS) + throw UbException(UB_EXARGS, "couldn't open file " + filename1); + MPI_File_read_at(file_handler1, (MPI_Offset)0, &arrPresence, 1, arrayPresenceType, MPI_STATUS_IGNORE); + MPI_File_close(&file_handler1); + + if (arrPresence.isAverageDensityArrayPresent) + readAverageDensityArray(step); + + if (arrPresence.isAverageVelocityArrayPresent) + readAverageVelocityArray(step); + + if (arrPresence.isAverageFluktuationsArrayPresent) + readAverageFluktuationsArray(step); + + if (arrPresence.isAverageTripleArrayPresent) + readAverageTripleArray(step); + + if (arrPresence.isShearStressValArrayPresent) + readShearStressValArray(step); + + if (arrPresence.isRelaxationFactorPresent) + readRelaxationFactor(step); } void MPIIORestartCoProcessor::readAverageDensityArray(int step) { - int rank, size; - MPI_Comm_rank(MPI_COMM_WORLD, &rank); - MPI_Comm_size(MPI_COMM_WORLD, &size); - - if (comm->isRoot()) - { - UBLOG(logINFO, "MPIIORestartCoProcessor::readAverageDensityArray start MPI IO rank = " << rank); - UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); - } - double start, finish; - if (comm->isRoot()) start = MPI_Wtime(); - - MPI_File file_handler; - std::string filename = path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + "/cpAverageDensityArray.bin"; - int rc = MPI_File_open(MPI_COMM_WORLD, filename.c_str(), MPI_MODE_RDONLY, MPI_INFO_NULL, &file_handler); - if (rc != MPI_SUCCESS) throw UbException(UB_EXARGS, "couldn't open file " + filename); - - // read count of blocks - int blocksCount = 0; - dataSetParam dataSetParamStr; - memset(&dataSetParamStr, 0, sizeof(dataSetParam)); - - MPI_File_read_at(file_handler, (MPI_Offset)(rank * sizeof(int)), &blocksCount, 1, MPI_INT, MPI_STATUS_IGNORE); - MPI_File_read_at(file_handler, (MPI_Offset)(size * sizeof(int)), &dataSetParamStr, 1, dataSetParamType, MPI_STATUS_IGNORE); - - DataSetSmallRestart* dataSetSmallArray = new DataSetSmallRestart[blocksCount]; - int doubleCountInBlock = dataSetParamStr.nx[0] * dataSetParamStr.nx[1] * dataSetParamStr.nx[2] * dataSetParamStr.nx[3]; - std::vector<double> doubleValuesArray(blocksCount * doubleCountInBlock); // double-values in all blocks - - // define MPI_types depending on the block-specific information - MPI_Type_contiguous(doubleCountInBlock, MPI_DOUBLE, &dataSetDoubleType); - MPI_Type_commit(&dataSetDoubleType); - - // calculate the read offset - MPI_Offset read_offset = (MPI_Offset)(size * sizeof(int)); - size_t next_read_offset = 0; - - if (size > 1) - { - if (rank == 0) - { - next_read_offset = read_offset + sizeof(dataSetParam) + blocksCount*(sizeof(DataSetSmallRestart) + doubleCountInBlock * sizeof(double)); - MPI_Send(&next_read_offset, 1, MPI_LONG_LONG_INT, 1, 5, MPI_COMM_WORLD); - } - else - { - MPI_Recv(&read_offset, 1, MPI_LONG_LONG_INT, rank - 1, 5, MPI_COMM_WORLD, MPI_STATUS_IGNORE); - next_read_offset = read_offset + sizeof(dataSetParam) + blocksCount*(sizeof(DataSetSmallRestart) + doubleCountInBlock * sizeof(double)); - if (rank < size - 1) - MPI_Send(&next_read_offset, 1, MPI_LONG_LONG_INT, rank + 1, 5, MPI_COMM_WORLD); - } - } - - MPI_File_read_at(file_handler, (MPI_Offset)(read_offset + sizeof(dataSetParam)), dataSetSmallArray, blocksCount, dataSetSmallType, MPI_STATUS_IGNORE); - if (doubleCountInBlock > 0) - MPI_File_read_at(file_handler, (MPI_Offset)(read_offset + sizeof(dataSetParam) + blocksCount * sizeof(DataSetSmallRestart)), &doubleValuesArray[0], blocksCount, dataSetDoubleType, MPI_STATUS_IGNORE); - MPI_File_close(&file_handler); - MPI_Type_free(&dataSetDoubleType); - - if (comm->isRoot()) - { - finish = MPI_Wtime(); - UBLOG(logINFO, "MPIIORestartCoProcessor::readAverageDensityArray time: " << finish - start << " s"); - UBLOG(logINFO, "MPIIORestartCoProcessor::readAverageDensityArray start of restore of data, rank = " << rank); - UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); - } - - size_t index = 0; - size_t nextVectorSize = dataSetParamStr.nx[0] * dataSetParamStr.nx[1] * dataSetParamStr.nx[2] * dataSetParamStr.nx[3]; - std::vector<double> vectorsOfValues; - for (int n = 0; n < blocksCount; n++) - { - vectorsOfValues.assign(doubleValuesArray.data() + index, doubleValuesArray.data() + index + nextVectorSize); - index += nextVectorSize; - - // fill mAverageDensity arrays - SPtr<AverageValuesArray3D> mAverageDensity; - mAverageDensity = CbArray4D<LBMReal, IndexerX4X3X2X1>::CbArray4DPtr(new CbArray4D<LBMReal, IndexerX4X3X2X1>(vectorsOfValues, dataSetParamStr.nx[0], dataSetParamStr.nx[1], dataSetParamStr.nx[2], dataSetParamStr.nx[3])); - - // find the nesessary block and fill it - SPtr<Block3D> block = grid->getBlock(dataSetSmallArray[n].x1, dataSetSmallArray[n].x2, dataSetSmallArray[n].x3, dataSetSmallArray[n].level); - block->getKernel()->getDataSet()->setAverageDensity(mAverageDensity); - } - - if (comm->isRoot()) - { - UBLOG(logINFO, "MPIIORestartCoProcessor::readAverageDensityArray end of restore of data, rank = " << rank); - UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); - } - - delete[] dataSetSmallArray; + int rank, size; + MPI_Comm_rank(MPI_COMM_WORLD, &rank); + MPI_Comm_size(MPI_COMM_WORLD, &size); + + if (comm->isRoot()) { + UBLOG(logINFO, "MPIIORestartCoProcessor::readAverageDensityArray start MPI IO rank = " << rank); + UBLOG(logINFO, "Physical Memory currently used by current process: " + << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); + } + double start, finish; + if (comm->isRoot()) + start = MPI_Wtime(); + + MPI_File file_handler; + std::string filename = path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + "/cpAverageDensityArray.bin"; + int rc = MPI_File_open(MPI_COMM_WORLD, filename.c_str(), MPI_MODE_RDONLY, MPI_INFO_NULL, &file_handler); + if (rc != MPI_SUCCESS) + throw UbException(UB_EXARGS, "couldn't open file " + filename); + + // read count of blocks + int blocksCount = 0; + dataSetParam dataSetParamStr; + memset(&dataSetParamStr, 0, sizeof(dataSetParam)); + + MPI_File_read_at(file_handler, (MPI_Offset)(rank * sizeof(int)), &blocksCount, 1, MPI_INT, MPI_STATUS_IGNORE); + MPI_File_read_at(file_handler, (MPI_Offset)(size * sizeof(int)), &dataSetParamStr, 1, dataSetParamType, + MPI_STATUS_IGNORE); + + DataSetSmallRestart *dataSetSmallArray = new DataSetSmallRestart[blocksCount]; + int doubleCountInBlock = + dataSetParamStr.nx[0] * dataSetParamStr.nx[1] * dataSetParamStr.nx[2] * dataSetParamStr.nx[3]; + std::vector<double> doubleValuesArray(blocksCount * doubleCountInBlock); // double-values in all blocks + + // define MPI_types depending on the block-specific information + MPI_Type_contiguous(doubleCountInBlock, MPI_DOUBLE, &dataSetDoubleType); + MPI_Type_commit(&dataSetDoubleType); + + // calculate the read offset + MPI_Offset read_offset = (MPI_Offset)(size * sizeof(int)); + size_t next_read_offset = 0; + + if (size > 1) { + if (rank == 0) { + next_read_offset = read_offset + sizeof(dataSetParam) + + blocksCount * (sizeof(DataSetSmallRestart) + doubleCountInBlock * sizeof(double)); + MPI_Send(&next_read_offset, 1, MPI_LONG_LONG_INT, 1, 5, MPI_COMM_WORLD); + } else { + MPI_Recv(&read_offset, 1, MPI_LONG_LONG_INT, rank - 1, 5, MPI_COMM_WORLD, MPI_STATUS_IGNORE); + next_read_offset = read_offset + sizeof(dataSetParam) + + blocksCount * (sizeof(DataSetSmallRestart) + doubleCountInBlock * sizeof(double)); + if (rank < size - 1) + MPI_Send(&next_read_offset, 1, MPI_LONG_LONG_INT, rank + 1, 5, MPI_COMM_WORLD); + } + } + + MPI_File_read_at(file_handler, (MPI_Offset)(read_offset + sizeof(dataSetParam)), dataSetSmallArray, blocksCount, + dataSetSmallType, MPI_STATUS_IGNORE); + if (doubleCountInBlock > 0) + MPI_File_read_at(file_handler, + (MPI_Offset)(read_offset + sizeof(dataSetParam) + blocksCount * sizeof(DataSetSmallRestart)), + &doubleValuesArray[0], blocksCount, dataSetDoubleType, MPI_STATUS_IGNORE); + MPI_File_close(&file_handler); + MPI_Type_free(&dataSetDoubleType); + + if (comm->isRoot()) { + finish = MPI_Wtime(); + UBLOG(logINFO, "MPIIORestartCoProcessor::readAverageDensityArray time: " << finish - start << " s"); + UBLOG(logINFO, "MPIIORestartCoProcessor::readAverageDensityArray start of restore of data, rank = " << rank); + UBLOG(logINFO, "Physical Memory currently used by current process: " + << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); + } + + size_t index = 0; + size_t nextVectorSize = + dataSetParamStr.nx[0] * dataSetParamStr.nx[1] * dataSetParamStr.nx[2] * dataSetParamStr.nx[3]; + std::vector<double> vectorsOfValues; + for (int n = 0; n < blocksCount; n++) { + vectorsOfValues.assign(doubleValuesArray.data() + index, doubleValuesArray.data() + index + nextVectorSize); + index += nextVectorSize; + + // fill mAverageDensity arrays + SPtr<AverageValuesArray3D> mAverageDensity; + mAverageDensity = CbArray4D<LBMReal, IndexerX4X3X2X1>::CbArray4DPtr( + new CbArray4D<LBMReal, IndexerX4X3X2X1>(vectorsOfValues, dataSetParamStr.nx[0], dataSetParamStr.nx[1], + dataSetParamStr.nx[2], dataSetParamStr.nx[3])); + + // find the nesessary block and fill it + SPtr<Block3D> block = grid->getBlock(dataSetSmallArray[n].x1, dataSetSmallArray[n].x2, dataSetSmallArray[n].x3, + dataSetSmallArray[n].level); + block->getKernel()->getDataSet()->setAverageDensity(mAverageDensity); + } + + if (comm->isRoot()) { + UBLOG(logINFO, "MPIIORestartCoProcessor::readAverageDensityArray end of restore of data, rank = " << rank); + UBLOG(logINFO, "Physical Memory currently used by current process: " + << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); + } + + delete[] dataSetSmallArray; } void MPIIORestartCoProcessor::readAverageVelocityArray(int step) { - int rank, size; - MPI_Comm_rank(MPI_COMM_WORLD, &rank); - MPI_Comm_size(MPI_COMM_WORLD, &size); - - if (comm->isRoot()) - { - UBLOG(logINFO, "MPIIORestartCoProcessor::readAverageVelocityArray start MPI IO rank = " << rank); - UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); - } - double start, finish; - if (comm->isRoot()) start = MPI_Wtime(); - - MPI_File file_handler; - std::string filename = path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + "/cpAverageVelocityArray.bin"; - int rc = MPI_File_open(MPI_COMM_WORLD, filename.c_str(), MPI_MODE_RDONLY, MPI_INFO_NULL, &file_handler); - if (rc != MPI_SUCCESS) throw UbException(UB_EXARGS, "couldn't open file " + filename); - - // read count of blocks - int blocksCount = 0; - dataSetParam dataSetParamStr; - MPI_File_read_at(file_handler, (MPI_Offset)(rank * sizeof(int)), &blocksCount, 1, MPI_INT, MPI_STATUS_IGNORE); - MPI_File_read_at(file_handler, (MPI_Offset)(size * sizeof(int)), &dataSetParamStr, 1, dataSetParamType, MPI_STATUS_IGNORE); - - DataSetSmallRestart* dataSetSmallArray = new DataSetSmallRestart[blocksCount]; - int doubleCountInBlock = dataSetParamStr.nx[0] * dataSetParamStr.nx[1] * dataSetParamStr.nx[2] * dataSetParamStr.nx[3]; - std::vector<double> doubleValuesArray(blocksCount * doubleCountInBlock); // double-values in all blocks - - // define MPI_types depending on the block-specific information - MPI_Type_contiguous(doubleCountInBlock, MPI_DOUBLE, &dataSetDoubleType); - MPI_Type_commit(&dataSetDoubleType); - - // calculate the read offset - MPI_Offset read_offset = (MPI_Offset)(size * sizeof(int)); - size_t next_read_offset = 0; - - if (size > 1) - { - if (rank == 0) - { - next_read_offset = read_offset + sizeof(dataSetParam) + blocksCount*(sizeof(DataSetSmallRestart) + doubleCountInBlock * sizeof(double)); - MPI_Send(&next_read_offset, 1, MPI_LONG_LONG_INT, 1, 5, MPI_COMM_WORLD); - } - else - { - MPI_Recv(&read_offset, 1, MPI_LONG_LONG_INT, rank - 1, 5, MPI_COMM_WORLD, MPI_STATUS_IGNORE); - next_read_offset = read_offset + sizeof(dataSetParam) + blocksCount*(sizeof(DataSetSmallRestart) + doubleCountInBlock * sizeof(double)); - if (rank < size - 1) - MPI_Send(&next_read_offset, 1, MPI_LONG_LONG_INT, rank + 1, 5, MPI_COMM_WORLD); - } - } - - MPI_File_read_at(file_handler, (MPI_Offset)(read_offset + sizeof(dataSetParam)), dataSetSmallArray, blocksCount, dataSetSmallType, MPI_STATUS_IGNORE); - if (doubleCountInBlock > 0) - MPI_File_read_at(file_handler, (MPI_Offset)(read_offset + sizeof(dataSetParam) + blocksCount * sizeof(DataSetSmallRestart)), &doubleValuesArray[0], blocksCount, dataSetDoubleType, MPI_STATUS_IGNORE); - MPI_File_close(&file_handler); - MPI_Type_free(&dataSetDoubleType); - - if (comm->isRoot()) - { - finish = MPI_Wtime(); - UBLOG(logINFO, "MPIIORestartCoProcessor::readAverageVelocityArray time: " << finish - start << " s"); - UBLOG(logINFO, "MPIIORestartCoProcessor::readAverageVelocityArray start of restore of data, rank = " << rank); - UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); - } - - size_t index = 0; - size_t nextVectorSize = dataSetParamStr.nx[0] * dataSetParamStr.nx[1] * dataSetParamStr.nx[2] * dataSetParamStr.nx[3]; - std::vector<double> vectorsOfValues; - for (int n = 0; n < blocksCount; n++) - { - vectorsOfValues.assign(doubleValuesArray.data() + index, doubleValuesArray.data() + index + nextVectorSize); - index += nextVectorSize; - - // fill mAverageVelocity array - SPtr<AverageValuesArray3D> mAverageVelocity; - mAverageVelocity = CbArray4D<LBMReal, IndexerX4X3X2X1>::CbArray4DPtr(new CbArray4D<LBMReal, IndexerX4X3X2X1>(vectorsOfValues, dataSetParamStr.nx[0], dataSetParamStr.nx[1], dataSetParamStr.nx[2], dataSetParamStr.nx[3])); - - // find the nesessary block and fill it - SPtr<Block3D> block = grid->getBlock(dataSetSmallArray[n].x1, dataSetSmallArray[n].x2, dataSetSmallArray[n].x3, dataSetSmallArray[n].level); - block->getKernel()->getDataSet()->setAverageVelocity(mAverageVelocity); - } - - if (comm->isRoot()) - { - UBLOG(logINFO, "MPIIORestartCoProcessor::readAverageVelocityArray end of restore of data, rank = " << rank); - UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); - } - - delete[] dataSetSmallArray; + int rank, size; + MPI_Comm_rank(MPI_COMM_WORLD, &rank); + MPI_Comm_size(MPI_COMM_WORLD, &size); + + if (comm->isRoot()) { + UBLOG(logINFO, "MPIIORestartCoProcessor::readAverageVelocityArray start MPI IO rank = " << rank); + UBLOG(logINFO, "Physical Memory currently used by current process: " + << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); + } + double start, finish; + if (comm->isRoot()) + start = MPI_Wtime(); + + MPI_File file_handler; + std::string filename = path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + "/cpAverageVelocityArray.bin"; + int rc = MPI_File_open(MPI_COMM_WORLD, filename.c_str(), MPI_MODE_RDONLY, MPI_INFO_NULL, &file_handler); + if (rc != MPI_SUCCESS) + throw UbException(UB_EXARGS, "couldn't open file " + filename); + + // read count of blocks + int blocksCount = 0; + dataSetParam dataSetParamStr; + MPI_File_read_at(file_handler, (MPI_Offset)(rank * sizeof(int)), &blocksCount, 1, MPI_INT, MPI_STATUS_IGNORE); + MPI_File_read_at(file_handler, (MPI_Offset)(size * sizeof(int)), &dataSetParamStr, 1, dataSetParamType, + MPI_STATUS_IGNORE); + + DataSetSmallRestart *dataSetSmallArray = new DataSetSmallRestart[blocksCount]; + int doubleCountInBlock = + dataSetParamStr.nx[0] * dataSetParamStr.nx[1] * dataSetParamStr.nx[2] * dataSetParamStr.nx[3]; + std::vector<double> doubleValuesArray(blocksCount * doubleCountInBlock); // double-values in all blocks + + // define MPI_types depending on the block-specific information + MPI_Type_contiguous(doubleCountInBlock, MPI_DOUBLE, &dataSetDoubleType); + MPI_Type_commit(&dataSetDoubleType); + + // calculate the read offset + MPI_Offset read_offset = (MPI_Offset)(size * sizeof(int)); + size_t next_read_offset = 0; + + if (size > 1) { + if (rank == 0) { + next_read_offset = read_offset + sizeof(dataSetParam) + + blocksCount * (sizeof(DataSetSmallRestart) + doubleCountInBlock * sizeof(double)); + MPI_Send(&next_read_offset, 1, MPI_LONG_LONG_INT, 1, 5, MPI_COMM_WORLD); + } else { + MPI_Recv(&read_offset, 1, MPI_LONG_LONG_INT, rank - 1, 5, MPI_COMM_WORLD, MPI_STATUS_IGNORE); + next_read_offset = read_offset + sizeof(dataSetParam) + + blocksCount * (sizeof(DataSetSmallRestart) + doubleCountInBlock * sizeof(double)); + if (rank < size - 1) + MPI_Send(&next_read_offset, 1, MPI_LONG_LONG_INT, rank + 1, 5, MPI_COMM_WORLD); + } + } + + MPI_File_read_at(file_handler, (MPI_Offset)(read_offset + sizeof(dataSetParam)), dataSetSmallArray, blocksCount, + dataSetSmallType, MPI_STATUS_IGNORE); + if (doubleCountInBlock > 0) + MPI_File_read_at(file_handler, + (MPI_Offset)(read_offset + sizeof(dataSetParam) + blocksCount * sizeof(DataSetSmallRestart)), + &doubleValuesArray[0], blocksCount, dataSetDoubleType, MPI_STATUS_IGNORE); + MPI_File_close(&file_handler); + MPI_Type_free(&dataSetDoubleType); + + if (comm->isRoot()) { + finish = MPI_Wtime(); + UBLOG(logINFO, "MPIIORestartCoProcessor::readAverageVelocityArray time: " << finish - start << " s"); + UBLOG(logINFO, "MPIIORestartCoProcessor::readAverageVelocityArray start of restore of data, rank = " << rank); + UBLOG(logINFO, "Physical Memory currently used by current process: " + << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); + } + + size_t index = 0; + size_t nextVectorSize = + dataSetParamStr.nx[0] * dataSetParamStr.nx[1] * dataSetParamStr.nx[2] * dataSetParamStr.nx[3]; + std::vector<double> vectorsOfValues; + for (int n = 0; n < blocksCount; n++) { + vectorsOfValues.assign(doubleValuesArray.data() + index, doubleValuesArray.data() + index + nextVectorSize); + index += nextVectorSize; + + // fill mAverageVelocity array + SPtr<AverageValuesArray3D> mAverageVelocity; + mAverageVelocity = CbArray4D<LBMReal, IndexerX4X3X2X1>::CbArray4DPtr( + new CbArray4D<LBMReal, IndexerX4X3X2X1>(vectorsOfValues, dataSetParamStr.nx[0], dataSetParamStr.nx[1], + dataSetParamStr.nx[2], dataSetParamStr.nx[3])); + + // find the nesessary block and fill it + SPtr<Block3D> block = grid->getBlock(dataSetSmallArray[n].x1, dataSetSmallArray[n].x2, dataSetSmallArray[n].x3, + dataSetSmallArray[n].level); + block->getKernel()->getDataSet()->setAverageVelocity(mAverageVelocity); + } + + if (comm->isRoot()) { + UBLOG(logINFO, "MPIIORestartCoProcessor::readAverageVelocityArray end of restore of data, rank = " << rank); + UBLOG(logINFO, "Physical Memory currently used by current process: " + << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); + } + + delete[] dataSetSmallArray; } void MPIIORestartCoProcessor::readAverageFluktuationsArray(int step) { - int rank, size; - MPI_Comm_rank(MPI_COMM_WORLD, &rank); - MPI_Comm_size(MPI_COMM_WORLD, &size); - - if (comm->isRoot()) - { - UBLOG(logINFO, "MPIIORestartCoProcessor::readAverageFluktuationsArray start MPI IO rank = " << rank); - UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); - } - double start, finish; - if (comm->isRoot()) start = MPI_Wtime(); - - MPI_File file_handler; - std::string filename = path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + "/cpAverageFluktuationsArray.bin"; - int rc = MPI_File_open(MPI_COMM_WORLD, filename.c_str(), MPI_MODE_RDONLY, MPI_INFO_NULL, &file_handler); - if (rc != MPI_SUCCESS) throw UbException(UB_EXARGS, "couldn't open file " + filename); - - // read count of blocks - int blocksCount = 0; - dataSetParam dataSetParamStr; - MPI_File_read_at(file_handler, (MPI_Offset)(rank * sizeof(int)), &blocksCount, 1, MPI_INT, MPI_STATUS_IGNORE); - MPI_File_read_at(file_handler, (MPI_Offset)(size * sizeof(int)), &dataSetParamStr, 1, dataSetParamType, MPI_STATUS_IGNORE); - - DataSetSmallRestart* dataSetSmallArray = new DataSetSmallRestart[blocksCount]; - int doubleCountInBlock = dataSetParamStr.nx[0] * dataSetParamStr.nx[1] * dataSetParamStr.nx[2] * dataSetParamStr.nx[3]; - std::vector<double> doubleValuesArray(blocksCount * doubleCountInBlock); // double-values in all blocks - - // define MPI_types depending on the block-specific information - MPI_Type_contiguous(doubleCountInBlock, MPI_DOUBLE, &dataSetDoubleType); - MPI_Type_commit(&dataSetDoubleType); - - // calculate the read offset - MPI_Offset read_offset = (MPI_Offset)(size * sizeof(int)); - size_t next_read_offset = 0; - - if (size > 1) - { - if (rank == 0) - { - next_read_offset = read_offset + sizeof(dataSetParam) + blocksCount*(sizeof(DataSetSmallRestart) + doubleCountInBlock * sizeof(double)); - MPI_Send(&next_read_offset, 1, MPI_LONG_LONG_INT, 1, 5, MPI_COMM_WORLD); - } - else - { - MPI_Recv(&read_offset, 1, MPI_LONG_LONG_INT, rank - 1, 5, MPI_COMM_WORLD, MPI_STATUS_IGNORE); - next_read_offset = read_offset + sizeof(dataSetParam) + blocksCount*(sizeof(DataSetSmallRestart) + doubleCountInBlock * sizeof(double)); - if (rank < size - 1) - MPI_Send(&next_read_offset, 1, MPI_LONG_LONG_INT, rank + 1, 5, MPI_COMM_WORLD); - } - } - - MPI_File_read_at(file_handler, (MPI_Offset)(read_offset + sizeof(dataSetParam)), dataSetSmallArray, blocksCount, dataSetSmallType, MPI_STATUS_IGNORE); - if (doubleCountInBlock > 0) - MPI_File_read_at(file_handler, (MPI_Offset)(read_offset + sizeof(dataSetParam) + blocksCount * sizeof(DataSetSmallRestart)), &doubleValuesArray[0], blocksCount, dataSetDoubleType, MPI_STATUS_IGNORE); - MPI_File_close(&file_handler); - MPI_Type_free(&dataSetDoubleType); - - if (comm->isRoot()) - { - finish = MPI_Wtime(); - UBLOG(logINFO, "MPIIORestartCoProcessor::readAverageFluktuationsArray time: " << finish - start << " s"); - UBLOG(logINFO, "MPIIORestartCoProcessor::readAverageFluktuationsArray start of restore of data, rank = " << rank); - UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); - } - - size_t index = 0; - size_t nextVectorSize = dataSetParamStr.nx[0] * dataSetParamStr.nx[1] * dataSetParamStr.nx[2] * dataSetParamStr.nx[3]; - std::vector<double> vectorsOfValues; - for (int n = 0; n < blocksCount; n++) - { - vectorsOfValues.assign(doubleValuesArray.data() + index, doubleValuesArray.data() + index + nextVectorSize); - index += nextVectorSize; - - // fill AverageFluktuations array - SPtr<AverageValuesArray3D> mAverageFluktuations; - mAverageFluktuations = CbArray4D<LBMReal, IndexerX4X3X2X1>::CbArray4DPtr(new CbArray4D<LBMReal, IndexerX4X3X2X1>(vectorsOfValues, dataSetParamStr.nx[0], dataSetParamStr.nx[1], dataSetParamStr.nx[2], dataSetParamStr.nx[3])); - - // find the nesessary block and fill it - SPtr<Block3D> block = grid->getBlock(dataSetSmallArray[n].x1, dataSetSmallArray[n].x2, dataSetSmallArray[n].x3, dataSetSmallArray[n].level); - block->getKernel()->getDataSet()->setAverageFluctuations(mAverageFluktuations); - } - - if (comm->isRoot()) - { - UBLOG(logINFO, "MPIIORestartCoProcessor::readAverageFluktuationsArray end of restore of data, rank = " << rank); - UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); - } - - delete[] dataSetSmallArray; + int rank, size; + MPI_Comm_rank(MPI_COMM_WORLD, &rank); + MPI_Comm_size(MPI_COMM_WORLD, &size); + + if (comm->isRoot()) { + UBLOG(logINFO, "MPIIORestartCoProcessor::readAverageFluktuationsArray start MPI IO rank = " << rank); + UBLOG(logINFO, "Physical Memory currently used by current process: " + << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); + } + double start, finish; + if (comm->isRoot()) + start = MPI_Wtime(); + + MPI_File file_handler; + std::string filename = + path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + "/cpAverageFluktuationsArray.bin"; + int rc = MPI_File_open(MPI_COMM_WORLD, filename.c_str(), MPI_MODE_RDONLY, MPI_INFO_NULL, &file_handler); + if (rc != MPI_SUCCESS) + throw UbException(UB_EXARGS, "couldn't open file " + filename); + + // read count of blocks + int blocksCount = 0; + dataSetParam dataSetParamStr; + MPI_File_read_at(file_handler, (MPI_Offset)(rank * sizeof(int)), &blocksCount, 1, MPI_INT, MPI_STATUS_IGNORE); + MPI_File_read_at(file_handler, (MPI_Offset)(size * sizeof(int)), &dataSetParamStr, 1, dataSetParamType, + MPI_STATUS_IGNORE); + + DataSetSmallRestart *dataSetSmallArray = new DataSetSmallRestart[blocksCount]; + int doubleCountInBlock = + dataSetParamStr.nx[0] * dataSetParamStr.nx[1] * dataSetParamStr.nx[2] * dataSetParamStr.nx[3]; + std::vector<double> doubleValuesArray(blocksCount * doubleCountInBlock); // double-values in all blocks + + // define MPI_types depending on the block-specific information + MPI_Type_contiguous(doubleCountInBlock, MPI_DOUBLE, &dataSetDoubleType); + MPI_Type_commit(&dataSetDoubleType); + + // calculate the read offset + MPI_Offset read_offset = (MPI_Offset)(size * sizeof(int)); + size_t next_read_offset = 0; + + if (size > 1) { + if (rank == 0) { + next_read_offset = read_offset + sizeof(dataSetParam) + + blocksCount * (sizeof(DataSetSmallRestart) + doubleCountInBlock * sizeof(double)); + MPI_Send(&next_read_offset, 1, MPI_LONG_LONG_INT, 1, 5, MPI_COMM_WORLD); + } else { + MPI_Recv(&read_offset, 1, MPI_LONG_LONG_INT, rank - 1, 5, MPI_COMM_WORLD, MPI_STATUS_IGNORE); + next_read_offset = read_offset + sizeof(dataSetParam) + + blocksCount * (sizeof(DataSetSmallRestart) + doubleCountInBlock * sizeof(double)); + if (rank < size - 1) + MPI_Send(&next_read_offset, 1, MPI_LONG_LONG_INT, rank + 1, 5, MPI_COMM_WORLD); + } + } + + MPI_File_read_at(file_handler, (MPI_Offset)(read_offset + sizeof(dataSetParam)), dataSetSmallArray, blocksCount, + dataSetSmallType, MPI_STATUS_IGNORE); + if (doubleCountInBlock > 0) + MPI_File_read_at(file_handler, + (MPI_Offset)(read_offset + sizeof(dataSetParam) + blocksCount * sizeof(DataSetSmallRestart)), + &doubleValuesArray[0], blocksCount, dataSetDoubleType, MPI_STATUS_IGNORE); + MPI_File_close(&file_handler); + MPI_Type_free(&dataSetDoubleType); + + if (comm->isRoot()) { + finish = MPI_Wtime(); + UBLOG(logINFO, "MPIIORestartCoProcessor::readAverageFluktuationsArray time: " << finish - start << " s"); + UBLOG(logINFO, + "MPIIORestartCoProcessor::readAverageFluktuationsArray start of restore of data, rank = " << rank); + UBLOG(logINFO, "Physical Memory currently used by current process: " + << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); + } + + size_t index = 0; + size_t nextVectorSize = + dataSetParamStr.nx[0] * dataSetParamStr.nx[1] * dataSetParamStr.nx[2] * dataSetParamStr.nx[3]; + std::vector<double> vectorsOfValues; + for (int n = 0; n < blocksCount; n++) { + vectorsOfValues.assign(doubleValuesArray.data() + index, doubleValuesArray.data() + index + nextVectorSize); + index += nextVectorSize; + + // fill AverageFluktuations array + SPtr<AverageValuesArray3D> mAverageFluktuations; + mAverageFluktuations = CbArray4D<LBMReal, IndexerX4X3X2X1>::CbArray4DPtr( + new CbArray4D<LBMReal, IndexerX4X3X2X1>(vectorsOfValues, dataSetParamStr.nx[0], dataSetParamStr.nx[1], + dataSetParamStr.nx[2], dataSetParamStr.nx[3])); + + // find the nesessary block and fill it + SPtr<Block3D> block = grid->getBlock(dataSetSmallArray[n].x1, dataSetSmallArray[n].x2, dataSetSmallArray[n].x3, + dataSetSmallArray[n].level); + block->getKernel()->getDataSet()->setAverageFluctuations(mAverageFluktuations); + } + + if (comm->isRoot()) { + UBLOG(logINFO, "MPIIORestartCoProcessor::readAverageFluktuationsArray end of restore of data, rank = " << rank); + UBLOG(logINFO, "Physical Memory currently used by current process: " + << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); + } + + delete[] dataSetSmallArray; } void MPIIORestartCoProcessor::readAverageTripleArray(int step) { - int rank, size; - MPI_Comm_rank(MPI_COMM_WORLD, &rank); - MPI_Comm_size(MPI_COMM_WORLD, &size); - - if (comm->isRoot()) - { - UBLOG(logINFO, "MPIIORestartCoProcessor::readAverageTripleArray start MPI IO rank = " << rank); - UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); - } - double start, finish; - if (comm->isRoot()) start = MPI_Wtime(); - - MPI_File file_handler; - std::string filename = path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + "/cpAverageTripleArray.bin"; - int rc = MPI_File_open(MPI_COMM_WORLD, filename.c_str(), MPI_MODE_RDONLY, MPI_INFO_NULL, &file_handler); - if (rc != MPI_SUCCESS) throw UbException(UB_EXARGS, "couldn't open file " + filename); - - // read count of blocks - int blocksCount = 0; - dataSetParam dataSetParamStr; - MPI_File_read_at(file_handler, (MPI_Offset)(rank * sizeof(int)), &blocksCount, 1, MPI_INT, MPI_STATUS_IGNORE); - MPI_File_read_at(file_handler, (MPI_Offset)(size * sizeof(int)), &dataSetParamStr, 1, dataSetParamType, MPI_STATUS_IGNORE); - - DataSetSmallRestart* dataSetSmallArray = new DataSetSmallRestart[blocksCount]; - int doubleCountInBlock = dataSetParamStr.nx[0] * dataSetParamStr.nx[1] * dataSetParamStr.nx[2] * dataSetParamStr.nx[3]; - std::vector<double> doubleValuesArray(blocksCount * doubleCountInBlock); // double-values in all blocks - - // define MPI_types depending on the block-specific information - MPI_Type_contiguous(doubleCountInBlock, MPI_DOUBLE, &dataSetDoubleType); - MPI_Type_commit(&dataSetDoubleType); - - // calculate the read offset - MPI_Offset read_offset = (MPI_Offset)(size * sizeof(int)); - size_t next_read_offset = 0; - - if (size > 1) - { - if (rank == 0) - { - next_read_offset = read_offset + sizeof(dataSetParam) + blocksCount*(sizeof(DataSetSmallRestart) + doubleCountInBlock * sizeof(double)); - MPI_Send(&next_read_offset, 1, MPI_LONG_LONG_INT, 1, 5, MPI_COMM_WORLD); - } - else - { - MPI_Recv(&read_offset, 1, MPI_LONG_LONG_INT, rank - 1, 5, MPI_COMM_WORLD, MPI_STATUS_IGNORE); - next_read_offset = read_offset + sizeof(dataSetParam) + blocksCount*(sizeof(DataSetSmallRestart) + doubleCountInBlock * sizeof(double)); - if (rank < size - 1) - MPI_Send(&next_read_offset, 1, MPI_LONG_LONG_INT, rank + 1, 5, MPI_COMM_WORLD); - } - } - - MPI_File_read_at(file_handler, (MPI_Offset)(read_offset + sizeof(dataSetParam)), dataSetSmallArray, blocksCount, dataSetSmallType, MPI_STATUS_IGNORE); - if (doubleCountInBlock > 0) - MPI_File_read_at(file_handler, (MPI_Offset)(read_offset + sizeof(dataSetParam) + blocksCount * sizeof(DataSetSmallRestart)), &doubleValuesArray[0], blocksCount, dataSetDoubleType, MPI_STATUS_IGNORE); - MPI_File_close(&file_handler); - MPI_Type_free(&dataSetDoubleType); - - if (comm->isRoot()) - { - finish = MPI_Wtime(); - UBLOG(logINFO, "MPIIORestartCoProcessor::readAverageTripleArray time: " << finish - start << " s"); - UBLOG(logINFO, "MPIIORestartCoProcessor::readAverageTripleArray start of restore of data, rank = " << rank); - UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); - } - - size_t index = 0; - size_t nextVectorSize = dataSetParamStr.nx[0] * dataSetParamStr.nx[1] * dataSetParamStr.nx[2] * dataSetParamStr.nx[3]; - std::vector<double> vectorsOfValues; - for (int n = 0; n < blocksCount; n++) - { - vectorsOfValues.assign(doubleValuesArray.data() + index, doubleValuesArray.data() + index + nextVectorSize); - index += nextVectorSize; - - // fill AverageTriplecorrelations array - SPtr<AverageValuesArray3D> mAverageTriplecorrelations; - mAverageTriplecorrelations = CbArray4D<LBMReal, IndexerX4X3X2X1>::CbArray4DPtr(new CbArray4D<LBMReal, IndexerX4X3X2X1>(vectorsOfValues, dataSetParamStr.nx[0], dataSetParamStr.nx[1], dataSetParamStr.nx[2], dataSetParamStr.nx[3])); - - // find the nesessary block and fill it - SPtr<Block3D> block = grid->getBlock(dataSetSmallArray[n].x1, dataSetSmallArray[n].x2, dataSetSmallArray[n].x3, dataSetSmallArray[n].level); - block->getKernel()->getDataSet()->setAverageTriplecorrelations(mAverageTriplecorrelations); - } - - if (comm->isRoot()) - { - UBLOG(logINFO, "MPIIORestartCoProcessor::readAverageTripleArray end of restore of data, rank = " << rank); - UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); - } - - delete[] dataSetSmallArray; + int rank, size; + MPI_Comm_rank(MPI_COMM_WORLD, &rank); + MPI_Comm_size(MPI_COMM_WORLD, &size); + + if (comm->isRoot()) { + UBLOG(logINFO, "MPIIORestartCoProcessor::readAverageTripleArray start MPI IO rank = " << rank); + UBLOG(logINFO, "Physical Memory currently used by current process: " + << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); + } + double start, finish; + if (comm->isRoot()) + start = MPI_Wtime(); + + MPI_File file_handler; + std::string filename = path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + "/cpAverageTripleArray.bin"; + int rc = MPI_File_open(MPI_COMM_WORLD, filename.c_str(), MPI_MODE_RDONLY, MPI_INFO_NULL, &file_handler); + if (rc != MPI_SUCCESS) + throw UbException(UB_EXARGS, "couldn't open file " + filename); + + // read count of blocks + int blocksCount = 0; + dataSetParam dataSetParamStr; + MPI_File_read_at(file_handler, (MPI_Offset)(rank * sizeof(int)), &blocksCount, 1, MPI_INT, MPI_STATUS_IGNORE); + MPI_File_read_at(file_handler, (MPI_Offset)(size * sizeof(int)), &dataSetParamStr, 1, dataSetParamType, + MPI_STATUS_IGNORE); + + DataSetSmallRestart *dataSetSmallArray = new DataSetSmallRestart[blocksCount]; + int doubleCountInBlock = + dataSetParamStr.nx[0] * dataSetParamStr.nx[1] * dataSetParamStr.nx[2] * dataSetParamStr.nx[3]; + std::vector<double> doubleValuesArray(blocksCount * doubleCountInBlock); // double-values in all blocks + + // define MPI_types depending on the block-specific information + MPI_Type_contiguous(doubleCountInBlock, MPI_DOUBLE, &dataSetDoubleType); + MPI_Type_commit(&dataSetDoubleType); + + // calculate the read offset + MPI_Offset read_offset = (MPI_Offset)(size * sizeof(int)); + size_t next_read_offset = 0; + + if (size > 1) { + if (rank == 0) { + next_read_offset = read_offset + sizeof(dataSetParam) + + blocksCount * (sizeof(DataSetSmallRestart) + doubleCountInBlock * sizeof(double)); + MPI_Send(&next_read_offset, 1, MPI_LONG_LONG_INT, 1, 5, MPI_COMM_WORLD); + } else { + MPI_Recv(&read_offset, 1, MPI_LONG_LONG_INT, rank - 1, 5, MPI_COMM_WORLD, MPI_STATUS_IGNORE); + next_read_offset = read_offset + sizeof(dataSetParam) + + blocksCount * (sizeof(DataSetSmallRestart) + doubleCountInBlock * sizeof(double)); + if (rank < size - 1) + MPI_Send(&next_read_offset, 1, MPI_LONG_LONG_INT, rank + 1, 5, MPI_COMM_WORLD); + } + } + + MPI_File_read_at(file_handler, (MPI_Offset)(read_offset + sizeof(dataSetParam)), dataSetSmallArray, blocksCount, + dataSetSmallType, MPI_STATUS_IGNORE); + if (doubleCountInBlock > 0) + MPI_File_read_at(file_handler, + (MPI_Offset)(read_offset + sizeof(dataSetParam) + blocksCount * sizeof(DataSetSmallRestart)), + &doubleValuesArray[0], blocksCount, dataSetDoubleType, MPI_STATUS_IGNORE); + MPI_File_close(&file_handler); + MPI_Type_free(&dataSetDoubleType); + + if (comm->isRoot()) { + finish = MPI_Wtime(); + UBLOG(logINFO, "MPIIORestartCoProcessor::readAverageTripleArray time: " << finish - start << " s"); + UBLOG(logINFO, "MPIIORestartCoProcessor::readAverageTripleArray start of restore of data, rank = " << rank); + UBLOG(logINFO, "Physical Memory currently used by current process: " + << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); + } + + size_t index = 0; + size_t nextVectorSize = + dataSetParamStr.nx[0] * dataSetParamStr.nx[1] * dataSetParamStr.nx[2] * dataSetParamStr.nx[3]; + std::vector<double> vectorsOfValues; + for (int n = 0; n < blocksCount; n++) { + vectorsOfValues.assign(doubleValuesArray.data() + index, doubleValuesArray.data() + index + nextVectorSize); + index += nextVectorSize; + + // fill AverageTriplecorrelations array + SPtr<AverageValuesArray3D> mAverageTriplecorrelations; + mAverageTriplecorrelations = CbArray4D<LBMReal, IndexerX4X3X2X1>::CbArray4DPtr( + new CbArray4D<LBMReal, IndexerX4X3X2X1>(vectorsOfValues, dataSetParamStr.nx[0], dataSetParamStr.nx[1], + dataSetParamStr.nx[2], dataSetParamStr.nx[3])); + + // find the nesessary block and fill it + SPtr<Block3D> block = grid->getBlock(dataSetSmallArray[n].x1, dataSetSmallArray[n].x2, dataSetSmallArray[n].x3, + dataSetSmallArray[n].level); + block->getKernel()->getDataSet()->setAverageTriplecorrelations(mAverageTriplecorrelations); + } + + if (comm->isRoot()) { + UBLOG(logINFO, "MPIIORestartCoProcessor::readAverageTripleArray end of restore of data, rank = " << rank); + UBLOG(logINFO, "Physical Memory currently used by current process: " + << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); + } + + delete[] dataSetSmallArray; } void MPIIORestartCoProcessor::readShearStressValArray(int step) { - int rank, size; - MPI_Comm_rank(MPI_COMM_WORLD, &rank); - MPI_Comm_size(MPI_COMM_WORLD, &size); - - if (comm->isRoot()) - { - UBLOG(logINFO, "MPIIORestartCoProcessor::readShearStressValArray start MPI IO rank = " << rank); - UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); - } - double start, finish; - if (comm->isRoot()) start = MPI_Wtime(); - - MPI_File file_handler; - std::string filename = path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + "/cpShearStressValArray.bin"; - int rc = MPI_File_open(MPI_COMM_WORLD, filename.c_str(), MPI_MODE_RDONLY, MPI_INFO_NULL, &file_handler); - if (rc != MPI_SUCCESS) throw UbException(UB_EXARGS, "couldn't open file " + filename); - - // read count of blocks - int blocksCount = 0; - dataSetParam dataSetParamStr; - MPI_File_read_at(file_handler, (MPI_Offset)(rank * sizeof(int)), &blocksCount, 1, MPI_INT, MPI_STATUS_IGNORE); - MPI_File_read_at(file_handler, (MPI_Offset)(size * sizeof(int)), &dataSetParamStr, 1, dataSetParamType, MPI_STATUS_IGNORE); - - DataSetSmallRestart* dataSetSmallArray = new DataSetSmallRestart[blocksCount]; - int doubleCountInBlock = dataSetParamStr.nx[0] * dataSetParamStr.nx[1] * dataSetParamStr.nx[2] * dataSetParamStr.nx[3]; - std::vector<double> doubleValuesArray(blocksCount * doubleCountInBlock); // double-values in all blocks - - // define MPI_types depending on the block-specific information - MPI_Type_contiguous(doubleCountInBlock, MPI_DOUBLE, &dataSetDoubleType); - MPI_Type_commit(&dataSetDoubleType); - - // calculate the read offset - MPI_Offset read_offset = (MPI_Offset)(size * sizeof(int)); - size_t next_read_offset = 0; - - if (size > 1) - { - if (rank == 0) - { - next_read_offset = read_offset + sizeof(dataSetParam) + blocksCount*(sizeof(DataSetSmallRestart) + doubleCountInBlock * sizeof(double)); - MPI_Send(&next_read_offset, 1, MPI_LONG_LONG_INT, 1, 5, MPI_COMM_WORLD); - } - else - { - MPI_Recv(&read_offset, 1, MPI_LONG_LONG_INT, rank - 1, 5, MPI_COMM_WORLD, MPI_STATUS_IGNORE); - next_read_offset = read_offset + sizeof(dataSetParam) + blocksCount*(sizeof(DataSetSmallRestart) + doubleCountInBlock * sizeof(double)); - if (rank < size - 1) - MPI_Send(&next_read_offset, 1, MPI_LONG_LONG_INT, rank + 1, 5, MPI_COMM_WORLD); - } - } - - MPI_File_read_at(file_handler, (MPI_Offset)(read_offset + sizeof(dataSetParam)), dataSetSmallArray, blocksCount, dataSetSmallType, MPI_STATUS_IGNORE); - if (doubleCountInBlock > 0) - MPI_File_read_at(file_handler, (MPI_Offset)(read_offset + sizeof(dataSetParam) + blocksCount * sizeof(DataSetSmallRestart)), &doubleValuesArray[0], blocksCount, dataSetDoubleType, MPI_STATUS_IGNORE); - MPI_File_close(&file_handler); - MPI_Type_free(&dataSetDoubleType); - - if (comm->isRoot()) - { - finish = MPI_Wtime(); - UBLOG(logINFO, "MPIIORestartCoProcessor::readShearStressValArray time: " << finish - start << " s"); - UBLOG(logINFO, "MPIIORestartCoProcessor::readShearStressValArray start of restore of data, rank = " << rank); - UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); - } - - size_t index = 0; - size_t nextVectorSize = dataSetParamStr.nx[0] * dataSetParamStr.nx[1] * dataSetParamStr.nx[2] * dataSetParamStr.nx[3]; - std::vector<double> vectorsOfValues; - for (int n = 0; n < blocksCount; n++) - { - vectorsOfValues.assign(doubleValuesArray.data() + index, doubleValuesArray.data() + index + nextVectorSize); - index += nextVectorSize; - - // fill ShearStressValuesArray array - SPtr<ShearStressValuesArray3D> mShearStressValues; - mShearStressValues = CbArray4D<LBMReal, IndexerX4X3X2X1>::CbArray4DPtr(new CbArray4D<LBMReal, IndexerX4X3X2X1>(vectorsOfValues, dataSetParamStr.nx[0], dataSetParamStr.nx[1], dataSetParamStr.nx[2], dataSetParamStr.nx[3])); - - // find the nesessary block and fill it - SPtr<Block3D> block = grid->getBlock(dataSetSmallArray[n].x1, dataSetSmallArray[n].x2, dataSetSmallArray[n].x3, dataSetSmallArray[n].level); - block->getKernel()->getDataSet()->setShearStressValues(mShearStressValues); - } - - if (comm->isRoot()) - { - UBLOG(logINFO, "MPIIORestartCoProcessor::readShearStressValArray end of restore of data, rank = " << rank); - UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); - } - - delete[] dataSetSmallArray; + int rank, size; + MPI_Comm_rank(MPI_COMM_WORLD, &rank); + MPI_Comm_size(MPI_COMM_WORLD, &size); + + if (comm->isRoot()) { + UBLOG(logINFO, "MPIIORestartCoProcessor::readShearStressValArray start MPI IO rank = " << rank); + UBLOG(logINFO, "Physical Memory currently used by current process: " + << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); + } + double start, finish; + if (comm->isRoot()) + start = MPI_Wtime(); + + MPI_File file_handler; + std::string filename = path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + "/cpShearStressValArray.bin"; + int rc = MPI_File_open(MPI_COMM_WORLD, filename.c_str(), MPI_MODE_RDONLY, MPI_INFO_NULL, &file_handler); + if (rc != MPI_SUCCESS) + throw UbException(UB_EXARGS, "couldn't open file " + filename); + + // read count of blocks + int blocksCount = 0; + dataSetParam dataSetParamStr; + MPI_File_read_at(file_handler, (MPI_Offset)(rank * sizeof(int)), &blocksCount, 1, MPI_INT, MPI_STATUS_IGNORE); + MPI_File_read_at(file_handler, (MPI_Offset)(size * sizeof(int)), &dataSetParamStr, 1, dataSetParamType, + MPI_STATUS_IGNORE); + + DataSetSmallRestart *dataSetSmallArray = new DataSetSmallRestart[blocksCount]; + int doubleCountInBlock = + dataSetParamStr.nx[0] * dataSetParamStr.nx[1] * dataSetParamStr.nx[2] * dataSetParamStr.nx[3]; + std::vector<double> doubleValuesArray(blocksCount * doubleCountInBlock); // double-values in all blocks + + // define MPI_types depending on the block-specific information + MPI_Type_contiguous(doubleCountInBlock, MPI_DOUBLE, &dataSetDoubleType); + MPI_Type_commit(&dataSetDoubleType); + + // calculate the read offset + MPI_Offset read_offset = (MPI_Offset)(size * sizeof(int)); + size_t next_read_offset = 0; + + if (size > 1) { + if (rank == 0) { + next_read_offset = read_offset + sizeof(dataSetParam) + + blocksCount * (sizeof(DataSetSmallRestart) + doubleCountInBlock * sizeof(double)); + MPI_Send(&next_read_offset, 1, MPI_LONG_LONG_INT, 1, 5, MPI_COMM_WORLD); + } else { + MPI_Recv(&read_offset, 1, MPI_LONG_LONG_INT, rank - 1, 5, MPI_COMM_WORLD, MPI_STATUS_IGNORE); + next_read_offset = read_offset + sizeof(dataSetParam) + + blocksCount * (sizeof(DataSetSmallRestart) + doubleCountInBlock * sizeof(double)); + if (rank < size - 1) + MPI_Send(&next_read_offset, 1, MPI_LONG_LONG_INT, rank + 1, 5, MPI_COMM_WORLD); + } + } + + MPI_File_read_at(file_handler, (MPI_Offset)(read_offset + sizeof(dataSetParam)), dataSetSmallArray, blocksCount, + dataSetSmallType, MPI_STATUS_IGNORE); + if (doubleCountInBlock > 0) + MPI_File_read_at(file_handler, + (MPI_Offset)(read_offset + sizeof(dataSetParam) + blocksCount * sizeof(DataSetSmallRestart)), + &doubleValuesArray[0], blocksCount, dataSetDoubleType, MPI_STATUS_IGNORE); + MPI_File_close(&file_handler); + MPI_Type_free(&dataSetDoubleType); + + if (comm->isRoot()) { + finish = MPI_Wtime(); + UBLOG(logINFO, "MPIIORestartCoProcessor::readShearStressValArray time: " << finish - start << " s"); + UBLOG(logINFO, "MPIIORestartCoProcessor::readShearStressValArray start of restore of data, rank = " << rank); + UBLOG(logINFO, "Physical Memory currently used by current process: " + << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); + } + + size_t index = 0; + size_t nextVectorSize = + dataSetParamStr.nx[0] * dataSetParamStr.nx[1] * dataSetParamStr.nx[2] * dataSetParamStr.nx[3]; + std::vector<double> vectorsOfValues; + for (int n = 0; n < blocksCount; n++) { + vectorsOfValues.assign(doubleValuesArray.data() + index, doubleValuesArray.data() + index + nextVectorSize); + index += nextVectorSize; + + // fill ShearStressValuesArray array + SPtr<ShearStressValuesArray3D> mShearStressValues; + mShearStressValues = CbArray4D<LBMReal, IndexerX4X3X2X1>::CbArray4DPtr( + new CbArray4D<LBMReal, IndexerX4X3X2X1>(vectorsOfValues, dataSetParamStr.nx[0], dataSetParamStr.nx[1], + dataSetParamStr.nx[2], dataSetParamStr.nx[3])); + + // find the nesessary block and fill it + SPtr<Block3D> block = grid->getBlock(dataSetSmallArray[n].x1, dataSetSmallArray[n].x2, dataSetSmallArray[n].x3, + dataSetSmallArray[n].level); + block->getKernel()->getDataSet()->setShearStressValues(mShearStressValues); + } + + if (comm->isRoot()) { + UBLOG(logINFO, "MPIIORestartCoProcessor::readShearStressValArray end of restore of data, rank = " << rank); + UBLOG(logINFO, "Physical Memory currently used by current process: " + << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); + } + + delete[] dataSetSmallArray; } void MPIIORestartCoProcessor::readRelaxationFactor(int step) { - int rank, size; - MPI_Comm_rank(MPI_COMM_WORLD, &rank); - MPI_Comm_size(MPI_COMM_WORLD, &size); - - if (comm->isRoot()) - { - UBLOG(logINFO, "MPIIORestartCoProcessor::readRelaxationFactor start MPI IO rank = " << rank); - UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); - } - double start, finish; - if (comm->isRoot()) start = MPI_Wtime(); - - MPI_File file_handler; - std::string filename = path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + "/cpRelaxationFactor.bin"; - int rc = MPI_File_open(MPI_COMM_WORLD, filename.c_str(), MPI_MODE_RDONLY, MPI_INFO_NULL, &file_handler); - if (rc != MPI_SUCCESS) throw UbException(UB_EXARGS, "couldn't open file " + filename); - - // read count of blocks - int blocksCount = 0; - dataSetParam dataSetParamStr; - MPI_File_read_at(file_handler, (MPI_Offset)(rank * sizeof(int)), &blocksCount, 1, MPI_INT, MPI_STATUS_IGNORE); - MPI_File_read_at(file_handler, (MPI_Offset)(size * sizeof(int)), &dataSetParamStr, 1, dataSetParamType, MPI_STATUS_IGNORE); - - DataSetSmallRestart* dataSetSmallArray = new DataSetSmallRestart[blocksCount]; - int doubleCountInBlock = dataSetParamStr.nx[0] * dataSetParamStr.nx[1] * dataSetParamStr.nx[2] * dataSetParamStr.nx[3]; - std::vector<double> doubleValuesArray(blocksCount * doubleCountInBlock); // double-values in all blocks - - // define MPI_types depending on the block-specific information - MPI_Type_contiguous(doubleCountInBlock, MPI_DOUBLE, &dataSetDoubleType); - MPI_Type_commit(&dataSetDoubleType); - - // calculate the read offset - MPI_Offset read_offset = (MPI_Offset)(size * sizeof(int)); - size_t next_read_offset = 0; - - if (size > 1) - { - if (rank == 0) - { - next_read_offset = read_offset + sizeof(dataSetParam) + blocksCount*(sizeof(DataSetSmallRestart) + doubleCountInBlock * sizeof(double)); - MPI_Send(&next_read_offset, 1, MPI_LONG_LONG_INT, 1, 5, MPI_COMM_WORLD); - } - else - { - MPI_Recv(&read_offset, 1, MPI_LONG_LONG_INT, rank - 1, 5, MPI_COMM_WORLD, MPI_STATUS_IGNORE); - next_read_offset = read_offset + sizeof(dataSetParam) + blocksCount*(sizeof(DataSetSmallRestart) + doubleCountInBlock * sizeof(double)); - if (rank < size - 1) - MPI_Send(&next_read_offset, 1, MPI_LONG_LONG_INT, rank + 1, 5, MPI_COMM_WORLD); - } - } - - MPI_File_read_at(file_handler, (MPI_Offset)(read_offset + sizeof(dataSetParam)), dataSetSmallArray, blocksCount, dataSetSmallType, MPI_STATUS_IGNORE); - if (doubleCountInBlock > 0) - MPI_File_read_at(file_handler, (MPI_Offset)(read_offset + sizeof(dataSetParam) + blocksCount * sizeof(DataSetSmallRestart)), &doubleValuesArray[0], blocksCount, dataSetDoubleType, MPI_STATUS_IGNORE); - MPI_File_close(&file_handler); - MPI_Type_free(&dataSetDoubleType); - - if (comm->isRoot()) - { - finish = MPI_Wtime(); - UBLOG(logINFO, "MPIIORestartCoProcessor::readRelaxationFactor time: " << finish - start << " s"); - UBLOG(logINFO, "MPIIORestartCoProcessor::readRelaxationFactor start of restore of data, rank = " << rank); - UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); - } - - size_t index = 0; - size_t nextVectorSize = dataSetParamStr.nx[0] * dataSetParamStr.nx[1] * dataSetParamStr.nx[2] * dataSetParamStr.nx[3]; - std::vector<double> vectorsOfValues; - for (int n = 0; n < blocksCount; n++) - { - vectorsOfValues.assign(doubleValuesArray.data() + index, doubleValuesArray.data() + index + nextVectorSize); - index += nextVectorSize; - - // fill RelaxationFactor array - SPtr<RelaxationFactorArray3D> mRelaxationFactor; - mRelaxationFactor = CbArray3D<LBMReal, IndexerX3X2X1>::CbArray3DPtr(new CbArray3D<LBMReal, IndexerX3X2X1>(vectorsOfValues, dataSetParamStr.nx[0], dataSetParamStr.nx[1], dataSetParamStr.nx[2])); - - // find the nesessary block and fill it - SPtr<Block3D> block = grid->getBlock(dataSetSmallArray[n].x1, dataSetSmallArray[n].x2, dataSetSmallArray[n].x3, dataSetSmallArray[n].level); - block->getKernel()->getDataSet()->setRelaxationFactor(mRelaxationFactor); - } - - if (comm->isRoot()) - { - UBLOG(logINFO, "MPIIORestartCoProcessor::readRelaxationFactor end of restore of data, rank = " << rank); - UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); - } - - delete[] dataSetSmallArray; + int rank, size; + MPI_Comm_rank(MPI_COMM_WORLD, &rank); + MPI_Comm_size(MPI_COMM_WORLD, &size); + + if (comm->isRoot()) { + UBLOG(logINFO, "MPIIORestartCoProcessor::readRelaxationFactor start MPI IO rank = " << rank); + UBLOG(logINFO, "Physical Memory currently used by current process: " + << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); + } + double start, finish; + if (comm->isRoot()) + start = MPI_Wtime(); + + MPI_File file_handler; + std::string filename = path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + "/cpRelaxationFactor.bin"; + int rc = MPI_File_open(MPI_COMM_WORLD, filename.c_str(), MPI_MODE_RDONLY, MPI_INFO_NULL, &file_handler); + if (rc != MPI_SUCCESS) + throw UbException(UB_EXARGS, "couldn't open file " + filename); + + // read count of blocks + int blocksCount = 0; + dataSetParam dataSetParamStr; + MPI_File_read_at(file_handler, (MPI_Offset)(rank * sizeof(int)), &blocksCount, 1, MPI_INT, MPI_STATUS_IGNORE); + MPI_File_read_at(file_handler, (MPI_Offset)(size * sizeof(int)), &dataSetParamStr, 1, dataSetParamType, + MPI_STATUS_IGNORE); + + DataSetSmallRestart *dataSetSmallArray = new DataSetSmallRestart[blocksCount]; + int doubleCountInBlock = + dataSetParamStr.nx[0] * dataSetParamStr.nx[1] * dataSetParamStr.nx[2] * dataSetParamStr.nx[3]; + std::vector<double> doubleValuesArray(blocksCount * doubleCountInBlock); // double-values in all blocks + + // define MPI_types depending on the block-specific information + MPI_Type_contiguous(doubleCountInBlock, MPI_DOUBLE, &dataSetDoubleType); + MPI_Type_commit(&dataSetDoubleType); + + // calculate the read offset + MPI_Offset read_offset = (MPI_Offset)(size * sizeof(int)); + size_t next_read_offset = 0; + + if (size > 1) { + if (rank == 0) { + next_read_offset = read_offset + sizeof(dataSetParam) + + blocksCount * (sizeof(DataSetSmallRestart) + doubleCountInBlock * sizeof(double)); + MPI_Send(&next_read_offset, 1, MPI_LONG_LONG_INT, 1, 5, MPI_COMM_WORLD); + } else { + MPI_Recv(&read_offset, 1, MPI_LONG_LONG_INT, rank - 1, 5, MPI_COMM_WORLD, MPI_STATUS_IGNORE); + next_read_offset = read_offset + sizeof(dataSetParam) + + blocksCount * (sizeof(DataSetSmallRestart) + doubleCountInBlock * sizeof(double)); + if (rank < size - 1) + MPI_Send(&next_read_offset, 1, MPI_LONG_LONG_INT, rank + 1, 5, MPI_COMM_WORLD); + } + } + + MPI_File_read_at(file_handler, (MPI_Offset)(read_offset + sizeof(dataSetParam)), dataSetSmallArray, blocksCount, + dataSetSmallType, MPI_STATUS_IGNORE); + if (doubleCountInBlock > 0) + MPI_File_read_at(file_handler, + (MPI_Offset)(read_offset + sizeof(dataSetParam) + blocksCount * sizeof(DataSetSmallRestart)), + &doubleValuesArray[0], blocksCount, dataSetDoubleType, MPI_STATUS_IGNORE); + MPI_File_close(&file_handler); + MPI_Type_free(&dataSetDoubleType); + + if (comm->isRoot()) { + finish = MPI_Wtime(); + UBLOG(logINFO, "MPIIORestartCoProcessor::readRelaxationFactor time: " << finish - start << " s"); + UBLOG(logINFO, "MPIIORestartCoProcessor::readRelaxationFactor start of restore of data, rank = " << rank); + UBLOG(logINFO, "Physical Memory currently used by current process: " + << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); + } + + size_t index = 0; + size_t nextVectorSize = + dataSetParamStr.nx[0] * dataSetParamStr.nx[1] * dataSetParamStr.nx[2] * dataSetParamStr.nx[3]; + std::vector<double> vectorsOfValues; + for (int n = 0; n < blocksCount; n++) { + vectorsOfValues.assign(doubleValuesArray.data() + index, doubleValuesArray.data() + index + nextVectorSize); + index += nextVectorSize; + + // fill RelaxationFactor array + SPtr<RelaxationFactorArray3D> mRelaxationFactor; + mRelaxationFactor = CbArray3D<LBMReal, IndexerX3X2X1>::CbArray3DPtr(new CbArray3D<LBMReal, IndexerX3X2X1>( + vectorsOfValues, dataSetParamStr.nx[0], dataSetParamStr.nx[1], dataSetParamStr.nx[2])); + + // find the nesessary block and fill it + SPtr<Block3D> block = grid->getBlock(dataSetSmallArray[n].x1, dataSetSmallArray[n].x2, dataSetSmallArray[n].x3, + dataSetSmallArray[n].level); + block->getKernel()->getDataSet()->setRelaxationFactor(mRelaxationFactor); + } + + if (comm->isRoot()) { + UBLOG(logINFO, "MPIIORestartCoProcessor::readRelaxationFactor end of restore of data, rank = " << rank); + UBLOG(logINFO, "Physical Memory currently used by current process: " + << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); + } + + delete[] dataSetSmallArray; } void MPIIORestartCoProcessor::readBoundaryConds(int step) { - int rank, size; - MPI_Comm_rank(MPI_COMM_WORLD, &rank); - MPI_Comm_size(MPI_COMM_WORLD, &size); - - if (comm->isRoot()) - { - UBLOG(logINFO, "MPIIORestartCoProcessor::readBoundaryConds start MPI IO rank = " << rank); - UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); - } - double start, finish; - if (comm->isRoot()) start = MPI_Wtime(); - - MPI_File file_handler; - std::string filename = path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + "/cpBC.bin"; - int rc = MPI_File_open(MPI_COMM_WORLD, filename.c_str(), MPI_MODE_RDONLY, MPI_INFO_NULL, &file_handler); - if (rc != MPI_SUCCESS) throw UbException(UB_EXARGS, "couldn't open file " + filename); - - int blocksCount = 0; - int dataCount1000 = 0; - int dataCount2 = 0; - MPI_Offset read_offset1 = (MPI_Offset)(rank * (3 * sizeof(int) + sizeof(boundCondParam))); - - // read count of blocks - MPI_File_read_at(file_handler, read_offset1, &blocksCount, 1, MPI_INT, MPI_STATUS_IGNORE); - // read count of big BoundaryCondition blocks - MPI_File_read_at(file_handler, (MPI_Offset)(read_offset1 + sizeof(int)), &dataCount1000, 1, MPI_INT, MPI_STATUS_IGNORE); - // read count of indexContainer values in all blocks - MPI_File_read_at(file_handler, (MPI_Offset)(read_offset1 + 2 * sizeof(int)), &dataCount2, 1, MPI_INT, MPI_STATUS_IGNORE); - // read count of bcindexmatrix values in every block - MPI_File_read_at(file_handler, (MPI_Offset)(read_offset1 + 3 * sizeof(int)), &boundCondParamStr, 1, boundCondParamType, MPI_STATUS_IGNORE); - - MPI_Type_contiguous(boundCondParamStr.bcindexmatrixCount, MPI_INT, &bcindexmatrixType); - MPI_Type_commit(&bcindexmatrixType); - - size_t dataCount = dataCount1000 * BLOCK_SIZE; - BCAddRestart* bcAddArray = new BCAddRestart[blocksCount]; - BoundaryCondition* bcArray = new BoundaryCondition[dataCount]; - BoundaryCondition* nullBouCond = new BoundaryCondition(); - memset(nullBouCond, 0, sizeof(BoundaryCondition)); - int* intArray1 = new int[blocksCount * boundCondParamStr.bcindexmatrixCount]; - int* intArray2 = new int[dataCount2]; - - MPI_Offset read_offset = (MPI_Offset)(size * (3 * sizeof(int) + sizeof(boundCondParam))); - size_t next_read_offset = 0; - - if (size>1) - { - if (rank == 0) - { - next_read_offset = read_offset + blocksCount * sizeof(BCAddRestart) + dataCount * sizeof(BoundaryCondition) + (blocksCount * boundCondParamStr.bcindexmatrixCount + dataCount2) * sizeof(int); - MPI_Send(&next_read_offset, 1, MPI_LONG_LONG_INT, 1, 5, MPI_COMM_WORLD); - } - else - { - MPI_Recv(&read_offset, 1, MPI_LONG_LONG_INT, rank - 1, 5, MPI_COMM_WORLD, MPI_STATUS_IGNORE); - next_read_offset = read_offset + blocksCount * sizeof(BCAddRestart) + dataCount * sizeof(BoundaryCondition) + (blocksCount * boundCondParamStr.bcindexmatrixCount + dataCount2) * sizeof(int); - if (rank<size - 1) - MPI_Send(&next_read_offset, 1, MPI_LONG_LONG_INT, rank + 1, 5, MPI_COMM_WORLD); - } - } - - MPI_File_read_at(file_handler, read_offset, bcAddArray, blocksCount, boundCondTypeAdd, MPI_STATUS_IGNORE); - MPI_File_read_at(file_handler, (MPI_Offset)(read_offset + blocksCount * sizeof(BCAddRestart)), &bcArray[0], dataCount1000, boundCondType1000, MPI_STATUS_IGNORE); - MPI_File_read_at(file_handler, (MPI_Offset)(read_offset + blocksCount * sizeof(BCAddRestart) + dataCount * sizeof(BoundaryCondition)), &intArray1[0], blocksCount, bcindexmatrixType, MPI_STATUS_IGNORE); - MPI_File_read_at(file_handler, (MPI_Offset)(read_offset + blocksCount * sizeof(BCAddRestart) + dataCount * sizeof(BoundaryCondition) + blocksCount * boundCondParamStr.bcindexmatrixCount * sizeof(int)), &intArray2[0], dataCount2, MPI_INT, MPI_STATUS_IGNORE); - - MPI_File_close(&file_handler); - MPI_Type_free(&bcindexmatrixType); - - if (comm->isRoot()) - { - finish = MPI_Wtime(); - UBLOG(logINFO, "MPIIORestartCoProcessor::readBoundaryConds time: " << finish - start << " s"); - UBLOG(logINFO, "MPIIORestartCoProcessor::readBoundaryConds start of restore of data, rank = " << rank); - UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); - } - - int index = 0, index1 = 0, index2 = 0; - std::vector<SPtr<BoundaryConditions>> bcVector; - std::vector<int> bcindexmatrixV; - std::vector<int> indexContainerV; - - for (size_t n = 0; n<blocksCount; n++) - { - bcVector.resize(0); - bcindexmatrixV.resize(0); - indexContainerV.resize(0); - - for (size_t ibc = 0; ibc<bcAddArray[n].boundCond_count; ibc++) - { - SPtr<BoundaryConditions> bc; - if (memcmp(&bcArray[index], nullBouCond, sizeof(BoundaryCondition)) == 0) - bc = SPtr<BoundaryConditions>(); - else - { - bc = SPtr<BoundaryConditions>(new BoundaryConditions); - bc->noslipBoundaryFlags = bcArray[index].noslipBoundaryFlags; - bc->slipBoundaryFlags = bcArray[index].slipBoundaryFlags; - bc->densityBoundaryFlags = bcArray[index].densityBoundaryFlags; - bc->velocityBoundaryFlags = bcArray[index].velocityBoundaryFlags; - bc->wallModelBoundaryFlags = bcArray[index].wallModelBoundaryFlags; - bc->bcVelocityX1 = bcArray[index].bcVelocityX1; - bc->bcVelocityX2 = bcArray[index].bcVelocityX2; - bc->bcVelocityX3 = bcArray[index].bcVelocityX3; - bc->bcDensity = bcArray[index].bcDensity; - bc->bcLodiDensity = bcArray[index].bcLodiDensity; - bc->bcLodiVelocityX1 = bcArray[index].bcLodiVelocityX1; - bc->bcLodiVelocityX2 = bcArray[index].bcLodiVelocityX2; - bc->bcLodiVelocityX3 = bcArray[index].bcLodiVelocityX3; - bc->bcLodiLentgh = bcArray[index].bcLodiLentgh; - - bc->nx1 = bcArray[index].nx1; - bc->nx2 = bcArray[index].nx2; - bc->nx3 = bcArray[index].nx3; - for (int iq = 0; iq<26; iq++) - bc->setQ(bcArray[index].q[iq], iq); - bc->setBcAlgorithmType(bcArray[index].algorithmType); - } - - bcVector.push_back(bc); - index++; - } - - for (int b1 = 0; b1 < boundCondParamStr.bcindexmatrixCount; b1++) - bcindexmatrixV.push_back(intArray1[index1++]); - - for (int b2 = 0; b2 < bcAddArray[n].indexContainer_count; b2++) - indexContainerV.push_back(intArray2[index2++]); - - CbArray3D<int, IndexerX3X2X1> bcim(bcindexmatrixV, boundCondParamStr.nx1, boundCondParamStr.nx2, boundCondParamStr.nx3); - - SPtr<Block3D> block = grid->getBlock(bcAddArray[n].x1, bcAddArray[n].x2, bcAddArray[n].x3, bcAddArray[n].level); - SPtr<BCProcessor> bcProc = bcProcessor->clone(block->getKernel()); - SPtr<BCArray3D> bcArr(new BCArray3D()); - bcArr->bcindexmatrix = bcim; - bcArr->bcvector = bcVector; - bcArr->indexContainer = indexContainerV; - bcProc->setBCArray(bcArr); - - block->getKernel()->setBCProcessor(bcProc); - } - - delete nullBouCond; - delete[] bcArray; - delete[] bcAddArray; - delete[] intArray1; - delete[] intArray2; - - if (comm->isRoot()) - { - UBLOG(logINFO, "MPIIORestartCoProcessor::readBoundaryConds end of restore of data, rank = " << rank); - UBLOG(logINFO, "Physical Memory currently used by current process: " << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); - } + int rank, size; + MPI_Comm_rank(MPI_COMM_WORLD, &rank); + MPI_Comm_size(MPI_COMM_WORLD, &size); + + if (comm->isRoot()) { + UBLOG(logINFO, "MPIIORestartCoProcessor::readBoundaryConds start MPI IO rank = " << rank); + UBLOG(logINFO, "Physical Memory currently used by current process: " + << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); + } + double start, finish; + if (comm->isRoot()) + start = MPI_Wtime(); + + MPI_File file_handler; + std::string filename = path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + "/cpBC.bin"; + int rc = MPI_File_open(MPI_COMM_WORLD, filename.c_str(), MPI_MODE_RDONLY, MPI_INFO_NULL, &file_handler); + if (rc != MPI_SUCCESS) + throw UbException(UB_EXARGS, "couldn't open file " + filename); + + int blocksCount = 0; + int dataCount1000 = 0; + int dataCount2 = 0; + MPI_Offset read_offset1 = (MPI_Offset)(rank * (3 * sizeof(int) + sizeof(boundCondParam))); + + // read count of blocks + MPI_File_read_at(file_handler, read_offset1, &blocksCount, 1, MPI_INT, MPI_STATUS_IGNORE); + // read count of big BoundaryCondition blocks + MPI_File_read_at(file_handler, (MPI_Offset)(read_offset1 + sizeof(int)), &dataCount1000, 1, MPI_INT, + MPI_STATUS_IGNORE); + // read count of indexContainer values in all blocks + MPI_File_read_at(file_handler, (MPI_Offset)(read_offset1 + 2 * sizeof(int)), &dataCount2, 1, MPI_INT, + MPI_STATUS_IGNORE); + // read count of bcindexmatrix values in every block + MPI_File_read_at(file_handler, (MPI_Offset)(read_offset1 + 3 * sizeof(int)), &boundCondParamStr, 1, + boundCondParamType, MPI_STATUS_IGNORE); + + MPI_Type_contiguous(boundCondParamStr.bcindexmatrixCount, MPI_INT, &bcindexmatrixType); + MPI_Type_commit(&bcindexmatrixType); + + size_t dataCount = dataCount1000 * BLOCK_SIZE; + BCAddRestart *bcAddArray = new BCAddRestart[blocksCount]; + BoundaryCondition *bcArray = new BoundaryCondition[dataCount]; + BoundaryCondition *nullBouCond = new BoundaryCondition(); + memset(nullBouCond, 0, sizeof(BoundaryCondition)); + int *intArray1 = new int[blocksCount * boundCondParamStr.bcindexmatrixCount]; + int *intArray2 = new int[dataCount2]; + + MPI_Offset read_offset = (MPI_Offset)(size * (3 * sizeof(int) + sizeof(boundCondParam))); + size_t next_read_offset = 0; + + if (size > 1) { + if (rank == 0) { + next_read_offset = read_offset + blocksCount * sizeof(BCAddRestart) + + dataCount * sizeof(BoundaryCondition) + + (blocksCount * boundCondParamStr.bcindexmatrixCount + dataCount2) * sizeof(int); + MPI_Send(&next_read_offset, 1, MPI_LONG_LONG_INT, 1, 5, MPI_COMM_WORLD); + } else { + MPI_Recv(&read_offset, 1, MPI_LONG_LONG_INT, rank - 1, 5, MPI_COMM_WORLD, MPI_STATUS_IGNORE); + next_read_offset = read_offset + blocksCount * sizeof(BCAddRestart) + + dataCount * sizeof(BoundaryCondition) + + (blocksCount * boundCondParamStr.bcindexmatrixCount + dataCount2) * sizeof(int); + if (rank < size - 1) + MPI_Send(&next_read_offset, 1, MPI_LONG_LONG_INT, rank + 1, 5, MPI_COMM_WORLD); + } + } + + MPI_File_read_at(file_handler, read_offset, bcAddArray, blocksCount, boundCondTypeAdd, MPI_STATUS_IGNORE); + MPI_File_read_at(file_handler, (MPI_Offset)(read_offset + blocksCount * sizeof(BCAddRestart)), &bcArray[0], + dataCount1000, boundCondType1000, MPI_STATUS_IGNORE); + MPI_File_read_at( + file_handler, + (MPI_Offset)(read_offset + blocksCount * sizeof(BCAddRestart) + dataCount * sizeof(BoundaryCondition)), + &intArray1[0], blocksCount, bcindexmatrixType, MPI_STATUS_IGNORE); + MPI_File_read_at(file_handler, + (MPI_Offset)(read_offset + blocksCount * sizeof(BCAddRestart) + + dataCount * sizeof(BoundaryCondition) + + blocksCount * boundCondParamStr.bcindexmatrixCount * sizeof(int)), + &intArray2[0], dataCount2, MPI_INT, MPI_STATUS_IGNORE); + + MPI_File_close(&file_handler); + MPI_Type_free(&bcindexmatrixType); + + if (comm->isRoot()) { + finish = MPI_Wtime(); + UBLOG(logINFO, "MPIIORestartCoProcessor::readBoundaryConds time: " << finish - start << " s"); + UBLOG(logINFO, "MPIIORestartCoProcessor::readBoundaryConds start of restore of data, rank = " << rank); + UBLOG(logINFO, "Physical Memory currently used by current process: " + << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); + } + + int index = 0, index1 = 0, index2 = 0; + std::vector<SPtr<BoundaryConditions>> bcVector; + std::vector<int> bcindexmatrixV; + std::vector<int> indexContainerV; + + for (size_t n = 0; n < blocksCount; n++) { + bcVector.resize(0); + bcindexmatrixV.resize(0); + indexContainerV.resize(0); + + for (size_t ibc = 0; ibc < bcAddArray[n].boundCond_count; ibc++) { + SPtr<BoundaryConditions> bc; + if (memcmp(&bcArray[index], nullBouCond, sizeof(BoundaryCondition)) == 0) + bc = SPtr<BoundaryConditions>(); + else { + bc = SPtr<BoundaryConditions>(new BoundaryConditions); + bc->noslipBoundaryFlags = bcArray[index].noslipBoundaryFlags; + bc->slipBoundaryFlags = bcArray[index].slipBoundaryFlags; + bc->densityBoundaryFlags = bcArray[index].densityBoundaryFlags; + bc->velocityBoundaryFlags = bcArray[index].velocityBoundaryFlags; + bc->wallModelBoundaryFlags = bcArray[index].wallModelBoundaryFlags; + bc->bcVelocityX1 = bcArray[index].bcVelocityX1; + bc->bcVelocityX2 = bcArray[index].bcVelocityX2; + bc->bcVelocityX3 = bcArray[index].bcVelocityX3; + bc->bcDensity = bcArray[index].bcDensity; + bc->bcLodiDensity = bcArray[index].bcLodiDensity; + bc->bcLodiVelocityX1 = bcArray[index].bcLodiVelocityX1; + bc->bcLodiVelocityX2 = bcArray[index].bcLodiVelocityX2; + bc->bcLodiVelocityX3 = bcArray[index].bcLodiVelocityX3; + bc->bcLodiLentgh = bcArray[index].bcLodiLentgh; + + bc->nx1 = bcArray[index].nx1; + bc->nx2 = bcArray[index].nx2; + bc->nx3 = bcArray[index].nx3; + for (int iq = 0; iq < 26; iq++) + bc->setQ(bcArray[index].q[iq], iq); + bc->setBcAlgorithmType(bcArray[index].algorithmType); + } + + bcVector.push_back(bc); + index++; + } + + for (int b1 = 0; b1 < boundCondParamStr.bcindexmatrixCount; b1++) + bcindexmatrixV.push_back(intArray1[index1++]); + + for (int b2 = 0; b2 < bcAddArray[n].indexContainer_count; b2++) + indexContainerV.push_back(intArray2[index2++]); + + CbArray3D<int, IndexerX3X2X1> bcim(bcindexmatrixV, boundCondParamStr.nx1, boundCondParamStr.nx2, + boundCondParamStr.nx3); + + SPtr<Block3D> block = grid->getBlock(bcAddArray[n].x1, bcAddArray[n].x2, bcAddArray[n].x3, bcAddArray[n].level); + SPtr<BCProcessor> bcProc = bcProcessor->clone(block->getKernel()); + SPtr<BCArray3D> bcArr(new BCArray3D()); + bcArr->bcindexmatrix = bcim; + bcArr->bcvector = bcVector; + bcArr->indexContainer = indexContainerV; + bcProc->setBCArray(bcArr); + + block->getKernel()->setBCProcessor(bcProc); + } + + delete nullBouCond; + delete[] bcArray; + delete[] bcAddArray; + delete[] intArray1; + delete[] intArray2; + + if (comm->isRoot()) { + UBLOG(logINFO, "MPIIORestartCoProcessor::readBoundaryConds end of restore of data, rank = " << rank); + UBLOG(logINFO, "Physical Memory currently used by current process: " + << Utilities::getPhysMemUsedByMe() / 1073741824.0 << " GB"); + } } ////////////////////////////////////////////////////////////////////////// -void MPIIORestartCoProcessor::setLBMKernel(SPtr<LBMKernel> kernel) -{ - this->lbmKernel = kernel; -} +void MPIIORestartCoProcessor::setLBMKernel(SPtr<LBMKernel> kernel) { this->lbmKernel = kernel; } ////////////////////////////////////////////////////////////////////////// -void MPIIORestartCoProcessor::setBCProcessor(SPtr<BCProcessor> bcProcessor) -{ - this->bcProcessor = bcProcessor; -} - +void MPIIORestartCoProcessor::setBCProcessor(SPtr<BCProcessor> bcProcessor) { this->bcProcessor = bcProcessor; } diff --git a/src/cpu/VirtualFluidsCore/CoProcessors/MPIIORestartCoProcessor.h b/src/cpu/VirtualFluidsCore/CoProcessors/MPIIORestartCoProcessor.h index fa4cf2619826babf733a0d1c3d5975e5d586a9ef..a5d65c206cef7f6be00ae955ded6b90247983cc7 100644 --- a/src/cpu/VirtualFluidsCore/CoProcessors/MPIIORestartCoProcessor.h +++ b/src/cpu/VirtualFluidsCore/CoProcessors/MPIIORestartCoProcessor.h @@ -5,8 +5,8 @@ //#include <PointerDefinitions.h> #include <string> -#include "MPIIODataStructures.h" #include "MPIIOCoProcessor.h" +#include "MPIIODataStructures.h" class Grid3D; class UbScheduler; @@ -14,63 +14,61 @@ class Communicator; class BCProcessor; class LBMKernel; - - -//! \class MPIIORestartCoProcessor -//! \brief Writes the grid each timestep into the files and reads the grip from the files before regenerating +//! \class MPIIORestartCoProcessor +//! \brief Writes the grid each timestep into the files and reads the grip from the files before regenerating class MPIIORestartCoProcessor : public MPIIOCoProcessor { public: - MPIIORestartCoProcessor(SPtr<Grid3D> grid, SPtr<UbScheduler> s, const std::string& path, SPtr<Communicator> comm); - ~MPIIORestartCoProcessor() override; - //! Each timestep writes the grid into the files - void process(double step) override; - //! Reads the grid from the files before grid reconstruction - void restart(int step); - //! Writes the blocks of the grid into the file cpBlocks.bin - void writeBlocks(int step); - //! Writes the datasets of the blocks into the file cpDataSet.bin - void writeDataSet(int step); - void writeAverageDensityArray(int step); - void writeAverageVelocityArray(int step); - void writeAverageFluktuationsArray(int step); - void writeAverageTripleArray(int step); - void writeShearStressValArray(int step); - void writeRelaxationFactor(int step); - //! Writes the boundary conditions of the blocks into the file cpBC.bin - void writeBoundaryConds(int step); + MPIIORestartCoProcessor(SPtr<Grid3D> grid, SPtr<UbScheduler> s, const std::string &path, SPtr<Communicator> comm); + ~MPIIORestartCoProcessor() override; + //! Each timestep writes the grid into the files + void process(double step) override; + //! Reads the grid from the files before grid reconstruction + void restart(int step); + //! Writes the blocks of the grid into the file cpBlocks.bin + void writeBlocks(int step); + //! Writes the datasets of the blocks into the file cpDataSet.bin + void writeDataSet(int step); + void writeAverageDensityArray(int step); + void writeAverageVelocityArray(int step); + void writeAverageFluktuationsArray(int step); + void writeAverageTripleArray(int step); + void writeShearStressValArray(int step); + void writeRelaxationFactor(int step); + //! Writes the boundary conditions of the blocks into the file cpBC.bin + void writeBoundaryConds(int step); - //! Reads the blocks of the grid from the file cpBlocks.bin - void readBlocks(int step); - //! Reads the datasets of the blocks from the file cpDataSet.bin - void readDataSet(int step); - void readAverageDensityArray(int step); - void readAverageVelocityArray(int step); - void readAverageFluktuationsArray(int step); - void readAverageTripleArray(int step); - void readShearStressValArray(int step); - void readRelaxationFactor(int step); - //! Reads the boundary conditions of the blocks from the file cpBC.bin - void readBoundaryConds(int step); - //! The function sets LBMKernel - void setLBMKernel(SPtr<LBMKernel> kernel); - //!The function sets BCProcessor - void setBCProcessor(SPtr<BCProcessor> bcProcessor); - //!The function truncates the data files - void clearAllFiles(int step); + //! Reads the blocks of the grid from the file cpBlocks.bin + void readBlocks(int step); + //! Reads the datasets of the blocks from the file cpDataSet.bin + void readDataSet(int step); + void readAverageDensityArray(int step); + void readAverageVelocityArray(int step); + void readAverageFluktuationsArray(int step); + void readAverageTripleArray(int step); + void readShearStressValArray(int step); + void readRelaxationFactor(int step); + //! Reads the boundary conditions of the blocks from the file cpBC.bin + void readBoundaryConds(int step); + //! The function sets LBMKernel + void setLBMKernel(SPtr<LBMKernel> kernel); + //! The function sets BCProcessor + void setBCProcessor(SPtr<BCProcessor> bcProcessor); + //! The function truncates the data files + void clearAllFiles(int step); protected: - //std::string path; - //SPtr<Communicator> comm; + // std::string path; + // SPtr<Communicator> comm; private: - //MPI_Datatype gridParamType, block3dType; - MPI_Datatype dataSetType, dataSetSmallType, dataSetDoubleType; - MPI_Datatype boundCondParamType, boundCondType1000, boundCondTypeAdd, bcindexmatrixType; + // MPI_Datatype gridParamType, block3dType; + MPI_Datatype dataSetType, dataSetSmallType, dataSetDoubleType; + MPI_Datatype boundCondParamType, boundCondType1000, boundCondTypeAdd, bcindexmatrixType; - MPIIODataStructures::boundCondParam boundCondParamStr; - SPtr<LBMKernel> lbmKernel; - SPtr<BCProcessor> bcProcessor; + MPIIODataStructures::boundCondParam boundCondParamStr; + SPtr<LBMKernel> lbmKernel; + SPtr<BCProcessor> bcProcessor; }; -#endif +#endif diff --git a/src/cpu/VirtualFluidsCore/CoProcessors/MicrophoneArrayCoProcessor.cpp b/src/cpu/VirtualFluidsCore/CoProcessors/MicrophoneArrayCoProcessor.cpp index 8ea0e64d5a937eabd5083b46dbc111a904a388ea..1a5edc27be0644478913fd9e93a84bf34a4a96f1 100644 --- a/src/cpu/VirtualFluidsCore/CoProcessors/MicrophoneArrayCoProcessor.cpp +++ b/src/cpu/VirtualFluidsCore/CoProcessors/MicrophoneArrayCoProcessor.cpp @@ -1,125 +1,125 @@ #include "MicrophoneArrayCoProcessor.h" -#include "Vector3D.h" -#include "Grid3D.h" -#include "ILBMKernel.h" -#include "Communicator.h" +#include "BCArray3D.h" +#include "BCProcessor.h" #include "Block3D.h" -#include "DistributionArray3D.h" -#include "DataSet3D.h" +#include "Communicator.h" #include "D3Q27System.h" +#include "DataSet3D.h" +#include "DistributionArray3D.h" +#include "Grid3D.h" +#include "ILBMKernel.h" #include "UbScheduler.h" -#include "BCProcessor.h" -#include "BCArray3D.h" +#include "Vector3D.h" #include <sstream> -MicrophoneArrayCoProcessor::MicrophoneArrayCoProcessor(SPtr<Grid3D> grid, SPtr<UbScheduler> s, const std::string & path, SPtr<Communicator> comm) : CoProcessor(grid, s), path(path), comm(comm) +MicrophoneArrayCoProcessor::MicrophoneArrayCoProcessor(SPtr<Grid3D> grid, SPtr<UbScheduler> s, const std::string &path, + SPtr<Communicator> comm) + : CoProcessor(grid, s), path(path), comm(comm) { - count = 0; - micID = 0; + count = 0; + micID = 0; } -MicrophoneArrayCoProcessor::~MicrophoneArrayCoProcessor() -= default; +MicrophoneArrayCoProcessor::~MicrophoneArrayCoProcessor() = default; void MicrophoneArrayCoProcessor::process(double step) { - if (microphones.size() > 0) - { - collectData(step); + if (microphones.size() > 0) { + collectData(step); - if (scheduler->isDue(step)) - writeFile(step); - } + if (scheduler->isDue(step)) + writeFile(step); + } - UBLOG(logDEBUG3, "MicrophoneArrayCoProcessor::process:" << step); + UBLOG(logDEBUG3, "MicrophoneArrayCoProcessor::process:" << step); } bool MicrophoneArrayCoProcessor::addMicrophone(Vector3D coords) { - micID++; -// UbTupleInt3 blockIndexes = grid->getBlockIndexes(coords[0], coords[1], coords[2]); + micID++; + // UbTupleInt3 blockIndexes = grid->getBlockIndexes(coords[0], coords[1], coords[2]); - int minInitLevel = this->grid->getCoarsestInitializedLevel(); - int maxInitLevel = this->grid->getFinestInitializedLevel(); + int minInitLevel = this->grid->getCoarsestInitializedLevel(); + int maxInitLevel = this->grid->getFinestInitializedLevel(); - for (int level = minInitLevel; level<=maxInitLevel; level++) - { - UbTupleInt3 blockIndexes = grid->getBlockIndexes(coords[0], coords[1], coords[2], level); - SPtr<Block3D> block = grid->getBlock(val<1>(blockIndexes), val<2>(blockIndexes), val<3>(blockIndexes), level); - if (block) - { - SPtr<ILBMKernel> kernel = block->getKernel(); - if (kernel) - { - SPtr<BCArray3D> bcarray = kernel->getBCProcessor()->getBCArray(); - UbTupleInt3 nodes = grid->getNodeIndexes(block, coords[0], coords[1], coords[2]); - if (!bcarray->isUndefined(val<1>(nodes), val<2>(nodes), val<3>(nodes))) - { + for (int level = minInitLevel; level <= maxInitLevel; level++) { + UbTupleInt3 blockIndexes = grid->getBlockIndexes(coords[0], coords[1], coords[2], level); + SPtr<Block3D> block = grid->getBlock(val<1>(blockIndexes), val<2>(blockIndexes), val<3>(blockIndexes), level); + if (block) { + SPtr<ILBMKernel> kernel = block->getKernel(); + if (kernel) { + SPtr<BCArray3D> bcarray = kernel->getBCProcessor()->getBCArray(); + UbTupleInt3 nodes = grid->getNodeIndexes(block, coords[0], coords[1], coords[2]); + if (!bcarray->isUndefined(val<1>(nodes), val<2>(nodes), val<3>(nodes))) { - if (kernel->getCompressible()) - { - calcMacros = &D3Q27System::calcCompMacroscopicValues; - } - else - { - calcMacros = &D3Q27System::calcIncompMacroscopicValues; - } - SPtr<Mic> mic(new Mic); - mic->id = micID; - mic->distridution = kernel->getDataSet()->getFdistributions(); - mic->nodeIndexes = grid->getNodeIndexes(block, coords[0], coords[1], coords[2]); - microphones.push_back(mic); + if (kernel->getCompressible()) { + calcMacros = &D3Q27System::calcCompMacroscopicValues; + } else { + calcMacros = &D3Q27System::calcIncompMacroscopicValues; + } + SPtr<Mic> mic(new Mic); + mic->id = micID; + mic->distridution = kernel->getDataSet()->getFdistributions(); + mic->nodeIndexes = grid->getNodeIndexes(block, coords[0], coords[1], coords[2]); + microphones.push_back(mic); - strVector.push_back(SPtr<std::stringstream>(new std::stringstream)); + strVector.push_back(SPtr<std::stringstream>(new std::stringstream)); - std::string fname = path+"/mic/mic_"+UbSystem::toString(micID)+".csv"; - std::ofstream ostr; - ostr.open(fname.c_str(), std::ios_base::out | std::ios_base::app); - if (!ostr) - { - ostr.clear(); - std::string path = UbSystem::getPathFromString(fname); - if (path.size()>0) { UbSystem::makeDirectory(path); ostr.open(fname.c_str(), std::ios_base::out | std::ios_base::app); } - if (!ostr) throw UbException(UB_EXARGS, "couldn't open file "+fname); - } - ostr << "#microphone position: " << coords[0] << "; " << coords[1] << "; " << coords[2] << "; " << "\n"; - ostr.close(); - return true; + std::string fname = path + "/mic/mic_" + UbSystem::toString(micID) + ".csv"; + std::ofstream ostr; + ostr.open(fname.c_str(), std::ios_base::out | std::ios_base::app); + if (!ostr) { + ostr.clear(); + std::string path = UbSystem::getPathFromString(fname); + if (path.size() > 0) { + UbSystem::makeDirectory(path); + ostr.open(fname.c_str(), std::ios_base::out | std::ios_base::app); + } + if (!ostr) + throw UbException(UB_EXARGS, "couldn't open file " + fname); + } + ostr << "#microphone position: " << coords[0] << "; " << coords[1] << "; " << coords[2] << "; " + << "\n"; + ostr.close(); + return true; + } } - } - } - } - return false; + } + } + return false; } void MicrophoneArrayCoProcessor::collectData(double step) { - for (int i = 0; i < microphones.size(); i++ ) - { - LBMReal f[D3Q27System::ENDF+1]; - microphones[i]->distridution->getDistribution(f, val<1>(microphones[i]->nodeIndexes), val<2>(microphones[i]->nodeIndexes), val<3>(microphones[i]->nodeIndexes)); - LBMReal vx1, vx2, vx3, rho; - calcMacros(f, rho, vx1, vx2, vx3); - *strVector[i] << step << ';' << rho << '\n'; - } + for (int i = 0; i < microphones.size(); i++) { + LBMReal f[D3Q27System::ENDF + 1]; + microphones[i]->distridution->getDistribution(f, val<1>(microphones[i]->nodeIndexes), + val<2>(microphones[i]->nodeIndexes), + val<3>(microphones[i]->nodeIndexes)); + LBMReal vx1, vx2, vx3, rho; + calcMacros(f, rho, vx1, vx2, vx3); + *strVector[i] << step << ';' << rho << '\n'; + } } -void MicrophoneArrayCoProcessor::writeFile(double /*step*/) +void MicrophoneArrayCoProcessor::writeFile(double /*step*/) { - for (int i = 0; i < microphones.size(); i++) - { - std::string fname = path+"/mic/mic_"+UbSystem::toString(microphones[i]->id)+".csv"; - std::ofstream ostr; - ostr.open(fname.c_str(), std::ios_base::out | std::ios_base::app); - if (!ostr) - { - ostr.clear(); - std::string path = UbSystem::getPathFromString(fname); - if (path.size()>0) { UbSystem::makeDirectory(path); ostr.open(fname.c_str(), std::ios_base::out | std::ios_base::app); } - if (!ostr) throw UbException(UB_EXARGS, "couldn't open file "+fname); - } - ostr << strVector[i]->str(); - ostr.close(); - strVector[i] = SPtr<std::stringstream>(new std::stringstream); - } + for (int i = 0; i < microphones.size(); i++) { + std::string fname = path + "/mic/mic_" + UbSystem::toString(microphones[i]->id) + ".csv"; + std::ofstream ostr; + ostr.open(fname.c_str(), std::ios_base::out | std::ios_base::app); + if (!ostr) { + ostr.clear(); + std::string path = UbSystem::getPathFromString(fname); + if (path.size() > 0) { + UbSystem::makeDirectory(path); + ostr.open(fname.c_str(), std::ios_base::out | std::ios_base::app); + } + if (!ostr) + throw UbException(UB_EXARGS, "couldn't open file " + fname); + } + ostr << strVector[i]->str(); + ostr.close(); + strVector[i] = SPtr<std::stringstream>(new std::stringstream); + } } \ No newline at end of file diff --git a/src/cpu/VirtualFluidsCore/CoProcessors/MicrophoneArrayCoProcessor.h b/src/cpu/VirtualFluidsCore/CoProcessors/MicrophoneArrayCoProcessor.h index 73821538b06e5da5d9f73d10ba9bb6d6613571b8..d6185df6be205442e2cf1dc7a58710232ae80edf 100644 --- a/src/cpu/VirtualFluidsCore/CoProcessors/MicrophoneArrayCoProcessor.h +++ b/src/cpu/VirtualFluidsCore/CoProcessors/MicrophoneArrayCoProcessor.h @@ -2,11 +2,11 @@ #define MicrophoneArrayCoProcessor_h__ #include "CoProcessor.h" +#include "LBMSystem.h" +#include "UbTuple.h" +#include <array> #include <string> #include <vector> -#include <array> -#include "UbTuple.h" -#include "LBMSystem.h" class Communicator; class Grid3D; @@ -22,36 +22,38 @@ class DistributionArray3D; class MicrophoneArrayCoProcessor : public CoProcessor { public: - MicrophoneArrayCoProcessor(SPtr<Grid3D> grid, SPtr<UbScheduler> s, const std::string& path, SPtr<Communicator> comm); - ~MicrophoneArrayCoProcessor() override; + MicrophoneArrayCoProcessor(SPtr<Grid3D> grid, SPtr<UbScheduler> s, const std::string &path, + SPtr<Communicator> comm); + ~MicrophoneArrayCoProcessor() override; - //! calls collectData. - void process(double step) override; + //! calls collectData. + void process(double step) override; + + //! add microphone + bool addMicrophone(Vector3D coords); - //! add microphone - bool addMicrophone(Vector3D coords); protected: - void collectData(double step); - void writeFile(double step); + void collectData(double step); + void writeFile(double step); + private: - std::string path; - SPtr<Communicator> comm; + std::string path; + SPtr<Communicator> comm; - struct Mic - { - unsigned int id; - SPtr<DistributionArray3D> distridution; - UbTupleInt3 nodeIndexes; - }; - std::vector< SPtr<Mic> > microphones; + struct Mic { + unsigned int id; + SPtr<DistributionArray3D> distridution; + UbTupleInt3 nodeIndexes; + }; + std::vector<SPtr<Mic>> microphones; - std::vector< SPtr<std::stringstream> > strVector; + std::vector<SPtr<std::stringstream>> strVector; - int count; - int micID; + int count; + int micID; - using CalcMacrosFct = void (*)(const LBMReal *const &, LBMReal &, LBMReal &, LBMReal &, LBMReal &); - CalcMacrosFct calcMacros; + using CalcMacrosFct = void (*)(const LBMReal *const &, LBMReal &, LBMReal &, LBMReal &, LBMReal &); + CalcMacrosFct calcMacros; }; #endif // MicrophoneArrayCoProcessor_h__ diff --git a/src/cpu/VirtualFluidsCore/CoProcessors/NUPSCounterCoProcessor.cpp b/src/cpu/VirtualFluidsCore/CoProcessors/NUPSCounterCoProcessor.cpp index 43652ec721991f00b5b5f6a47122ec807bb4e60c..46cbba0df4b96fddec45c7c696de51d74e9bc6eb 100644 --- a/src/cpu/VirtualFluidsCore/CoProcessors/NUPSCounterCoProcessor.cpp +++ b/src/cpu/VirtualFluidsCore/CoProcessors/NUPSCounterCoProcessor.cpp @@ -1,28 +1,28 @@ //======================================================================================= -// ____ ____ __ ______ __________ __ __ __ __ -// \ \ | | | | | _ \ |___ ___| | | | | / \ | | -// \ \ | | | | | |_) | | | | | | | / \ | | -// \ \ | | | | | _ / | | | | | | / /\ \ | | -// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ -// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| -// \ \ | | ________________________________________________________________ -// \ \ | | | ______________________________________________________________| -// \ \| | | | __ __ __ __ ______ _______ -// \ | | |_____ | | | | | | | | | _ \ / _____) -// \ | | _____| | | | | | | | | | | \ \ \_______ +// ____ ____ __ ______ __________ __ __ __ __ +// \ \ | | | | | _ \ |___ ___| | | | | / \ | | +// \ \ | | | | | |_) | | | | | | | / \ | | +// \ \ | | | | | _ / | | | | | | / /\ \ | | +// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ +// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| +// \ \ | | ________________________________________________________________ +// \ \ | | | ______________________________________________________________| +// \ \| | | | __ __ __ __ ______ _______ +// \ | | |_____ | | | | | | | | | _ \ / _____) +// \ | | _____| | | | | | | | | | | \ \ \_______ // \ | | | | |_____ | \_/ | | | | |_/ / _____ | -// \ _____| |__| |________| \_______/ |__| |______/ (_______/ +// \ _____| |__| |________| \_______/ |__| |______/ (_______/ // -// This file is part of VirtualFluids. VirtualFluids is free software: you can +// This file is part of VirtualFluids. VirtualFluids is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of +// License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. -// -// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// +// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License along // with VirtualFluids (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>. // @@ -34,60 +34,52 @@ #include "NUPSCounterCoProcessor.h" #include "Communicator.h" -#include "UbScheduler.h" #include "Grid3D.h" +#include "UbScheduler.h" -NUPSCounterCoProcessor::NUPSCounterCoProcessor(SPtr<Grid3D> grid, SPtr<UbScheduler> s, int numOfThreads, SPtr<Communicator> comm) - : CoProcessor(grid, s), - numOfThreads(numOfThreads), - nup(0), - nup_t(0), - nupsStep(0.0), - comm(comm) +NUPSCounterCoProcessor::NUPSCounterCoProcessor(SPtr<Grid3D> grid, SPtr<UbScheduler> s, int numOfThreads, + SPtr<Communicator> comm) + : CoProcessor(grid, s), numOfThreads(numOfThreads), nup(0), nup_t(0), nupsStep(0.0), comm(comm) { - if (comm->getProcessID() == comm->getRoot()) - { - timer.resetAndStart(); + if (comm->getProcessID() == comm->getRoot()) { + timer.resetAndStart(); - double nop = comm->getNumberOfProcesses(); - int minInitLevel = grid->getCoarsestInitializedLevel(); - int maxInitLevel = grid->getFinestInitializedLevel(); - UbTupleInt3 blocknx = grid->getBlockNX(); - double nod = (double)(val<1>(blocknx)) * (double)(val<2>(blocknx)) * (double)(val<3>(blocknx)); - nup = 0; + double nop = comm->getNumberOfProcesses(); + int minInitLevel = grid->getCoarsestInitializedLevel(); + int maxInitLevel = grid->getFinestInitializedLevel(); + UbTupleInt3 blocknx = grid->getBlockNX(); + double nod = (double)(val<1>(blocknx)) * (double)(val<2>(blocknx)) * (double)(val<3>(blocknx)); + nup = 0; - for(int level = minInitLevel; level<=maxInitLevel; level++) - { - int nob = grid->getNumberOfBlocks(level); - nup_t += (double)(1<<level) * nob * nod; - } - nup = nup_t / nop; - } + for (int level = minInitLevel; level <= maxInitLevel; level++) { + int nob = grid->getNumberOfBlocks(level); + nup_t += (double)(1 << level) * nob * nod; + } + nup = nup_t / nop; + } } ////////////////////////////////////////////////////////////////////////// -NUPSCounterCoProcessor::~NUPSCounterCoProcessor() -= default; +NUPSCounterCoProcessor::~NUPSCounterCoProcessor() = default; ////////////////////////////////////////////////////////////////////////// void NUPSCounterCoProcessor::process(double step) { - if(scheduler->isDue(step) ) - collectData(step); + if (scheduler->isDue(step)) + collectData(step); } ////////////////////////////////////////////////////////////////////////// void NUPSCounterCoProcessor::collectData(double step) { - if (comm->getProcessID() == comm->getRoot()) - { - double time = timer.stop(); - double nups_t = nup_t*(step-nupsStep)/time; - double nups = nup*(step-nupsStep)/time; - double tnups = nups/(double)numOfThreads; - UBLOG(logINFO, "Calculation step = "<<step); - UBLOG(logINFO, "Total performance = "<<nups_t<<" NUPS"); - UBLOG(logINFO, "Performance per process = "<<nups<<" NUPS"); - UBLOG(logINFO, "Performance per thread = "<<tnups<<" NUPS"); - UBLOG(logINFO, "Time for " << step-nupsStep <<" steps = "<< time <<" s"); - nupsStep = step; - timer.resetAndStart(); - } + if (comm->getProcessID() == comm->getRoot()) { + double time = timer.stop(); + double nups_t = nup_t * (step - nupsStep) / time; + double nups = nup * (step - nupsStep) / time; + double tnups = nups / (double)numOfThreads; + UBLOG(logINFO, "Calculation step = " << step); + UBLOG(logINFO, "Total performance = " << nups_t << " NUPS"); + UBLOG(logINFO, "Performance per process = " << nups << " NUPS"); + UBLOG(logINFO, "Performance per thread = " << tnups << " NUPS"); + UBLOG(logINFO, "Time for " << step - nupsStep << " steps = " << time << " s"); + nupsStep = step; + timer.resetAndStart(); + } } diff --git a/src/cpu/VirtualFluidsCore/CoProcessors/NUPSCounterCoProcessor.h b/src/cpu/VirtualFluidsCore/CoProcessors/NUPSCounterCoProcessor.h index f111a4b8cc4389217cdcfb758908d294733d6ba0..61d2ba0b69a96959b07d5e1901da62ab7abdaa1a 100644 --- a/src/cpu/VirtualFluidsCore/CoProcessors/NUPSCounterCoProcessor.h +++ b/src/cpu/VirtualFluidsCore/CoProcessors/NUPSCounterCoProcessor.h @@ -1,28 +1,28 @@ //======================================================================================= -// ____ ____ __ ______ __________ __ __ __ __ -// \ \ | | | | | _ \ |___ ___| | | | | / \ | | -// \ \ | | | | | |_) | | | | | | | / \ | | -// \ \ | | | | | _ / | | | | | | / /\ \ | | -// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ -// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| -// \ \ | | ________________________________________________________________ -// \ \ | | | ______________________________________________________________| -// \ \| | | | __ __ __ __ ______ _______ -// \ | | |_____ | | | | | | | | | _ \ / _____) -// \ | | _____| | | | | | | | | | | \ \ \_______ +// ____ ____ __ ______ __________ __ __ __ __ +// \ \ | | | | | _ \ |___ ___| | | | | / \ | | +// \ \ | | | | | |_) | | | | | | | / \ | | +// \ \ | | | | | _ / | | | | | | / /\ \ | | +// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ +// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| +// \ \ | | ________________________________________________________________ +// \ \ | | | ______________________________________________________________| +// \ \| | | | __ __ __ __ ______ _______ +// \ | | |_____ | | | | | | | | | _ \ / _____) +// \ | | _____| | | | | | | | | | | \ \ \_______ // \ | | | | |_____ | \_/ | | | | |_/ / _____ | -// \ _____| |__| |________| \_______/ |__| |______/ (_______/ +// \ _____| |__| |________| \_______/ |__| |______/ (_______/ // -// This file is part of VirtualFluids. VirtualFluids is free software: you can +// This file is part of VirtualFluids. VirtualFluids is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of +// License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. -// -// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// +// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License along // with VirtualFluids (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>. // @@ -45,33 +45,32 @@ class UbScheduler; //! \class NUPSCounterCoProcessor //! \brief A class calculates Nodal Updates Per Second (NUPS) -class NUPSCounterCoProcessor: public CoProcessor +class NUPSCounterCoProcessor : public CoProcessor { public: - //! \brief Construct NUPSCounterCoProcessor object for grid object and scheduler object. - //! \pre The Grid3D and UbScheduler objects must exist. - //! \param grid is observable Grid3D object - //! \param s is UbScheduler object for scheduling of observer - //! \param numOfThreads is number of threads - //! \param comm is Communicator object - NUPSCounterCoProcessor(SPtr<Grid3D> grid, SPtr<UbScheduler> s, int numOfThreads, SPtr<Communicator> comm); - ~NUPSCounterCoProcessor() override; + //! \brief Construct NUPSCounterCoProcessor object for grid object and scheduler object. + //! \pre The Grid3D and UbScheduler objects must exist. + //! \param grid is observable Grid3D object + //! \param s is UbScheduler object for scheduling of observer + //! \param numOfThreads is number of threads + //! \param comm is Communicator object + NUPSCounterCoProcessor(SPtr<Grid3D> grid, SPtr<UbScheduler> s, int numOfThreads, SPtr<Communicator> comm); + ~NUPSCounterCoProcessor() override; - void process(double step)override; + void process(double step) override; protected: - //! Collect data for calculation of NUPS - //! \param step is a time step - void collectData(double step); - UbTimer timer; - int numOfThreads; - double numberOfNodes; - double numberOfBlocks; - double nup; - double nup_t; - double nupsStep; - SPtr<Communicator> comm; + //! Collect data for calculation of NUPS + //! \param step is a time step + void collectData(double step); + UbTimer timer; + int numOfThreads; + double numberOfNodes; + double numberOfBlocks; + double nup; + double nup_t; + double nupsStep; + SPtr<Communicator> comm; }; - -#endif +#endif diff --git a/src/cpu/VirtualFluidsCore/CoProcessors/PressureCoefficientCoProcessor.cpp b/src/cpu/VirtualFluidsCore/CoProcessors/PressureCoefficientCoProcessor.cpp index 417f713a7c1e7ad111f7f8c95322613a0bbc12c6..b350f441b3b237032ca24cd4a3743c3cf629a89e 100644 --- a/src/cpu/VirtualFluidsCore/CoProcessors/PressureCoefficientCoProcessor.cpp +++ b/src/cpu/VirtualFluidsCore/CoProcessors/PressureCoefficientCoProcessor.cpp @@ -1,221 +1,209 @@ #include "PressureCoefficientCoProcessor.h" #include <WbWriterVtkXmlASCII.h> -#include "LBMKernel.h" +#include "BCArray3D.h" #include "BCProcessor.h" -#include "DataSet3D.h" #include "Block3D.h" -#include "UbScheduler.h" -#include "Grid3D.h" #include "Communicator.h" -#include "GbCuboid3D.h" #include "D3Q27Interactor.h" -#include "BCArray3D.h" +#include "DataSet3D.h" +#include "GbCuboid3D.h" +#include "Grid3D.h" +#include "LBMKernel.h" +#include "UbScheduler.h" PressureCoefficientCoProcessor::PressureCoefficientCoProcessor(SPtr<Grid3D> grid, SPtr<UbScheduler> s, - GbCuboid3DPtr plane, - const std::string& path, SPtr<Communicator> comm) - : CoProcessor(grid, s), - plane(plane), - path(path), - comm(comm) + GbCuboid3DPtr plane, const std::string &path, + SPtr<Communicator> comm) + : CoProcessor(grid, s), plane(plane), path(path), comm(comm) { - maxStep = scheduler->getMaxEnd(); - numberOfSteps = int(maxStep - scheduler->getMinBegin()); + maxStep = scheduler->getMaxEnd(); + numberOfSteps = int(maxStep - scheduler->getMinBegin()); } ////////////////////////////////////////////////////////////////////////// -PressureCoefficientCoProcessor::~PressureCoefficientCoProcessor() -= default; +PressureCoefficientCoProcessor::~PressureCoefficientCoProcessor() = default; ////////////////////////////////////////////////////////////////////////// void PressureCoefficientCoProcessor::process(double step) { - if (scheduler->isDue(step)) - collectData(step); + if (scheduler->isDue(step)) + collectData(step); - UBLOG(logDEBUG3, "D3Q27ForcesCoProcessor::update:" << step); + UBLOG(logDEBUG3, "D3Q27ForcesCoProcessor::update:" << step); } ////////////////////////////////////////////////////////////////////////// void PressureCoefficientCoProcessor::collectData(double step) { - calculateRho(); + calculateRho(); - if (step == maxStep) - { - writeValues((int)step); - } + if (step == maxStep) { + writeValues((int)step); + } } ////////////////////////////////////////////////////////////////////////// void PressureCoefficientCoProcessor::calculateRho() { - double f[D3Q27System::ENDF+1]; - double vx1, vx2, vx3, rho; - std::vector<double> values; - std::vector<double> rvalues; - - for(SPtr<D3Q27Interactor> interactor : interactors) - { - typedef std::map<SPtr<Block3D>, std::set< std::vector<int> > > TransNodeIndicesMap; - for(TransNodeIndicesMap::value_type t : interactor->getBcNodeIndicesMap()) - { - SPtr<Block3D> block = t.first; - std::set< std::vector<int> >& bcNodeIndicesSet = t.second; - - SPtr<ILBMKernel> kernel = block->getKernel(); - SPtr<BCArray3D> bcArray = kernel->getBCProcessor()->getBCArray(); - SPtr<DistributionArray3D> distributions = kernel->getDataSet()->getFdistributions(); - - UbTupleDouble3 org = grid->getBlockWorldCoordinates(block); -// UbTupleDouble3 blockLengths = grid->getBlockLengths(block); - UbTupleDouble3 nodeOffset = grid->getNodeOffset(block); - double dx = grid->getDeltaX(block); - - if (kernel->getCompressible()) - { - calcMacros = &D3Q27System::calcCompMacroscopicValues; - } - else - { - calcMacros = &D3Q27System::calcIncompMacroscopicValues; - } - - int ghostLayerWidth = kernel->getGhostLayerWidth(); - int minX1 = ghostLayerWidth; - int maxX1 = (int)bcArray->getNX1() - 1 - ghostLayerWidth; - int minX2 = ghostLayerWidth; - int maxX2 = (int)bcArray->getNX2() - 1 - ghostLayerWidth; - int minX3 = ghostLayerWidth; - int maxX3 = (int)bcArray->getNX3() - 1 - ghostLayerWidth; - - for(std::vector<int> node : bcNodeIndicesSet) - { - int x1 = node[0]; - int x2 = node[1]; - int x3 = node[2]; - - //without ghost nodes - if (x1 < minX1 || x1 > maxX1 || x2 < minX2 || x2 > maxX2 ||x3 < minX3 || x3 > maxX3) continue; - - if (bcArray->isFluid(x1, x2, x3)) //es kann sein, dass der node von einem anderen interactor z.B. als solid gemarkt wurde!!! - { - double cx1 = val<1>(org) - val<1>(nodeOffset) + x1*dx; - double cx2 = val<2>(org) - val<2>(nodeOffset) + x2*dx; - double cx3 = val<3>(org) - val<3>(nodeOffset) + x3*dx; - if (plane->isPointInGbObject3D(cx1, cx2, cx3)) - { - distributions->getDistribution(f, x1, x2, x3); - calcMacros(f, rho, vx1, vx2, vx3); - values.push_back(cx1); - values.push_back(cx2); - values.push_back(cx3); - values.push_back(rho); - } + double f[D3Q27System::ENDF + 1]; + double vx1, vx2, vx3, rho; + std::vector<double> values; + std::vector<double> rvalues; + + for (SPtr<D3Q27Interactor> interactor : interactors) { + typedef std::map<SPtr<Block3D>, std::set<std::vector<int>>> TransNodeIndicesMap; + for (TransNodeIndicesMap::value_type t : interactor->getBcNodeIndicesMap()) { + SPtr<Block3D> block = t.first; + std::set<std::vector<int>> &bcNodeIndicesSet = t.second; + + SPtr<ILBMKernel> kernel = block->getKernel(); + SPtr<BCArray3D> bcArray = kernel->getBCProcessor()->getBCArray(); + SPtr<DistributionArray3D> distributions = kernel->getDataSet()->getFdistributions(); + + UbTupleDouble3 org = grid->getBlockWorldCoordinates(block); + // UbTupleDouble3 blockLengths = grid->getBlockLengths(block); + UbTupleDouble3 nodeOffset = grid->getNodeOffset(block); + double dx = grid->getDeltaX(block); + + if (kernel->getCompressible()) { + calcMacros = &D3Q27System::calcCompMacroscopicValues; + } else { + calcMacros = &D3Q27System::calcIncompMacroscopicValues; } - } - - } - } - - comm->allGather(values, rvalues); - if (comm->getProcessID() == comm->getRoot()) - { - if (outValues.size() == 0) - { - outValues.resize(rvalues.size()); - } - int size = (int)rvalues.size(); - for (int i = 0; i < size; i+=4) - { - outValues[i] = rvalues[i]; - outValues[i+1] = rvalues[i+1]; - outValues[i+2] = rvalues[i+2]; - outValues[i+3] += rvalues[i+3]; - } - } + int ghostLayerWidth = kernel->getGhostLayerWidth(); + int minX1 = ghostLayerWidth; + int maxX1 = (int)bcArray->getNX1() - 1 - ghostLayerWidth; + int minX2 = ghostLayerWidth; + int maxX2 = (int)bcArray->getNX2() - 1 - ghostLayerWidth; + int minX3 = ghostLayerWidth; + int maxX3 = (int)bcArray->getNX3() - 1 - ghostLayerWidth; + + for (std::vector<int> node : bcNodeIndicesSet) { + int x1 = node[0]; + int x2 = node[1]; + int x3 = node[2]; + + // without ghost nodes + if (x1 < minX1 || x1 > maxX1 || x2 < minX2 || x2 > maxX2 || x3 < minX3 || x3 > maxX3) + continue; + + if (bcArray->isFluid( + x1, x2, + x3)) // es kann sein, dass der node von einem anderen interactor z.B. als solid gemarkt wurde!!! + { + double cx1 = val<1>(org) - val<1>(nodeOffset) + x1 * dx; + double cx2 = val<2>(org) - val<2>(nodeOffset) + x2 * dx; + double cx3 = val<3>(org) - val<3>(nodeOffset) + x3 * dx; + if (plane->isPointInGbObject3D(cx1, cx2, cx3)) { + distributions->getDistribution(f, x1, x2, x3); + calcMacros(f, rho, vx1, vx2, vx3); + values.push_back(cx1); + values.push_back(cx2); + values.push_back(cx3); + values.push_back(rho); + } + } + } + } + } + + comm->allGather(values, rvalues); + if (comm->getProcessID() == comm->getRoot()) { + if (outValues.size() == 0) { + outValues.resize(rvalues.size()); + } + int size = (int)rvalues.size(); + for (int i = 0; i < size; i += 4) { + outValues[i] = rvalues[i]; + outValues[i + 1] = rvalues[i + 1]; + outValues[i + 2] = rvalues[i + 2]; + outValues[i + 3] += rvalues[i + 3]; + } + } } ////////////////////////////////////////////////////////////////////////// void PressureCoefficientCoProcessor::writeValues(int step) { - if (comm->getProcessID() == comm->getRoot()) - { - datanames.resize(0); - datanames.emplace_back("rho"); - data.resize(datanames.size()); - - std::ofstream ostr; - std::string fname = path+UbSystem::toString(step)+".csv"; - ostr.open(fname.c_str(), std::ios_base::out); - if (!ostr) - { - ostr.clear(); - std::string path = UbSystem::getPathFromString(fname); - if (path.size()>0) { UbSystem::makeDirectory(path); ostr.open(fname.c_str(), std::ios_base::out); } - if (!ostr) throw UbException(UB_EXARGS, "couldn't open file "+fname); - } - - ostr << "x1;x2;x3;rho\n"; - - int size = (int)outValues.size(); - for (int i = 0; i < size; i+=4) - { - ostr << outValues[i] << ";" << outValues[i+1] <<";" << outValues[i+2] << ";" << outValues[i+3]/numberOfSteps << std::endl; - - int index = 0; - nodes.push_back(makeUbTuple(float(outValues[i]), - float(outValues[i+1]), - float(outValues[i+2]))); - - data[index++].push_back(outValues[i+3]/numberOfSteps); - } - - ostr.close(); - - WbWriterVtkXmlASCII::getInstance()->writeNodesWithNodeData(path+UbSystem::toString(step), nodes, datanames, data); - - fname = path+UbSystem::toString(step)+".bin"; - std::ofstream out(fname.c_str(), std::ios::out | std::ios::binary); - if (!out) - { - out.clear(); //flags ruecksetzen (ansonsten liefert utern if(!out) weiterhin true!!! - std::string path = UbSystem::getPathFromString(fname); - if (path.size()>0) { UbSystem::makeDirectory(path); out.open(fname.c_str(), std::ios::out | std::ios::binary); } - if (!out) throw UbException(UB_EXARGS, "couldn't open file "+fname); - } - - out.write((char*)&outValues[0], outValues.size()*sizeof(double)); - - out.close(); - - UBLOG(logINFO, "PressureCoefficientCoProcessor::writeValues() step: " << (int)step); - } + if (comm->getProcessID() == comm->getRoot()) { + datanames.resize(0); + datanames.emplace_back("rho"); + data.resize(datanames.size()); + + std::ofstream ostr; + std::string fname = path + UbSystem::toString(step) + ".csv"; + ostr.open(fname.c_str(), std::ios_base::out); + if (!ostr) { + ostr.clear(); + std::string path = UbSystem::getPathFromString(fname); + if (path.size() > 0) { + UbSystem::makeDirectory(path); + ostr.open(fname.c_str(), std::ios_base::out); + } + if (!ostr) + throw UbException(UB_EXARGS, "couldn't open file " + fname); + } + + ostr << "x1;x2;x3;rho\n"; + + int size = (int)outValues.size(); + for (int i = 0; i < size; i += 4) { + ostr << outValues[i] << ";" << outValues[i + 1] << ";" << outValues[i + 2] << ";" + << outValues[i + 3] / numberOfSteps << std::endl; + + int index = 0; + nodes.push_back(makeUbTuple(float(outValues[i]), float(outValues[i + 1]), float(outValues[i + 2]))); + + data[index++].push_back(outValues[i + 3] / numberOfSteps); + } + + ostr.close(); + + WbWriterVtkXmlASCII::getInstance()->writeNodesWithNodeData(path + UbSystem::toString(step), nodes, datanames, + data); + + fname = path + UbSystem::toString(step) + ".bin"; + std::ofstream out(fname.c_str(), std::ios::out | std::ios::binary); + if (!out) { + out.clear(); // flags ruecksetzen (ansonsten liefert utern if(!out) weiterhin true!!! + std::string path = UbSystem::getPathFromString(fname); + if (path.size() > 0) { + UbSystem::makeDirectory(path); + out.open(fname.c_str(), std::ios::out | std::ios::binary); + } + if (!out) + throw UbException(UB_EXARGS, "couldn't open file " + fname); + } + + out.write((char *)&outValues[0], outValues.size() * sizeof(double)); + + out.close(); + + UBLOG(logINFO, "PressureCoefficientCoProcessor::writeValues() step: " << (int)step); + } } void PressureCoefficientCoProcessor::readValues(int step) { - if (comm->isRoot()) - { - std::string fname = path+UbSystem::toString(step)+".bin"; - std::ifstream in(fname.c_str(), std::ios::in | std::ios::binary); - if (!in) - { - throw UbException(UB_EXARGS, "couldn't open file "+fname); - } + if (comm->isRoot()) { + std::string fname = path + UbSystem::toString(step) + ".bin"; + std::ifstream in(fname.c_str(), std::ios::in | std::ios::binary); + if (!in) { + throw UbException(UB_EXARGS, "couldn't open file " + fname); + } - // get length of file: - in.seekg(0, in.end); - int length = (int)in.tellg(); - in.seekg(0, in.beg); + // get length of file: + in.seekg(0, in.end); + int length = (int)in.tellg(); + in.seekg(0, in.beg); - outValues.resize(length/sizeof(double)); + outValues.resize(length / sizeof(double)); - in.read((char*)&outValues[0], length); + in.read((char *)&outValues[0], length); - in.close(); + in.close(); - UBLOG(logINFO, "PressureCoefficientCoProcessor::readValues() step: " << (int)step); - } + UBLOG(logINFO, "PressureCoefficientCoProcessor::readValues() step: " << (int)step); + } } ////////////////////////////////////////////////////////////////////////// void PressureCoefficientCoProcessor::addInteractor(SPtr<D3Q27Interactor> interactor) { - interactors.push_back(interactor); + interactors.push_back(interactor); } diff --git a/src/cpu/VirtualFluidsCore/CoProcessors/PressureCoefficientCoProcessor.h b/src/cpu/VirtualFluidsCore/CoProcessors/PressureCoefficientCoProcessor.h index 441e6ca8e6480c59c4e1196ff5fddac22eb3f355..f8f1d80d9c3185a13ab7ceebd579929f441c25e0 100644 --- a/src/cpu/VirtualFluidsCore/CoProcessors/PressureCoefficientCoProcessor.h +++ b/src/cpu/VirtualFluidsCore/CoProcessors/PressureCoefficientCoProcessor.h @@ -9,48 +9,45 @@ #include "LBMSystem.h" #include "UbTuple.h" - class GbCuboid3D; class D3Q27Interactor; class Communicator; class Grid3D; class UbScheduler; -class PressureCoefficientCoProcessor: public CoProcessor +class PressureCoefficientCoProcessor : public CoProcessor { public: - PressureCoefficientCoProcessor(SPtr<Grid3D> grid, SPtr<UbScheduler> s, - SPtr<GbCuboid3D> plane, const std::string& path, SPtr<Communicator> comm); - ~PressureCoefficientCoProcessor() override; + PressureCoefficientCoProcessor(SPtr<Grid3D> grid, SPtr<UbScheduler> s, SPtr<GbCuboid3D> plane, + const std::string &path, SPtr<Communicator> comm); + ~PressureCoefficientCoProcessor() override; - void process(double step) override; + void process(double step) override; - void addInteractor(SPtr<D3Q27Interactor> interactor); - void readValues(int step); + void addInteractor(SPtr<D3Q27Interactor> interactor); + void readValues(int step); protected: - void collectData(double step); - void calculateRho(); - void writeValues(int step); + void collectData(double step); + void calculateRho(); + void writeValues(int step); private: SPtr<GbCuboid3D> plane; - std::string path; - SPtr<Communicator> comm; - std::vector<SPtr<D3Q27Interactor> > interactors; - int numberOfSteps; - double maxStep; + std::string path; + SPtr<Communicator> comm; + std::vector<SPtr<D3Q27Interactor>> interactors; + int numberOfSteps; + double maxStep; - std::vector<UbTupleFloat3> nodes; - std::vector<std::string> datanames; - std::vector<std::vector<double> > data; + std::vector<UbTupleFloat3> nodes; + std::vector<std::string> datanames; + std::vector<std::vector<double>> data; - std::vector<double> outValues; + std::vector<double> outValues; - using CalcMacrosFct = void (*)(const LBMReal *const &, LBMReal &, LBMReal &, LBMReal &, LBMReal &); - CalcMacrosFct calcMacros; + using CalcMacrosFct = void (*)(const LBMReal *const &, LBMReal &, LBMReal &, LBMReal &, LBMReal &); + CalcMacrosFct calcMacros; }; #endif // PressureDistributionCoProcessor_h__ - - diff --git a/src/cpu/VirtualFluidsCore/CoProcessors/PressureDifferenceCoProcessor.cpp b/src/cpu/VirtualFluidsCore/CoProcessors/PressureDifferenceCoProcessor.cpp index 46399e0bd0033e6437744f5e99bb847e7134a249..e9b94dc6a225cd1b3b8a70126a242dd42e8e5b0c 100644 --- a/src/cpu/VirtualFluidsCore/CoProcessors/PressureDifferenceCoProcessor.cpp +++ b/src/cpu/VirtualFluidsCore/CoProcessors/PressureDifferenceCoProcessor.cpp @@ -9,93 +9,113 @@ #include <fstream> +#include "Communicator.h" +#include "Grid3D.h" #include "IntegrateValuesHelper.h" #include "LBMUnitConverter.h" -#include "Communicator.h" #include "UbScheduler.h" -#include "Grid3D.h" - -PressureDifferenceCoProcessor::PressureDifferenceCoProcessor(SPtr<Grid3D> grid, SPtr<UbScheduler> s, const std::string& path, - SPtr<IntegrateValuesHelper> h1, SPtr<IntegrateValuesHelper> h2, - LBMReal rhoReal, LBMReal uReal, LBMReal uLB, - SPtr<Communicator> comm) +PressureDifferenceCoProcessor::PressureDifferenceCoProcessor(SPtr<Grid3D> grid, SPtr<UbScheduler> s, + const std::string &path, SPtr<IntegrateValuesHelper> h1, + SPtr<IntegrateValuesHelper> h2, LBMReal rhoReal, + LBMReal uReal, LBMReal uLB, SPtr<Communicator> comm) - : CoProcessor(grid, s) - , path(path) - , h1(h1) - , h2(h2) - ,comm(comm) + : CoProcessor(grid, s), path(path), h1(h1), h2(h2), comm(comm) { - if (comm->getProcessID() == comm->getRoot()) - { - std::ofstream ostr; - std::string fname = path; - ostr.open(fname.c_str(), std::ios_base::out); - if(!ostr) - { - ostr.clear(); - std::string file_path = UbSystem::getPathFromString(fname); - if(file_path.size()>0){ UbSystem::makeDirectory(file_path); ostr.open(fname.c_str(), std::ios_base::out);} - if(!ostr) throw UbException(UB_EXARGS,"couldn't open file "+fname); - } - ostr << "step" << "\t" << "nodes1" << "\t" << "nodes2" << "\t"; - ostr << "sRho1" << "\t" << "p1_1" << "\t" << "sRho2" << "\t" << "p1_2" << "\t" << "deltaP1"<< "\t"; - ostr << "sPress1" << "\t" << "p2_1" << "\t" << "sPress2" << "\t" << "p2_2" << "\t" << "deltaP2"; - ostr << std::endl; - ostr.close(); + if (comm->getProcessID() == comm->getRoot()) { + std::ofstream ostr; + std::string fname = path; + ostr.open(fname.c_str(), std::ios_base::out); + if (!ostr) { + ostr.clear(); + std::string file_path = UbSystem::getPathFromString(fname); + if (file_path.size() > 0) { + UbSystem::makeDirectory(file_path); + ostr.open(fname.c_str(), std::ios_base::out); + } + if (!ostr) + throw UbException(UB_EXARGS, "couldn't open file " + fname); + } + ostr << "step" + << "\t" + << "nodes1" + << "\t" + << "nodes2" + << "\t"; + ostr << "sRho1" + << "\t" + << "p1_1" + << "\t" + << "sRho2" + << "\t" + << "p1_2" + << "\t" + << "deltaP1" + << "\t"; + ostr << "sPress1" + << "\t" + << "p2_1" + << "\t" + << "sPress2" + << "\t" + << "p2_2" + << "\t" + << "deltaP2"; + ostr << std::endl; + ostr.close(); - factor1 = (1.0/3.0)*rhoReal*(uReal/uLB)*(uReal/uLB); - factor2 = rhoReal*(uReal/uLB)*(uReal/uLB); - } + factor1 = (1.0 / 3.0) * rhoReal * (uReal / uLB) * (uReal / uLB); + factor2 = rhoReal * (uReal / uLB) * (uReal / uLB); + } } ////////////////////////////////////////////////////////////////////////// -PressureDifferenceCoProcessor::~PressureDifferenceCoProcessor() -= default; +PressureDifferenceCoProcessor::~PressureDifferenceCoProcessor() = default; ////////////////////////////////////////////////////////////////////////// void PressureDifferenceCoProcessor::process(double step) { - if(scheduler->isDue(step) ) - collectData(step); + if (scheduler->isDue(step)) + collectData(step); } ////////////////////////////////////////////////////////////////////////// void PressureDifferenceCoProcessor::collectData(double step) { - h1->calculateMQ(); - h2->calculateMQ(); - - if (comm->getProcessID() == comm->getRoot()) - { - int istep = static_cast<int>(step); - std::ofstream ostr; - double nn1 = h1->getNumberOfFluidsNodes(); - double nn2 = h2->getNumberOfFluidsNodes(); - double rho1 = h1->getRho(); - double rho2 = h2->getRho(); - double p1_1 = (rho1/nn1) * factor1; - double p1_2 = (rho2/nn2) * factor1; - double dp1 = p1_1 - p1_2; + h1->calculateMQ(); + h2->calculateMQ(); + + if (comm->getProcessID() == comm->getRoot()) { + int istep = static_cast<int>(step); + std::ofstream ostr; + double nn1 = h1->getNumberOfFluidsNodes(); + double nn2 = h2->getNumberOfFluidsNodes(); + double rho1 = h1->getRho(); + double rho2 = h2->getRho(); + double p1_1 = (rho1 / nn1) * factor1; + double p1_2 = (rho2 / nn2) * factor1; + double dp1 = p1_1 - p1_2; - //double press1 = h1->getPress(); - //double press2 = h2->getPress(); - //double p2_1 = (press1/nn1) * factor2; - //double p2_2 = (press2/nn2) * factor2; - //double dp2 = p2_1 - p2_2; + // double press1 = h1->getPress(); + // double press2 = h2->getPress(); + // double p2_1 = (press1/nn1) * factor2; + // double p2_2 = (press2/nn2) * factor2; + // double dp2 = p2_1 - p2_2; - std::string fname = path; - ostr.open(fname.c_str(), std::ios_base::out | std::ios_base::app); - if(!ostr) - { - ostr.clear(); - std::string path = UbSystem::getPathFromString(fname); - if(path.size()>0){ UbSystem::makeDirectory(path); ostr.open(fname.c_str(), std::ios_base::out | std::ios_base::app);} - if(!ostr) throw UbException(UB_EXARGS,"couldn't open file "+fname); - } + std::string fname = path; + ostr.open(fname.c_str(), std::ios_base::out | std::ios_base::app); + if (!ostr) { + ostr.clear(); + std::string path = UbSystem::getPathFromString(fname); + if (path.size() > 0) { + UbSystem::makeDirectory(path); + ostr.open(fname.c_str(), std::ios_base::out | std::ios_base::app); + } + if (!ostr) + throw UbException(UB_EXARGS, "couldn't open file " + fname); + } - ostr << istep << "\t" << nn1 << "\t" << nn2 << "\t"; - ostr << rho1 << "\t" << p1_1 << "\t" << rho2 << "\t" << p1_2 << "\t" << dp1 << "\t"; - //ostr << press1 << "\t" << p2_1 << "\t" << press2 << "\t" << p2_2 << "\t" << dp2; - ostr << std::endl; - ostr.close(); - } + ostr << istep << "\t" << nn1 << "\t" << nn2 << "\t"; + ostr << rho1 << "\t" << p1_1 << "\t" << rho2 << "\t" << p1_2 << "\t" << dp1 << "\t"; + // ostr << press1 << "\t" << p2_1 << "\t" << press2 << "\t" << p2_2 << "\t" << dp2; + ostr << std::endl; + ostr.close(); + } } diff --git a/src/cpu/VirtualFluidsCore/CoProcessors/PressureDifferenceCoProcessor.h b/src/cpu/VirtualFluidsCore/CoProcessors/PressureDifferenceCoProcessor.h index c3903443d199a35704fa5b34f8498e97e48da713..e805c250ba4132d2f90560bfb48e6f361b2e467a 100644 --- a/src/cpu/VirtualFluidsCore/CoProcessors/PressureDifferenceCoProcessor.h +++ b/src/cpu/VirtualFluidsCore/CoProcessors/PressureDifferenceCoProcessor.h @@ -20,25 +20,27 @@ class UbScheduler; class LBMUnitConverter; class IntegrateValuesHelper; -class PressureDifferenceCoProcessor: public CoProcessor { +class PressureDifferenceCoProcessor : public CoProcessor +{ public: - PressureDifferenceCoProcessor(SPtr<Grid3D> grid, SPtr<UbScheduler> s, const std::string& path, - SPtr<IntegrateValuesHelper> h1, SPtr<IntegrateValuesHelper> h2, - LBMReal rhoReal, LBMReal uReal, LBMReal uLB, - /*const SPtr<LBMUnitConverter> conv,*/ SPtr<Communicator> comm); - ~PressureDifferenceCoProcessor() override; + PressureDifferenceCoProcessor(SPtr<Grid3D> grid, SPtr<UbScheduler> s, const std::string &path, + SPtr<IntegrateValuesHelper> h1, SPtr<IntegrateValuesHelper> h2, LBMReal rhoReal, + LBMReal uReal, LBMReal uLB, + /*const SPtr<LBMUnitConverter> conv,*/ SPtr<Communicator> comm); + ~PressureDifferenceCoProcessor() override; - void process(double step) override; + void process(double step) override; protected: SPtr<IntegrateValuesHelper> h1, h2; - std::string path; - SPtr<LBMUnitConverter> conv; - void collectData(double step); + std::string path; + SPtr<LBMUnitConverter> conv; + void collectData(double step); SPtr<Communicator> comm; - LBMReal factor1; //= (1/3)*rhoReal*(uReal/uLB)^2 for calculation pReal = rhoLB * (1/3)*rhoReal*(uReal/uLB)^2, rhoReal and uReal in SI - LBMReal factor2; //= rhoReal*(uReal/uLB)^2 for calculation pReal = press * rhoReal*(uReal/uLB)^2, rhoReal and uReal in SI + LBMReal factor1; //= (1/3)*rhoReal*(uReal/uLB)^2 for calculation pReal = rhoLB * (1/3)*rhoReal*(uReal/uLB)^2, + //rhoReal and uReal in SI + LBMReal factor2; //= rhoReal*(uReal/uLB)^2 for calculation pReal = press * rhoReal*(uReal/uLB)^2, rhoReal and + //uReal in SI }; - #endif /* D3Q27RHODIFFERENCECoProcessor_H_ */ diff --git a/src/cpu/VirtualFluidsCore/CoProcessors/QCriterionCoProcessor.cpp b/src/cpu/VirtualFluidsCore/CoProcessors/QCriterionCoProcessor.cpp index 75801803c79bb41093ba9092c2b87026335b9837..1aaa4bf119668284c292babedb70218638201ddc 100644 --- a/src/cpu/VirtualFluidsCore/CoProcessors/QCriterionCoProcessor.cpp +++ b/src/cpu/VirtualFluidsCore/CoProcessors/QCriterionCoProcessor.cpp @@ -1,392 +1,357 @@ #include "QCriterionCoProcessor.h" -#include "LBMKernel.h" #include "BCProcessor.h" -#include "basics/writer/WbWriterVtkXmlASCII.h" +#include "Block3D.h" #include "DataSet3D.h" #include "Grid3D.h" -#include "Block3D.h" +#include "LBMKernel.h" +#include "basics/writer/WbWriterVtkXmlASCII.h" +#include "BCArray3D.h" #include "Communicator.h" #include "UbScheduler.h" -#include "BCArray3D.h" - -QCriterionCoProcessor::QCriterionCoProcessor(SPtr<Grid3D> grid, const std::string& path, - WbWriter* const writer, - SPtr<UbScheduler> s, SPtr<Communicator> comm) - : CoProcessor(grid, s), - path(path), - comm(comm), - writer(writer) +QCriterionCoProcessor::QCriterionCoProcessor(SPtr<Grid3D> grid, const std::string &path, WbWriter *const writer, + SPtr<UbScheduler> s, SPtr<Communicator> comm) + : CoProcessor(grid, s), path(path), comm(comm), writer(writer) { - init(); + init(); } ////////////////////////////////////////////////////////////////////////// void QCriterionCoProcessor::init() { - gridRank = comm->getProcessID(); - minInitLevel = this->grid->getCoarsestInitializedLevel(); - maxInitLevel = this->grid->getFinestInitializedLevel(); + gridRank = comm->getProcessID(); + minInitLevel = this->grid->getCoarsestInitializedLevel(); + maxInitLevel = this->grid->getFinestInitializedLevel(); - blockVector.resize(maxInitLevel+1); + blockVector.resize(maxInitLevel + 1); - for(int level = minInitLevel; level<=maxInitLevel;level++) - { - grid->getBlocks(level, gridRank, true, blockVector[level]); //grid: private variable in CoProcessor. Initialized by filling with blocks - } + for (int level = minInitLevel; level <= maxInitLevel; level++) { + grid->getBlocks( + level, gridRank, true, + blockVector[level]); // grid: private variable in CoProcessor. Initialized by filling with blocks + } } ////////////////////////////////////////////////////////////////////////// void QCriterionCoProcessor::process(double step) { - if(scheduler->isDue(step) ) - collectData(step); + if (scheduler->isDue(step)) + collectData(step); - UBLOG(logDEBUG3, "QCriterionCoProcessor::update:" << step); + UBLOG(logDEBUG3, "QCriterionCoProcessor::update:" << step); } ////////////////////////////////////////////////////////////////////////// void QCriterionCoProcessor::collectData(double step) { - int istep = static_cast<int>(step); - - for(int level = minInitLevel; level<=maxInitLevel;level++) - { - for(SPtr<Block3D> block : blockVector[level]) - { - if (block) - { - addData(block); - - } - } - } - - std::string partName = writer->writeOctsWithNodeData(path+ UbSystem::toString(gridRank)+ "_" + UbSystem::toString(istep),nodes,cells,datanames,data); - size_t found=partName.find_last_of("//"); - std::string piece = partName.substr(found+1); - - std::vector<std::string> cellDataNames; - - //distributed writing as in MacroscopicValuesCoProcessor.cpp - std::vector<std::string> pieces = comm->gather(piece); //comm: MPI-Wrapper - if (comm->getProcessID() == comm->getRoot()) - { - std::string pname = WbWriterVtkXmlASCII::getInstance()->writeParallelFile(path+"_"+UbSystem::toString(istep),pieces,datanames,cellDataNames); - - std::vector<std::string> filenames; - filenames.push_back(pname); - if (step == CoProcessor::scheduler->getMinBegin()) //first time in timeseries - { - WbWriterVtkXmlASCII::getInstance()->writeCollection(path+"_collection",filenames,istep,false); - } - else - { - WbWriterVtkXmlASCII::getInstance()->addFilesToCollection(path+"_collection",filenames,istep,false); - } - UBLOG(logINFO,"QCriterionCoProcessor step: " << istep); - } - - clearData(); - - + int istep = static_cast<int>(step); + + for (int level = minInitLevel; level <= maxInitLevel; level++) { + for (SPtr<Block3D> block : blockVector[level]) { + if (block) { + addData(block); + } + } + } + + std::string partName = writer->writeOctsWithNodeData( + path + UbSystem::toString(gridRank) + "_" + UbSystem::toString(istep), nodes, cells, datanames, data); + size_t found = partName.find_last_of("//"); + std::string piece = partName.substr(found + 1); + + std::vector<std::string> cellDataNames; + + // distributed writing as in MacroscopicValuesCoProcessor.cpp + std::vector<std::string> pieces = comm->gather(piece); // comm: MPI-Wrapper + if (comm->getProcessID() == comm->getRoot()) { + std::string pname = WbWriterVtkXmlASCII::getInstance()->writeParallelFile( + path + "_" + UbSystem::toString(istep), pieces, datanames, cellDataNames); + + std::vector<std::string> filenames; + filenames.push_back(pname); + if (step == CoProcessor::scheduler->getMinBegin()) // first time in timeseries + { + WbWriterVtkXmlASCII::getInstance()->writeCollection(path + "_collection", filenames, istep, false); + } else { + WbWriterVtkXmlASCII::getInstance()->addFilesToCollection(path + "_collection", filenames, istep, false); + } + UBLOG(logINFO, "QCriterionCoProcessor step: " << istep); + } + + clearData(); } ////////////////////////////////////////////////////////////////////////// void QCriterionCoProcessor::clearData() { - nodes.clear(); - cells.clear(); - datanames.clear(); - data.clear(); + nodes.clear(); + cells.clear(); + datanames.clear(); + data.clear(); } ////////////////////////////////////////////////////////////////////////// void QCriterionCoProcessor::addData(const SPtr<Block3D> block) { - UbTupleDouble3 org = grid->getBlockWorldCoordinates(block); -// UbTupleDouble3 blockLengths = grid->getBlockLengths(block); - UbTupleDouble3 nodeOffset = grid->getNodeOffset(block); - double dx = grid->getDeltaX(block); - - //Diese Daten werden geschrieben: - datanames.resize(0); - datanames.emplace_back("q"); - datanames.emplace_back("scaleFactor"); - data.resize(datanames.size()); - - - SPtr<ILBMKernel> kernel = block->getKernel(); - SPtr<BCArray3D> bcArray = kernel->getBCProcessor()->getBCArray(); - SPtr<DistributionArray3D> distributions = kernel->getDataSet()->getFdistributions(); - - unsigned int SWB,SEB,NEB,NWB,SWT,SET,NET,NWT; - - int minX1 = 0; - int minX2 = 0; - int minX3 = 0; - - int maxX1 = (int)(distributions->getNX1()); - int maxX2 = (int)(distributions->getNX2()); - int maxX3 = (int)(distributions->getNX3()); - - int currentLevel = block->getLevel(); - //nummern vergeben und node std::vector erstellen + daten sammeln - CbArray3D<int> nodeNumbers((int)maxX1, (int)maxX2, (int)maxX3,-1); - maxX1 -= 2; //-2 wegen ghost layer: - maxX2 -= 2; //0-maxXi-1 ist arraygroesse. - maxX3 -= 2; //ueberlapp 1 in +,- Richtung. zum schreiben werden statt feldern von 1 bis (max-2) felder von 0 bis max-3 verwendet! - - - int nr = (int)nodes.size(); - - for(int ix3=minX3; ix3<=maxX3; ix3++) - { - for(int ix2=minX2; ix2<=maxX2; ix2++) - { - for(int ix1=minX1; ix1<=maxX1; ix1++) - { - if(!bcArray->isUndefined(ix1,ix2,ix3) && !bcArray->isSolid(ix1,ix2,ix3)) - { - //nodeNumbers-vektor wird mit koordinaten befuellt - int index = 0; - nodeNumbers(ix1,ix2,ix3) = nr++; - nodes.push_back( makeUbTuple(float(val<1>(org) - val<1>(nodeOffset) + ix1*dx), - float(val<2>(org) - val<2>(nodeOffset) + ix2*dx), - float(val<3>(org) - val<3>(nodeOffset) + ix3*dx)) ); - - ///////////////////////////// - // Geschwindigkeitsvektoren - LBMReal vE[3]; - LBMReal vW[3]; - LBMReal vN[3]; - LBMReal vS[3]; - LBMReal vT[3]; - LBMReal vB[3]; - //hole geschwindigkeiten an nachbarknoten - getNeighborVelocities(1,0,0, ix1, ix2, ix3, block, vE, vW); - getNeighborVelocities(0,1,0, ix1, ix2, ix3, block, vN, vS); - getNeighborVelocities(0,0,1, ix1, ix2, ix3, block, vT, vB); - ////////////////////////////////// - //derivatives - LBMReal duxdy=(vN[xdir]-vS[xdir])*0.5; - LBMReal duydx=(vE[ydir]-vW[ydir])*0.5; - LBMReal duxdz=(vT[xdir]-vB[xdir])*0.5; - LBMReal duzdx=(vE[zdir]-vW[zdir])*0.5; - LBMReal duydz=(vT[ydir]-vB[ydir])*0.5; - LBMReal duzdy=(vN[zdir]-vS[zdir])*0.5; - - LBMReal duxdx=(vE[xdir]-vW[xdir])*0.5; - LBMReal duydy=(vN[ydir]-vS[ydir])*0.5; - LBMReal duzdz=(vT[zdir]-vB[zdir])*0.5; - - LBMReal scaleFactor=(double)(1<<(currentLevel-minInitLevel));//pow(2.0,(double)(currentLevel-minInitLevel));//finer grid -> current level higher. coarsest grid: currentLevel=minInitLevel=0 - // Q=-0.5*(S_ij S_ij - Omega_ij Omega_ij) => regions where vorticity is larger than strain rate - LBMReal q=-(duxdy*duydx+duxdz*duzdx+duydz*duzdy+duxdx*duxdx+duydy*duydy+duzdz*duzdz)*scaleFactor; - - data[index++].push_back( q ); - data[index++].push_back( scaleFactor ); - - } - } - } - } - maxX1 -= 1; - maxX2 -= 1; - maxX3 -= 1; - //cell vector erstellen - for(int ix3=minX3; ix3<=maxX3; ix3++) - { - for(int ix2=minX2; ix2<=maxX2; ix2++) - { - for(int ix1=minX1; ix1<=maxX1; ix1++) - { - if( (SWB=nodeNumbers( ix1 , ix2, ix3 )) >= 0 - && (SEB=nodeNumbers( ix1+1, ix2, ix3 )) >= 0 - && (NEB=nodeNumbers( ix1+1, ix2+1, ix3 )) >= 0 - && (NWB=nodeNumbers( ix1 , ix2+1, ix3 )) >= 0 - && (SWT=nodeNumbers( ix1 , ix2, ix3+1 )) >= 0 - && (SET=nodeNumbers( ix1+1, ix2, ix3+1 )) >= 0 - && (NET=nodeNumbers( ix1+1, ix2+1, ix3+1 )) >= 0 - && (NWT=nodeNumbers( ix1 , ix2+1, ix3+1 )) >= 0 ) - { - // for valid points: neighbors are added to cells-vector - cells.push_back( makeUbTuple(SWB,SEB,NEB,NWB,SWT,SET,NET,NWT) ); - } - } - } - } - + UbTupleDouble3 org = grid->getBlockWorldCoordinates(block); + // UbTupleDouble3 blockLengths = grid->getBlockLengths(block); + UbTupleDouble3 nodeOffset = grid->getNodeOffset(block); + double dx = grid->getDeltaX(block); + + // Diese Daten werden geschrieben: + datanames.resize(0); + datanames.emplace_back("q"); + datanames.emplace_back("scaleFactor"); + data.resize(datanames.size()); + + SPtr<ILBMKernel> kernel = block->getKernel(); + SPtr<BCArray3D> bcArray = kernel->getBCProcessor()->getBCArray(); + SPtr<DistributionArray3D> distributions = kernel->getDataSet()->getFdistributions(); + + unsigned int SWB, SEB, NEB, NWB, SWT, SET, NET, NWT; + + int minX1 = 0; + int minX2 = 0; + int minX3 = 0; + + int maxX1 = (int)(distributions->getNX1()); + int maxX2 = (int)(distributions->getNX2()); + int maxX3 = (int)(distributions->getNX3()); + + int currentLevel = block->getLevel(); + // nummern vergeben und node std::vector erstellen + daten sammeln + CbArray3D<int> nodeNumbers((int)maxX1, (int)maxX2, (int)maxX3, -1); + maxX1 -= 2; //-2 wegen ghost layer: + maxX2 -= 2; // 0-maxXi-1 ist arraygroesse. + maxX3 -= 2; // ueberlapp 1 in +,- Richtung. zum schreiben werden statt feldern von 1 bis (max-2) felder von 0 bis + // max-3 verwendet! + + int nr = (int)nodes.size(); + + for (int ix3 = minX3; ix3 <= maxX3; ix3++) { + for (int ix2 = minX2; ix2 <= maxX2; ix2++) { + for (int ix1 = minX1; ix1 <= maxX1; ix1++) { + if (!bcArray->isUndefined(ix1, ix2, ix3) && !bcArray->isSolid(ix1, ix2, ix3)) { + // nodeNumbers-vektor wird mit koordinaten befuellt + int index = 0; + nodeNumbers(ix1, ix2, ix3) = nr++; + nodes.push_back(makeUbTuple(float(val<1>(org) - val<1>(nodeOffset) + ix1 * dx), + float(val<2>(org) - val<2>(nodeOffset) + ix2 * dx), + float(val<3>(org) - val<3>(nodeOffset) + ix3 * dx))); + + ///////////////////////////// + // Geschwindigkeitsvektoren + LBMReal vE[3]; + LBMReal vW[3]; + LBMReal vN[3]; + LBMReal vS[3]; + LBMReal vT[3]; + LBMReal vB[3]; + // hole geschwindigkeiten an nachbarknoten + getNeighborVelocities(1, 0, 0, ix1, ix2, ix3, block, vE, vW); + getNeighborVelocities(0, 1, 0, ix1, ix2, ix3, block, vN, vS); + getNeighborVelocities(0, 0, 1, ix1, ix2, ix3, block, vT, vB); + ////////////////////////////////// + // derivatives + LBMReal duxdy = (vN[xdir] - vS[xdir]) * 0.5; + LBMReal duydx = (vE[ydir] - vW[ydir]) * 0.5; + LBMReal duxdz = (vT[xdir] - vB[xdir]) * 0.5; + LBMReal duzdx = (vE[zdir] - vW[zdir]) * 0.5; + LBMReal duydz = (vT[ydir] - vB[ydir]) * 0.5; + LBMReal duzdy = (vN[zdir] - vS[zdir]) * 0.5; + + LBMReal duxdx = (vE[xdir] - vW[xdir]) * 0.5; + LBMReal duydy = (vN[ydir] - vS[ydir]) * 0.5; + LBMReal duzdz = (vT[zdir] - vB[zdir]) * 0.5; + + LBMReal scaleFactor = + (double)(1 + << (currentLevel - + minInitLevel)); // pow(2.0,(double)(currentLevel-minInitLevel));//finer grid -> + // current level higher. coarsest grid: currentLevel=minInitLevel=0 + // Q=-0.5*(S_ij S_ij - Omega_ij Omega_ij) => regions where vorticity is larger than strain rate + LBMReal q = -(duxdy * duydx + duxdz * duzdx + duydz * duzdy + duxdx * duxdx + duydy * duydy + + duzdz * duzdz) * + scaleFactor; + + data[index++].push_back(q); + data[index++].push_back(scaleFactor); + } + } + } + } + maxX1 -= 1; + maxX2 -= 1; + maxX3 -= 1; + // cell vector erstellen + for (int ix3 = minX3; ix3 <= maxX3; ix3++) { + for (int ix2 = minX2; ix2 <= maxX2; ix2++) { + for (int ix1 = minX1; ix1 <= maxX1; ix1++) { + if ((SWB = nodeNumbers(ix1, ix2, ix3)) >= 0 && (SEB = nodeNumbers(ix1 + 1, ix2, ix3)) >= 0 && + (NEB = nodeNumbers(ix1 + 1, ix2 + 1, ix3)) >= 0 && (NWB = nodeNumbers(ix1, ix2 + 1, ix3)) >= 0 && + (SWT = nodeNumbers(ix1, ix2, ix3 + 1)) >= 0 && (SET = nodeNumbers(ix1 + 1, ix2, ix3 + 1)) >= 0 && + (NET = nodeNumbers(ix1 + 1, ix2 + 1, ix3 + 1)) >= 0 && + (NWT = nodeNumbers(ix1, ix2 + 1, ix3 + 1)) >= 0) { + // for valid points: neighbors are added to cells-vector + cells.push_back(makeUbTuple(SWB, SEB, NEB, NWB, SWT, SET, NET, NWT)); + } + } + } + } } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -void QCriterionCoProcessor::getNeighborVelocities(int offx, int offy, int offz, int ix1, int ix2, int ix3, const SPtr<Block3D> block, LBMReal* vE, LBMReal* vW) +void QCriterionCoProcessor::getNeighborVelocities(int offx, int offy, int offz, int ix1, int ix2, int ix3, + const SPtr<Block3D> block, LBMReal *vE, LBMReal *vW) { - SPtr<ILBMKernel> kernel = block->getKernel(); - SPtr<BCArray3D> bcArray = kernel->getBCProcessor()->getBCArray(); - SPtr<DistributionArray3D> distributions = kernel->getDataSet()->getFdistributions(); - - bool compressible = block->getKernel()->getCompressible(); - -// int minX1 = 0; -// int minX2 = 0; -// int minX3 = 0; - - int maxX1 = (int)(distributions->getNX1()); - int maxX2 = (int)(distributions->getNX2()); - int maxX3 = (int)(distributions->getNX3()); - if (maxX1<3) throw UbException(UB_EXARGS,"QCriterionCoProcessor: NX1 too small for FD stencils!"); - maxX1 -= 2; - maxX2 -= 2; - maxX3 -= 2; - bool checkInterpolation=true; - bool neighNodeIsBC=false; - SPtr<BoundaryConditions> bcPtr; - - int rankSelf= block->getRank(); - - if (!(offx+offy+offz)==1) // FIXME: logical not is only applied to the left hand side of this comparison - throw UbException(UB_EXARGS,"getNeighborVelocities called for diagonal directions!"); - - //////get neighbor nodes, if existent - if ((ix1==0 && offx==1) || (ix2==0 && offy==1) || (ix3==0 && offz==1)) - { - int RankNeighborW; - Vector3D orgNodeRW = grid->getNodeCoordinates(block, ix1, ix2, ix3); - double xp000= orgNodeRW[0]; - double yp000= orgNodeRW[1]; - double zp000= orgNodeRW[2]; - - int currentLevel = block->getLevel(); - UbTupleInt3 blockIndexes = grid->getBlockIndexes(xp000,yp000, zp000,currentLevel); - SPtr<Block3D> blockNeighW; - - if ((val<1>(blockIndexes)!=0 && offx==1) || (val<2>(blockIndexes)!=0 && offy==1) || (val<3>(blockIndexes)!=0 && offz==1)) - { - - blockNeighW = grid->getBlock(val<1>(blockIndexes)-offx, val<2>(blockIndexes)-offy, val<3>(blockIndexes)-offz, currentLevel); - - } - else if (offx==1 && grid->isPeriodicX1()) - { - blockNeighW = grid->getBlock((grid->getNX1()-1), val<2>(blockIndexes), val<3>(blockIndexes), currentLevel); - } - else if (offy==1 && grid->isPeriodicX1()) - { - blockNeighW = grid->getBlock(val<1>(blockIndexes),(grid->getNX2()-1), val<3>(blockIndexes), currentLevel); - } - else if (offz==1 && grid->isPeriodicX1()) - { - blockNeighW = grid->getBlock( val<1>(blockIndexes), val<2>(blockIndexes),(grid->getNX3()-1), currentLevel); - } - else neighNodeIsBC; // FIXME??? - - if(blockNeighW && blockNeighW->isActive()) - { - RankNeighborW= blockNeighW->getRank(); - } - else - { - - blockNeighW = block; - RankNeighborW= blockNeighW->getRank(); - checkInterpolation=false; - } - if (RankNeighborW!=rankSelf) - { - - blockNeighW = block; - RankNeighborW= blockNeighW->getRank(); - checkInterpolation=false; - } - - /////////////////////////////////////// - ////compute distribution at neighboring nodes from neighboring blocks - - if (!checkInterpolation || neighNodeIsBC) - { - SPtr<ILBMKernel> kernelW = blockNeighW->getKernel(); - SPtr<BCArray3D> bcArrayW = kernelW->getBCProcessor()->getBCArray(); - SPtr<DistributionArray3D> distributionsW = kernelW->getDataSet()->getFdistributions(); - LBMReal fW2[27]; - LBMReal fW[27]; - LBMReal f0[27]; - LBMReal fE[27]; - LBMReal v0[3]; - LBMReal vW2[3]; - //distributionsW->getDistribution(fW2, std::max(ix1+2*offx,1), std::max(ix2+2*offy,1), std::max(ix3+2*offz,1)); - //distributionsW->getDistribution(fW, std::max(ix1+offx,1), std::max(ix2+offy,1), std::max(ix3+offz,1)); - //distributionsW->getDistribution(f0, std::max(ix1 ,1), std::max(ix2 ,1), std::max(ix3 ,1)); - //distributions->getDistribution(fE, std::max(ix1+offx ,1), std::max(ix2+offy ,1), std::max(ix3+offz ,1)); //E:= plus 1 - distributionsW->getDistribution(fW2, std::max(ix1+2*offx,0), std::max(ix2+2*offy,0), std::max(ix3+2*offz,0)); - distributionsW->getDistribution(fW, std::max(ix1+offx,0), std::max(ix2+offy,0), std::max(ix3+offz,0)); - distributionsW->getDistribution(f0, std::max(ix1 ,0), std::max(ix2 ,0), std::max(ix3 ,0)); - distributions->getDistribution(fE, std::max(ix1+offx ,0), std::max(ix2+offy ,0), std::max(ix3+offz ,0)); //E:= plus 1 - - computeVelocity(fE,vE,compressible); - computeVelocity(fW,vW,compressible); - computeVelocity(fW2,vW2,compressible); - computeVelocity(f0,v0,compressible); - //second order non-symetric interpolation - vW[0]=v0[0]*1.5-vW[0]+0.5*vW2[0]; - vW[1]=v0[1]*1.5-vW[1]+0.5*vW2[1]; - vW[2]=v0[2]*1.5-vW[2]+0.5*vW2[2]; - //throw UbException(UB_EXARGS,"Parallel or Non-Uniform Simulation -- not yet implemented"); - } - else - { - SPtr<ILBMKernel> kernelW = blockNeighW->getKernel(); - SPtr<BCArray3D> bcArrayW = kernelW->getBCProcessor()->getBCArray(); - SPtr<DistributionArray3D> distributionsW = kernelW->getDataSet()->getFdistributions(); - LBMReal fW[27]; - - if (offx==1) - { - distributionsW->getDistribution(fW, (distributions->getNX1())-1, ix2, ix3); //moved one block backward, now get last entry - } - else if (offy==1) - { - distributionsW->getDistribution(fW, ix1,(distributions->getNX2())-1, ix3); - - } - else if (offz==1) - { - distributionsW->getDistribution(fW, ix1,ix2,distributions->getNX3()-1); - } - computeVelocity(fW,vW,compressible); - } - - - } - else - { - //data available in current block: - LBMReal fW[27]; - distributions->getDistribution(fW, ix1-offx, ix2-offy, ix3-offz); - computeVelocity(fW,vW,compressible); - - } - if (checkInterpolation) - { - //in plus-direction data is available in current block because of ghost layers - LBMReal fE[27]; - distributions->getDistribution(fE, ix1+offx, ix2+offy, ix3+offz); //E:= plus 1 - computeVelocity(fE,vE,compressible); - } + SPtr<ILBMKernel> kernel = block->getKernel(); + SPtr<BCArray3D> bcArray = kernel->getBCProcessor()->getBCArray(); + SPtr<DistributionArray3D> distributions = kernel->getDataSet()->getFdistributions(); + + bool compressible = block->getKernel()->getCompressible(); + + // int minX1 = 0; + // int minX2 = 0; + // int minX3 = 0; + + int maxX1 = (int)(distributions->getNX1()); + int maxX2 = (int)(distributions->getNX2()); + int maxX3 = (int)(distributions->getNX3()); + if (maxX1 < 3) + throw UbException(UB_EXARGS, "QCriterionCoProcessor: NX1 too small for FD stencils!"); + maxX1 -= 2; + maxX2 -= 2; + maxX3 -= 2; + bool checkInterpolation = true; + bool neighNodeIsBC = false; + SPtr<BoundaryConditions> bcPtr; + + int rankSelf = block->getRank(); + + if (!(offx + offy + offz) == 1) // FIXME: logical not is only applied to the left hand side of this comparison + throw UbException(UB_EXARGS, "getNeighborVelocities called for diagonal directions!"); + + //////get neighbor nodes, if existent + if ((ix1 == 0 && offx == 1) || (ix2 == 0 && offy == 1) || (ix3 == 0 && offz == 1)) { + int RankNeighborW; + Vector3D orgNodeRW = grid->getNodeCoordinates(block, ix1, ix2, ix3); + double xp000 = orgNodeRW[0]; + double yp000 = orgNodeRW[1]; + double zp000 = orgNodeRW[2]; + + int currentLevel = block->getLevel(); + UbTupleInt3 blockIndexes = grid->getBlockIndexes(xp000, yp000, zp000, currentLevel); + SPtr<Block3D> blockNeighW; + + if ((val<1>(blockIndexes) != 0 && offx == 1) || (val<2>(blockIndexes) != 0 && offy == 1) || + (val<3>(blockIndexes) != 0 && offz == 1)) { + + blockNeighW = grid->getBlock(val<1>(blockIndexes) - offx, val<2>(blockIndexes) - offy, + val<3>(blockIndexes) - offz, currentLevel); + + } else if (offx == 1 && grid->isPeriodicX1()) { + blockNeighW = + grid->getBlock((grid->getNX1() - 1), val<2>(blockIndexes), val<3>(blockIndexes), currentLevel); + } else if (offy == 1 && grid->isPeriodicX1()) { + blockNeighW = + grid->getBlock(val<1>(blockIndexes), (grid->getNX2() - 1), val<3>(blockIndexes), currentLevel); + } else if (offz == 1 && grid->isPeriodicX1()) { + blockNeighW = + grid->getBlock(val<1>(blockIndexes), val<2>(blockIndexes), (grid->getNX3() - 1), currentLevel); + } else + neighNodeIsBC; // FIXME??? + + if (blockNeighW && blockNeighW->isActive()) { + RankNeighborW = blockNeighW->getRank(); + } else { + + blockNeighW = block; + RankNeighborW = blockNeighW->getRank(); + checkInterpolation = false; + } + if (RankNeighborW != rankSelf) { + + blockNeighW = block; + RankNeighborW = blockNeighW->getRank(); + checkInterpolation = false; + } + + /////////////////////////////////////// + ////compute distribution at neighboring nodes from neighboring blocks + + if (!checkInterpolation || neighNodeIsBC) { + SPtr<ILBMKernel> kernelW = blockNeighW->getKernel(); + SPtr<BCArray3D> bcArrayW = kernelW->getBCProcessor()->getBCArray(); + SPtr<DistributionArray3D> distributionsW = kernelW->getDataSet()->getFdistributions(); + LBMReal fW2[27]; + LBMReal fW[27]; + LBMReal f0[27]; + LBMReal fE[27]; + LBMReal v0[3]; + LBMReal vW2[3]; + // distributionsW->getDistribution(fW2, std::max(ix1+2*offx,1), std::max(ix2+2*offy,1), + // std::max(ix3+2*offz,1)); distributionsW->getDistribution(fW, std::max(ix1+offx,1), std::max(ix2+offy,1), + // std::max(ix3+offz,1)); distributionsW->getDistribution(f0, std::max(ix1 ,1), std::max(ix2 ,1), + // std::max(ix3 ,1)); distributions->getDistribution(fE, std::max(ix1+offx ,1), std::max(ix2+offy ,1), + // std::max(ix3+offz ,1)); //E:= plus 1 + distributionsW->getDistribution(fW2, std::max(ix1 + 2 * offx, 0), std::max(ix2 + 2 * offy, 0), + std::max(ix3 + 2 * offz, 0)); + distributionsW->getDistribution(fW, std::max(ix1 + offx, 0), std::max(ix2 + offy, 0), + std::max(ix3 + offz, 0)); + distributionsW->getDistribution(f0, std::max(ix1, 0), std::max(ix2, 0), std::max(ix3, 0)); + distributions->getDistribution(fE, std::max(ix1 + offx, 0), std::max(ix2 + offy, 0), + std::max(ix3 + offz, 0)); // E:= plus 1 + + computeVelocity(fE, vE, compressible); + computeVelocity(fW, vW, compressible); + computeVelocity(fW2, vW2, compressible); + computeVelocity(f0, v0, compressible); + // second order non-symetric interpolation + vW[0] = v0[0] * 1.5 - vW[0] + 0.5 * vW2[0]; + vW[1] = v0[1] * 1.5 - vW[1] + 0.5 * vW2[1]; + vW[2] = v0[2] * 1.5 - vW[2] + 0.5 * vW2[2]; + // throw UbException(UB_EXARGS,"Parallel or Non-Uniform Simulation -- not yet implemented"); + } else { + SPtr<ILBMKernel> kernelW = blockNeighW->getKernel(); + SPtr<BCArray3D> bcArrayW = kernelW->getBCProcessor()->getBCArray(); + SPtr<DistributionArray3D> distributionsW = kernelW->getDataSet()->getFdistributions(); + LBMReal fW[27]; + + if (offx == 1) { + distributionsW->getDistribution(fW, (distributions->getNX1()) - 1, ix2, + ix3); // moved one block backward, now get last entry + } else if (offy == 1) { + distributionsW->getDistribution(fW, ix1, (distributions->getNX2()) - 1, ix3); + + } else if (offz == 1) { + distributionsW->getDistribution(fW, ix1, ix2, distributions->getNX3() - 1); + } + computeVelocity(fW, vW, compressible); + } + + } else { + // data available in current block: + LBMReal fW[27]; + distributions->getDistribution(fW, ix1 - offx, ix2 - offy, ix3 - offz); + computeVelocity(fW, vW, compressible); + } + if (checkInterpolation) { + // in plus-direction data is available in current block because of ghost layers + LBMReal fE[27]; + distributions->getDistribution(fE, ix1 + offx, ix2 + offy, ix3 + offz); // E:= plus 1 + computeVelocity(fE, vE, compressible); + } } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -void QCriterionCoProcessor::computeVelocity(LBMReal* f, LBMReal* v, bool compressible) +void QCriterionCoProcessor::computeVelocity(LBMReal *f, LBMReal *v, bool compressible) { - ////////////////////////////////////////////////////////////////////////// - //compute x,y,z-velocity components from distribution - ////////////////////////////////////////////////////////////////////////// - if (compressible) - { - v[xdir] = D3Q27System::getCompVelocityX1(f); - v[ydir] = D3Q27System::getCompVelocityX2(f); - v[zdir] = D3Q27System::getCompVelocityX3(f); - } - else - { - v[xdir] = D3Q27System::getIncompVelocityX1(f); - v[ydir] = D3Q27System::getIncompVelocityX2(f); - v[zdir] = D3Q27System::getIncompVelocityX3(f); - } + ////////////////////////////////////////////////////////////////////////// + // compute x,y,z-velocity components from distribution + ////////////////////////////////////////////////////////////////////////// + if (compressible) { + v[xdir] = D3Q27System::getCompVelocityX1(f); + v[ydir] = D3Q27System::getCompVelocityX2(f); + v[zdir] = D3Q27System::getCompVelocityX3(f); + } else { + v[xdir] = D3Q27System::getIncompVelocityX1(f); + v[ydir] = D3Q27System::getIncompVelocityX2(f); + v[zdir] = D3Q27System::getIncompVelocityX3(f); + } } diff --git a/src/cpu/VirtualFluidsCore/CoProcessors/QCriterionCoProcessor.h b/src/cpu/VirtualFluidsCore/CoProcessors/QCriterionCoProcessor.h index 506922db8e58c934b4144f561caed96a0dda2af4..0227687526a0e0f46339d3342162a26393063872 100644 --- a/src/cpu/VirtualFluidsCore/CoProcessors/QCriterionCoProcessor.h +++ b/src/cpu/VirtualFluidsCore/CoProcessors/QCriterionCoProcessor.h @@ -2,7 +2,6 @@ //! \brief Created on: 25.08.2013 //! \author: Sonja Uphoff - #ifndef QCriterionCoProcessor_H #define QCriterionCoProcessor_H @@ -20,48 +19,47 @@ class UbScheduler; class WbWriter; class Block3D; -//! \brief Computes the value Q with which vortices can be visualized as isocontours to Q=0, writes to .vtk, For uniform, serial setups only! -//! \details writes at given time intervals specified in scheduler (s) -//! Processing: paraview, take isolines of entry for Q-criterion vortex detection +//! \brief Computes the value Q with which vortices can be visualized as isocontours to Q=0, writes to .vtk, For +//! uniform, serial setups only! \details writes at given time intervals specified in scheduler (s) +//! Processing: paraview, take isolines of entry for Q-criterion vortex detection //! Q-Criterion: Visualize Vorteces as regions where Vorticity is larger than strain rate (Hunt, 1988) -//! \author Sonja Uphoff +//! \author Sonja Uphoff class QCriterionCoProcessor : public CoProcessor { public: - QCriterionCoProcessor(SPtr<Grid3D> grid, const std::string& path, WbWriter* const writer, - SPtr<UbScheduler> s, SPtr<Communicator> comm); - //! Make update if timestep is write-timestep specified in SPtr<UbScheduler> s - void process(double step) override; + QCriterionCoProcessor(SPtr<Grid3D> grid, const std::string &path, WbWriter *const writer, SPtr<UbScheduler> s, + SPtr<Communicator> comm); + //! Make update if timestep is write-timestep specified in SPtr<UbScheduler> s + void process(double step) override; protected: - //! Prepare data and write in .vtk file - void collectData(double step); - //! Q is computed for all points in a block. Data for writing is added to data and cell vectors. - void addData(const SPtr<Block3D> block); - //! After writing to .vtk-file, all vectors are reset - void clearData(); - //! Computes macroscopic velocities - void computeVelocity(LBMReal* f, LBMReal* v, bool compressible); - //! Computes average and RMS values of macroscopic quantities - void getNeighborVelocities(int offx, int offy, int offz, int ix1, int ix2, int ix3,const SPtr<Block3D> block, LBMReal* vE,LBMReal* vW); + //! Prepare data and write in .vtk file + void collectData(double step); + //! Q is computed for all points in a block. Data for writing is added to data and cell vectors. + void addData(const SPtr<Block3D> block); + //! After writing to .vtk-file, all vectors are reset + void clearData(); + //! Computes macroscopic velocities + void computeVelocity(LBMReal *f, LBMReal *v, bool compressible); + //! Computes average and RMS values of macroscopic quantities + void getNeighborVelocities(int offx, int offy, int offz, int ix1, int ix2, int ix3, const SPtr<Block3D> block, + LBMReal *vE, LBMReal *vW); private: - void init(); - std::vector<UbTupleFloat3> nodes; - std::vector<UbTupleUInt8> cells; - std::vector<std::string> datanames; //only one entry for QKrit-CoProcessor: Q - std::vector<std::vector<double> > data; - std::vector<std::vector<SPtr<Block3D> > > blockVector; - int minInitLevel; //go through all levels for block vector of current process from minInitLevel to maxInitLevel - int maxInitLevel; - int gridRank; //comm-Rank des aktuellen prozesses - std::string path; - WbWriter* writer; + void init(); + std::vector<UbTupleFloat3> nodes; + std::vector<UbTupleUInt8> cells; + std::vector<std::string> datanames; // only one entry for QKrit-CoProcessor: Q + std::vector<std::vector<double>> data; + std::vector<std::vector<SPtr<Block3D>>> blockVector; + int minInitLevel; // go through all levels for block vector of current process from minInitLevel to maxInitLevel + int maxInitLevel; + int gridRank; // comm-Rank des aktuellen prozesses + std::string path; + WbWriter *writer; SPtr<Communicator> comm; - enum Values{xdir = 0, ydir = 1, zdir = 2}; //labels for the different components + enum Values { xdir = 0, ydir = 1, zdir = 2 }; // labels for the different components }; #endif - - diff --git a/src/cpu/VirtualFluidsCore/CoProcessors/ShearStressCoProcessor.cpp b/src/cpu/VirtualFluidsCore/CoProcessors/ShearStressCoProcessor.cpp index 5487936b53f3b370198e60e076527e749c499d43..3b546a702726fca63d23f72dc0b04545ad544525 100644 --- a/src/cpu/VirtualFluidsCore/CoProcessors/ShearStressCoProcessor.cpp +++ b/src/cpu/VirtualFluidsCore/CoProcessors/ShearStressCoProcessor.cpp @@ -2,699 +2,940 @@ #include "BCProcessor.h" #include "WbWriterVtkXmlASCII.h" +#include "BCArray3D.h" #include "Block3D.h" -#include "DataSet3D.h" -#include "LBMKernel.h" #include "Communicator.h" #include "D3Q27Interactor.h" -#include "UbScheduler.h" -#include "BCArray3D.h" -#include "InterpolationProcessor.h" +#include "DataSet3D.h" #include "Grid3D.h" +#include "InterpolationProcessor.h" +#include "LBMKernel.h" +#include "UbScheduler.h" -ShearStressCoProcessor::ShearStressCoProcessor(SPtr<Grid3D> grid, const std::string& path, - WbWriter* const writer, - SPtr<UbScheduler> s,SPtr<UbScheduler> rs) - : CoProcessor(grid, s), - Resetscheduler(rs), - path(path), - writer(writer) +ShearStressCoProcessor::ShearStressCoProcessor(SPtr<Grid3D> grid, const std::string &path, WbWriter *const writer, + SPtr<UbScheduler> s, SPtr<UbScheduler> rs) + : CoProcessor(grid, s), Resetscheduler(rs), path(path), writer(writer) { - SPtr<Communicator> comm = Communicator::getInstance(); - normals.push_back(0); - normals.push_back(0); - normals.push_back(1); - gridRank = grid->getRank(); - minInitLevel = this->grid->getCoarsestInitializedLevel(); - maxInitLevel = this->grid->getFinestInitializedLevel(); - - blockVector.resize(maxInitLevel+1); - for(int level = minInitLevel; level<=maxInitLevel;level++) - { - grid->getBlocks(level, gridRank, true, blockVector[level]); - for(SPtr<Block3D> block : blockVector[level]) - { - UbTupleInt3 nx = grid->getBlockNX(); - SPtr<ShearStressValuesArray3D> shearStressValues = SPtr<ShearStressValuesArray3D>(new ShearStressValuesArray3D(14, val<1>(nx)+1, val<2>(nx)+1, val<3>(nx)+1, 0.0)); - block->getKernel()->getDataSet()->setShearStressValues(shearStressValues); - } - } + SPtr<Communicator> comm = Communicator::getInstance(); + normals.push_back(0); + normals.push_back(0); + normals.push_back(1); + gridRank = grid->getRank(); + minInitLevel = this->grid->getCoarsestInitializedLevel(); + maxInitLevel = this->grid->getFinestInitializedLevel(); + + blockVector.resize(maxInitLevel + 1); + for (int level = minInitLevel; level <= maxInitLevel; level++) { + grid->getBlocks(level, gridRank, true, blockVector[level]); + for (SPtr<Block3D> block : blockVector[level]) { + UbTupleInt3 nx = grid->getBlockNX(); + SPtr<ShearStressValuesArray3D> shearStressValues = SPtr<ShearStressValuesArray3D>( + new ShearStressValuesArray3D(14, val<1>(nx) + 1, val<2>(nx) + 1, val<3>(nx) + 1, 0.0)); + block->getKernel()->getDataSet()->setShearStressValues(shearStressValues); + } + } } ////////////////////////////////////////////////////////////////////////// -ShearStressCoProcessor::~ShearStressCoProcessor() -= default; +ShearStressCoProcessor::~ShearStressCoProcessor() = default; ////////////////////////////////////////////////////////////////////////// -void ShearStressCoProcessor::process( double step ) +void ShearStressCoProcessor::process(double step) { - if (step==0) - { - initDistance(); - } - calculateShearStress(step); - if(scheduler->isDue(step) ) - collectData(step); - UBLOG(logDEBUG3, "D3Q27ShearStressCoProcessor::update:" << step); + if (step == 0) { + initDistance(); + } + calculateShearStress(step); + if (scheduler->isDue(step)) + collectData(step); + UBLOG(logDEBUG3, "D3Q27ShearStressCoProcessor::update:" << step); } ////////////////////////////////////////////////////////////////////////// void ShearStressCoProcessor::collectData(double step) { - using namespace std; - - int istep = int(step); - addData(); - - //string partName = writer->writeNodesWithNodeData(path+ UbSystem::toString(gridRank)+ "_" + UbSystem::toString(istep),nodes,datanames,data); - //size_t found=partName.find_last_of("//"); - //string piece = partName.substr(found+1); - - //vector<string> cellDataNames; - - //SPtr<Communicator> comm = Communicator::getInstance(); - //vector<string> pieces = comm->gatherStrings(piece); - //if (comm->getProcessID() == comm->getRoot()) - //{ - // string pname = WbWriterVtkXmlASCII::getInstance()->writeParallelFile(path+"_"+UbSystem::toString(istep),pieces,datanames,cellDataNames); - - // vector<string> filenames; - // filenames.push_back(pname); - // if (step == CoProcessor::scheduler->getMinBegin()) - // { - // WbWriterVtkXmlASCII::getInstance()->writeCollection(path+"__Shear_collection",filenames,istep,false); - // } - // else - // { - // WbWriterVtkXmlASCII::getInstance()->addFilesToCollection(path+"__Shear_collection",filenames,istep,false); - // } - // UBLOG(logINFO,"D3Q27ShearStressCoProcessor step: " << istep); - //} - - string pfilePath, partPath, subfolder, cfilePath; - subfolder = "shs"+UbSystem::toString(istep); - pfilePath = path+"/shs/"+subfolder; - cfilePath = path+"/shs/shs_collection"; - partPath = pfilePath+"/shs"+UbSystem::toString(gridRank)+ "_" + UbSystem::toString(istep); - - string partName = writer->writeNodesWithNodeData(partPath,nodes,datanames,data); - size_t found=partName.find_last_of("/"); - string piece = partName.substr(found+1); - piece = subfolder + "/" + piece; - - vector<string> cellDataNames; - SPtr<Communicator> comm = Communicator::getInstance(); - vector<string> pieces = comm->gather(piece); - if (comm->getProcessID() == comm->getRoot()) - { - string pname = WbWriterVtkXmlASCII::getInstance()->writeParallelFile(pfilePath,pieces,datanames,cellDataNames); - found=pname.find_last_of("/"); - piece = pname.substr(found+1); - - vector<string> filenames; - filenames.push_back(piece); - if (step == CoProcessor::scheduler->getMinBegin()) - { - WbWriterVtkXmlASCII::getInstance()->writeCollection(cfilePath,filenames,istep,false); - } - else - { - WbWriterVtkXmlASCII::getInstance()->addFilesToCollection(cfilePath,filenames,istep,false); - } - UBLOG(logINFO,"D3Q27ShearStressCoProcessor step: " << istep); - } - - clearData(); + using namespace std; + + int istep = int(step); + addData(); + + // string partName = writer->writeNodesWithNodeData(path+ UbSystem::toString(gridRank)+ "_" + + // UbSystem::toString(istep),nodes,datanames,data); size_t found=partName.find_last_of("//"); string piece = + // partName.substr(found+1); + + // vector<string> cellDataNames; + + // SPtr<Communicator> comm = Communicator::getInstance(); + // vector<string> pieces = comm->gatherStrings(piece); + // if (comm->getProcessID() == comm->getRoot()) + //{ + // string pname = + // WbWriterVtkXmlASCII::getInstance()->writeParallelFile(path+"_"+UbSystem::toString(istep),pieces,datanames,cellDataNames); + + // vector<string> filenames; + // filenames.push_back(pname); + // if (step == CoProcessor::scheduler->getMinBegin()) + // { + // WbWriterVtkXmlASCII::getInstance()->writeCollection(path+"__Shear_collection",filenames,istep,false); + // } + // else + // { + // WbWriterVtkXmlASCII::getInstance()->addFilesToCollection(path+"__Shear_collection",filenames,istep,false); + // } + // UBLOG(logINFO,"D3Q27ShearStressCoProcessor step: " << istep); + //} + + string pfilePath, partPath, subfolder, cfilePath; + subfolder = "shs" + UbSystem::toString(istep); + pfilePath = path + "/shs/" + subfolder; + cfilePath = path + "/shs/shs_collection"; + partPath = pfilePath + "/shs" + UbSystem::toString(gridRank) + "_" + UbSystem::toString(istep); + + string partName = writer->writeNodesWithNodeData(partPath, nodes, datanames, data); + size_t found = partName.find_last_of("/"); + string piece = partName.substr(found + 1); + piece = subfolder + "/" + piece; + + vector<string> cellDataNames; + SPtr<Communicator> comm = Communicator::getInstance(); + vector<string> pieces = comm->gather(piece); + if (comm->getProcessID() == comm->getRoot()) { + string pname = + WbWriterVtkXmlASCII::getInstance()->writeParallelFile(pfilePath, pieces, datanames, cellDataNames); + found = pname.find_last_of("/"); + piece = pname.substr(found + 1); + + vector<string> filenames; + filenames.push_back(piece); + if (step == CoProcessor::scheduler->getMinBegin()) { + WbWriterVtkXmlASCII::getInstance()->writeCollection(cfilePath, filenames, istep, false); + } else { + WbWriterVtkXmlASCII::getInstance()->addFilesToCollection(cfilePath, filenames, istep, false); + } + UBLOG(logINFO, "D3Q27ShearStressCoProcessor step: " << istep); + } + + clearData(); } ////////////////////////////////////////////////////////////////////////// void ShearStressCoProcessor::clearData() { - nodes.clear(); - datanames.clear(); - data.clear(); + nodes.clear(); + datanames.clear(); + data.clear(); } ////////////////////////////////////////////////////////////////////////// void ShearStressCoProcessor::calculateShearStress(double timeStep) { - using namespace D3Q27System; - - LBMReal f[27]; - LBMReal vx, vy, vz, sxx, syy, szz, sxy, syz, sxz; - - for(SPtr<D3Q27Interactor> interactor : interactors) - { - typedef std::map<SPtr<Block3D>, std::set< std::vector<int> > > TransNodeIndicesMap; - for(TransNodeIndicesMap::value_type t : interactor->getBcNodeIndicesMap()) - { - SPtr<Block3D> block = t.first; - std::set< std::vector<int> >& transNodeIndicesSet = t.second; - - SPtr<ILBMKernel> kernel = block->getKernel(); - SPtr<BCArray3D> bcArray = kernel->getBCProcessor()->getBCArray(); - SPtr<DistributionArray3D> distributions = kernel->getDataSet()->getFdistributions(); - SPtr<ShearStressValuesArray3D> ssv = kernel->getDataSet()->getShearStressValues(); - - int ghostLayer = kernel->getGhostLayerWidth(); - LBMReal collFactor = kernel->getCollisionFactor(); - - int minX1 = ghostLayer; - int maxX1 = (int)bcArray->getNX1() - 1 - ghostLayer; - int minX2 = ghostLayer; - int maxX2 = (int)bcArray->getNX2() - 1 - ghostLayer; - int minX3 = ghostLayer; - int maxX3 = (int)bcArray->getNX3() - 1 - ghostLayer; - - for(std::vector<int> node : transNodeIndicesSet) - { - int ix1 = node[0]; - int ix2 = node[1]; - int ix3 = node[2]; - - //without ghost nodes - if (ix1 < minX1 || ix1 > maxX1 || ix2 < minX2 || ix2 > maxX2 ||ix3 < minX3 || ix3 > maxX3 ) continue; - - if(bcArray->isFluid(ix1,ix2,ix3)) - { - double q=(*ssv)(normalq,ix1,ix2,ix3) ; - double numPoint=(*ssv)(numberOfPoint,ix1,ix2,ix3) ; - if (q==0||numPoint!=3)continue; - // if (q==0)continue; - ////////////////////////////////////////////////////////////////////////// - //read distribution - //////////////////////////////////////////////////////////////////////////// - distributions->getDistribution(f, ix1, ix2, ix3); - ////////////////////////////////////////////////////////////////////////// - //compute velocity - ////////////////////////////////////////////////////////////////////////// - vx = ((((f[TNE]-f[BSW]) + (f[TSE]-f[BNW])) + ((f[BSE]-f[TNW]) + (f[BNE]-f[TSW]))) + - (((f[BE]-f[TW]) + (f[TE]-f[BW])) + ((f[SE]-f[NW]) + (f[NE]-f[SW]))) + - (f[E]-f[W])); - - vy = ((((f[TNE]-f[BSW]) + (f[BNW]-f[TSE])) + ((f[TNW]-f[BSE]) + (f[BNE]-f[TSW]))) + - (((f[BN]-f[TS]) + (f[TN]-f[BS])) + ((f[NW]-f[SE]) + (f[NE]-f[SW]))) + - (f[N]-f[S])); - - vz = ((((f[TNE]-f[BSW]) + (f[TSE]-f[BNW])) + ((f[TNW]-f[BSE]) + (f[TSW]-f[BNE]))) + - (((f[TS]-f[BN]) + (f[TN]-f[BS])) + ((f[TW]-f[BE]) + (f[TE]-f[BW]))) + - (f[T]-f[B])); - - - sxy = 3.0 * collFactor/(collFactor - 1.0)* ( ((f[TNE] + f[BSW])-(f[TSE]+f[BNW]))+(-(f[BSE]+f[TNW])+ (f[TSW]+f[BNE])) - +(((f[NE] + f[SW]) - (f[SE] + f[NW]))) -vx*vy); - - sxz = 3.0 * collFactor/(collFactor-1.0)*(((f[TNE] + f[BSW])+(f[TSE]+f[BNW]))+(-(f[BSE]+f[TNW])- (f[TSW]+f[BNE])) - +((f[TE] + f[BW])-(f[BE]+ f[TW])) -vx*vz); - - syz = 3.0 * collFactor/(collFactor-1.0)*(((f[TNE] + f[BSW])-(f[TSE]+f[BNW]))+((f[BSE]+f[TNW])- (f[TSW]+f[BNE])) - +(-(f[BN] + f[TS]) + (f[TN] + f[BS])) -vy*vz); - - LBMReal dxxMyy =3.0/2.0 * collFactor/(collFactor-1.0)* (((f[TE] + f[BW])+(f[BE]+ f[TW])) - -((f[BN] + f[TS]) + (f[TN] + f[BS]))+((f[E] + f[W])-(f[N] + f[S]))-vx*vx+vy*vy); - - LBMReal dxxMzz =3.0/2.0 * collFactor/(collFactor-1.0)*((((f[NE] + f[SW]) + (f[SE] + f[NW])) - -((f[BN] + f[TS]) + (f[TN] + f[BS])))+((f[E] + f[W])-(f[T] + f[B])) -vx*vx +vz*vz); - - // LBMReal dyyMzz =3.0/2.0 *collFactor/(collFactor-1.0)*((((f[NE] + f[SW]) + (f[SE] + f[NW]))-((f[TE] + f[BW])+(f[BE]+ f[TW]))) - // +((f[N] + f[S])-(f[T] + f[B])) -vy*vy +vz*vz); - - sxx=(dxxMyy+dxxMzz)/3.0; // weil dxxPyyPzz=0 - - syy=(dxxMzz-2*dxxMyy)/3.0; - - szz=(dxxMyy-2*dxxMzz)/3.0; - - ////////////////////////////////////////////////////////////////////////// - //compute average values - ////////////////////////////////////////////////////////////////////////// - (*ssv)(AvVx,ix1,ix2,ix3) = ((*ssv)(AvVx,ix1,ix2,ix3)*timeStep + vx)/(timeStep+1.0); - (*ssv)(AvVy,ix1,ix2,ix3) = ((*ssv)(AvVy,ix1,ix2,ix3)*timeStep + vy)/(timeStep+1.0); - (*ssv)(AvVz,ix1,ix2,ix3) = ((*ssv)(AvVz,ix1,ix2,ix3)*timeStep + vz)/(timeStep+1.0); - - (*ssv)(AvSxx,ix1,ix2,ix3) = ((*ssv)(AvSxx,ix1,ix2,ix3)*timeStep + sxx)/(timeStep+1.0); - (*ssv)(AvSyy,ix1,ix2,ix3) = ((*ssv)(AvSyy,ix1,ix2,ix3)*timeStep + syy)/(timeStep+1.0); - (*ssv)(AvSzz,ix1,ix2,ix3) = ((*ssv)(AvSzz,ix1,ix2,ix3)*timeStep + szz)/(timeStep+1.0); - (*ssv)(AvSxy,ix1,ix2,ix3) = ((*ssv)(AvSxy,ix1,ix2,ix3)*timeStep + sxy)/(timeStep+1.0); - (*ssv)(AvSyz,ix1,ix2,ix3) = ((*ssv)(AvSyz,ix1,ix2,ix3)*timeStep + syz)/(timeStep+1.0); - (*ssv)(AvSxz,ix1,ix2,ix3) = ((*ssv)(AvSxz,ix1,ix2,ix3)*timeStep + sxz)/(timeStep+1.0); + using namespace D3Q27System; + + LBMReal f[27]; + LBMReal vx, vy, vz, sxx, syy, szz, sxy, syz, sxz; + + for (SPtr<D3Q27Interactor> interactor : interactors) { + typedef std::map<SPtr<Block3D>, std::set<std::vector<int>>> TransNodeIndicesMap; + for (TransNodeIndicesMap::value_type t : interactor->getBcNodeIndicesMap()) { + SPtr<Block3D> block = t.first; + std::set<std::vector<int>> &transNodeIndicesSet = t.second; + + SPtr<ILBMKernel> kernel = block->getKernel(); + SPtr<BCArray3D> bcArray = kernel->getBCProcessor()->getBCArray(); + SPtr<DistributionArray3D> distributions = kernel->getDataSet()->getFdistributions(); + SPtr<ShearStressValuesArray3D> ssv = kernel->getDataSet()->getShearStressValues(); + + int ghostLayer = kernel->getGhostLayerWidth(); + LBMReal collFactor = kernel->getCollisionFactor(); + + int minX1 = ghostLayer; + int maxX1 = (int)bcArray->getNX1() - 1 - ghostLayer; + int minX2 = ghostLayer; + int maxX2 = (int)bcArray->getNX2() - 1 - ghostLayer; + int minX3 = ghostLayer; + int maxX3 = (int)bcArray->getNX3() - 1 - ghostLayer; + + for (std::vector<int> node : transNodeIndicesSet) { + int ix1 = node[0]; + int ix2 = node[1]; + int ix3 = node[2]; + + // without ghost nodes + if (ix1 < minX1 || ix1 > maxX1 || ix2 < minX2 || ix2 > maxX2 || ix3 < minX3 || ix3 > maxX3) + continue; + + if (bcArray->isFluid(ix1, ix2, ix3)) { + double q = (*ssv)(normalq, ix1, ix2, ix3); + double numPoint = (*ssv)(numberOfPoint, ix1, ix2, ix3); + if (q == 0 || numPoint != 3) + continue; + // if (q==0)continue; + ////////////////////////////////////////////////////////////////////////// + // read distribution + //////////////////////////////////////////////////////////////////////////// + distributions->getDistribution(f, ix1, ix2, ix3); + ////////////////////////////////////////////////////////////////////////// + // compute velocity + ////////////////////////////////////////////////////////////////////////// + vx = ((((f[TNE] - f[BSW]) + (f[TSE] - f[BNW])) + ((f[BSE] - f[TNW]) + (f[BNE] - f[TSW]))) + + (((f[BE] - f[TW]) + (f[TE] - f[BW])) + ((f[SE] - f[NW]) + (f[NE] - f[SW]))) + (f[E] - f[W])); + + vy = ((((f[TNE] - f[BSW]) + (f[BNW] - f[TSE])) + ((f[TNW] - f[BSE]) + (f[BNE] - f[TSW]))) + + (((f[BN] - f[TS]) + (f[TN] - f[BS])) + ((f[NW] - f[SE]) + (f[NE] - f[SW]))) + (f[N] - f[S])); + + vz = ((((f[TNE] - f[BSW]) + (f[TSE] - f[BNW])) + ((f[TNW] - f[BSE]) + (f[TSW] - f[BNE]))) + + (((f[TS] - f[BN]) + (f[TN] - f[BS])) + ((f[TW] - f[BE]) + (f[TE] - f[BW]))) + (f[T] - f[B])); + + sxy = 3.0 * collFactor / (collFactor - 1.0) * + (((f[TNE] + f[BSW]) - (f[TSE] + f[BNW])) + (-(f[BSE] + f[TNW]) + (f[TSW] + f[BNE])) + + (((f[NE] + f[SW]) - (f[SE] + f[NW]))) - vx * vy); + + sxz = 3.0 * collFactor / (collFactor - 1.0) * + (((f[TNE] + f[BSW]) + (f[TSE] + f[BNW])) + (-(f[BSE] + f[TNW]) - (f[TSW] + f[BNE])) + + ((f[TE] + f[BW]) - (f[BE] + f[TW])) - vx * vz); + + syz = 3.0 * collFactor / (collFactor - 1.0) * + (((f[TNE] + f[BSW]) - (f[TSE] + f[BNW])) + ((f[BSE] + f[TNW]) - (f[TSW] + f[BNE])) + + (-(f[BN] + f[TS]) + (f[TN] + f[BS])) - vy * vz); + + LBMReal dxxMyy = 3.0 / 2.0 * collFactor / (collFactor - 1.0) * + (((f[TE] + f[BW]) + (f[BE] + f[TW])) - ((f[BN] + f[TS]) + (f[TN] + f[BS])) + + ((f[E] + f[W]) - (f[N] + f[S])) - vx * vx + vy * vy); + + LBMReal dxxMzz = 3.0 / 2.0 * collFactor / (collFactor - 1.0) * + ((((f[NE] + f[SW]) + (f[SE] + f[NW])) - ((f[BN] + f[TS]) + (f[TN] + f[BS]))) + + ((f[E] + f[W]) - (f[T] + f[B])) - vx * vx + vz * vz); + + // LBMReal dyyMzz =3.0/2.0 *collFactor/(collFactor-1.0)*((((f[NE] + f[SW]) + (f[SE] + + // f[NW]))-((f[TE] + f[BW])+(f[BE]+ f[TW]))) + // +((f[N] + f[S])-(f[T] + f[B])) -vy*vy +vz*vz); + + sxx = (dxxMyy + dxxMzz) / 3.0; // weil dxxPyyPzz=0 + + syy = (dxxMzz - 2 * dxxMyy) / 3.0; + + szz = (dxxMyy - 2 * dxxMzz) / 3.0; + + ////////////////////////////////////////////////////////////////////////// + // compute average values + ////////////////////////////////////////////////////////////////////////// + (*ssv)(AvVx, ix1, ix2, ix3) = ((*ssv)(AvVx, ix1, ix2, ix3) * timeStep + vx) / (timeStep + 1.0); + (*ssv)(AvVy, ix1, ix2, ix3) = ((*ssv)(AvVy, ix1, ix2, ix3) * timeStep + vy) / (timeStep + 1.0); + (*ssv)(AvVz, ix1, ix2, ix3) = ((*ssv)(AvVz, ix1, ix2, ix3) * timeStep + vz) / (timeStep + 1.0); + + (*ssv)(AvSxx, ix1, ix2, ix3) = ((*ssv)(AvSxx, ix1, ix2, ix3) * timeStep + sxx) / (timeStep + 1.0); + (*ssv)(AvSyy, ix1, ix2, ix3) = ((*ssv)(AvSyy, ix1, ix2, ix3) * timeStep + syy) / (timeStep + 1.0); + (*ssv)(AvSzz, ix1, ix2, ix3) = ((*ssv)(AvSzz, ix1, ix2, ix3) * timeStep + szz) / (timeStep + 1.0); + (*ssv)(AvSxy, ix1, ix2, ix3) = ((*ssv)(AvSxy, ix1, ix2, ix3) * timeStep + sxy) / (timeStep + 1.0); + (*ssv)(AvSyz, ix1, ix2, ix3) = ((*ssv)(AvSyz, ix1, ix2, ix3) * timeStep + syz) / (timeStep + 1.0); + (*ssv)(AvSxz, ix1, ix2, ix3) = ((*ssv)(AvSxz, ix1, ix2, ix3) * timeStep + sxz) / (timeStep + 1.0); + } } - } - - } - } + } + } } ////////////////////////////////////////////////////////////////////////// void ShearStressCoProcessor::addData() { - //Diese Daten werden geschrieben: - datanames.resize(0); - datanames.emplace_back("y^plus"); - datanames.emplace_back("u_tau"); - //datanames.push_back("yPlusFD"); - - data.resize(datanames.size()); - - for(const auto& interactor : interactors) - { - using TransNodeIndicesMap = std::map<SPtr<Block3D>, std::set<std::vector<int> > >; - for(TransNodeIndicesMap::value_type t : interactor->getBcNodeIndicesMap()) - { - SPtr<Block3D> block = t.first; - std::set< std::vector<int> >& transNodeIndicesSet = t.second; - - UbTupleDouble3 org = grid->getBlockWorldCoordinates(block); -// UbTupleDouble3 blockLengths = grid->getBlockLengths(block); - UbTupleDouble3 nodeOffset = grid->getNodeOffset(block); - double dx = grid->getDeltaX(block); - - SPtr<ILBMKernel> kernel = block->getKernel(); - SPtr<BCArray3D> bcArray = kernel->getBCProcessor()->getBCArray(); - SPtr<DistributionArray3D> distributions = kernel->getDataSet()->getFdistributions(); - SPtr<ShearStressValuesArray3D> ssv = kernel->getDataSet()->getShearStressValues(); - - int ghostLayer = kernel->getGhostLayerWidth(); - LBMReal collFactor = kernel->getCollisionFactor(); - - int minX1 = ghostLayer; - int maxX1 = (int)bcArray->getNX1() - 1 - ghostLayer; - int minX2 = ghostLayer; - int maxX2 = (int)bcArray->getNX2() - 1 - ghostLayer; - int minX3 = ghostLayer; - int maxX3 = (int)bcArray->getNX3() - 1 - ghostLayer; - -// int level=block->getLevel(); -// if(level==1) -// { -// int le=0; -// } - for(std::vector<int> node : transNodeIndicesSet) - { - int ix1 = node[0]; - int ix2 = node[1]; - int ix3 = node[2]; - - //without ghost nodes - if (ix1 < minX1 || ix1 > maxX1 || ix2 < minX2 || ix2 > maxX2 ||ix3 < minX3 || ix3 > maxX3 ) continue; - - if(bcArray->isFluid(ix1,ix2,ix3)) - { - double q=(*ssv)(normalq,ix1,ix2,ix3) ; - double numPoint=(*ssv)(numberOfPoint,ix1,ix2,ix3) ; - if (q==0||numPoint!=3)continue; - // if (q==0)continue; - - int index = 0; - nodes.push_back( makeUbTuple(float(val<1>(org) - val<1>(nodeOffset) + ix1*dx), - float(val<2>(org) - val<2>(nodeOffset) + ix2*dx), - float(val<3>(org) - val<3>(nodeOffset) + ix3*dx)) ); - - //////get normal and distance////// - double A,B,C; - A= (*ssv)(normalX1,ix1,ix2,ix3) ; - B= (*ssv)(normalX2,ix1,ix2,ix3) ; - C= (*ssv)(normalX3,ix1,ix2,ix3) ; - - /////////// - //compute y plus - //double vtxSonja, vtySonja, vtzSonja; //tangent velocity - // double temp = (*av)(ix1,ix2,ix3,AvVx)*A+(*av)(ix1,ix2,ix3,AvVy)*B+(*av)(ix1,ix2,ix3,AvVz)*C; - // vtxSonja = (*av)(ix1,ix2,ix3,AvVx)-normals[0]*temp; - // vtySonja = (*av)(ix1,ix2,ix3,AvVy)-normals[1]*temp; - // vtzSonja = (*av)(ix1,ix2,ix3,AvVz)-normals[2]*temp; - - double vtx= (B*B*(*ssv)(AvVx,ix1,ix2,ix3) + C*C*(*ssv)(AvVx,ix1,ix2,ix3) - A*B*(*ssv)(AvVy,ix1,ix2,ix3) - A*C*(*ssv)(AvVy,ix1,ix2,ix3))/(A*A+B*B+C*C); - double vty=(-(A*B*(*ssv)(AvVx,ix1,ix2,ix3)) + A*A*(*ssv)(AvVy,ix1,ix2,ix3) + C*C*(*ssv)(AvVy,ix1,ix2,ix3) - B*C*(*ssv)(AvVz,ix1,ix2,ix3))/(A*A+B*B+C*C); - double vtz=(-(A*C*(*ssv)(AvVx,ix1,ix2,ix3)) - B*C*(*ssv)(AvVy,ix1,ix2,ix3) + A*A*(*ssv)(AvVz,ix1,ix2,ix3) + B*B*(*ssv)(AvVz,ix1,ix2,ix3))/(A*A+B*B+C*C); - - double normVt = sqrt(vtx*vtx+vty*vty+vtz*vtz)+1e-100; - double nvtx = vtx / normVt; - double nvty = vty / normVt; - double nvtz = vtz / normVt; - - double sx=0.5*((*ssv)(AvSxx,ix1,ix2,ix3)*nvtx+(*ssv)(AvSxy,ix1,ix2,ix3)*nvty+(*ssv)(AvSxz,ix1,ix2,ix3)*nvtz); - double sy=0.5*((*ssv)(AvSxy,ix1,ix2,ix3)*nvtx+(*ssv)(AvSyy,ix1,ix2,ix3)*nvty+(*ssv)(AvSyz,ix1,ix2,ix3)*nvtz); - double sz=0.5*((*ssv)(AvSxz,ix1,ix2,ix3)*nvtx+(*ssv)(AvSyz,ix1,ix2,ix3)*nvty+(*ssv)(AvSzz,ix1,ix2,ix3)*nvtz); - double sabs=sqrt(sx*sx+sy*sy+sz*sz); - - double viscosity = (1.0/3.0)*(1.0/collFactor-0.5); - double rho = 1.0; - double utau=sqrt(viscosity/rho*sabs); - - // double q=(*av)(ix1,ix2,ix3,normalq) ; - double yPlus = (utau*q)/viscosity; - - data[index++].push_back(yPlus); - data[index++].push_back(utau); + // Diese Daten werden geschrieben: + datanames.resize(0); + datanames.emplace_back("y^plus"); + datanames.emplace_back("u_tau"); + // datanames.push_back("yPlusFD"); + + data.resize(datanames.size()); + + for (const auto &interactor : interactors) { + using TransNodeIndicesMap = std::map<SPtr<Block3D>, std::set<std::vector<int>>>; + for (TransNodeIndicesMap::value_type t : interactor->getBcNodeIndicesMap()) { + SPtr<Block3D> block = t.first; + std::set<std::vector<int>> &transNodeIndicesSet = t.second; + + UbTupleDouble3 org = grid->getBlockWorldCoordinates(block); + // UbTupleDouble3 blockLengths = grid->getBlockLengths(block); + UbTupleDouble3 nodeOffset = grid->getNodeOffset(block); + double dx = grid->getDeltaX(block); + + SPtr<ILBMKernel> kernel = block->getKernel(); + SPtr<BCArray3D> bcArray = kernel->getBCProcessor()->getBCArray(); + SPtr<DistributionArray3D> distributions = kernel->getDataSet()->getFdistributions(); + SPtr<ShearStressValuesArray3D> ssv = kernel->getDataSet()->getShearStressValues(); + + int ghostLayer = kernel->getGhostLayerWidth(); + LBMReal collFactor = kernel->getCollisionFactor(); + + int minX1 = ghostLayer; + int maxX1 = (int)bcArray->getNX1() - 1 - ghostLayer; + int minX2 = ghostLayer; + int maxX2 = (int)bcArray->getNX2() - 1 - ghostLayer; + int minX3 = ghostLayer; + int maxX3 = (int)bcArray->getNX3() - 1 - ghostLayer; + + // int level=block->getLevel(); + // if(level==1) + // { + // int le=0; + // } + for (std::vector<int> node : transNodeIndicesSet) { + int ix1 = node[0]; + int ix2 = node[1]; + int ix3 = node[2]; + + // without ghost nodes + if (ix1 < minX1 || ix1 > maxX1 || ix2 < minX2 || ix2 > maxX2 || ix3 < minX3 || ix3 > maxX3) + continue; + + if (bcArray->isFluid(ix1, ix2, ix3)) { + double q = (*ssv)(normalq, ix1, ix2, ix3); + double numPoint = (*ssv)(numberOfPoint, ix1, ix2, ix3); + if (q == 0 || numPoint != 3) + continue; + // if (q==0)continue; + + int index = 0; + nodes.push_back(makeUbTuple(float(val<1>(org) - val<1>(nodeOffset) + ix1 * dx), + float(val<2>(org) - val<2>(nodeOffset) + ix2 * dx), + float(val<3>(org) - val<3>(nodeOffset) + ix3 * dx))); + + //////get normal and distance////// + double A, B, C; + A = (*ssv)(normalX1, ix1, ix2, ix3); + B = (*ssv)(normalX2, ix1, ix2, ix3); + C = (*ssv)(normalX3, ix1, ix2, ix3); + + /////////// + // compute y plus + // double vtxSonja, vtySonja, vtzSonja; //tangent velocity + // double temp = (*av)(ix1,ix2,ix3,AvVx)*A+(*av)(ix1,ix2,ix3,AvVy)*B+(*av)(ix1,ix2,ix3,AvVz)*C; + // vtxSonja = (*av)(ix1,ix2,ix3,AvVx)-normals[0]*temp; + // vtySonja = (*av)(ix1,ix2,ix3,AvVy)-normals[1]*temp; + // vtzSonja = (*av)(ix1,ix2,ix3,AvVz)-normals[2]*temp; + + double vtx = (B * B * (*ssv)(AvVx, ix1, ix2, ix3) + C * C * (*ssv)(AvVx, ix1, ix2, ix3) - + A * B * (*ssv)(AvVy, ix1, ix2, ix3) - A * C * (*ssv)(AvVy, ix1, ix2, ix3)) / + (A * A + B * B + C * C); + double vty = (-(A * B * (*ssv)(AvVx, ix1, ix2, ix3)) + A * A * (*ssv)(AvVy, ix1, ix2, ix3) + + C * C * (*ssv)(AvVy, ix1, ix2, ix3) - B * C * (*ssv)(AvVz, ix1, ix2, ix3)) / + (A * A + B * B + C * C); + double vtz = (-(A * C * (*ssv)(AvVx, ix1, ix2, ix3)) - B * C * (*ssv)(AvVy, ix1, ix2, ix3) + + A * A * (*ssv)(AvVz, ix1, ix2, ix3) + B * B * (*ssv)(AvVz, ix1, ix2, ix3)) / + (A * A + B * B + C * C); + + double normVt = sqrt(vtx * vtx + vty * vty + vtz * vtz) + 1e-100; + double nvtx = vtx / normVt; + double nvty = vty / normVt; + double nvtz = vtz / normVt; + + double sx = 0.5 * ((*ssv)(AvSxx, ix1, ix2, ix3) * nvtx + (*ssv)(AvSxy, ix1, ix2, ix3) * nvty + + (*ssv)(AvSxz, ix1, ix2, ix3) * nvtz); + double sy = 0.5 * ((*ssv)(AvSxy, ix1, ix2, ix3) * nvtx + (*ssv)(AvSyy, ix1, ix2, ix3) * nvty + + (*ssv)(AvSyz, ix1, ix2, ix3) * nvtz); + double sz = 0.5 * ((*ssv)(AvSxz, ix1, ix2, ix3) * nvtx + (*ssv)(AvSyz, ix1, ix2, ix3) * nvty + + (*ssv)(AvSzz, ix1, ix2, ix3) * nvtz); + double sabs = sqrt(sx * sx + sy * sy + sz * sz); + + double viscosity = (1.0 / 3.0) * (1.0 / collFactor - 0.5); + double rho = 1.0; + double utau = sqrt(viscosity / rho * sabs); + + // double q=(*av)(ix1,ix2,ix3,normalq) ; + double yPlus = (utau * q) / viscosity; + + data[index++].push_back(yPlus); + data[index++].push_back(utau); + } } - } - } - } - + } + } } ////////////////////////////////////////////////////////////////////////// void ShearStressCoProcessor::reset(double step) { - if(Resetscheduler->isDue(step) ) - resetData(step); + if (Resetscheduler->isDue(step)) + resetData(step); - UBLOG(logDEBUG3, "resetCoProcessor::update:" << step); + UBLOG(logDEBUG3, "resetCoProcessor::update:" << step); } ////////////////////////////////////////////////////////////////////////// -void ShearStressCoProcessor::resetData(double /*step*/) +void ShearStressCoProcessor::resetData(double /*step*/) { - for(int level = minInitLevel; level<=maxInitLevel;level++) - { - for(const auto& block : blockVector[level]) - { - if (block) - { -// UbTupleDouble3 org = grid->getBlockWorldCoordinates(block); -// UbTupleDouble3 blockLengths = grid->getBlockLengths(block); -// UbTupleDouble3 nodeOffset = grid->getNodeOffset(block); -// double dx = grid->getDeltaX(block); - - SPtr<ILBMKernel> kernel = block->getKernel(); - SPtr<BCArray3D> bcArray = kernel->getBCProcessor()->getBCArray(); - SPtr<DistributionArray3D> distributions = kernel->getDataSet()->getFdistributions(); - SPtr<ShearStressValuesArray3D> ssv = kernel->getDataSet()->getShearStressValues(); - - int minX1 = 0; - int minX2 = 0; - int minX3 = 0; - - int maxX1 = int(distributions->getNX1()); - int maxX2 = int(distributions->getNX2()); - int maxX3 = int(distributions->getNX3()); - - for(int ix3=minX3; ix3<maxX3-1; ix3++) - { - for(int ix2=minX2; ix2<maxX2-1; ix2++) - { - for(int ix1=minX1; ix1<maxX1-1; ix1++) - { - if(!bcArray->isUndefined(ix1,ix2,ix3) && !bcArray->isSolid(ix1,ix2,ix3)) - { - ////////////////////////////////////////////////////////////////////////// - //compute average values - ////////////////////////////////////////////////////////////////////////// - (*ssv)(AvVx,ix1,ix2,ix3) = 0.0; - (*ssv)(AvVy,ix1,ix2,ix3) = 0.0; - (*ssv)(AvVz,ix1,ix2,ix3) = 0.0; - - (*ssv)(AvSxx,ix1,ix2,ix3) = 0.0; - (*ssv)(AvSyy,ix1,ix2,ix3) = 0.0; - (*ssv)(AvSzz,ix1,ix2,ix3) = 0.0; - (*ssv)(AvSxy,ix1,ix2,ix3) = 0.0; - (*ssv)(AvSyz,ix1,ix2,ix3) = 0.0; - (*ssv)(AvSxz,ix1,ix2,ix3) = 0.0; - ////////////////////////////////////////////////////////////////////////// - } - } - } + for (int level = minInitLevel; level <= maxInitLevel; level++) { + for (const auto &block : blockVector[level]) { + if (block) { + // UbTupleDouble3 org = grid->getBlockWorldCoordinates(block); + // UbTupleDouble3 blockLengths = grid->getBlockLengths(block); + // UbTupleDouble3 nodeOffset = grid->getNodeOffset(block); + // double dx = grid->getDeltaX(block); + + SPtr<ILBMKernel> kernel = block->getKernel(); + SPtr<BCArray3D> bcArray = kernel->getBCProcessor()->getBCArray(); + SPtr<DistributionArray3D> distributions = kernel->getDataSet()->getFdistributions(); + SPtr<ShearStressValuesArray3D> ssv = kernel->getDataSet()->getShearStressValues(); + + int minX1 = 0; + int minX2 = 0; + int minX3 = 0; + + int maxX1 = int(distributions->getNX1()); + int maxX2 = int(distributions->getNX2()); + int maxX3 = int(distributions->getNX3()); + + for (int ix3 = minX3; ix3 < maxX3 - 1; ix3++) { + for (int ix2 = minX2; ix2 < maxX2 - 1; ix2++) { + for (int ix1 = minX1; ix1 < maxX1 - 1; ix1++) { + if (!bcArray->isUndefined(ix1, ix2, ix3) && !bcArray->isSolid(ix1, ix2, ix3)) { + ////////////////////////////////////////////////////////////////////////// + // compute average values + ////////////////////////////////////////////////////////////////////////// + (*ssv)(AvVx, ix1, ix2, ix3) = 0.0; + (*ssv)(AvVy, ix1, ix2, ix3) = 0.0; + (*ssv)(AvVz, ix1, ix2, ix3) = 0.0; + + (*ssv)(AvSxx, ix1, ix2, ix3) = 0.0; + (*ssv)(AvSyy, ix1, ix2, ix3) = 0.0; + (*ssv)(AvSzz, ix1, ix2, ix3) = 0.0; + (*ssv)(AvSxy, ix1, ix2, ix3) = 0.0; + (*ssv)(AvSyz, ix1, ix2, ix3) = 0.0; + (*ssv)(AvSxz, ix1, ix2, ix3) = 0.0; + ////////////////////////////////////////////////////////////////////////// + } + } + } + } } - } - } - } + } + } } ////////////////////////////////////////////////////////////////////////// -void ShearStressCoProcessor::addInteractor( SPtr<D3Q27Interactor> interactor ) -{ - interactors.push_back(interactor); -} +void ShearStressCoProcessor::addInteractor(SPtr<D3Q27Interactor> interactor) { interactors.push_back(interactor); } ////////////////////////////////////////////////////////////////////////// -void ShearStressCoProcessor::findPlane(int ix1,int ix2,int ix3,SPtr<Grid3D> grid,SPtr<Block3D> block,double &A,double &B,double &C,double &D,double &ii) +void ShearStressCoProcessor::findPlane(int ix1, int ix2, int ix3, SPtr<Grid3D> grid, SPtr<Block3D> block, double &A, + double &B, double &C, double &D, double &ii) { - double x1plane=0.0,y1plane=0.0,z1plane=0.0; - double x2plane=0.0,y2plane=0.0,z2plane=0.0; - double x3plane=0.0,y3plane=0.0,z3plane=0.0; - SPtr<BoundaryConditions> bcPtr; - double dx = grid->getDeltaX(block); - SPtr<ILBMKernel> kernel = block->getKernel(); - SPtr<DistributionArray3D> distributions = kernel->getDataSet()->getFdistributions(); - SPtr<BCArray3D> bcArray = kernel->getBCProcessor()->getBCArray(); - bcPtr=bcArray->getBC(ix1,ix2,ix3); - int x,y,z; - - - if(InterpolationProcessor::iCellHasSolid(bcArray, ix1, ix2, ix3)) { x = ix1;y = ix2;z = ix3;} - else if(InterpolationProcessor::iCellHasSolid(bcArray, ix1 , ix2-1, ix3 )) { x = ix1+0; y = ix2-1; z = ix3+0;}//S - else if(InterpolationProcessor::iCellHasSolid(bcArray, ix1 , ix2 , ix3-1)) { x = ix1+0; y = ix2+0; z = ix3-1;}//B - else if(InterpolationProcessor::iCellHasSolid(bcArray, ix1-1, ix2 , ix3 )) { x = ix1-1; y = ix2+0; z = ix3+0;}//w - else if(InterpolationProcessor::iCellHasSolid(bcArray, ix1 , ix2-1, ix3-1)) { x = ix1+0; y = ix2-1; z = ix3-1;}//BS - else if(InterpolationProcessor::iCellHasSolid(bcArray, ix1-1, ix2 , ix3-1)) { x = ix1-1; y = ix2+0; z = ix3-1;}//BW - else if(InterpolationProcessor::iCellHasSolid(bcArray, ix1-1, ix2-1, ix3 )) { x = ix1-1; y = ix2-1; z = ix3+0;}//SW - - else if(InterpolationProcessor::iCellHasSolid(bcArray, ix1-1, ix2-1, ix3-1)) { x = ix1-1; y = ix2-1; z = ix3-1;}//BSW - else if(InterpolationProcessor::iCellHasSolid(bcArray, ix1+1, ix2 , ix3 )) { x = ix1+1; y = ix2+0; z = ix3+0;}//E - else if(InterpolationProcessor::iCellHasSolid(bcArray, ix1 , ix2+1, ix3 )) { x = ix1+0; y = ix2+1; z = ix3+0;}//N - else if(InterpolationProcessor::iCellHasSolid(bcArray, ix1 , ix2 , ix3+1)) { x = ix1+0; y = ix2+0; z = ix3+1;}//T - else if(InterpolationProcessor::iCellHasSolid(bcArray, ix1+1, ix2+1, ix3 )) { x = ix1+1; y = ix2+1; z = ix3+0;}//NE - else if(InterpolationProcessor::iCellHasSolid(bcArray, ix1+1, ix2 , ix3+1)) { x = ix1+1; y = ix2+0; z = ix3+1;}//TE - else if(InterpolationProcessor::iCellHasSolid(bcArray, ix1 , ix2+1, ix3+1)) { x = ix1+0; y = ix2+1; z = ix3+1;}//TN - else if(InterpolationProcessor::iCellHasSolid(bcArray, ix1+1, ix2+1, ix3+1)) { x = ix1+1; y = ix2+1; z = ix3+1;}//TNE - - else if(InterpolationProcessor::iCellHasSolid(bcArray, ix1+1, ix2-1, ix3 )) { x = ix1+1; y = ix2-1; z = ix3+0;}//SE - else if(InterpolationProcessor::iCellHasSolid(bcArray, ix1-1, ix2+1, ix3 )) { x = ix1-1; y = ix2+1; z = ix3+0;}//NW - else if(InterpolationProcessor::iCellHasSolid(bcArray, ix1+1, ix2 , ix3-1)) { x = ix1+1; y = ix2+0; z = ix3-1;}//BE - else if(InterpolationProcessor::iCellHasSolid(bcArray, ix1-1, ix2 , ix3+1)) { x = ix1-1; y = ix2+0; z = ix3+1;}//TW - else if(InterpolationProcessor::iCellHasSolid(bcArray, ix1+0, ix2+1, ix3-1)) { x = ix1+0; y = ix2+1; z = ix3-1;}//BN - else if(InterpolationProcessor::iCellHasSolid(bcArray, ix1+0, ix2-1, ix3+1)) { x = ix1+0; y = ix2-1; z = ix3+1;}//TS - - else if(InterpolationProcessor::iCellHasSolid(bcArray, ix1-1, ix2+1, ix3+1)) { x = ix1-1; y = ix2+1; z = ix3+1;}//TNW - else if(InterpolationProcessor::iCellHasSolid(bcArray, ix1+1, ix2-1, ix3+1)) { x = ix1+1; y = ix2-1; z = ix3+1;}//TSE - else if(InterpolationProcessor::iCellHasSolid(bcArray, ix1-1, ix2-1, ix3+1)) { x = ix1-1; y = ix2-1; z = ix3+1;}//TSW - else if(InterpolationProcessor::iCellHasSolid(bcArray, ix1+1, ix2+1, ix3-1)) { x = ix1+1; y = ix2+1; z = ix3-1;}//BNE - else if(InterpolationProcessor::iCellHasSolid(bcArray, ix1-1, ix2+1, ix3-1)) { x = ix1-1; y = ix2+1; z = ix3-1;}//BNW - else if(InterpolationProcessor::iCellHasSolid(bcArray, ix1+1, ix2-1, ix3-1)) { x = ix1+1; y = ix2-1; z = ix3-1;}//BSE - - - else {{UB_THROW( UbException(UB_EXARGS,"there is no cell ix1="+UbSystem::toString(ix1)+"ix2="+UbSystem::toString(ix2)+"ix3="+UbSystem::toString(ix3)+"GlobalID="+UbSystem::toString(block->getGlobalID())+"dx="+UbSystem::toString(dx) - +"T="+UbSystem::toString(bcPtr->getQ(D3Q27System::T))+"B="+UbSystem::toString(bcPtr->getQ(D3Q27System::B)) - +"E="+UbSystem::toString(bcPtr->getQ(D3Q27System::E))+"W="+UbSystem::toString(bcPtr->getQ(D3Q27System::W))+"N="+UbSystem::toString(bcPtr->getQ(D3Q27System::N)) - +"S="+UbSystem::toString(bcPtr->getQ(D3Q27System::S))+"NE="+UbSystem::toString(bcPtr->getQ(D3Q27System::NE))+"SW="+UbSystem::toString(bcPtr->getQ(D3Q27System::SW)) - +"SE="+UbSystem::toString(bcPtr->getQ(D3Q27System::SE))+"NW="+UbSystem::toString(bcPtr->getQ(D3Q27System::NW)) - +"TE="+ - UbSystem::toString(bcPtr->getQ(D3Q27System::TE))+"BW="+UbSystem::toString(bcPtr->getQ(D3Q27System::BW))+"BE="+UbSystem::toString(bcPtr->getQ(D3Q27System::BE))+"TW="+ - UbSystem::toString(bcPtr->getQ(D3Q27System::TW))+"TN="+UbSystem::toString(bcPtr->getQ(D3Q27System::TN))+"BS="+UbSystem::toString(bcPtr->getQ(D3Q27System::BS))+"BN="+ - UbSystem::toString(bcPtr->getQ(D3Q27System::BN))+"TS="+UbSystem::toString(bcPtr->getQ(D3Q27System::TS))+"TNE="+UbSystem::toString(bcPtr->getQ(D3Q27System::TNE))+"TNW="+ - UbSystem::toString(bcPtr->getQ(D3Q27System::TNW))+"TSE="+UbSystem::toString(bcPtr->getQ(D3Q27System::TSE))+"TSW="+UbSystem::toString(bcPtr->getQ(D3Q27System::TSW))+"BNE="+ - UbSystem::toString(bcPtr->getQ(D3Q27System::BNE))+"BNW="+UbSystem::toString(bcPtr->getQ(D3Q27System::BNW))+"BSE="+UbSystem::toString(bcPtr->getQ(D3Q27System::BSE))+"BSW="+UbSystem::toString(bcPtr->getQ(D3Q27System::BSW)*dx) - ) ) ;}} - - - if(InterpolationProcessor::iCellHasSolid(bcArray, x, y, z)) - { - for(int i = x; i <= x + 1; i++){ - for(int j = y; j <= y + 1; j++){ - for (int k = z; k <= z + 1; k++) - { - Vector3D pointplane1 = grid->getNodeCoordinates(block, i, j, k); - - double iph=pointplane1[0]; - double jph=pointplane1[1]; - double kph=pointplane1[2]; - - if(!bcArray->isSolid(i, j, k)) - { - SPtr<BoundaryConditions> bcPtrIn=bcArray->getBC(i,j,k); - if(bcPtrIn) - { - for(int fdir=D3Q27System::FSTARTDIR; fdir<=D3Q27System::FENDDIR; fdir++) - { - if( ii<=2) - { - LBMReal q = bcPtrIn->getQ(fdir); - if (q!=999.00000) - { - if ( fdir==D3Q27System::E ) - { - //if(!bcArray->isSolid(i, j, k))continue; - if (i+q<=x+1) - { - if (ii==0) { x1plane=iph+q*dx; y1plane=jph; z1plane=kph; ii++; } - else if (ii==1) { x2plane=iph+q*dx; y2plane=jph; z2plane=kph; if (x1plane!=x2plane||y1plane!=y2plane||z1plane!=z2plane) ii++; } - else if(ii==2) { x3plane=iph+q*dx; y3plane=jph; z3plane=kph; if ((x3plane!=x1plane||y3plane!=y1plane||z3plane!=z1plane)&&(x2plane!=x3plane||y2plane!=y3plane||z2plane!=z3plane)) ii++;} - } - } - if ( fdir==D3Q27System::W ) - { - //if(!bcArray->isSolid(i, j, k))continue; - if (i-q>=x) - { - if (ii==0) { x1plane=iph-q*dx; y1plane=jph; z1plane=kph; ii++; } - else if (ii==1) { x2plane=iph-q*dx; y2plane=jph; z2plane=kph; if (x1plane!=x2plane||y1plane!=y2plane||z1plane!=z2plane) ii++; } - else if(ii==2) { x3plane=iph-q*dx; y3plane=jph; z3plane=kph; if ((x3plane!=x1plane||y3plane!=y1plane||z3plane!=z1plane)&&(x2plane!=x3plane||y2plane!=y3plane||z2plane!=z3plane)) ii++;} - } - } - if ( fdir==D3Q27System::N ) - { - //if(!bcArray->isSolid(i, j, k))continue; - if(j+q<=y+1) - { - if (ii==0) { x1plane=iph; y1plane=jph+q*dx; z1plane=kph; ii++; } - else if (ii==1) { x2plane=iph; y2plane=jph+q*dx; z2plane=kph; if (x1plane!=x2plane||y1plane!=y2plane||z1plane!=z2plane) ii++; } - else if (ii==2) { x3plane=iph; y3plane=jph+q*dx; z3plane=kph; if ((x3plane!=x1plane||y3plane!=y1plane||z3plane!=z1plane)&&(x2plane!=x3plane||y2plane!=y3plane||z2plane!=z3plane)) ii++;} - } - } - if ( fdir==D3Q27System::S ) - { - //if(!bcArray->isSolid(i, j, k))continue; - if (j-q>=y) - { - if (ii==0) { x1plane=iph; y1plane=jph-q*dx; z1plane=kph; ii++; } - else if (ii==1) { x2plane=iph; y2plane=jph-q*dx; z2plane=kph; if (x1plane!=x2plane||y1plane!=y2plane||z1plane!=z2plane) ii++; } - else if (ii==2) { x3plane=iph; y3plane=jph-q*dx; z3plane=kph; if ((x3plane!=x1plane||y3plane!=y1plane||z3plane!=z1plane)&&(x2plane!=x3plane||y2plane!=y3plane||z2plane!=z3plane)) ii++;} - } - } - - if ( fdir==D3Q27System::T ) - { - //if(!bcArray->isSolid(i, j, k))continue; - if(k+q<=z+1) - { - if (ii==0) { x1plane=iph; y1plane=jph; z1plane=kph+q*dx; ii++; } - else if (ii==1) { x2plane=iph; y2plane=jph; z2plane=kph+q*dx; if (x1plane!=x2plane||y1plane!=y2plane||z1plane!=z2plane) ii++; } - else if (ii==2) { x3plane=iph; y3plane=jph; z3plane=kph+q*dx; if ((x3plane!=x1plane||y3plane!=y1plane||z3plane!=z1plane)&&(x2plane!=x3plane||y2plane!=y3plane||z2plane!=z3plane)) ii++;} - } - } - if ( fdir==D3Q27System::B ) - { - //if(!bcArray->isSolid(i, j, k))continue; - if (k-q>=z) - { - if (ii==0) { x1plane=iph; y1plane=jph; z1plane=kph-q*dx; ii++; } - else if (ii==1) { x2plane=iph; y2plane=jph; z2plane=kph-q*dx; if (x1plane!=x2plane||y1plane!=y2plane||z1plane!=z2plane) ii++; } - else if (ii==2) { x3plane=iph; y3plane=jph; z3plane=kph-q*dx; if ((x3plane!=x1plane||y3plane!=y1plane||z3plane!=z1plane)&&(x2plane!=x3plane||y2plane!=y3plane||z2plane!=z3plane)) ii++;} - } - } - - } + double x1plane = 0.0, y1plane = 0.0, z1plane = 0.0; + double x2plane = 0.0, y2plane = 0.0, z2plane = 0.0; + double x3plane = 0.0, y3plane = 0.0, z3plane = 0.0; + SPtr<BoundaryConditions> bcPtr; + double dx = grid->getDeltaX(block); + SPtr<ILBMKernel> kernel = block->getKernel(); + SPtr<DistributionArray3D> distributions = kernel->getDataSet()->getFdistributions(); + SPtr<BCArray3D> bcArray = kernel->getBCProcessor()->getBCArray(); + bcPtr = bcArray->getBC(ix1, ix2, ix3); + int x, y, z; + + if (InterpolationProcessor::iCellHasSolid(bcArray, ix1, ix2, ix3)) { + x = ix1; + y = ix2; + z = ix3; + } else if (InterpolationProcessor::iCellHasSolid(bcArray, ix1, ix2 - 1, ix3)) { + x = ix1 + 0; + y = ix2 - 1; + z = ix3 + 0; + } // S + else if (InterpolationProcessor::iCellHasSolid(bcArray, ix1, ix2, ix3 - 1)) { + x = ix1 + 0; + y = ix2 + 0; + z = ix3 - 1; + } // B + else if (InterpolationProcessor::iCellHasSolid(bcArray, ix1 - 1, ix2, ix3)) { + x = ix1 - 1; + y = ix2 + 0; + z = ix3 + 0; + } // w + else if (InterpolationProcessor::iCellHasSolid(bcArray, ix1, ix2 - 1, ix3 - 1)) { + x = ix1 + 0; + y = ix2 - 1; + z = ix3 - 1; + } // BS + else if (InterpolationProcessor::iCellHasSolid(bcArray, ix1 - 1, ix2, ix3 - 1)) { + x = ix1 - 1; + y = ix2 + 0; + z = ix3 - 1; + } // BW + else if (InterpolationProcessor::iCellHasSolid(bcArray, ix1 - 1, ix2 - 1, ix3)) { + x = ix1 - 1; + y = ix2 - 1; + z = ix3 + 0; + } // SW + + else if (InterpolationProcessor::iCellHasSolid(bcArray, ix1 - 1, ix2 - 1, ix3 - 1)) { + x = ix1 - 1; + y = ix2 - 1; + z = ix3 - 1; + } // BSW + else if (InterpolationProcessor::iCellHasSolid(bcArray, ix1 + 1, ix2, ix3)) { + x = ix1 + 1; + y = ix2 + 0; + z = ix3 + 0; + } // E + else if (InterpolationProcessor::iCellHasSolid(bcArray, ix1, ix2 + 1, ix3)) { + x = ix1 + 0; + y = ix2 + 1; + z = ix3 + 0; + } // N + else if (InterpolationProcessor::iCellHasSolid(bcArray, ix1, ix2, ix3 + 1)) { + x = ix1 + 0; + y = ix2 + 0; + z = ix3 + 1; + } // T + else if (InterpolationProcessor::iCellHasSolid(bcArray, ix1 + 1, ix2 + 1, ix3)) { + x = ix1 + 1; + y = ix2 + 1; + z = ix3 + 0; + } // NE + else if (InterpolationProcessor::iCellHasSolid(bcArray, ix1 + 1, ix2, ix3 + 1)) { + x = ix1 + 1; + y = ix2 + 0; + z = ix3 + 1; + } // TE + else if (InterpolationProcessor::iCellHasSolid(bcArray, ix1, ix2 + 1, ix3 + 1)) { + x = ix1 + 0; + y = ix2 + 1; + z = ix3 + 1; + } // TN + else if (InterpolationProcessor::iCellHasSolid(bcArray, ix1 + 1, ix2 + 1, ix3 + 1)) { + x = ix1 + 1; + y = ix2 + 1; + z = ix3 + 1; + } // TNE + + else if (InterpolationProcessor::iCellHasSolid(bcArray, ix1 + 1, ix2 - 1, ix3)) { + x = ix1 + 1; + y = ix2 - 1; + z = ix3 + 0; + } // SE + else if (InterpolationProcessor::iCellHasSolid(bcArray, ix1 - 1, ix2 + 1, ix3)) { + x = ix1 - 1; + y = ix2 + 1; + z = ix3 + 0; + } // NW + else if (InterpolationProcessor::iCellHasSolid(bcArray, ix1 + 1, ix2, ix3 - 1)) { + x = ix1 + 1; + y = ix2 + 0; + z = ix3 - 1; + } // BE + else if (InterpolationProcessor::iCellHasSolid(bcArray, ix1 - 1, ix2, ix3 + 1)) { + x = ix1 - 1; + y = ix2 + 0; + z = ix3 + 1; + } // TW + else if (InterpolationProcessor::iCellHasSolid(bcArray, ix1 + 0, ix2 + 1, ix3 - 1)) { + x = ix1 + 0; + y = ix2 + 1; + z = ix3 - 1; + } // BN + else if (InterpolationProcessor::iCellHasSolid(bcArray, ix1 + 0, ix2 - 1, ix3 + 1)) { + x = ix1 + 0; + y = ix2 - 1; + z = ix3 + 1; + } // TS + + else if (InterpolationProcessor::iCellHasSolid(bcArray, ix1 - 1, ix2 + 1, ix3 + 1)) { + x = ix1 - 1; + y = ix2 + 1; + z = ix3 + 1; + } // TNW + else if (InterpolationProcessor::iCellHasSolid(bcArray, ix1 + 1, ix2 - 1, ix3 + 1)) { + x = ix1 + 1; + y = ix2 - 1; + z = ix3 + 1; + } // TSE + else if (InterpolationProcessor::iCellHasSolid(bcArray, ix1 - 1, ix2 - 1, ix3 + 1)) { + x = ix1 - 1; + y = ix2 - 1; + z = ix3 + 1; + } // TSW + else if (InterpolationProcessor::iCellHasSolid(bcArray, ix1 + 1, ix2 + 1, ix3 - 1)) { + x = ix1 + 1; + y = ix2 + 1; + z = ix3 - 1; + } // BNE + else if (InterpolationProcessor::iCellHasSolid(bcArray, ix1 - 1, ix2 + 1, ix3 - 1)) { + x = ix1 - 1; + y = ix2 + 1; + z = ix3 - 1; + } // BNW + else if (InterpolationProcessor::iCellHasSolid(bcArray, ix1 + 1, ix2 - 1, ix3 - 1)) { + x = ix1 + 1; + y = ix2 - 1; + z = ix3 - 1; + } // BSE + + else { + { + UB_THROW(UbException(UB_EXARGS, "there is no cell ix1=" + UbSystem::toString(ix1) + + "ix2=" + UbSystem::toString(ix2) + "ix3=" + UbSystem::toString(ix3) + + "GlobalID=" + UbSystem::toString(block->getGlobalID()) + + "dx=" + UbSystem::toString(dx) + + "T=" + UbSystem::toString(bcPtr->getQ(D3Q27System::T)) + + "B=" + UbSystem::toString(bcPtr->getQ(D3Q27System::B)) + + "E=" + UbSystem::toString(bcPtr->getQ(D3Q27System::E)) + + "W=" + UbSystem::toString(bcPtr->getQ(D3Q27System::W)) + + "N=" + UbSystem::toString(bcPtr->getQ(D3Q27System::N)) + + "S=" + UbSystem::toString(bcPtr->getQ(D3Q27System::S)) + + "NE=" + UbSystem::toString(bcPtr->getQ(D3Q27System::NE)) + + "SW=" + UbSystem::toString(bcPtr->getQ(D3Q27System::SW)) + + "SE=" + UbSystem::toString(bcPtr->getQ(D3Q27System::SE)) + + "NW=" + UbSystem::toString(bcPtr->getQ(D3Q27System::NW)) + + "TE=" + UbSystem::toString(bcPtr->getQ(D3Q27System::TE)) + + "BW=" + UbSystem::toString(bcPtr->getQ(D3Q27System::BW)) + + "BE=" + UbSystem::toString(bcPtr->getQ(D3Q27System::BE)) + + "TW=" + UbSystem::toString(bcPtr->getQ(D3Q27System::TW)) + + "TN=" + UbSystem::toString(bcPtr->getQ(D3Q27System::TN)) + + "BS=" + UbSystem::toString(bcPtr->getQ(D3Q27System::BS)) + + "BN=" + UbSystem::toString(bcPtr->getQ(D3Q27System::BN)) + + "TS=" + UbSystem::toString(bcPtr->getQ(D3Q27System::TS)) + + "TNE=" + UbSystem::toString(bcPtr->getQ(D3Q27System::TNE)) + + "TNW=" + UbSystem::toString(bcPtr->getQ(D3Q27System::TNW)) + + "TSE=" + UbSystem::toString(bcPtr->getQ(D3Q27System::TSE)) + + "TSW=" + UbSystem::toString(bcPtr->getQ(D3Q27System::TSW)) + + "BNE=" + UbSystem::toString(bcPtr->getQ(D3Q27System::BNE)) + + "BNW=" + UbSystem::toString(bcPtr->getQ(D3Q27System::BNW)) + + "BSE=" + UbSystem::toString(bcPtr->getQ(D3Q27System::BSE)) + + "BSW=" + UbSystem::toString(bcPtr->getQ(D3Q27System::BSW) * dx))); + } + } + + if (InterpolationProcessor::iCellHasSolid(bcArray, x, y, z)) { + for (int i = x; i <= x + 1; i++) { + for (int j = y; j <= y + 1; j++) { + for (int k = z; k <= z + 1; k++) { + Vector3D pointplane1 = grid->getNodeCoordinates(block, i, j, k); + + double iph = pointplane1[0]; + double jph = pointplane1[1]; + double kph = pointplane1[2]; + + if (!bcArray->isSolid(i, j, k)) { + SPtr<BoundaryConditions> bcPtrIn = bcArray->getBC(i, j, k); + if (bcPtrIn) { + for (int fdir = D3Q27System::FSTARTDIR; fdir <= D3Q27System::FENDDIR; fdir++) { + if (ii <= 2) { + LBMReal q = bcPtrIn->getQ(fdir); + if (q != 999.00000) { + if (fdir == D3Q27System::E) { + // if(!bcArray->isSolid(i, j, k))continue; + if (i + q <= x + 1) { + if (ii == 0) { + x1plane = iph + q * dx; + y1plane = jph; + z1plane = kph; + ii++; + } else if (ii == 1) { + x2plane = iph + q * dx; + y2plane = jph; + z2plane = kph; + if (x1plane != x2plane || y1plane != y2plane || z1plane != z2plane) + ii++; + } else if (ii == 2) { + x3plane = iph + q * dx; + y3plane = jph; + z3plane = kph; + if ((x3plane != x1plane || y3plane != y1plane || + z3plane != z1plane) && + (x2plane != x3plane || y2plane != y3plane || + z2plane != z3plane)) + ii++; + } + } + } + if (fdir == D3Q27System::W) { + // if(!bcArray->isSolid(i, j, k))continue; + if (i - q >= x) { + if (ii == 0) { + x1plane = iph - q * dx; + y1plane = jph; + z1plane = kph; + ii++; + } else if (ii == 1) { + x2plane = iph - q * dx; + y2plane = jph; + z2plane = kph; + if (x1plane != x2plane || y1plane != y2plane || z1plane != z2plane) + ii++; + } else if (ii == 2) { + x3plane = iph - q * dx; + y3plane = jph; + z3plane = kph; + if ((x3plane != x1plane || y3plane != y1plane || + z3plane != z1plane) && + (x2plane != x3plane || y2plane != y3plane || + z2plane != z3plane)) + ii++; + } + } + } + if (fdir == D3Q27System::N) { + // if(!bcArray->isSolid(i, j, k))continue; + if (j + q <= y + 1) { + if (ii == 0) { + x1plane = iph; + y1plane = jph + q * dx; + z1plane = kph; + ii++; + } else if (ii == 1) { + x2plane = iph; + y2plane = jph + q * dx; + z2plane = kph; + if (x1plane != x2plane || y1plane != y2plane || z1plane != z2plane) + ii++; + } else if (ii == 2) { + x3plane = iph; + y3plane = jph + q * dx; + z3plane = kph; + if ((x3plane != x1plane || y3plane != y1plane || + z3plane != z1plane) && + (x2plane != x3plane || y2plane != y3plane || + z2plane != z3plane)) + ii++; + } + } + } + if (fdir == D3Q27System::S) { + // if(!bcArray->isSolid(i, j, k))continue; + if (j - q >= y) { + if (ii == 0) { + x1plane = iph; + y1plane = jph - q * dx; + z1plane = kph; + ii++; + } else if (ii == 1) { + x2plane = iph; + y2plane = jph - q * dx; + z2plane = kph; + if (x1plane != x2plane || y1plane != y2plane || z1plane != z2plane) + ii++; + } else if (ii == 2) { + x3plane = iph; + y3plane = jph - q * dx; + z3plane = kph; + if ((x3plane != x1plane || y3plane != y1plane || + z3plane != z1plane) && + (x2plane != x3plane || y2plane != y3plane || + z2plane != z3plane)) + ii++; + } + } + } + + if (fdir == D3Q27System::T) { + // if(!bcArray->isSolid(i, j, k))continue; + if (k + q <= z + 1) { + if (ii == 0) { + x1plane = iph; + y1plane = jph; + z1plane = kph + q * dx; + ii++; + } else if (ii == 1) { + x2plane = iph; + y2plane = jph; + z2plane = kph + q * dx; + if (x1plane != x2plane || y1plane != y2plane || z1plane != z2plane) + ii++; + } else if (ii == 2) { + x3plane = iph; + y3plane = jph; + z3plane = kph + q * dx; + if ((x3plane != x1plane || y3plane != y1plane || + z3plane != z1plane) && + (x2plane != x3plane || y2plane != y3plane || + z2plane != z3plane)) + ii++; + } + } + } + if (fdir == D3Q27System::B) { + // if(!bcArray->isSolid(i, j, k))continue; + if (k - q >= z) { + if (ii == 0) { + x1plane = iph; + y1plane = jph; + z1plane = kph - q * dx; + ii++; + } else if (ii == 1) { + x2plane = iph; + y2plane = jph; + z2plane = kph - q * dx; + if (x1plane != x2plane || y1plane != y2plane || z1plane != z2plane) + ii++; + } else if (ii == 2) { + x3plane = iph; + y3plane = jph; + z3plane = kph - q * dx; + if ((x3plane != x1plane || y3plane != y1plane || + z3plane != z1plane) && + (x2plane != x3plane || y2plane != y3plane || + z2plane != z3plane)) + ii++; + } + } + } + } + } + } } - } - } - } + } + } } - } - } - - A = y1plane* (z2plane - z3plane) + y2plane*(z3plane - z1plane) + y3plane* (z1plane - z2plane); - B = z1plane* (x2plane - x3plane) + z2plane*(x3plane - x1plane) + z3plane* (x1plane - x2plane) ; - C = x1plane* (y2plane - y3plane) + x2plane*(y3plane - y1plane) + x3plane* (y1plane - y2plane) ; - D =-( x1plane*(y2plane*z3plane - y3plane*z2plane)+x2plane*(y3plane*z1plane - y1plane*z3plane) + x3plane* (y1plane* z2plane - y2plane* z1plane)); - } - if(ii!=3){ - - {{UB_THROW( UbException(UB_EXARGS,"ii is="+UbSystem::toString(ii)+" ix1="+UbSystem::toString(ix1)+" ix2="+UbSystem::toString(ix2)+" ix3="+UbSystem::toString(ix3)+" Block3D::GlobalID="+UbSystem::toString(block->getGlobalID())+" dx="+UbSystem::toString(dx) - +" T="+UbSystem::toString(bcPtr->getQ(D3Q27System::T))+" B="+UbSystem::toString(bcPtr->getQ(D3Q27System::B)) - +" E="+UbSystem::toString(bcPtr->getQ(D3Q27System::E))+" W="+UbSystem::toString(bcPtr->getQ(D3Q27System::W))+" N="+UbSystem::toString(bcPtr->getQ(D3Q27System::N)) - +" S="+UbSystem::toString(bcPtr->getQ(D3Q27System::S))+" NE="+UbSystem::toString(bcPtr->getQ(D3Q27System::NE))+" SW="+UbSystem::toString(bcPtr->getQ(D3Q27System::SW)) - +" SE="+UbSystem::toString(bcPtr->getQ(D3Q27System::SE))+" NW="+UbSystem::toString(bcPtr->getQ(D3Q27System::NW)) - +" TE="+ - UbSystem::toString(bcPtr->getQ(D3Q27System::TE))+" BW="+UbSystem::toString(bcPtr->getQ(D3Q27System::BW))+" BE="+UbSystem::toString(bcPtr->getQ(D3Q27System::BE))+" TW="+ - UbSystem::toString(bcPtr->getQ(D3Q27System::TW))+" TN="+UbSystem::toString(bcPtr->getQ(D3Q27System::TN))+" BS="+UbSystem::toString(bcPtr->getQ(D3Q27System::BS))+" BN="+ - UbSystem::toString(bcPtr->getQ(D3Q27System::BN))+" TS="+UbSystem::toString(bcPtr->getQ(D3Q27System::TS))+" TNE="+UbSystem::toString(bcPtr->getQ(D3Q27System::TNE))+" TNW="+ - UbSystem::toString(bcPtr->getQ(D3Q27System::TNW))+" TSE="+UbSystem::toString(bcPtr->getQ(D3Q27System::TSE))+" TSW="+UbSystem::toString(bcPtr->getQ(D3Q27System::TSW))+" BNE="+ - UbSystem::toString(bcPtr->getQ(D3Q27System::BNE))+" BNW="+UbSystem::toString(bcPtr->getQ(D3Q27System::BNW))+" BSE="+UbSystem::toString(bcPtr->getQ(D3Q27System::BSE))+" BSW="+UbSystem::toString(bcPtr->getQ(D3Q27System::BSW)) - ) ) ;}} - - } + } + + A = y1plane * (z2plane - z3plane) + y2plane * (z3plane - z1plane) + y3plane * (z1plane - z2plane); + B = z1plane * (x2plane - x3plane) + z2plane * (x3plane - x1plane) + z3plane * (x1plane - x2plane); + C = x1plane * (y2plane - y3plane) + x2plane * (y3plane - y1plane) + x3plane * (y1plane - y2plane); + D = -(x1plane * (y2plane * z3plane - y3plane * z2plane) + x2plane * (y3plane * z1plane - y1plane * z3plane) + + x3plane * (y1plane * z2plane - y2plane * z1plane)); + } + if (ii != 3) { + + { + { + UB_THROW(UbException( + UB_EXARGS, "ii is=" + UbSystem::toString(ii) + " ix1=" + UbSystem::toString(ix1) + + " ix2=" + UbSystem::toString(ix2) + " ix3=" + UbSystem::toString(ix3) + + " Block3D::GlobalID=" + UbSystem::toString(block->getGlobalID()) + " dx=" + + UbSystem::toString(dx) + " T=" + UbSystem::toString(bcPtr->getQ(D3Q27System::T)) + + " B=" + UbSystem::toString(bcPtr->getQ(D3Q27System::B)) + + " E=" + UbSystem::toString(bcPtr->getQ(D3Q27System::E)) + + " W=" + UbSystem::toString(bcPtr->getQ(D3Q27System::W)) + + " N=" + UbSystem::toString(bcPtr->getQ(D3Q27System::N)) + + " S=" + UbSystem::toString(bcPtr->getQ(D3Q27System::S)) + + " NE=" + UbSystem::toString(bcPtr->getQ(D3Q27System::NE)) + + " SW=" + UbSystem::toString(bcPtr->getQ(D3Q27System::SW)) + + " SE=" + UbSystem::toString(bcPtr->getQ(D3Q27System::SE)) + + " NW=" + UbSystem::toString(bcPtr->getQ(D3Q27System::NW)) + + " TE=" + UbSystem::toString(bcPtr->getQ(D3Q27System::TE)) + + " BW=" + UbSystem::toString(bcPtr->getQ(D3Q27System::BW)) + + " BE=" + UbSystem::toString(bcPtr->getQ(D3Q27System::BE)) + + " TW=" + UbSystem::toString(bcPtr->getQ(D3Q27System::TW)) + + " TN=" + UbSystem::toString(bcPtr->getQ(D3Q27System::TN)) + + " BS=" + UbSystem::toString(bcPtr->getQ(D3Q27System::BS)) + + " BN=" + UbSystem::toString(bcPtr->getQ(D3Q27System::BN)) + + " TS=" + UbSystem::toString(bcPtr->getQ(D3Q27System::TS)) + + " TNE=" + UbSystem::toString(bcPtr->getQ(D3Q27System::TNE)) + + " TNW=" + UbSystem::toString(bcPtr->getQ(D3Q27System::TNW)) + + " TSE=" + UbSystem::toString(bcPtr->getQ(D3Q27System::TSE)) + + " TSW=" + UbSystem::toString(bcPtr->getQ(D3Q27System::TSW)) + + " BNE=" + UbSystem::toString(bcPtr->getQ(D3Q27System::BNE)) + + " BNW=" + UbSystem::toString(bcPtr->getQ(D3Q27System::BNW)) + + " BSE=" + UbSystem::toString(bcPtr->getQ(D3Q27System::BSE)) + + " BSW=" + UbSystem::toString(bcPtr->getQ(D3Q27System::BSW)))); + } + } + } } //////////////////////////////////////////////////////////////////////////////////////////////////////// -bool ShearStressCoProcessor::checkUndefindedNodes( SPtr<BCArray3D> bcArray,int ix1,int ix2,int ix3) +bool ShearStressCoProcessor::checkUndefindedNodes(SPtr<BCArray3D> bcArray, int ix1, int ix2, int ix3) { - for(int i = ix1; i <= ix1 + 1; i++){ - for(int j = ix2; j <= ix2 + 1; j++){ - for (int k = ix3; k <= ix3 + 1; k++) - { - if(bcArray->isUndefined(i, j, k)) return true; - } - } - } - return false; + for (int i = ix1; i <= ix1 + 1; i++) { + for (int j = ix2; j <= ix2 + 1; j++) { + for (int k = ix3; k <= ix3 + 1; k++) { + if (bcArray->isUndefined(i, j, k)) + return true; + } + } + } + return false; } ////////////////////////////////////////////////////////////////////////////////////// void ShearStressCoProcessor::initDistance() { - for(const auto& interactor : interactors) - { -// typedef std::map<SPtr<Block3D>, std::set< std::vector<int> > > TransNodeIndicesMap; - for (const auto& t : interactor->getBcNodeIndicesMap()) - { - SPtr<Block3D> block = t.first; - const std::set< std::vector<int> >& transNodeIndicesSet = t.second; - -// UbTupleDouble3 org = grid->getBlockWorldCoordinates(block); -// UbTupleDouble3 blockLengths = grid->getBlockLengths(block); -// UbTupleDouble3 nodeOffset = grid->getNodeOffset(block); -// double dx = grid->getDeltaX(block); - - SPtr<ILBMKernel> kernel = block->getKernel(); - SPtr<BCArray3D> bcArray = kernel->getBCProcessor()->getBCArray(); - SPtr<DistributionArray3D> distributions = kernel->getDataSet()->getFdistributions(); - SPtr<ShearStressValuesArray3D> ssv = kernel->getDataSet()->getShearStressValues(); - - int ghostLayer = kernel->getGhostLayerWidth(); -// LBMReal collFactor = kernel->getCollisionFactor(); - - int minX1 = ghostLayer; - int maxX1 = (int)bcArray->getNX1() - 1 - ghostLayer; - int minX2 = ghostLayer; - int maxX2 = (int)bcArray->getNX2() - 1 - ghostLayer; - int minX3 = ghostLayer; - int maxX3 = (int)bcArray->getNX3() - 1 - ghostLayer; - - for(std::vector<int> node : transNodeIndicesSet) - { - int ix1 = node[0]; - int ix2 = node[1]; - int ix3 = node[2]; - - //without ghost nodes - if (ix1 < minX1 || ix1 > maxX1 || ix2 < minX2 || ix2 > maxX2 ||ix3 < minX3 || ix3 > maxX3 ) continue; - - if(bcArray->isFluid(ix1,ix2,ix3) ) - { - SPtr<BoundaryConditions> bc = bcArray->getBC(ix1,ix2,ix3); - if((bc->hasDensityBoundary()||bc->hasVelocityBoundary()))continue; - int numberOfCorner=0; - - if(bc->getQ(D3Q27System::T) !=999.000){ numberOfCorner++;} - if(bc->getQ(D3Q27System::B) !=999.000){ numberOfCorner++;} - if(bc->getQ(D3Q27System::E) !=999.000){ numberOfCorner++;} - if(bc->getQ(D3Q27System::W) !=999.000){ numberOfCorner++;} - if(bc->getQ(D3Q27System::N) !=999.000){ numberOfCorner++;} - if(bc->getQ(D3Q27System::S) !=999.000){ numberOfCorner++;} - // if(bc->hasVelocityBoundary()||bc->hasDensityBoundary())continue; - if(numberOfCorner>1)continue; - if(checkUndefindedNodes( bcArray, ix1,ix2,ix3))continue; - - - //////get normal and distance////// - double A,B,C,D,ii=0.0; - findPlane(ix1,ix2,ix3,grid,block,A,B,C,D,ii); - Vector3D pointplane1 = grid->getNodeCoordinates(block, ix1,ix2,ix3); - double ix1ph= pointplane1[0]; - double ix2ph= pointplane1[1]; - double ix3ph= pointplane1[2]; - double normalDis; - if(ii!=3) - { - UB_THROW( UbException(UB_EXARGS,"not enough points to create plane"+UbSystem::toString(ii))); - } - else - { - double s = A*ix1ph + B*ix2ph + C*ix3ph + D;//The sign of s = Ax + By + Cz + D determines which side the point (x,y,z) lies with respect to the plane. If s > 0 then the point lies on the same side as the normal (A,B,C). If s < 0 then it lies on the opposite side, if s = 0 then the point (x,y,z) lies on the plane. - if (s>0){s=1;} else if (s<0){s=-1;}else {s=0;} - - normalDis=((A*ix1ph + B*ix2ph + C*ix3ph + D)/sqrt(A*A+B*B+C*C));///distance point to plane xp-Xw=distance - normalDis*=s; - - (*ssv)(normalX1,ix1,ix2,ix3) = A; - (*ssv)(normalX2,ix1,ix2,ix3) = B; - (*ssv)(normalX3,ix1,ix2,ix3) = C; - (*ssv)(normalq,ix1,ix2,ix3) = normalDis; - (*ssv)(numberOfPoint,ix1,ix2,ix3) = ii; - - } + for (const auto &interactor : interactors) { + // typedef std::map<SPtr<Block3D>, std::set< std::vector<int> > > TransNodeIndicesMap; + for (const auto &t : interactor->getBcNodeIndicesMap()) { + SPtr<Block3D> block = t.first; + const std::set<std::vector<int>> &transNodeIndicesSet = t.second; + + // UbTupleDouble3 org = grid->getBlockWorldCoordinates(block); + // UbTupleDouble3 blockLengths = grid->getBlockLengths(block); + // UbTupleDouble3 nodeOffset = grid->getNodeOffset(block); + // double dx = grid->getDeltaX(block); + + SPtr<ILBMKernel> kernel = block->getKernel(); + SPtr<BCArray3D> bcArray = kernel->getBCProcessor()->getBCArray(); + SPtr<DistributionArray3D> distributions = kernel->getDataSet()->getFdistributions(); + SPtr<ShearStressValuesArray3D> ssv = kernel->getDataSet()->getShearStressValues(); + + int ghostLayer = kernel->getGhostLayerWidth(); + // LBMReal collFactor = kernel->getCollisionFactor(); + + int minX1 = ghostLayer; + int maxX1 = (int)bcArray->getNX1() - 1 - ghostLayer; + int minX2 = ghostLayer; + int maxX2 = (int)bcArray->getNX2() - 1 - ghostLayer; + int minX3 = ghostLayer; + int maxX3 = (int)bcArray->getNX3() - 1 - ghostLayer; + + for (std::vector<int> node : transNodeIndicesSet) { + int ix1 = node[0]; + int ix2 = node[1]; + int ix3 = node[2]; + + // without ghost nodes + if (ix1 < minX1 || ix1 > maxX1 || ix2 < minX2 || ix2 > maxX2 || ix3 < minX3 || ix3 > maxX3) + continue; + + if (bcArray->isFluid(ix1, ix2, ix3)) { + SPtr<BoundaryConditions> bc = bcArray->getBC(ix1, ix2, ix3); + if ((bc->hasDensityBoundary() || bc->hasVelocityBoundary())) + continue; + int numberOfCorner = 0; + + if (bc->getQ(D3Q27System::T) != 999.000) { + numberOfCorner++; + } + if (bc->getQ(D3Q27System::B) != 999.000) { + numberOfCorner++; + } + if (bc->getQ(D3Q27System::E) != 999.000) { + numberOfCorner++; + } + if (bc->getQ(D3Q27System::W) != 999.000) { + numberOfCorner++; + } + if (bc->getQ(D3Q27System::N) != 999.000) { + numberOfCorner++; + } + if (bc->getQ(D3Q27System::S) != 999.000) { + numberOfCorner++; + } + // if(bc->hasVelocityBoundary()||bc->hasDensityBoundary())continue; + if (numberOfCorner > 1) + continue; + if (checkUndefindedNodes(bcArray, ix1, ix2, ix3)) + continue; + + //////get normal and distance////// + double A, B, C, D, ii = 0.0; + findPlane(ix1, ix2, ix3, grid, block, A, B, C, D, ii); + Vector3D pointplane1 = grid->getNodeCoordinates(block, ix1, ix2, ix3); + double ix1ph = pointplane1[0]; + double ix2ph = pointplane1[1]; + double ix3ph = pointplane1[2]; + double normalDis; + if (ii != 3) { + UB_THROW(UbException(UB_EXARGS, "not enough points to create plane" + UbSystem::toString(ii))); + } else { + double s = A * ix1ph + B * ix2ph + C * ix3ph + + D; // The sign of s = Ax + By + Cz + D determines which side the point (x,y,z) lies + // with respect to the plane. If s > 0 then the point lies on the same side as the + // normal (A,B,C). If s < 0 then it lies on the opposite side, if s = 0 then the + // point (x,y,z) lies on the plane. + if (s > 0) { + s = 1; + } else if (s < 0) { + s = -1; + } else { + s = 0; + } + + normalDis = ((A * ix1ph + B * ix2ph + C * ix3ph + D) / + sqrt(A * A + B * B + C * C)); /// distance point to plane xp-Xw=distance + normalDis *= s; + + (*ssv)(normalX1, ix1, ix2, ix3) = A; + (*ssv)(normalX2, ix1, ix2, ix3) = B; + (*ssv)(normalX3, ix1, ix2, ix3) = C; + (*ssv)(normalq, ix1, ix2, ix3) = normalDis; + (*ssv)(numberOfPoint, ix1, ix2, ix3) = ii; + } + } } - } - } - } + } + } } diff --git a/src/cpu/VirtualFluidsCore/CoProcessors/ShearStressCoProcessor.h b/src/cpu/VirtualFluidsCore/CoProcessors/ShearStressCoProcessor.h index a054fa36eb02b6dfb825472cea549f90c00c558f..995589b9e8b84334ea108cddac8e49bbbfa1c535 100644 --- a/src/cpu/VirtualFluidsCore/CoProcessors/ShearStressCoProcessor.h +++ b/src/cpu/VirtualFluidsCore/CoProcessors/ShearStressCoProcessor.h @@ -2,8 +2,8 @@ #define D3Q27ShearStressCoProcessor_H #include <PointerDefinitions.h> -#include <vector> #include <string> +#include <vector> #include <basics/utilities/UbTuple.h> @@ -17,53 +17,69 @@ class BCArray3D; class WbWriter; //! \brief Computes the shear stress and y plus values and writes to parallel .vtk -//! \details writes at given time intervals specified in scheduler (s) and resets according to scheduler (rs). -//! Take root to obtain during post processing (paraview). -//! \author K. Kucher, S. Uphoff, M. Geier, E. Goraki Fard +//! \details writes at given time intervals specified in scheduler (s) and resets according to scheduler (rs). +//! Take root to obtain during post processing (paraview). +//! \author K. Kucher, S. Uphoff, M. Geier, E. Goraki Fard -class ShearStressCoProcessor: public CoProcessor +class ShearStressCoProcessor : public CoProcessor { public: - //! Default constructor - ShearStressCoProcessor()= default; - //! Constructor - ShearStressCoProcessor(SPtr<Grid3D> grid, const std::string& path, WbWriter* const writer, - SPtr<UbScheduler> s, SPtr<UbScheduler> rs); - ~ShearStressCoProcessor() override; - - void process(double step) override; + //! Default constructor + ShearStressCoProcessor() = default; + //! Constructor + ShearStressCoProcessor(SPtr<Grid3D> grid, const std::string &path, WbWriter *const writer, SPtr<UbScheduler> s, + SPtr<UbScheduler> rs); + ~ShearStressCoProcessor() override; + + void process(double step) override; + + void addInteractor(SPtr<D3Q27Interactor> interactor); - void addInteractor(SPtr<D3Q27Interactor> interactor); protected: - //! Computes average and shear stress values of macroscopic quantities - void calculateShearStress(double timeStep); - //! Prepare data and write in .vtk file - void collectData(double step); - //! Reset data - void resetData(double step); - //! prepare data - void addData(); - void clearData(); - void reset(double step); - void findPlane(int ix1,int ix2,int ix3, SPtr<Grid3D> grid, SPtr<Block3D> block,double &A,double &B,double &C,double &D,double &ii); - bool checkUndefindedNodes(SPtr<BCArray3D> bcArray,int ix1,int ix2,int ix3); - void initDistance(); + //! Computes average and shear stress values of macroscopic quantities + void calculateShearStress(double timeStep); + //! Prepare data and write in .vtk file + void collectData(double step); + //! Reset data + void resetData(double step); + //! prepare data + void addData(); + void clearData(); + void reset(double step); + void findPlane(int ix1, int ix2, int ix3, SPtr<Grid3D> grid, SPtr<Block3D> block, double &A, double &B, double &C, + double &D, double &ii); + bool checkUndefindedNodes(SPtr<BCArray3D> bcArray, int ix1, int ix2, int ix3); + void initDistance(); private: - std::vector<UbTupleFloat3> nodes; - std::vector<std::string> datanames; - std::vector<std::vector<double> > data; - std::string path; - std::vector<SPtr<D3Q27Interactor> > interactors; - std::vector<double> normals; - int gridRank; - WbWriter* writer; - SPtr<UbScheduler> Resetscheduler; //additional scheduler to restart averaging after a given interval - int minInitLevel; //min init level - int maxInitLevel; - std::vector<std::vector<SPtr<Block3D> > > blockVector; - enum Values{AvVx = 0, AvVy = 1, AvVz = 2, AvSxx = 3, AvSyy = 4, AvSzz = 5, AvSxy = 6, AvSyz = 7, AvSxz = 8, normalX1 = 9, normalX2 = 10, normalX3 = 11, normalq = 12,numberOfPoint=13}; + std::vector<UbTupleFloat3> nodes; + std::vector<std::string> datanames; + std::vector<std::vector<double>> data; + std::string path; + std::vector<SPtr<D3Q27Interactor>> interactors; + std::vector<double> normals; + int gridRank; + WbWriter *writer; + SPtr<UbScheduler> Resetscheduler; // additional scheduler to restart averaging after a given interval + int minInitLevel; // min init level + int maxInitLevel; + std::vector<std::vector<SPtr<Block3D>>> blockVector; + enum Values { + AvVx = 0, + AvVy = 1, + AvVz = 2, + AvSxx = 3, + AvSyy = 4, + AvSzz = 5, + AvSxy = 6, + AvSyz = 7, + AvSxz = 8, + normalX1 = 9, + normalX2 = 10, + normalX3 = 11, + normalq = 12, + numberOfPoint = 13 + }; }; - #endif /* D3Q27ShearStressCoProcessor_H */ diff --git a/src/cpu/VirtualFluidsCore/CoProcessors/TimeAveragedValuesCoProcessor.cpp b/src/cpu/VirtualFluidsCore/CoProcessors/TimeAveragedValuesCoProcessor.cpp index b3a92e95f5632c771c06725f3b9891e83f66f294..eb702a5484de8ee066690c6981d5a89ad6c4f509 100644 --- a/src/cpu/VirtualFluidsCore/CoProcessors/TimeAveragedValuesCoProcessor.cpp +++ b/src/cpu/VirtualFluidsCore/CoProcessors/TimeAveragedValuesCoProcessor.cpp @@ -1,999 +1,907 @@ #include "TimeAveragedValuesCoProcessor.h" - -#include "LBMKernel.h" #include "BCProcessor.h" +#include "LBMKernel.h" -#include "basics/writer/WbWriterVtkXmlASCII.h" -#include "DataSet3D.h" -#include "Grid3D.h" #include "Block3D.h" #include "Communicator.h" +#include "DataSet3D.h" +#include "Grid3D.h" #include "UbScheduler.h" +#include "basics/writer/WbWriterVtkXmlASCII.h" #include "BCArray3D.h" - -TimeAveragedValuesCoProcessor::TimeAveragedValuesCoProcessor() -= default; +TimeAveragedValuesCoProcessor::TimeAveragedValuesCoProcessor() = default; ////////////////////////////////////////////////////////////////////////// -TimeAveragedValuesCoProcessor::TimeAveragedValuesCoProcessor(SPtr<Grid3D> grid, const std::string& path, WbWriter* const writer, - SPtr<UbScheduler> s, SPtr<Communicator> comm, int options) - : CoProcessor(grid, s), - path(path), - writer(writer), - comm(comm), - options(options) +TimeAveragedValuesCoProcessor::TimeAveragedValuesCoProcessor(SPtr<Grid3D> grid, const std::string &path, + WbWriter *const writer, SPtr<UbScheduler> s, + SPtr<Communicator> comm, int options) + : CoProcessor(grid, s), path(path), writer(writer), comm(comm), options(options) { - init(); - planarAveraging = false; - timeAveraging = true; + init(); + planarAveraging = false; + timeAveraging = true; } ////////////////////////////////////////////////////////////////////////// -TimeAveragedValuesCoProcessor::TimeAveragedValuesCoProcessor(SPtr<Grid3D> grid, const std::string& path, WbWriter* const writer, - SPtr<UbScheduler> s, SPtr<Communicator> comm, int options, - std::vector<int> levels, std::vector<double>& levelCoords, std::vector<double>& bounds, bool timeAveraging) - : CoProcessor(grid, s), - path(path), - writer(writer), - comm(comm), - options(options), - levels(levels), - levelCoords(levelCoords), - bounds(bounds), - timeAveraging(timeAveraging) +TimeAveragedValuesCoProcessor::TimeAveragedValuesCoProcessor(SPtr<Grid3D> grid, const std::string &path, + WbWriter *const writer, SPtr<UbScheduler> s, + SPtr<Communicator> comm, int options, + std::vector<int> levels, std::vector<double> &levelCoords, + std::vector<double> &bounds, bool timeAveraging) + : CoProcessor(grid, s), path(path), writer(writer), comm(comm), options(options), levels(levels), + levelCoords(levelCoords), bounds(bounds), timeAveraging(timeAveraging) { - init(); - planarAveraging = true; + init(); + planarAveraging = true; } ////////////////////////////////////////////////////////////////////////// void TimeAveragedValuesCoProcessor::init() { - root = comm->isRoot(); - gridRank = grid->getRank(); - minInitLevel = this->grid->getCoarsestInitializedLevel(); - maxInitLevel = this->grid->getFinestInitializedLevel(); - - withGhostLayer = false; - iMinC = 1; - - minStep = scheduler->getMinBegin(); - maxStep = scheduler->getMaxEnd(); - numberOfSteps = (maxStep - minStep); - - //function pointer - using namespace D3Q27System; - calcMacros = NULL; - if (compressible) - { - calcMacros = &calcCompMacroscopicValues; - } - else - { - calcMacros = &calcIncompMacroscopicValues; - } - - double begin = scheduler->getMinBegin(); - double gridTimeStep = grid->getTimeStep(); - - if (gridTimeStep == begin || gridTimeStep == 0) - { - initData(); - } - else - { - blockVector.clear(); - blockVector.resize(maxInitLevel + 1); - for (int level = minInitLevel; level <= maxInitLevel; level++) - { - grid->getBlocks(level, gridRank, true, blockVector[level]); - if (blockVector[level].size() > 0) compressible = blockVector[level][0]->getKernel()->getCompressible(); - } - } + root = comm->isRoot(); + gridRank = grid->getRank(); + minInitLevel = this->grid->getCoarsestInitializedLevel(); + maxInitLevel = this->grid->getFinestInitializedLevel(); + + withGhostLayer = false; + iMinC = 1; + + minStep = scheduler->getMinBegin(); + maxStep = scheduler->getMaxEnd(); + numberOfSteps = (maxStep - minStep); + + // function pointer + using namespace D3Q27System; + calcMacros = NULL; + if (compressible) { + calcMacros = &calcCompMacroscopicValues; + } else { + calcMacros = &calcIncompMacroscopicValues; + } + + double begin = scheduler->getMinBegin(); + double gridTimeStep = grid->getTimeStep(); + + if (gridTimeStep == begin || gridTimeStep == 0) { + initData(); + } else { + blockVector.clear(); + blockVector.resize(maxInitLevel + 1); + for (int level = minInitLevel; level <= maxInitLevel; level++) { + grid->getBlocks(level, gridRank, true, blockVector[level]); + if (blockVector[level].size() > 0) + compressible = blockVector[level][0]->getKernel()->getCompressible(); + } + } } ////////////////////////////////////////////////////////////////////////// void TimeAveragedValuesCoProcessor::initData() { - blockVector.clear(); - blockVector.resize(maxInitLevel + 1); - - for (int level = minInitLevel; level <= maxInitLevel; level++) - { - grid->getBlocks(level, gridRank, true, blockVector[level]); - - if (blockVector[level].size() > 0) - compressible = blockVector[level][0]->getKernel()->getCompressible(); - - for (SPtr<Block3D> block : blockVector[level]) - { - UbTupleInt3 nx = grid->getBlockNX(); - - if ((options&Density) == Density) - { - SPtr<AverageValuesArray3D> ar = SPtr<AverageValuesArray3D>(new AverageValuesArray3D(2, val<1>(nx) + 1, val<2>(nx) + 1, val<3>(nx) + 1, 0.0)); - block->getKernel()->getDataSet()->setAverageDensity(ar); - } - - if ((options&Velocity) == Velocity) - { - SPtr<AverageValuesArray3D> av = SPtr<AverageValuesArray3D>(new AverageValuesArray3D(3, val<1>(nx) + 1, val<2>(nx) + 1, val<3>(nx) + 1, 0.0)); - block->getKernel()->getDataSet()->setAverageVelocity(av); - } - - if ((options&Fluctuations) == Fluctuations) - { - SPtr<AverageValuesArray3D> af = SPtr<AverageValuesArray3D>(new AverageValuesArray3D(6, val<1>(nx) + 1, val<2>(nx) + 1, val<3>(nx) + 1, 0.0)); - block->getKernel()->getDataSet()->setAverageFluctuations(af); - } - - if ((options&Triplecorrelations) == Triplecorrelations) - { - SPtr<AverageValuesArray3D> at = SPtr<AverageValuesArray3D>(new AverageValuesArray3D(10, val<1>(nx) + 1, val<2>(nx) + 1, val<3>(nx) + 1, 0.0)); - block->getKernel()->getDataSet()->setAverageTriplecorrelations(at); - } - } - } + blockVector.clear(); + blockVector.resize(maxInitLevel + 1); + + for (int level = minInitLevel; level <= maxInitLevel; level++) { + grid->getBlocks(level, gridRank, true, blockVector[level]); + + if (blockVector[level].size() > 0) + compressible = blockVector[level][0]->getKernel()->getCompressible(); + + for (SPtr<Block3D> block : blockVector[level]) { + UbTupleInt3 nx = grid->getBlockNX(); + + if ((options & Density) == Density) { + SPtr<AverageValuesArray3D> ar = SPtr<AverageValuesArray3D>( + new AverageValuesArray3D(2, val<1>(nx) + 1, val<2>(nx) + 1, val<3>(nx) + 1, 0.0)); + block->getKernel()->getDataSet()->setAverageDensity(ar); + } + + if ((options & Velocity) == Velocity) { + SPtr<AverageValuesArray3D> av = SPtr<AverageValuesArray3D>( + new AverageValuesArray3D(3, val<1>(nx) + 1, val<2>(nx) + 1, val<3>(nx) + 1, 0.0)); + block->getKernel()->getDataSet()->setAverageVelocity(av); + } + + if ((options & Fluctuations) == Fluctuations) { + SPtr<AverageValuesArray3D> af = SPtr<AverageValuesArray3D>( + new AverageValuesArray3D(6, val<1>(nx) + 1, val<2>(nx) + 1, val<3>(nx) + 1, 0.0)); + block->getKernel()->getDataSet()->setAverageFluctuations(af); + } + + if ((options & Triplecorrelations) == Triplecorrelations) { + SPtr<AverageValuesArray3D> at = SPtr<AverageValuesArray3D>( + new AverageValuesArray3D(10, val<1>(nx) + 1, val<2>(nx) + 1, val<3>(nx) + 1, 0.0)); + block->getKernel()->getDataSet()->setAverageTriplecorrelations(at); + } + } + } } ////////////////////////////////////////////////////////////////////////// void TimeAveragedValuesCoProcessor::process(double step) { - if (step == minStep) - { - initData(); - numberOfSteps = (maxStep - minStep)+1; - //DEBUG///////////////////// - //UBLOG(logINFO, "process::step = " << step << ", minStep = " << minStep << ", maxStep = " << maxStep << ", numberOfSteps = " << numberOfSteps << " init()"); - //////////////////////////// - } - calculateSubtotal(step); - - if (step == maxStep) - { - //DEBUG///////////////////// - //UBLOG(logINFO, "process::step = " << step << ", minStep = " << minStep << ", maxStep = " << maxStep << ", numberOfSteps = " << numberOfSteps); - //////////////////////////// - - //calculateAverageValues((double)numberOfFineSteps); - calculateAverageValues(numberOfSteps); - - if (timeAveraging) - { - collectData(step); - } - - if (planarAveraging) - { - planarAverage(step); - } - } - - UBLOG(logDEBUG3, "AverageValuesCoProcessor::update:" << step); + if (step == minStep) { + initData(); + numberOfSteps = (maxStep - minStep) + 1; + // DEBUG///////////////////// + // UBLOG(logINFO, "process::step = " << step << ", minStep = " << minStep << ", maxStep = " << maxStep << ", + // numberOfSteps = " << numberOfSteps << " init()"); + //////////////////////////// + } + calculateSubtotal(step); + + if (step == maxStep) { + // DEBUG///////////////////// + // UBLOG(logINFO, "process::step = " << step << ", minStep = " << minStep << ", maxStep = " << maxStep << ", + // numberOfSteps = " << numberOfSteps); + //////////////////////////// + + // calculateAverageValues((double)numberOfFineSteps); + calculateAverageValues(numberOfSteps); + + if (timeAveraging) { + collectData(step); + } + + if (planarAveraging) { + planarAverage(step); + } + } + + UBLOG(logDEBUG3, "AverageValuesCoProcessor::update:" << step); } ////////////////////////////////////////////////////////////////////////// void TimeAveragedValuesCoProcessor::collectData(double step) { - int istep = int(step); - - for (int level = minInitLevel; level <= maxInitLevel; level++) - { - for (SPtr<Block3D> block : blockVector[level]) - { - if (block) - { - addData(block); - } - } - } - - std::string pfilePath, partPath, subfolder, cfilePath; - subfolder = "tav" + UbSystem::toString(istep); - pfilePath = path + "/tav/" + subfolder; - partPath = pfilePath + "/tav" + UbSystem::toString(gridRank) + "_" + UbSystem::toString(istep); - - std::string partName = writer->writeOctsWithNodeData(partPath, nodes, cells, datanames, data); - size_t found = partName.find_last_of("/"); - std::string piece = partName.substr(found + 1); - piece = subfolder + "/" + piece; - - std::vector<std::string> cellDataNames; - std::vector<std::string> pieces = comm->gather(piece); - if (root) - { - std::string pname = WbWriterVtkXmlASCII::getInstance()->writeParallelFile(pfilePath, pieces, datanames, cellDataNames); - UBLOG(logINFO, "TimeAveragedValuesCoProcessor::collectData() step: " << istep); - } - - clearData(); + int istep = int(step); + + for (int level = minInitLevel; level <= maxInitLevel; level++) { + for (SPtr<Block3D> block : blockVector[level]) { + if (block) { + addData(block); + } + } + } + + std::string pfilePath, partPath, subfolder, cfilePath; + subfolder = "tav" + UbSystem::toString(istep); + pfilePath = path + "/tav/" + subfolder; + partPath = pfilePath + "/tav" + UbSystem::toString(gridRank) + "_" + UbSystem::toString(istep); + + std::string partName = writer->writeOctsWithNodeData(partPath, nodes, cells, datanames, data); + size_t found = partName.find_last_of("/"); + std::string piece = partName.substr(found + 1); + piece = subfolder + "/" + piece; + + std::vector<std::string> cellDataNames; + std::vector<std::string> pieces = comm->gather(piece); + if (root) { + std::string pname = + WbWriterVtkXmlASCII::getInstance()->writeParallelFile(pfilePath, pieces, datanames, cellDataNames); + UBLOG(logINFO, "TimeAveragedValuesCoProcessor::collectData() step: " << istep); + } + + clearData(); } ////////////////////////////////////////////////////////////////////////// void TimeAveragedValuesCoProcessor::clearData() { - nodes.clear(); - cells.clear(); - datanames.clear(); - data.clear(); + nodes.clear(); + cells.clear(); + datanames.clear(); + data.clear(); } ////////////////////////////////////////////////////////////////////////// void TimeAveragedValuesCoProcessor::addData(const SPtr<Block3D> block) { - UbTupleDouble3 org = grid->getBlockWorldCoordinates(block); -// UbTupleDouble3 blockLengths = grid->getBlockLengths(block); - UbTupleDouble3 nodeOffset = grid->getNodeOffset(block); - double dx = grid->getDeltaX(block); - int level = block->getLevel(); - - //Diese Daten werden geschrieben: - datanames.resize(0); - - datanames.emplace_back("level"); - datanames.emplace_back("Rho"); - - if ((options&Density) == Density) - { - datanames.emplace_back("taRho"); - datanames.emplace_back("taRhoF"); - } - - if ((options&Velocity) == Velocity) - { - datanames.emplace_back("taVx"); - datanames.emplace_back("taVy"); - datanames.emplace_back("taVz"); - } - - if ((options&Fluctuations) == Fluctuations) - { - datanames.emplace_back("taVxx"); - datanames.emplace_back("taVyy"); - datanames.emplace_back("taVzz"); - datanames.emplace_back("taVxy"); - datanames.emplace_back("taVxz"); - datanames.emplace_back("taVyz"); - datanames.emplace_back("taVyz"); - } - - if ((options&Triplecorrelations) == Triplecorrelations) - { - datanames.emplace_back("taVxxx"); - datanames.emplace_back("taVxxy"); - datanames.emplace_back("taVxxz"); - datanames.emplace_back("taVyyy"); - datanames.emplace_back("taVyyx"); - datanames.emplace_back("taVyyz"); - datanames.emplace_back("taVzzz"); - datanames.emplace_back("taVzzx"); - datanames.emplace_back("taVzzy"); - datanames.emplace_back("taVxyz"); - } - - - //datanames.push_back("AvP"); - //datanames.push_back("AvPrms"); - - - data.resize(datanames.size()); - - SPtr<ILBMKernel> kernel = block->getKernel(); - SPtr<BCArray3D> bcArray = kernel->getBCProcessor()->getBCArray(); - SPtr<DistributionArray3D> distributions = kernel->getDataSet()->getFdistributions(); - SPtr<AverageValuesArray3D> ar = kernel->getDataSet()->getAverageDensity(); - SPtr<AverageValuesArray3D> av = kernel->getDataSet()->getAverageVelocity(); - SPtr<AverageValuesArray3D> af = kernel->getDataSet()->getAverageFluctuations(); - SPtr<AverageValuesArray3D> at = kernel->getDataSet()->getAverageTriplecorrelations(); - //int ghostLayerWidth = kernel->getGhostLayerWidth(); - - //knotennummerierung faengt immer bei 0 an! - unsigned int SWB, SEB, NEB, NWB, SWT, SET, NET, NWT; - - int minX1 = iMinC; - int minX2 = iMinC; - int minX3 = iMinC; - - int maxX1 = int(distributions->getNX1()); - int maxX2 = int(distributions->getNX2()); - int maxX3 = int(distributions->getNX3()); - - //nummern vergeben und node vector erstellen + daten sammeln - CbArray3D<int> nodeNumbers((int)maxX1, (int)maxX2, (int)maxX3, -1); - - maxX1 -= 2; - maxX2 -= 2; - maxX3 -= 2; - - LBMReal f[D3Q27System::ENDF + 1]; - LBMReal vx1, vx2, vx3, rho; - - //D3Q27BoundaryConditionPtr bcPtr; - - int nr = (int)nodes.size(); - - for (int ix3 = minX3; ix3 <= maxX3; ix3++) - { - for (int ix2 = minX2; ix2 <= maxX2; ix2++) - { - for (int ix1 = minX1; ix1 <= maxX1; ix1++) - { - if (!bcArray->isUndefined(ix1, ix2, ix3) && !bcArray->isSolid(ix1, ix2, ix3)) - { - int index = 0; - nodeNumbers(ix1, ix2, ix3) = nr++; - nodes.push_back(makeUbTuple(float(val<1>(org) - val<1>(nodeOffset) + ix1*dx), - float(val<2>(org) - val<2>(nodeOffset) + ix2*dx), - float(val<3>(org) - val<3>(nodeOffset) + ix3*dx))); - - data[index++].push_back(level); - - distributions->getDistribution(f, ix1, ix2, ix3); - calcMacros(f, rho, vx1, vx2, vx3); - - data[index++].push_back(rho); - - - - if ((options&Density) == Density) - { - data[index++].push_back((*ar)(Rho, ix1, ix2, ix3)); - data[index++].push_back((*ar)(RhoF, ix1, ix2, ix3)); - } - - if ((options&Velocity) == Velocity) - { - data[index++].push_back((*av)(Vx, ix1, ix2, ix3)); - data[index++].push_back((*av)(Vy, ix1, ix2, ix3)); - data[index++].push_back((*av)(Vz, ix1, ix2, ix3)); - } - - if ((options&Fluctuations) == Fluctuations) - { - data[index++].push_back((*af)(Vxx, ix1, ix2, ix3)); - data[index++].push_back((*af)(Vyy, ix1, ix2, ix3)); - data[index++].push_back((*af)(Vzz, ix1, ix2, ix3)); - data[index++].push_back((*af)(Vxy, ix1, ix2, ix3)); - data[index++].push_back((*af)(Vxz, ix1, ix2, ix3)); - data[index++].push_back((*af)(Vyz, ix1, ix2, ix3)); - } - - if ((options&Triplecorrelations) == Triplecorrelations) - { - data[index++].push_back((*at)(Vxxx, ix1, ix2, ix3)); - data[index++].push_back((*at)(Vxxy, ix1, ix2, ix3)); - data[index++].push_back((*at)(Vxxz, ix1, ix2, ix3)); - data[index++].push_back((*at)(Vyyy, ix1, ix2, ix3)); - data[index++].push_back((*at)(Vyyx, ix1, ix2, ix3)); - data[index++].push_back((*at)(Vyyz, ix1, ix2, ix3)); - data[index++].push_back((*at)(Vzzz, ix1, ix2, ix3)); - data[index++].push_back((*at)(Vzzx, ix1, ix2, ix3)); - data[index++].push_back((*at)(Vzzy, ix1, ix2, ix3)); - data[index++].push_back((*at)(Vxyz, ix1, ix2, ix3)); - } + UbTupleDouble3 org = grid->getBlockWorldCoordinates(block); + // UbTupleDouble3 blockLengths = grid->getBlockLengths(block); + UbTupleDouble3 nodeOffset = grid->getNodeOffset(block); + double dx = grid->getDeltaX(block); + int level = block->getLevel(); + + // Diese Daten werden geschrieben: + datanames.resize(0); + + datanames.emplace_back("level"); + datanames.emplace_back("Rho"); + + if ((options & Density) == Density) { + datanames.emplace_back("taRho"); + datanames.emplace_back("taRhoF"); + } + + if ((options & Velocity) == Velocity) { + datanames.emplace_back("taVx"); + datanames.emplace_back("taVy"); + datanames.emplace_back("taVz"); + } + + if ((options & Fluctuations) == Fluctuations) { + datanames.emplace_back("taVxx"); + datanames.emplace_back("taVyy"); + datanames.emplace_back("taVzz"); + datanames.emplace_back("taVxy"); + datanames.emplace_back("taVxz"); + datanames.emplace_back("taVyz"); + datanames.emplace_back("taVyz"); + } + + if ((options & Triplecorrelations) == Triplecorrelations) { + datanames.emplace_back("taVxxx"); + datanames.emplace_back("taVxxy"); + datanames.emplace_back("taVxxz"); + datanames.emplace_back("taVyyy"); + datanames.emplace_back("taVyyx"); + datanames.emplace_back("taVyyz"); + datanames.emplace_back("taVzzz"); + datanames.emplace_back("taVzzx"); + datanames.emplace_back("taVzzy"); + datanames.emplace_back("taVxyz"); + } + + // datanames.push_back("AvP"); + // datanames.push_back("AvPrms"); + + data.resize(datanames.size()); + + SPtr<ILBMKernel> kernel = block->getKernel(); + SPtr<BCArray3D> bcArray = kernel->getBCProcessor()->getBCArray(); + SPtr<DistributionArray3D> distributions = kernel->getDataSet()->getFdistributions(); + SPtr<AverageValuesArray3D> ar = kernel->getDataSet()->getAverageDensity(); + SPtr<AverageValuesArray3D> av = kernel->getDataSet()->getAverageVelocity(); + SPtr<AverageValuesArray3D> af = kernel->getDataSet()->getAverageFluctuations(); + SPtr<AverageValuesArray3D> at = kernel->getDataSet()->getAverageTriplecorrelations(); + // int ghostLayerWidth = kernel->getGhostLayerWidth(); + + // knotennummerierung faengt immer bei 0 an! + unsigned int SWB, SEB, NEB, NWB, SWT, SET, NET, NWT; + + int minX1 = iMinC; + int minX2 = iMinC; + int minX3 = iMinC; + + int maxX1 = int(distributions->getNX1()); + int maxX2 = int(distributions->getNX2()); + int maxX3 = int(distributions->getNX3()); + + // nummern vergeben und node vector erstellen + daten sammeln + CbArray3D<int> nodeNumbers((int)maxX1, (int)maxX2, (int)maxX3, -1); + + maxX1 -= 2; + maxX2 -= 2; + maxX3 -= 2; + + LBMReal f[D3Q27System::ENDF + 1]; + LBMReal vx1, vx2, vx3, rho; + + // D3Q27BoundaryConditionPtr bcPtr; + + int nr = (int)nodes.size(); + + for (int ix3 = minX3; ix3 <= maxX3; ix3++) { + for (int ix2 = minX2; ix2 <= maxX2; ix2++) { + for (int ix1 = minX1; ix1 <= maxX1; ix1++) { + if (!bcArray->isUndefined(ix1, ix2, ix3) && !bcArray->isSolid(ix1, ix2, ix3)) { + int index = 0; + nodeNumbers(ix1, ix2, ix3) = nr++; + nodes.push_back(makeUbTuple(float(val<1>(org) - val<1>(nodeOffset) + ix1 * dx), + float(val<2>(org) - val<2>(nodeOffset) + ix2 * dx), + float(val<3>(org) - val<3>(nodeOffset) + ix3 * dx))); + + data[index++].push_back(level); + + distributions->getDistribution(f, ix1, ix2, ix3); + calcMacros(f, rho, vx1, vx2, vx3); + + data[index++].push_back(rho); + + if ((options & Density) == Density) { + data[index++].push_back((*ar)(Rho, ix1, ix2, ix3)); + data[index++].push_back((*ar)(RhoF, ix1, ix2, ix3)); + } + + if ((options & Velocity) == Velocity) { + data[index++].push_back((*av)(Vx, ix1, ix2, ix3)); + data[index++].push_back((*av)(Vy, ix1, ix2, ix3)); + data[index++].push_back((*av)(Vz, ix1, ix2, ix3)); + } + + if ((options & Fluctuations) == Fluctuations) { + data[index++].push_back((*af)(Vxx, ix1, ix2, ix3)); + data[index++].push_back((*af)(Vyy, ix1, ix2, ix3)); + data[index++].push_back((*af)(Vzz, ix1, ix2, ix3)); + data[index++].push_back((*af)(Vxy, ix1, ix2, ix3)); + data[index++].push_back((*af)(Vxz, ix1, ix2, ix3)); + data[index++].push_back((*af)(Vyz, ix1, ix2, ix3)); + } + + if ((options & Triplecorrelations) == Triplecorrelations) { + data[index++].push_back((*at)(Vxxx, ix1, ix2, ix3)); + data[index++].push_back((*at)(Vxxy, ix1, ix2, ix3)); + data[index++].push_back((*at)(Vxxz, ix1, ix2, ix3)); + data[index++].push_back((*at)(Vyyy, ix1, ix2, ix3)); + data[index++].push_back((*at)(Vyyx, ix1, ix2, ix3)); + data[index++].push_back((*at)(Vyyz, ix1, ix2, ix3)); + data[index++].push_back((*at)(Vzzz, ix1, ix2, ix3)); + data[index++].push_back((*at)(Vzzx, ix1, ix2, ix3)); + data[index++].push_back((*at)(Vzzy, ix1, ix2, ix3)); + data[index++].push_back((*at)(Vxyz, ix1, ix2, ix3)); + } + } } - } - } - } - - maxX1 -= 1; - maxX2 -= 1; - maxX3 -= 1; - - //cell vector erstellen - for (int ix3 = minX3; ix3 <= maxX3; ix3++) - { - for (int ix2 = minX2; ix2 <= maxX2; ix2++) - { - for (int ix1 = minX1; ix1 <= maxX1; ix1++) - { - if ((SWB = nodeNumbers(ix1, ix2, ix3)) >= 0 - && (SEB = nodeNumbers(ix1 + 1, ix2, ix3)) >= 0 - && (NEB = nodeNumbers(ix1 + 1, ix2 + 1, ix3)) >= 0 - && (NWB = nodeNumbers(ix1, ix2 + 1, ix3)) >= 0 - && (SWT = nodeNumbers(ix1, ix2, ix3 + 1)) >= 0 - && (SET = nodeNumbers(ix1 + 1, ix2, ix3 + 1)) >= 0 - && (NET = nodeNumbers(ix1 + 1, ix2 + 1, ix3 + 1)) >= 0 - && (NWT = nodeNumbers(ix1, ix2 + 1, ix3 + 1)) >= 0) - { - cells.push_back(makeUbTuple(SWB, SEB, NEB, NWB, SWT, SET, NET, NWT)); + } + } + + maxX1 -= 1; + maxX2 -= 1; + maxX3 -= 1; + + // cell vector erstellen + for (int ix3 = minX3; ix3 <= maxX3; ix3++) { + for (int ix2 = minX2; ix2 <= maxX2; ix2++) { + for (int ix1 = minX1; ix1 <= maxX1; ix1++) { + if ((SWB = nodeNumbers(ix1, ix2, ix3)) >= 0 && (SEB = nodeNumbers(ix1 + 1, ix2, ix3)) >= 0 && + (NEB = nodeNumbers(ix1 + 1, ix2 + 1, ix3)) >= 0 && (NWB = nodeNumbers(ix1, ix2 + 1, ix3)) >= 0 && + (SWT = nodeNumbers(ix1, ix2, ix3 + 1)) >= 0 && (SET = nodeNumbers(ix1 + 1, ix2, ix3 + 1)) >= 0 && + (NET = nodeNumbers(ix1 + 1, ix2 + 1, ix3 + 1)) >= 0 && + (NWT = nodeNumbers(ix1, ix2 + 1, ix3 + 1)) >= 0) { + cells.push_back(makeUbTuple(SWB, SEB, NEB, NWB, SWT, SET, NET, NWT)); + } } - } - } - } + } + } } ////////////////////////////////////////////////////////////////////////// void TimeAveragedValuesCoProcessor::calculateAverageValues(double timeSteps) { - for (int level = minInitLevel; level <= maxInitLevel; level++) - { - int i; - //#ifdef _OPENMP - // #pragma omp parallel for - //#endif - //for(SPtr<Block3D> block : blockVector[level]) - for (i = 0; i < blockVector[level].size(); i++) - { - SPtr<Block3D> block = blockVector[level][i]; - if (block) - { - SPtr<ILBMKernel> kernel = block->getKernel(); - SPtr<BCArray3D> bcArray = kernel->getBCProcessor()->getBCArray(); - SPtr<DistributionArray3D> distributions = kernel->getDataSet()->getFdistributions(); - SPtr<AverageValuesArray3D> ar = kernel->getDataSet()->getAverageDensity(); - SPtr<AverageValuesArray3D> av = kernel->getDataSet()->getAverageVelocity(); - SPtr<AverageValuesArray3D> af = kernel->getDataSet()->getAverageFluctuations(); - SPtr<AverageValuesArray3D> at = kernel->getDataSet()->getAverageTriplecorrelations(); - - int minX1 = iMinC; - int minX2 = iMinC; - int minX3 = iMinC; - - int maxX1 = int(distributions->getNX1()); - int maxX2 = int(distributions->getNX2()); - int maxX3 = int(distributions->getNX3()); - - maxX1 -= 2; - maxX2 -= 2; - maxX3 -= 2; - - LBMReal rho, ux, uy, uz, uxx, uzz, uyy, uxy, uxz, uyz, rhof; - - for (int ix3 = minX3; ix3 <= maxX3; ix3++) - { - for (int ix2 = minX2; ix2 <= maxX2; ix2++) - { - for (int ix1 = minX1; ix1 <= maxX1; ix1++) - { - if (!bcArray->isUndefined(ix1, ix2, ix3) && !bcArray->isSolid(ix1, ix2, ix3)) - { - ////////////////////////////////////////////////////////////////////////// - //compute average values - ////////////////////////////////////////////////////////////////////////// - - //mean density - if ((options&Density) == Density) - { - rho = (*ar)(Rho, ix1, ix2, ix3) / timeSteps; - rhof = (*ar)(RhoF, ix1, ix2, ix3) / timeSteps; - (*ar)(Rho, ix1, ix2, ix3) = rho; - (*ar)(RhoF, ix1, ix2, ix3) = rhof - rho*rho; - } - - //mean velocity - if ((options&Velocity) == Velocity) - { - ux = (*av)(Vx, ix1, ix2, ix3) / timeSteps; - uy = (*av)(Vy, ix1, ix2, ix3) / timeSteps; - uz = (*av)(Vz, ix1, ix2, ix3) / timeSteps; - - (*av)(Vx, ix1, ix2, ix3) = ux; - (*av)(Vy, ix1, ix2, ix3) = uy; - (*av)(Vz, ix1, ix2, ix3) = uz; - } - - //fluctuations - if ((options&Fluctuations) == Fluctuations) - { - uxx = (*af)(Vxx, ix1, ix2, ix3) / timeSteps; - uyy = (*af)(Vyy, ix1, ix2, ix3) / timeSteps; - uzz = (*af)(Vzz, ix1, ix2, ix3) / timeSteps; - uxy = (*af)(Vxy, ix1, ix2, ix3) / timeSteps; - uxz = (*af)(Vxz, ix1, ix2, ix3) / timeSteps; - uyz = (*af)(Vyz, ix1, ix2, ix3) / timeSteps; - - (*af)(Vxx, ix1, ix2, ix3) = uxx - ux*ux; - (*af)(Vyy, ix1, ix2, ix3) = uyy - uy*uy; - (*af)(Vzz, ix1, ix2, ix3) = uzz - uz*uz; - (*af)(Vxy, ix1, ix2, ix3) = uxy - ux*uy; - (*af)(Vxz, ix1, ix2, ix3) = uxz - ux*uz; - (*af)(Vyz, ix1, ix2, ix3) = uyz - uy*uz; - } - - if ((options&Triplecorrelations) == Triplecorrelations) - { - //triple-correlations - (*at)(Vxxx, ix1, ix2, ix3) = (*at)(Vxxx, ix1, ix2, ix3) / timeSteps - 3.0 * uxx*ux + 2.0 * ux*ux*ux; - (*at)(Vxxy, ix1, ix2, ix3) = (*at)(Vxxy, ix1, ix2, ix3) / timeSteps - 2.0 * uxy*ux - uxx*uy + 2.0 * ux*ux*uy; - (*at)(Vxxz, ix1, ix2, ix3) = (*at)(Vxxz, ix1, ix2, ix3) / timeSteps - 2.0 * uxz*ux - uxx*uz + 2.0 * ux*ux*uz; - (*at)(Vyyy, ix1, ix2, ix3) = (*at)(Vyyy, ix1, ix2, ix3) / timeSteps - 3.0 * uyy*uy + 2.0 * uy*uy*uy; - (*at)(Vyyx, ix1, ix2, ix3) = (*at)(Vyyx, ix1, ix2, ix3) / timeSteps - 2.0 * uxy*uy - uyy*ux + 2.0 * uy*uy*ux; - (*at)(Vyyz, ix1, ix2, ix3) = (*at)(Vyyz, ix1, ix2, ix3) / timeSteps - 2.0 * uyz*uy - uyy*uz + 2.0 * uy*uy*uz; - (*at)(Vzzz, ix1, ix2, ix3) = (*at)(Vzzz, ix1, ix2, ix3) / timeSteps - 3.0 * uzz*uz + 2.0 * uz*uz*uz; - (*at)(Vzzx, ix1, ix2, ix3) = (*at)(Vzzx, ix1, ix2, ix3) / timeSteps - 2.0 * uxz*uz - uzz*ux + 2.0 * uz*uz*ux; - (*at)(Vzzy, ix1, ix2, ix3) = (*at)(Vzzy, ix1, ix2, ix3) / timeSteps - 2.0 * uyz*uz - uzz*uy + 2.0 * uz*uz*uy; - (*at)(Vxyz, ix1, ix2, ix3) = (*at)(Vxyz, ix1, ix2, ix3) / timeSteps - uxy*uz - uxz*uy - uyz*ux + 2.0 * ux*uy*uz; + for (int level = minInitLevel; level <= maxInitLevel; level++) { + int i; + //#ifdef _OPENMP + // #pragma omp parallel for + //#endif + // for(SPtr<Block3D> block : blockVector[level]) + for (i = 0; i < blockVector[level].size(); i++) { + SPtr<Block3D> block = blockVector[level][i]; + if (block) { + SPtr<ILBMKernel> kernel = block->getKernel(); + SPtr<BCArray3D> bcArray = kernel->getBCProcessor()->getBCArray(); + SPtr<DistributionArray3D> distributions = kernel->getDataSet()->getFdistributions(); + SPtr<AverageValuesArray3D> ar = kernel->getDataSet()->getAverageDensity(); + SPtr<AverageValuesArray3D> av = kernel->getDataSet()->getAverageVelocity(); + SPtr<AverageValuesArray3D> af = kernel->getDataSet()->getAverageFluctuations(); + SPtr<AverageValuesArray3D> at = kernel->getDataSet()->getAverageTriplecorrelations(); + + int minX1 = iMinC; + int minX2 = iMinC; + int minX3 = iMinC; + + int maxX1 = int(distributions->getNX1()); + int maxX2 = int(distributions->getNX2()); + int maxX3 = int(distributions->getNX3()); + + maxX1 -= 2; + maxX2 -= 2; + maxX3 -= 2; + + LBMReal rho, ux, uy, uz, uxx, uzz, uyy, uxy, uxz, uyz, rhof; + + for (int ix3 = minX3; ix3 <= maxX3; ix3++) { + for (int ix2 = minX2; ix2 <= maxX2; ix2++) { + for (int ix1 = minX1; ix1 <= maxX1; ix1++) { + if (!bcArray->isUndefined(ix1, ix2, ix3) && !bcArray->isSolid(ix1, ix2, ix3)) { + ////////////////////////////////////////////////////////////////////////// + // compute average values + ////////////////////////////////////////////////////////////////////////// + + // mean density + if ((options & Density) == Density) { + rho = (*ar)(Rho, ix1, ix2, ix3) / timeSteps; + rhof = (*ar)(RhoF, ix1, ix2, ix3) / timeSteps; + (*ar)(Rho, ix1, ix2, ix3) = rho; + (*ar)(RhoF, ix1, ix2, ix3) = rhof - rho * rho; + } + + // mean velocity + if ((options & Velocity) == Velocity) { + ux = (*av)(Vx, ix1, ix2, ix3) / timeSteps; + uy = (*av)(Vy, ix1, ix2, ix3) / timeSteps; + uz = (*av)(Vz, ix1, ix2, ix3) / timeSteps; + + (*av)(Vx, ix1, ix2, ix3) = ux; + (*av)(Vy, ix1, ix2, ix3) = uy; + (*av)(Vz, ix1, ix2, ix3) = uz; + } + + // fluctuations + if ((options & Fluctuations) == Fluctuations) { + uxx = (*af)(Vxx, ix1, ix2, ix3) / timeSteps; + uyy = (*af)(Vyy, ix1, ix2, ix3) / timeSteps; + uzz = (*af)(Vzz, ix1, ix2, ix3) / timeSteps; + uxy = (*af)(Vxy, ix1, ix2, ix3) / timeSteps; + uxz = (*af)(Vxz, ix1, ix2, ix3) / timeSteps; + uyz = (*af)(Vyz, ix1, ix2, ix3) / timeSteps; + + (*af)(Vxx, ix1, ix2, ix3) = uxx - ux * ux; + (*af)(Vyy, ix1, ix2, ix3) = uyy - uy * uy; + (*af)(Vzz, ix1, ix2, ix3) = uzz - uz * uz; + (*af)(Vxy, ix1, ix2, ix3) = uxy - ux * uy; + (*af)(Vxz, ix1, ix2, ix3) = uxz - ux * uz; + (*af)(Vyz, ix1, ix2, ix3) = uyz - uy * uz; + } + + if ((options & Triplecorrelations) == Triplecorrelations) { + // triple-correlations + (*at)(Vxxx, ix1, ix2, ix3) = + (*at)(Vxxx, ix1, ix2, ix3) / timeSteps - 3.0 * uxx * ux + 2.0 * ux * ux * ux; + (*at)(Vxxy, ix1, ix2, ix3) = (*at)(Vxxy, ix1, ix2, ix3) / timeSteps - + 2.0 * uxy * ux - uxx * uy + 2.0 * ux * ux * uy; + (*at)(Vxxz, ix1, ix2, ix3) = (*at)(Vxxz, ix1, ix2, ix3) / timeSteps - + 2.0 * uxz * ux - uxx * uz + 2.0 * ux * ux * uz; + (*at)(Vyyy, ix1, ix2, ix3) = + (*at)(Vyyy, ix1, ix2, ix3) / timeSteps - 3.0 * uyy * uy + 2.0 * uy * uy * uy; + (*at)(Vyyx, ix1, ix2, ix3) = (*at)(Vyyx, ix1, ix2, ix3) / timeSteps - + 2.0 * uxy * uy - uyy * ux + 2.0 * uy * uy * ux; + (*at)(Vyyz, ix1, ix2, ix3) = (*at)(Vyyz, ix1, ix2, ix3) / timeSteps - + 2.0 * uyz * uy - uyy * uz + 2.0 * uy * uy * uz; + (*at)(Vzzz, ix1, ix2, ix3) = + (*at)(Vzzz, ix1, ix2, ix3) / timeSteps - 3.0 * uzz * uz + 2.0 * uz * uz * uz; + (*at)(Vzzx, ix1, ix2, ix3) = (*at)(Vzzx, ix1, ix2, ix3) / timeSteps - + 2.0 * uxz * uz - uzz * ux + 2.0 * uz * uz * ux; + (*at)(Vzzy, ix1, ix2, ix3) = (*at)(Vzzy, ix1, ix2, ix3) / timeSteps - + 2.0 * uyz * uz - uzz * uy + 2.0 * uz * uz * uy; + (*at)(Vxyz, ix1, ix2, ix3) = (*at)(Vxyz, ix1, ix2, ix3) / timeSteps - uxy * uz - + uxz * uy - uyz * ux + 2.0 * ux * uy * uz; + } + ////////////////////////////////////////////////////////////////////////// + } } - ////////////////////////////////////////////////////////////////////////// - } - } - } + } + } } - } - } - } + } + } } ////////////////////////////////////////////////////////////////////////// void TimeAveragedValuesCoProcessor::calculateSubtotal(double step) { - if (scheduler->isDue(step)) - { - - //DEBUG///////////////////// - //UBLOG(logINFO, "calculateSubtotal::step = " << step); - //////////////////////////// - LBMReal f[27]; - - -//#ifdef _OPENMP -//#pragma omp parallel private (f) -//#endif - { - for (int level = minInitLevel; level <= maxInitLevel; level++) - { - int i; -//#ifdef _OPENMP -//#pragma omp for schedule(dynamic) -//#endif - //for(SPtr<Block3D> block : blockVector[level]) - for (i = 0; i < blockVector[level].size(); i++) - { - SPtr<Block3D> block = blockVector[level][i]; - if (block) - { - SPtr<ILBMKernel> kernel = block->getKernel(); - SPtr<BCArray3D> bcArray = kernel->getBCProcessor()->getBCArray(); - SPtr<DistributionArray3D> distributions = kernel->getDataSet()->getFdistributions(); - SPtr<AverageValuesArray3D> ar = kernel->getDataSet()->getAverageDensity(); - SPtr<AverageValuesArray3D> av = kernel->getDataSet()->getAverageVelocity(); - SPtr<AverageValuesArray3D> af = kernel->getDataSet()->getAverageFluctuations(); - SPtr<AverageValuesArray3D> at = kernel->getDataSet()->getAverageTriplecorrelations(); - - int minX1 = iMinC; - int minX2 = iMinC; - int minX3 = iMinC; - - int maxX1 = int(distributions->getNX1()); - int maxX2 = int(distributions->getNX2()); - int maxX3 = int(distributions->getNX3()); - - maxX1 -= 2; - maxX2 -= 2; - maxX3 -= 2; - - for (int ix3 = minX3; ix3 <= maxX3; ix3++) - { - for (int ix2 = minX2; ix2 <= maxX2; ix2++) - { - for (int ix1 = minX1; ix1 <= maxX1; ix1++) - { - if (!bcArray->isUndefined(ix1, ix2, ix3) && !bcArray->isSolid(ix1, ix2, ix3)) - { - ////////////////////////////////////////////////////////////////////////// - //read distribution - //////////////////////////////////////////////////////////////////////////// - - distributions->getDistribution(f, ix1, ix2, ix3); - ////////////////////////////////////////////////////////////////////////// - //compute velocity - ////////////////////////////////////////////////////////////////////////// - LBMReal vx, vy, vz, rho; - calcMacros(f, rho, vx, vy, vz); - //double press = D3Q27System::calcPress(f, rho, vx, vy, vz); - - ////////////////////////////////////////////////////////////////////////// - //compute subtotals - ////////////////////////////////////////////////////////////////////////// - - //mean density - if ((options&Density) == Density) - { - (*ar)(0, ix1, ix2, ix3) = (*ar)(Rho, ix1, ix2, ix3) + rho; - (*ar)(RhoF, ix1, ix2, ix3) = (*ar)(RhoF, ix1, ix2, ix3) + rho*rho; - } - - //mean velocity - if ((options&Velocity) == Velocity) - { - (*av)(Vx, ix1, ix2, ix3) = (*av)(Vx, ix1, ix2, ix3) + vx; - (*av)(Vy, ix1, ix2, ix3) = (*av)(Vy, ix1, ix2, ix3) + vy; - (*av)(Vz, ix1, ix2, ix3) = (*av)(Vz, ix1, ix2, ix3) + vz; - } - - //fluctuations - if ((options&Fluctuations) == Fluctuations) - { - (*af)(Vxx, ix1, ix2, ix3) = (*af)(Vxx, ix1, ix2, ix3) + vx*vx; - (*af)(Vyy, ix1, ix2, ix3) = (*af)(Vyy, ix1, ix2, ix3) + vy*vy; - (*af)(Vzz, ix1, ix2, ix3) = (*af)(Vzz, ix1, ix2, ix3) + vz*vz; - (*af)(Vxy, ix1, ix2, ix3) = (*af)(Vxy, ix1, ix2, ix3) + vx*vy; - (*af)(Vxz, ix1, ix2, ix3) = (*af)(Vxz, ix1, ix2, ix3) + vx*vz; - (*af)(Vyz, ix1, ix2, ix3) = (*af)(Vyz, ix1, ix2, ix3) + vy*vz; - } - - //triple-correlations - if ((options&Triplecorrelations) == Triplecorrelations) - { - (*at)(Vxxx, ix1, ix2, ix3) = (*at)(Vxxx, ix1, ix2, ix3) + vx*vx*vx; - (*at)(Vxxy, ix1, ix2, ix3) = (*at)(Vxxy, ix1, ix2, ix3) + vx*vx*vy; - (*at)(Vxxz, ix1, ix2, ix3) = (*at)(Vxxz, ix1, ix2, ix3) + vx*vx*vz; - (*at)(Vyyy, ix1, ix2, ix3) = (*at)(Vyyy, ix1, ix2, ix3) + vy*vy*vy; - (*at)(Vyyx, ix1, ix2, ix3) = (*at)(Vyyx, ix1, ix2, ix3) + vy*vy*vx; - (*at)(Vyyz, ix1, ix2, ix3) = (*at)(Vyyz, ix1, ix2, ix3) + vy*vy*vz; - (*at)(Vzzz, ix1, ix2, ix3) = (*at)(Vzzz, ix1, ix2, ix3) + vz*vz*vz; - (*at)(Vzzx, ix1, ix2, ix3) = (*at)(Vzzx, ix1, ix2, ix3) + vz*vz*vx; - (*at)(Vzzy, ix1, ix2, ix3) = (*at)(Vzzy, ix1, ix2, ix3) + vz*vz*vy; - (*at)(Vxyz, ix1, ix2, ix3) = (*at)(Vxyz, ix1, ix2, ix3) + vx*vy*vz; - } - ////////////////////////////////////////////////////////////////////////// - } + if (scheduler->isDue(step)) { + + // DEBUG///////////////////// + // UBLOG(logINFO, "calculateSubtotal::step = " << step); + //////////////////////////// + LBMReal f[27]; + + //#ifdef _OPENMP + //#pragma omp parallel private (f) + //#endif + { + for (int level = minInitLevel; level <= maxInitLevel; level++) { + int i; + //#ifdef _OPENMP + //#pragma omp for schedule(dynamic) + //#endif + // for(SPtr<Block3D> block : blockVector[level]) + for (i = 0; i < blockVector[level].size(); i++) { + SPtr<Block3D> block = blockVector[level][i]; + if (block) { + SPtr<ILBMKernel> kernel = block->getKernel(); + SPtr<BCArray3D> bcArray = kernel->getBCProcessor()->getBCArray(); + SPtr<DistributionArray3D> distributions = kernel->getDataSet()->getFdistributions(); + SPtr<AverageValuesArray3D> ar = kernel->getDataSet()->getAverageDensity(); + SPtr<AverageValuesArray3D> av = kernel->getDataSet()->getAverageVelocity(); + SPtr<AverageValuesArray3D> af = kernel->getDataSet()->getAverageFluctuations(); + SPtr<AverageValuesArray3D> at = kernel->getDataSet()->getAverageTriplecorrelations(); + + int minX1 = iMinC; + int minX2 = iMinC; + int minX3 = iMinC; + + int maxX1 = int(distributions->getNX1()); + int maxX2 = int(distributions->getNX2()); + int maxX3 = int(distributions->getNX3()); + + maxX1 -= 2; + maxX2 -= 2; + maxX3 -= 2; + + for (int ix3 = minX3; ix3 <= maxX3; ix3++) { + for (int ix2 = minX2; ix2 <= maxX2; ix2++) { + for (int ix1 = minX1; ix1 <= maxX1; ix1++) { + if (!bcArray->isUndefined(ix1, ix2, ix3) && !bcArray->isSolid(ix1, ix2, ix3)) { + ////////////////////////////////////////////////////////////////////////// + // read distribution + //////////////////////////////////////////////////////////////////////////// + + distributions->getDistribution(f, ix1, ix2, ix3); + ////////////////////////////////////////////////////////////////////////// + // compute velocity + ////////////////////////////////////////////////////////////////////////// + LBMReal vx, vy, vz, rho; + calcMacros(f, rho, vx, vy, vz); + // double press = D3Q27System::calcPress(f, rho, vx, vy, vz); + + ////////////////////////////////////////////////////////////////////////// + // compute subtotals + ////////////////////////////////////////////////////////////////////////// + + // mean density + if ((options & Density) == Density) { + (*ar)(0, ix1, ix2, ix3) = (*ar)(Rho, ix1, ix2, ix3) + rho; + (*ar)(RhoF, ix1, ix2, ix3) = (*ar)(RhoF, ix1, ix2, ix3) + rho * rho; + } + + // mean velocity + if ((options & Velocity) == Velocity) { + (*av)(Vx, ix1, ix2, ix3) = (*av)(Vx, ix1, ix2, ix3) + vx; + (*av)(Vy, ix1, ix2, ix3) = (*av)(Vy, ix1, ix2, ix3) + vy; + (*av)(Vz, ix1, ix2, ix3) = (*av)(Vz, ix1, ix2, ix3) + vz; + } + + // fluctuations + if ((options & Fluctuations) == Fluctuations) { + (*af)(Vxx, ix1, ix2, ix3) = (*af)(Vxx, ix1, ix2, ix3) + vx * vx; + (*af)(Vyy, ix1, ix2, ix3) = (*af)(Vyy, ix1, ix2, ix3) + vy * vy; + (*af)(Vzz, ix1, ix2, ix3) = (*af)(Vzz, ix1, ix2, ix3) + vz * vz; + (*af)(Vxy, ix1, ix2, ix3) = (*af)(Vxy, ix1, ix2, ix3) + vx * vy; + (*af)(Vxz, ix1, ix2, ix3) = (*af)(Vxz, ix1, ix2, ix3) + vx * vz; + (*af)(Vyz, ix1, ix2, ix3) = (*af)(Vyz, ix1, ix2, ix3) + vy * vz; + } + + // triple-correlations + if ((options & Triplecorrelations) == Triplecorrelations) { + (*at)(Vxxx, ix1, ix2, ix3) = (*at)(Vxxx, ix1, ix2, ix3) + vx * vx * vx; + (*at)(Vxxy, ix1, ix2, ix3) = (*at)(Vxxy, ix1, ix2, ix3) + vx * vx * vy; + (*at)(Vxxz, ix1, ix2, ix3) = (*at)(Vxxz, ix1, ix2, ix3) + vx * vx * vz; + (*at)(Vyyy, ix1, ix2, ix3) = (*at)(Vyyy, ix1, ix2, ix3) + vy * vy * vy; + (*at)(Vyyx, ix1, ix2, ix3) = (*at)(Vyyx, ix1, ix2, ix3) + vy * vy * vx; + (*at)(Vyyz, ix1, ix2, ix3) = (*at)(Vyyz, ix1, ix2, ix3) + vy * vy * vz; + (*at)(Vzzz, ix1, ix2, ix3) = (*at)(Vzzz, ix1, ix2, ix3) + vz * vz * vz; + (*at)(Vzzx, ix1, ix2, ix3) = (*at)(Vzzx, ix1, ix2, ix3) + vz * vz * vx; + (*at)(Vzzy, ix1, ix2, ix3) = (*at)(Vzzy, ix1, ix2, ix3) + vz * vz * vy; + (*at)(Vxyz, ix1, ix2, ix3) = (*at)(Vxyz, ix1, ix2, ix3) + vx * vy * vz; + } + ////////////////////////////////////////////////////////////////////////// + } + } + } } - } - } - } + } + } } - } - } - } + } + } } ////////////////////////////////////////////////////////////////////////// void TimeAveragedValuesCoProcessor::planarAverage(double step) { - std::ofstream ostr; - - if (root) - { - int istep = int(step); - std::string fname = path + "/tav/" + "tav" + UbSystem::toString(istep) + ".csv"; - - - ostr.open(fname.c_str(), std::ios_base::out); - if (!ostr) - { - ostr.clear(); - std::string path = UbSystem::getPathFromString(fname); - if (path.size() > 0) { UbSystem::makeDirectory(path); ostr.open(fname.c_str(), std::ios_base::out); } - if (!ostr) throw UbException(UB_EXARGS, "couldn't open file " + fname); - } - - ostr << "z"; - - if ((options&Density) == Density) - { - ostr << ";Rho;RhoF"; - } - //mean velocity - if ((options&Velocity) == Velocity) - { - ostr << ";Vx;Vy;Vz"; - } - //fluctuations - if ((options&Fluctuations) == Fluctuations) - { - ostr << ";Vxx;Vyy;Vzz;Vxy;Vxz;Vyz"; - } - //triple-correlations - if ((options&Triplecorrelations) == Triplecorrelations) - { - ostr << ";Vxxx;Vxxy;Vxxz;Vyyy;Vyyx;Vyyz;Vzzz;Vzzx;Vzzy;Vxyz"; - } - ostr << "\n"; - } - - int size = (int)levels.size(); - int sizeOfLevelCoords = (int)levelCoords.size(); - - if (2 * size != sizeOfLevelCoords) - { - UB_THROW(UbException(UB_EXARGS, "Number of levels coordinates don't match number of levels!")); - } - - int k = 0; - - for (int i = 0; i < size; i++) - { - int level = levels[i]; - double dx = grid->getDeltaX(level); - double start = levelCoords[k]; - double stop = levelCoords[k + 1]; - - for (double j = start; j <stop; j += dx) - { - IntegrateValuesHelper intValHelp(grid, comm, - bounds[0], bounds[1], j, - bounds[3], bounds[4], j + dx, level); - - std::vector<IntegrateValuesHelper::CalcNodes> cnodes = intValHelp.getCNodes(); - //if (cnodes.size() == 0) - //{ - // continue; - //} - calculateAverageValuesForPlane(cnodes); - - if (root) - { - double numberOfFluidsNodes = intValHelp.getNumberOfFluidsNodes(); - if (numberOfFluidsNodes > 0) - { - ostr << j + 0.5*dx << std::setprecision(15); - - //mean density - if ((options&Density) == Density) - { - double rho = saRho / numberOfFluidsNodes; - double rhoF = saRhoF / numberOfFluidsNodes; - ostr << ";" << rho << ";" << rhoF; - } - - //mean velocity - if ((options&Velocity) == Velocity) - { - double Vx = saVx / numberOfFluidsNodes; - double Vy = saVy / numberOfFluidsNodes; - double Vz = saVz / numberOfFluidsNodes; - ostr << ";" << Vx << ";" << Vy << ";" << Vz; - } - //fluctuations - if ((options&Fluctuations) == Fluctuations) - { - double Vxx = saVxx / numberOfFluidsNodes; - double Vyy = saVyy / numberOfFluidsNodes; - double Vzz = saVzz / numberOfFluidsNodes; - double Vxy = saVxy / numberOfFluidsNodes; - double Vxz = saVxz / numberOfFluidsNodes; - double Vyz = saVyz / numberOfFluidsNodes; - ostr << ";" << Vxx << ";" << Vyy << ";" << Vzz << ";" << Vxy << ";" << Vxz << ";" << Vyz; - } - //triple-correlations - if ((options&Triplecorrelations) == Triplecorrelations) - { - double Vxxx = saVxxx / numberOfFluidsNodes; - double Vxxy = saVxxy / numberOfFluidsNodes; - double Vxxz = saVxxz / numberOfFluidsNodes; - double Vyyy = saVyyy / numberOfFluidsNodes; - double Vyyx = saVyyx / numberOfFluidsNodes; - double Vyyz = saVyyz / numberOfFluidsNodes; - double Vzzz = saVzzz / numberOfFluidsNodes; - double Vzzx = saVzzx / numberOfFluidsNodes; - double Vzzy = saVzzy / numberOfFluidsNodes; - double Vxyz = saVxyz / numberOfFluidsNodes; - ostr << ";" << Vxxx << ";" << Vxxy << ";" << Vxxz << ";" << Vyyy << ";" << Vyyx << ";" << Vyyz << ";" << Vzzz << ";" << Vzzx << ";" << Vzzy << ";" << Vxyz; - } - ostr << "\n"; + std::ofstream ostr; + + if (root) { + int istep = int(step); + std::string fname = path + "/tav/" + "tav" + UbSystem::toString(istep) + ".csv"; + + ostr.open(fname.c_str(), std::ios_base::out); + if (!ostr) { + ostr.clear(); + std::string path = UbSystem::getPathFromString(fname); + if (path.size() > 0) { + UbSystem::makeDirectory(path); + ostr.open(fname.c_str(), std::ios_base::out); } - } - } - k += 2; - } - - if (root) - { - ostr.close(); - UBLOG(logINFO, "TimeAveragedValuesCoProcessor::planarAverage() step: " << (int)step); - } + if (!ostr) + throw UbException(UB_EXARGS, "couldn't open file " + fname); + } + + ostr << "z"; + + if ((options & Density) == Density) { + ostr << ";Rho;RhoF"; + } + // mean velocity + if ((options & Velocity) == Velocity) { + ostr << ";Vx;Vy;Vz"; + } + // fluctuations + if ((options & Fluctuations) == Fluctuations) { + ostr << ";Vxx;Vyy;Vzz;Vxy;Vxz;Vyz"; + } + // triple-correlations + if ((options & Triplecorrelations) == Triplecorrelations) { + ostr << ";Vxxx;Vxxy;Vxxz;Vyyy;Vyyx;Vyyz;Vzzz;Vzzx;Vzzy;Vxyz"; + } + ostr << "\n"; + } + + int size = (int)levels.size(); + int sizeOfLevelCoords = (int)levelCoords.size(); + + if (2 * size != sizeOfLevelCoords) { + UB_THROW(UbException(UB_EXARGS, "Number of levels coordinates don't match number of levels!")); + } + + int k = 0; + + for (int i = 0; i < size; i++) { + int level = levels[i]; + double dx = grid->getDeltaX(level); + double start = levelCoords[k]; + double stop = levelCoords[k + 1]; + + for (double j = start; j < stop; j += dx) { + IntegrateValuesHelper intValHelp(grid, comm, bounds[0], bounds[1], j, bounds[3], bounds[4], j + dx, level); + + std::vector<IntegrateValuesHelper::CalcNodes> cnodes = intValHelp.getCNodes(); + // if (cnodes.size() == 0) + //{ + // continue; + //} + calculateAverageValuesForPlane(cnodes); + + if (root) { + double numberOfFluidsNodes = intValHelp.getNumberOfFluidsNodes(); + if (numberOfFluidsNodes > 0) { + ostr << j + 0.5 * dx << std::setprecision(15); + + // mean density + if ((options & Density) == Density) { + double rho = saRho / numberOfFluidsNodes; + double rhoF = saRhoF / numberOfFluidsNodes; + ostr << ";" << rho << ";" << rhoF; + } + + // mean velocity + if ((options & Velocity) == Velocity) { + double Vx = saVx / numberOfFluidsNodes; + double Vy = saVy / numberOfFluidsNodes; + double Vz = saVz / numberOfFluidsNodes; + ostr << ";" << Vx << ";" << Vy << ";" << Vz; + } + // fluctuations + if ((options & Fluctuations) == Fluctuations) { + double Vxx = saVxx / numberOfFluidsNodes; + double Vyy = saVyy / numberOfFluidsNodes; + double Vzz = saVzz / numberOfFluidsNodes; + double Vxy = saVxy / numberOfFluidsNodes; + double Vxz = saVxz / numberOfFluidsNodes; + double Vyz = saVyz / numberOfFluidsNodes; + ostr << ";" << Vxx << ";" << Vyy << ";" << Vzz << ";" << Vxy << ";" << Vxz << ";" << Vyz; + } + // triple-correlations + if ((options & Triplecorrelations) == Triplecorrelations) { + double Vxxx = saVxxx / numberOfFluidsNodes; + double Vxxy = saVxxy / numberOfFluidsNodes; + double Vxxz = saVxxz / numberOfFluidsNodes; + double Vyyy = saVyyy / numberOfFluidsNodes; + double Vyyx = saVyyx / numberOfFluidsNodes; + double Vyyz = saVyyz / numberOfFluidsNodes; + double Vzzz = saVzzz / numberOfFluidsNodes; + double Vzzx = saVzzx / numberOfFluidsNodes; + double Vzzy = saVzzy / numberOfFluidsNodes; + double Vxyz = saVxyz / numberOfFluidsNodes; + ostr << ";" << Vxxx << ";" << Vxxy << ";" << Vxxz << ";" << Vyyy << ";" << Vyyx << ";" << Vyyz + << ";" << Vzzz << ";" << Vzzx << ";" << Vzzy << ";" << Vxyz; + } + ostr << "\n"; + } + } + } + k += 2; + } + + if (root) { + ostr.close(); + UBLOG(logINFO, "TimeAveragedValuesCoProcessor::planarAverage() step: " << (int)step); + } } ////////////////////////////////////////////////////////////////////////// void TimeAveragedValuesCoProcessor::reset() { - for (int level = minInitLevel; level <= maxInitLevel; level++) - { - for (SPtr<Block3D> block : blockVector[level]) - { - if (block) - { - SPtr<AverageValuesArray3D> arho = block->getKernel()->getDataSet()->getAverageDensity(); - if (arho) - { - arho->reset(0.0); - } - - SPtr<AverageValuesArray3D> avel = block->getKernel()->getDataSet()->getAverageVelocity(); - if (avel) - { - avel->reset(0.0); - } - - SPtr<AverageValuesArray3D> afl = block->getKernel()->getDataSet()->getAverageFluctuations(); - if (afl) - { - afl->reset(0.0); + for (int level = minInitLevel; level <= maxInitLevel; level++) { + for (SPtr<Block3D> block : blockVector[level]) { + if (block) { + SPtr<AverageValuesArray3D> arho = block->getKernel()->getDataSet()->getAverageDensity(); + if (arho) { + arho->reset(0.0); + } + + SPtr<AverageValuesArray3D> avel = block->getKernel()->getDataSet()->getAverageVelocity(); + if (avel) { + avel->reset(0.0); + } + + SPtr<AverageValuesArray3D> afl = block->getKernel()->getDataSet()->getAverageFluctuations(); + if (afl) { + afl->reset(0.0); + } + + SPtr<AverageValuesArray3D> atrp = block->getKernel()->getDataSet()->getAverageTriplecorrelations(); + if (atrp) { + atrp->reset(0.0); + } } - - SPtr<AverageValuesArray3D> atrp = block->getKernel()->getDataSet()->getAverageTriplecorrelations(); - if (atrp) - { - atrp->reset(0.0); - } - } - } - } + } + } } ////////////////////////////////////////////////////////////////////////// void TimeAveragedValuesCoProcessor::setWithGhostLayer(bool val) { - withGhostLayer = val; - - if (withGhostLayer) - { - iMinC = 0; - } - else - { - iMinC = 1; - } + withGhostLayer = val; + + if (withGhostLayer) { + iMinC = 0; + } else { + iMinC = 1; + } } ////////////////////////////////////////////////////////////////////////// -bool TimeAveragedValuesCoProcessor::getWithGhostLayer() -{ - return withGhostLayer; -} +bool TimeAveragedValuesCoProcessor::getWithGhostLayer() { return withGhostLayer; } ////////////////////////////////////////////////////////////////////////// -void TimeAveragedValuesCoProcessor::calculateAverageValuesForPlane(std::vector<IntegrateValuesHelper::CalcNodes>& cnodes) +void TimeAveragedValuesCoProcessor::calculateAverageValuesForPlane( + std::vector<IntegrateValuesHelper::CalcNodes> &cnodes) { - saVx = 0; - saVy = 0; - saVz = 0; - - saVxx = 0; - saVyy = 0; - saVzz = 0; - saVxy = 0; - saVxz = 0; - saVyz = 0; - - saVxxx = 0; - saVxxy = 0; - saVxxz = 0; - saVyyy = 0; - saVyyx = 0; - saVyyz = 0; - saVzzz = 0; - saVzzx = 0; - saVzzy = 0; - saVxyz = 0; - - saRho = 0; - saRhoF = 0; - - double lsaVx = 0; - double lsaVy = 0; - double lsaVz = 0; - - double lsaVxx = 0; - double lsaVyy = 0; - double lsaVzz = 0; - double lsaVxy = 0; - double lsaVxz = 0; - double lsaVyz = 0; - - double lsaVxxx = 0; - double lsaVxxy = 0; - double lsaVxxz = 0; - double lsaVyyy = 0; - double lsaVyyx = 0; - double lsaVyyz = 0; - double lsaVzzz = 0; - double lsaVzzx = 0; - double lsaVzzy = 0; - double lsaVxyz = 0; - - double lsaRho = 0; - double lsaRhoF = 0; - - for (IntegrateValuesHelper::CalcNodes cn : cnodes) - { - SPtr<ILBMKernel> kernel = cn.block->getKernel(); - SPtr<AverageValuesArray3D> averagedDensity = kernel->getDataSet()->getAverageDensity(); - SPtr<AverageValuesArray3D> averagedVelocity = kernel->getDataSet()->getAverageVelocity(); - SPtr<AverageValuesArray3D> averagedFluctuations = kernel->getDataSet()->getAverageFluctuations(); - SPtr<AverageValuesArray3D> averagedTriplecorrelations = kernel->getDataSet()->getAverageTriplecorrelations(); - - for (UbTupleInt3 node : cn.nodes) - { - double aRho = (*averagedDensity)(Rho, val<1>(node), val<2>(node), val<3>(node)); - double aRhoF = (*averagedDensity)(RhoF, val<1>(node), val<2>(node), val<3>(node)); - - double aVx = (*averagedVelocity)(Vx, val<1>(node), val<2>(node), val<3>(node)); - double aVy = (*averagedVelocity)(Vy, val<1>(node), val<2>(node), val<3>(node)); - double aVz = (*averagedVelocity)(Vz, val<1>(node), val<2>(node), val<3>(node)); - - double aVxx = (*averagedFluctuations)(Vxx, val<1>(node), val<2>(node), val<3>(node)); - double aVyy = (*averagedFluctuations)(Vyy, val<1>(node), val<2>(node), val<3>(node)); - double aVzz = (*averagedFluctuations)(Vzz, val<1>(node), val<2>(node), val<3>(node)); - double aVxy = (*averagedFluctuations)(Vxy, val<1>(node), val<2>(node), val<3>(node)); - double aVxz = (*averagedFluctuations)(Vxz, val<1>(node), val<2>(node), val<3>(node)); - double aVyz = (*averagedFluctuations)(Vyz, val<1>(node), val<2>(node), val<3>(node)); - - - double aVxxx = (*averagedTriplecorrelations)(Vxxx, val<1>(node), val<2>(node), val<3>(node)); - double aVxxy = (*averagedTriplecorrelations)(Vxxy, val<1>(node), val<2>(node), val<3>(node)); - double aVxxz = (*averagedTriplecorrelations)(Vxxz, val<1>(node), val<2>(node), val<3>(node)); - double aVyyy = (*averagedTriplecorrelations)(Vyyy, val<1>(node), val<2>(node), val<3>(node)); - double aVyyx = (*averagedTriplecorrelations)(Vyyx, val<1>(node), val<2>(node), val<3>(node)); - double aVyyz = (*averagedTriplecorrelations)(Vyyz, val<1>(node), val<2>(node), val<3>(node)); - double aVzzz = (*averagedTriplecorrelations)(Vzzz, val<1>(node), val<2>(node), val<3>(node)); - double aVzzx = (*averagedTriplecorrelations)(Vzzx, val<1>(node), val<2>(node), val<3>(node)); - double aVzzy = (*averagedTriplecorrelations)(Vzzy, val<1>(node), val<2>(node), val<3>(node)); - double aVxyz = (*averagedTriplecorrelations)(Vxyz, val<1>(node), val<2>(node), val<3>(node)); - - lsaRho += aRho; - lsaRhoF += aRhoF; - - lsaVx += aVx; - lsaVy += aVy; - lsaVz += aVz; - - lsaVxx += aVxx; - lsaVyy += aVyy; - lsaVzz += aVzz; - lsaVxy += aVxy; - lsaVxz += aVxz; - lsaVyz += aVyz; - - lsaVxxx += aVxxx; - lsaVxxy += aVxxy; - lsaVxxz += aVxxz; - lsaVyyy += aVyyy; - lsaVyyx += aVyyx; - lsaVyyz += aVyyz; - lsaVzzz += aVzzz; - lsaVzzx += aVzzx; - lsaVzzy += aVzzy; - lsaVxyz += aVxyz; - } - } - std::vector<double> values; - std::vector<double> rvalues; - - values.push_back(lsaRho); - values.push_back(lsaRhoF); - - values.push_back(lsaVx); - values.push_back(lsaVy); - values.push_back(lsaVz); - - values.push_back(lsaVxx); - values.push_back(lsaVyy); - values.push_back(lsaVzz); - values.push_back(lsaVxy); - values.push_back(lsaVxz); - values.push_back(lsaVyz); - - values.push_back(lsaVxxx); - values.push_back(lsaVxxy); - values.push_back(lsaVxxz); - values.push_back(lsaVyyy); - values.push_back(lsaVyyx); - values.push_back(lsaVyyz); - values.push_back(lsaVzzz); - values.push_back(lsaVzzx); - values.push_back(lsaVzzy); - values.push_back(lsaVxyz); - - rvalues = comm->gather(values); - if (root) - { - for (int i = 0; i < (int)rvalues.size(); i += 21) - { - saRho += rvalues[i]; - saRhoF += rvalues[i + 1]; - - saVx += rvalues[i + 2]; - saVy += rvalues[i + 3]; - saVz += rvalues[i + 4]; - - saVxx += rvalues[i + 5]; - saVyy += rvalues[i + 6]; - saVzz += rvalues[i + 7]; - saVxy += rvalues[i + 8]; - saVxz += rvalues[i + 9]; - saVyz += rvalues[i + 10]; - - saVxxx += rvalues[i + 11]; - saVxxy += rvalues[i + 12]; - saVxxz += rvalues[i + 13]; - saVyyy += rvalues[i + 14]; - saVyyx += rvalues[i + 15]; - saVyyz += rvalues[i + 16]; - saVzzz += rvalues[i + 17]; - saVzzx += rvalues[i + 18]; - saVzzy += rvalues[i + 19]; - saVxyz += rvalues[i + 20]; - } - } + saVx = 0; + saVy = 0; + saVz = 0; + + saVxx = 0; + saVyy = 0; + saVzz = 0; + saVxy = 0; + saVxz = 0; + saVyz = 0; + + saVxxx = 0; + saVxxy = 0; + saVxxz = 0; + saVyyy = 0; + saVyyx = 0; + saVyyz = 0; + saVzzz = 0; + saVzzx = 0; + saVzzy = 0; + saVxyz = 0; + + saRho = 0; + saRhoF = 0; + + double lsaVx = 0; + double lsaVy = 0; + double lsaVz = 0; + + double lsaVxx = 0; + double lsaVyy = 0; + double lsaVzz = 0; + double lsaVxy = 0; + double lsaVxz = 0; + double lsaVyz = 0; + + double lsaVxxx = 0; + double lsaVxxy = 0; + double lsaVxxz = 0; + double lsaVyyy = 0; + double lsaVyyx = 0; + double lsaVyyz = 0; + double lsaVzzz = 0; + double lsaVzzx = 0; + double lsaVzzy = 0; + double lsaVxyz = 0; + + double lsaRho = 0; + double lsaRhoF = 0; + + for (IntegrateValuesHelper::CalcNodes cn : cnodes) { + SPtr<ILBMKernel> kernel = cn.block->getKernel(); + SPtr<AverageValuesArray3D> averagedDensity = kernel->getDataSet()->getAverageDensity(); + SPtr<AverageValuesArray3D> averagedVelocity = kernel->getDataSet()->getAverageVelocity(); + SPtr<AverageValuesArray3D> averagedFluctuations = kernel->getDataSet()->getAverageFluctuations(); + SPtr<AverageValuesArray3D> averagedTriplecorrelations = kernel->getDataSet()->getAverageTriplecorrelations(); + + for (UbTupleInt3 node : cn.nodes) { + double aRho = (*averagedDensity)(Rho, val<1>(node), val<2>(node), val<3>(node)); + double aRhoF = (*averagedDensity)(RhoF, val<1>(node), val<2>(node), val<3>(node)); + + double aVx = (*averagedVelocity)(Vx, val<1>(node), val<2>(node), val<3>(node)); + double aVy = (*averagedVelocity)(Vy, val<1>(node), val<2>(node), val<3>(node)); + double aVz = (*averagedVelocity)(Vz, val<1>(node), val<2>(node), val<3>(node)); + + double aVxx = (*averagedFluctuations)(Vxx, val<1>(node), val<2>(node), val<3>(node)); + double aVyy = (*averagedFluctuations)(Vyy, val<1>(node), val<2>(node), val<3>(node)); + double aVzz = (*averagedFluctuations)(Vzz, val<1>(node), val<2>(node), val<3>(node)); + double aVxy = (*averagedFluctuations)(Vxy, val<1>(node), val<2>(node), val<3>(node)); + double aVxz = (*averagedFluctuations)(Vxz, val<1>(node), val<2>(node), val<3>(node)); + double aVyz = (*averagedFluctuations)(Vyz, val<1>(node), val<2>(node), val<3>(node)); + + double aVxxx = (*averagedTriplecorrelations)(Vxxx, val<1>(node), val<2>(node), val<3>(node)); + double aVxxy = (*averagedTriplecorrelations)(Vxxy, val<1>(node), val<2>(node), val<3>(node)); + double aVxxz = (*averagedTriplecorrelations)(Vxxz, val<1>(node), val<2>(node), val<3>(node)); + double aVyyy = (*averagedTriplecorrelations)(Vyyy, val<1>(node), val<2>(node), val<3>(node)); + double aVyyx = (*averagedTriplecorrelations)(Vyyx, val<1>(node), val<2>(node), val<3>(node)); + double aVyyz = (*averagedTriplecorrelations)(Vyyz, val<1>(node), val<2>(node), val<3>(node)); + double aVzzz = (*averagedTriplecorrelations)(Vzzz, val<1>(node), val<2>(node), val<3>(node)); + double aVzzx = (*averagedTriplecorrelations)(Vzzx, val<1>(node), val<2>(node), val<3>(node)); + double aVzzy = (*averagedTriplecorrelations)(Vzzy, val<1>(node), val<2>(node), val<3>(node)); + double aVxyz = (*averagedTriplecorrelations)(Vxyz, val<1>(node), val<2>(node), val<3>(node)); + + lsaRho += aRho; + lsaRhoF += aRhoF; + + lsaVx += aVx; + lsaVy += aVy; + lsaVz += aVz; + + lsaVxx += aVxx; + lsaVyy += aVyy; + lsaVzz += aVzz; + lsaVxy += aVxy; + lsaVxz += aVxz; + lsaVyz += aVyz; + + lsaVxxx += aVxxx; + lsaVxxy += aVxxy; + lsaVxxz += aVxxz; + lsaVyyy += aVyyy; + lsaVyyx += aVyyx; + lsaVyyz += aVyyz; + lsaVzzz += aVzzz; + lsaVzzx += aVzzx; + lsaVzzy += aVzzy; + lsaVxyz += aVxyz; + } + } + std::vector<double> values; + std::vector<double> rvalues; + + values.push_back(lsaRho); + values.push_back(lsaRhoF); + + values.push_back(lsaVx); + values.push_back(lsaVy); + values.push_back(lsaVz); + + values.push_back(lsaVxx); + values.push_back(lsaVyy); + values.push_back(lsaVzz); + values.push_back(lsaVxy); + values.push_back(lsaVxz); + values.push_back(lsaVyz); + + values.push_back(lsaVxxx); + values.push_back(lsaVxxy); + values.push_back(lsaVxxz); + values.push_back(lsaVyyy); + values.push_back(lsaVyyx); + values.push_back(lsaVyyz); + values.push_back(lsaVzzz); + values.push_back(lsaVzzx); + values.push_back(lsaVzzy); + values.push_back(lsaVxyz); + + rvalues = comm->gather(values); + if (root) { + for (int i = 0; i < (int)rvalues.size(); i += 21) { + saRho += rvalues[i]; + saRhoF += rvalues[i + 1]; + + saVx += rvalues[i + 2]; + saVy += rvalues[i + 3]; + saVz += rvalues[i + 4]; + + saVxx += rvalues[i + 5]; + saVyy += rvalues[i + 6]; + saVzz += rvalues[i + 7]; + saVxy += rvalues[i + 8]; + saVxz += rvalues[i + 9]; + saVyz += rvalues[i + 10]; + + saVxxx += rvalues[i + 11]; + saVxxy += rvalues[i + 12]; + saVxxz += rvalues[i + 13]; + saVyyy += rvalues[i + 14]; + saVyyx += rvalues[i + 15]; + saVyyz += rvalues[i + 16]; + saVzzz += rvalues[i + 17]; + saVzzx += rvalues[i + 18]; + saVzzy += rvalues[i + 19]; + saVxyz += rvalues[i + 20]; + } + } } diff --git a/src/cpu/VirtualFluidsCore/CoProcessors/TimeAveragedValuesCoProcessor.h b/src/cpu/VirtualFluidsCore/CoProcessors/TimeAveragedValuesCoProcessor.h index e88a859a9df8c478007cbab7fa8af883c57fb01f..70dd79f062331be762603d07576675a123f7770b 100644 --- a/src/cpu/VirtualFluidsCore/CoProcessors/TimeAveragedValuesCoProcessor.h +++ b/src/cpu/VirtualFluidsCore/CoProcessors/TimeAveragedValuesCoProcessor.h @@ -6,8 +6,8 @@ #include <vector> #include "CoProcessor.h" -#include "LBMSystem.h" #include "IntegrateValuesHelper.h" +#include "LBMSystem.h" class Communicator; class Grid3D; @@ -16,108 +16,110 @@ class WbWriter; class Block3D; //! \brief Computes the time averaged mean velocity and RMS values and writes to parallel .vtk -//! \details writes at given time intervals specified in scheduler (s), does averaging according to scheduler (Avs) and resets according to scheduler (rs). <br> -//! Computes the time averaged mean velocity \f$ u_{mean}=\frac{1}{N}\sum\limits_{i=1}^n u_{i} \f$ and RMS of fluctuations. You need to calculate a square root before plotting RMS. <br> -// -//! \author Konstantin Kutscher +//! \details writes at given time intervals specified in scheduler (s), does averaging according to scheduler (Avs) and +//! resets according to scheduler (rs). <br> +//! Computes the time averaged mean velocity \f$ u_{mean}=\frac{1}{N}\sum\limits_{i=1}^n u_{i} \f$ and RMS of +//! fluctuations. You need to calculate a square root before plotting RMS. <br> +// +//! \author Konstantin Kutscher // \f$ u_{mean}=\frac{1}{N}\sum\limits_{i=1}^n u_{i} \f$ - class TimeAveragedValuesCoProcessor : public CoProcessor { public: - enum Options - { - Density = 1, - Velocity = 2, - Fluctuations = 4, - Triplecorrelations = 8, - - //Velocity = 1, - //Fluctuations = 2, - //Triplecorrelations = 4, - }; + enum Options { + Density = 1, + Velocity = 2, + Fluctuations = 4, + Triplecorrelations = 8, + + // Velocity = 1, + // Fluctuations = 2, + // Triplecorrelations = 4, + }; + public: - TimeAveragedValuesCoProcessor(); - TimeAveragedValuesCoProcessor(SPtr<Grid3D> grid, const std::string& path, WbWriter* const writer, - SPtr<UbScheduler> s, SPtr<Communicator> comm, int options); - TimeAveragedValuesCoProcessor(SPtr<Grid3D> grid, const std::string& path, WbWriter* const writer, - SPtr<UbScheduler> s, SPtr<Communicator> comm, int options, std::vector<int> levels, std::vector<double>& levelCoords, std::vector<double>& bounds, bool timeAveraging = true); - //! Make update - void process(double step) override; - //! Computes subtotal of velocity , fluctuations and triple correlations - void calculateSubtotal(double step); - void addLevelCoordinate(double c); - void reset(); - void setWithGhostLayer(bool val); - bool getWithGhostLayer(); + TimeAveragedValuesCoProcessor(); + TimeAveragedValuesCoProcessor(SPtr<Grid3D> grid, const std::string &path, WbWriter *const writer, + SPtr<UbScheduler> s, SPtr<Communicator> comm, int options); + TimeAveragedValuesCoProcessor(SPtr<Grid3D> grid, const std::string &path, WbWriter *const writer, + SPtr<UbScheduler> s, SPtr<Communicator> comm, int options, std::vector<int> levels, + std::vector<double> &levelCoords, std::vector<double> &bounds, + bool timeAveraging = true); + //! Make update + void process(double step) override; + //! Computes subtotal of velocity , fluctuations and triple correlations + void calculateSubtotal(double step); + void addLevelCoordinate(double c); + void reset(); + void setWithGhostLayer(bool val); + bool getWithGhostLayer(); protected: - //! Prepare data and write in .vtk file - void collectData(double step); - //! prepare data - void addData(const SPtr<Block3D> block); - void clearData(); - //! Computes average values of velocity , fluctuations and triple correlations - void calculateAverageValues(double timeStep); - - void init(); - void initData(); - void planarAverage(double step); - void calculateAverageValuesForPlane(std::vector<IntegrateValuesHelper::CalcNodes>& cnodes); + //! Prepare data and write in .vtk file + void collectData(double step); + //! prepare data + void addData(const SPtr<Block3D> block); + void clearData(); + //! Computes average values of velocity , fluctuations and triple correlations + void calculateAverageValues(double timeStep); + + void init(); + void initData(); + void planarAverage(double step); + void calculateAverageValuesForPlane(std::vector<IntegrateValuesHelper::CalcNodes> &cnodes); private: SPtr<Communicator> comm; - std::vector<UbTupleFloat3> nodes; - std::vector<UbTupleUInt8> cells; - std::vector<std::string> datanames; - std::vector<std::vector<double> > data; - std::vector<std::vector<SPtr<Block3D> > > blockVector; - bool root; - int minInitLevel; //min init level - int maxInitLevel; - int gridRank; - int resetStepRMS; - int resetStepMeans; - double averageInterval; - std::string path; - WbWriter* writer; - bool restart, compressible; - SPtr<UbScheduler> averageScheduler; //additional scheduler to averaging after a given interval - SPtr<UbScheduler> resetSchedulerRMS; //additional scheduler to restart averaging after a given interval - SPtr<UbScheduler> resetSchedulerMeans; //additional scheduler to restart averaging after a given interval - //labels for the different components, e.g. AvVxx for time averaged RMS: 1/n SUM((U-Umean)^2) - //you need to calculate a square root before plotting RMS - enum Density { Rho, RhoF }; - enum Velocity { Vx, Vy, Vz }; - enum Fluctuations { Vxx, Vyy, Vzz, Vxy, Vxz, Vyz }; - enum Triplecorrelations { Vxxx, Vxxy, Vxxz, Vyyy, Vyyx, Vyyz, Vzzz, Vzzx, Vzzy, Vxyz }; - - double saRho, saRhoF; - double saVx, saVy, saVz; - double saVxx, saVyy, saVzz, saVxy, saVxz, saVyz; - double saVxxx, saVxxy, saVxxz, saVyyy, saVyyx, saVyyz, saVzzz, saVzzx, saVzzy, saVxyz; - - int options; - double numberOfSteps; - double minStep; - double maxStep; - - int iMinX1, iMinX2, iMinX3; - //int iMaxX1, iMaxX2, iMaxX3; - int iMinC; - int iMaxC; - - using CalcMacrosFct = void (*)(const LBMReal *const &, LBMReal &, LBMReal &, LBMReal &, LBMReal &); - CalcMacrosFct calcMacros; - - bool planarAveraging; - bool timeAveraging; - std::vector<double> levelCoords; - std::vector<int> levels; - std::vector<double> bounds; - - bool withGhostLayer; - + std::vector<UbTupleFloat3> nodes; + std::vector<UbTupleUInt8> cells; + std::vector<std::string> datanames; + std::vector<std::vector<double>> data; + std::vector<std::vector<SPtr<Block3D>>> blockVector; + bool root; + int minInitLevel; // min init level + int maxInitLevel; + int gridRank; + int resetStepRMS; + int resetStepMeans; + double averageInterval; + std::string path; + WbWriter *writer; + bool restart, compressible; + SPtr<UbScheduler> averageScheduler; // additional scheduler to averaging after a given interval + SPtr<UbScheduler> resetSchedulerRMS; // additional scheduler to restart averaging after a given interval + SPtr<UbScheduler> resetSchedulerMeans; // additional scheduler to restart averaging after a given interval + // labels for the different components, e.g. AvVxx for time averaged RMS: 1/n SUM((U-Umean)^2) + // you need to calculate a square root before plotting RMS + enum Density { Rho, RhoF }; + enum Velocity { Vx, Vy, Vz }; + enum Fluctuations { Vxx, Vyy, Vzz, Vxy, Vxz, Vyz }; + enum Triplecorrelations { Vxxx, Vxxy, Vxxz, Vyyy, Vyyx, Vyyz, Vzzz, Vzzx, Vzzy, Vxyz }; + + double saRho, saRhoF; + double saVx, saVy, saVz; + double saVxx, saVyy, saVzz, saVxy, saVxz, saVyz; + double saVxxx, saVxxy, saVxxz, saVyyy, saVyyx, saVyyz, saVzzz, saVzzx, saVzzy, saVxyz; + + int options; + double numberOfSteps; + double minStep; + double maxStep; + + int iMinX1, iMinX2, iMinX3; + // int iMaxX1, iMaxX2, iMaxX3; + int iMinC; + int iMaxC; + + using CalcMacrosFct = void (*)(const LBMReal *const &, LBMReal &, LBMReal &, LBMReal &, LBMReal &); + CalcMacrosFct calcMacros; + + bool planarAveraging; + bool timeAveraging; + std::vector<double> levelCoords; + std::vector<int> levels; + std::vector<double> bounds; + + bool withGhostLayer; }; #endif diff --git a/src/cpu/VirtualFluidsCore/CoProcessors/TimeDependentBCCoProcessor.cpp b/src/cpu/VirtualFluidsCore/CoProcessors/TimeDependentBCCoProcessor.cpp index d1308a1102592f8ced9c781a7a31fa4d8fb65dd8..1540ef953b583be39dd7e5e4c1ee3dc678f0d12f 100644 --- a/src/cpu/VirtualFluidsCore/CoProcessors/TimeDependentBCCoProcessor.cpp +++ b/src/cpu/VirtualFluidsCore/CoProcessors/TimeDependentBCCoProcessor.cpp @@ -1,32 +1,22 @@ #include "TimeDependentBCCoProcessor.h" +#include "Grid3D.h" #include "Interactor3D.h" #include "UbScheduler.h" -#include "Grid3D.h" -TimeDependentBCCoProcessor::TimeDependentBCCoProcessor(SPtr<Grid3D> grid, SPtr<UbScheduler> s) : CoProcessor(grid, s) -{ - -} +TimeDependentBCCoProcessor::TimeDependentBCCoProcessor(SPtr<Grid3D> grid, SPtr<UbScheduler> s) : CoProcessor(grid, s) {} ////////////////////////////////////////////////////////////////////////// -TimeDependentBCCoProcessor::~TimeDependentBCCoProcessor() -= default; +TimeDependentBCCoProcessor::~TimeDependentBCCoProcessor() = default; ////////////////////////////////////////////////////////////////////////// void TimeDependentBCCoProcessor::process(double step) { - if(scheduler->isDue(step) ) - { - for (SPtr<Interactor3D> inter : interactors) - inter->updateInteractor(step); - UBLOG(logDEBUG3, "TimeDependentBCCoProcessor::update:" << step); - } + if (scheduler->isDue(step)) { + for (SPtr<Interactor3D> inter : interactors) + inter->updateInteractor(step); + UBLOG(logDEBUG3, "TimeDependentBCCoProcessor::update:" << step); + } } ////////////////////////////////////////////////////////////////////////// -void TimeDependentBCCoProcessor::addInteractor( SPtr<Interactor3D> interactor ) -{ - interactors.push_back(interactor); -} +void TimeDependentBCCoProcessor::addInteractor(SPtr<Interactor3D> interactor) { interactors.push_back(interactor); } ////////////////////////////////////////////////////////////////////////// - - diff --git a/src/cpu/VirtualFluidsCore/CoProcessors/TimeDependentBCCoProcessor.h b/src/cpu/VirtualFluidsCore/CoProcessors/TimeDependentBCCoProcessor.h index e316a1d19e921ac8af0a3588e791ad0045ba58b6..0483c9f826c7d1b110bd8fb07016dc5b997bad40 100644 --- a/src/cpu/VirtualFluidsCore/CoProcessors/TimeDependentBCCoProcessor.h +++ b/src/cpu/VirtualFluidsCore/CoProcessors/TimeDependentBCCoProcessor.h @@ -1,31 +1,30 @@ #ifndef TimeDependentBCCoProcessor_H #define TimeDependentBCCoProcessor_H -#include <vector> #include <PointerDefinitions.h> +#include <vector> #include "CoProcessor.h" class Interactor3D; class Grid3D; -//! \brief The class update interactors depend of time step. +//! \brief The class update interactors depend of time step. //! \details TimeDependentBCCoProcessor update every time step information in BCAdapters throw Interactors //! \author Sonja Uphoff, Kostyantyn Kucher class TimeDependentBCCoProcessor : public CoProcessor { public: - TimeDependentBCCoProcessor(SPtr<Grid3D> grid, SPtr<UbScheduler> s); - ~TimeDependentBCCoProcessor() override; + TimeDependentBCCoProcessor(SPtr<Grid3D> grid, SPtr<UbScheduler> s); + ~TimeDependentBCCoProcessor() override; - void process(double step) override; + void process(double step) override; - //! add interactors to CoProcessor - void addInteractor(SPtr<Interactor3D> interactor); + //! add interactors to CoProcessor + void addInteractor(SPtr<Interactor3D> interactor); private: - std::vector<SPtr<Interactor3D> > interactors; + std::vector<SPtr<Interactor3D>> interactors; }; - #endif /* TimeDependentBCCoProcessor_H */ diff --git a/src/cpu/VirtualFluidsCore/CoProcessors/TimeseriesCoProcessor.cpp b/src/cpu/VirtualFluidsCore/CoProcessors/TimeseriesCoProcessor.cpp index 8f0ff8c9975e78d639345f7c86d69bd0fbbf4788..8103d646643bf350f65c299ee73625978c3c6f6a 100644 --- a/src/cpu/VirtualFluidsCore/CoProcessors/TimeseriesCoProcessor.cpp +++ b/src/cpu/VirtualFluidsCore/CoProcessors/TimeseriesCoProcessor.cpp @@ -1,86 +1,84 @@ /* -* TimeseriesWriterCoProcessor.h -* -* Created on: 08.05.2013 -* Author: uphoff -*/ + * TimeseriesWriterCoProcessor.h + * + * Created on: 08.05.2013 + * Author: uphoff + */ #include "TimeseriesCoProcessor.h" #include <fstream> +#include "Communicator.h" +#include "Grid3D.h" #include "IntegrateValuesHelper.h" #include "LBMUnitConverter.h" -#include "Communicator.h" #include "UbScheduler.h" -#include "Grid3D.h" - -TimeseriesCoProcessor::TimeseriesCoProcessor(SPtr<Grid3D> grid, SPtr<UbScheduler> s, - SPtr<IntegrateValuesHelper> h1, - const std::string& path, SPtr<Communicator> comm) - : CoProcessor(grid, s), - h1(h1), - path(path), - comm(comm) +TimeseriesCoProcessor::TimeseriesCoProcessor(SPtr<Grid3D> grid, SPtr<UbScheduler> s, SPtr<IntegrateValuesHelper> h1, + const std::string &path, SPtr<Communicator> comm) + : CoProcessor(grid, s), h1(h1), path(path), comm(comm) { - if (comm->getProcessID() == comm->getRoot()) - { - std::ofstream ostr; - //fname = path+"/timeseries/timeseries"+UbSystem::toString(grid->getTimeStep())+".csv"; - fname = path+".csv"; - UBLOG(logINFO, "TimeseriesWriterCoProcessor::fname:" << fname); - ostr.open(fname.c_str(), std::ios_base::out | std::ios_base::app); - if(!ostr) - { - ostr.clear(); - std::string file_path = UbSystem::getPathFromString(fname); - if (file_path.size()>0) { UbSystem::makeDirectory(file_path); ostr.open(fname.c_str(), std::ios_base::out | std::ios_base::app); } - if(!ostr) throw UbException(UB_EXARGS,"couldn't open file "+fname); - } - ostr << "step;rho;vx;vy;vz;volume\n"; - ostr.close(); - UBLOG(logINFO, "TimeseriesWriterCoProcessor::Constructor:end"); - } + if (comm->getProcessID() == comm->getRoot()) { + std::ofstream ostr; + // fname = path+"/timeseries/timeseries"+UbSystem::toString(grid->getTimeStep())+".csv"; + fname = path + ".csv"; + UBLOG(logINFO, "TimeseriesWriterCoProcessor::fname:" << fname); + ostr.open(fname.c_str(), std::ios_base::out | std::ios_base::app); + if (!ostr) { + ostr.clear(); + std::string file_path = UbSystem::getPathFromString(fname); + if (file_path.size() > 0) { + UbSystem::makeDirectory(file_path); + ostr.open(fname.c_str(), std::ios_base::out | std::ios_base::app); + } + if (!ostr) + throw UbException(UB_EXARGS, "couldn't open file " + fname); + } + ostr << "step;rho;vx;vy;vz;volume\n"; + ostr.close(); + UBLOG(logINFO, "TimeseriesWriterCoProcessor::Constructor:end"); + } } ////////////////////////////////////////////////////////////////////////// -TimeseriesCoProcessor::~TimeseriesCoProcessor() -= default; +TimeseriesCoProcessor::~TimeseriesCoProcessor() = default; ////////////////////////////////////////////////////////////////////////// void TimeseriesCoProcessor::process(double step) { - if(scheduler->isDue(step) ) - collectData(step); + if (scheduler->isDue(step)) + collectData(step); } ////////////////////////////////////////////////////////////////////////// void TimeseriesCoProcessor::collectData(double step) { - h1->calculateMQ(); + h1->calculateMQ(); - UBLOG(logDEBUG3, "TimeseriesWriterCoProcessor::update:" << step); + UBLOG(logDEBUG3, "TimeseriesWriterCoProcessor::update:" << step); - if (comm->getProcessID() == comm->getRoot()) - { - int istep = static_cast<int>(step); - std::ofstream ostr; - double cellsVolume = h1->getCellsVolume(); + if (comm->getProcessID() == comm->getRoot()) { + int istep = static_cast<int>(step); + std::ofstream ostr; + double cellsVolume = h1->getCellsVolume(); - double rho=(h1->getRho())/cellsVolume; - double vx= (h1->getVx1())/cellsVolume; - double vy= (h1->getVx2())/cellsVolume; - double vz= (h1->getVx3())/cellsVolume; - double volume = cellsVolume; + double rho = (h1->getRho()) / cellsVolume; + double vx = (h1->getVx1()) / cellsVolume; + double vy = (h1->getVx2()) / cellsVolume; + double vz = (h1->getVx3()) / cellsVolume; + double volume = cellsVolume; - ostr.open(fname.c_str(), std::ios_base::out | std::ios_base::app); - if(!ostr) - { - ostr.clear(); - std::string path = UbSystem::getPathFromString(fname); - if(path.size()>0){ UbSystem::makeDirectory(path); ostr.open(fname.c_str(), std::ios_base::out | std::ios_base::app);} - if(!ostr) throw UbException(UB_EXARGS,"couldn't open file "+fname); - } + ostr.open(fname.c_str(), std::ios_base::out | std::ios_base::app); + if (!ostr) { + ostr.clear(); + std::string path = UbSystem::getPathFromString(fname); + if (path.size() > 0) { + UbSystem::makeDirectory(path); + ostr.open(fname.c_str(), std::ios_base::out | std::ios_base::app); + } + if (!ostr) + throw UbException(UB_EXARGS, "couldn't open file " + fname); + } - ostr << istep << ";" << rho <<";" << vx << ";" << vy << ";" << vz << ";" << volume << "\n"; - ostr.close(); - } + ostr << istep << ";" << rho << ";" << vx << ";" << vy << ";" << vz << ";" << volume << "\n"; + ostr.close(); + } } diff --git a/src/cpu/VirtualFluidsCore/CoProcessors/TimeseriesCoProcessor.h b/src/cpu/VirtualFluidsCore/CoProcessors/TimeseriesCoProcessor.h index 981344167a90eeefdfae5a93e7cc8d7d8842d809..b59a68b66d4d42080824d44c339c03fffe27f269 100644 --- a/src/cpu/VirtualFluidsCore/CoProcessors/TimeseriesCoProcessor.h +++ b/src/cpu/VirtualFluidsCore/CoProcessors/TimeseriesCoProcessor.h @@ -26,7 +26,8 @@ class IntegrateValuesHelper; class TimeseriesCoProcessor : public CoProcessor { public: - TimeseriesCoProcessor(SPtr<Grid3D> grid, SPtr<UbScheduler> s, SPtr<IntegrateValuesHelper> h1, const std::string& path, SPtr<Communicator> comm); + TimeseriesCoProcessor(SPtr<Grid3D> grid, SPtr<UbScheduler> s, SPtr<IntegrateValuesHelper> h1, + const std::string &path, SPtr<Communicator> comm); ~TimeseriesCoProcessor() override; //! calls collectData. @@ -44,5 +45,4 @@ private: std::string fname; }; - #endif /* TimeseriesCoProcessor_H */ diff --git a/src/cpu/VirtualFluidsCore/CoProcessors/TurbulenceIntensityCoProcessor.cpp b/src/cpu/VirtualFluidsCore/CoProcessors/TurbulenceIntensityCoProcessor.cpp index 9f1a383c259f26d6dc9e4e357ff11d9d46d74845..864918f03a194a46c198a64912930b0b8f1859fb 100644 --- a/src/cpu/VirtualFluidsCore/CoProcessors/TurbulenceIntensityCoProcessor.cpp +++ b/src/cpu/VirtualFluidsCore/CoProcessors/TurbulenceIntensityCoProcessor.cpp @@ -1,268 +1,248 @@ #include "TurbulenceIntensityCoProcessor.h" -#include "LBMKernel.h" +#include "BCArray3D.h" #include "BCProcessor.h" -#include "basics/writer/WbWriterVtkXmlASCII.h" -#include "basics/utilities/UbMath.h" +#include "Block3D.h" +#include "Communicator.h" #include "DataSet3D.h" #include "Grid3D.h" -#include "Block3D.h" +#include "LBMKernel.h" #include "LBMUnitConverter.h" -#include "Communicator.h" #include "UbScheduler.h" -#include "BCArray3D.h" +#include "basics/utilities/UbMath.h" +#include "basics/writer/WbWriterVtkXmlASCII.h" -TurbulenceIntensityCoProcessor::TurbulenceIntensityCoProcessor(SPtr<Grid3D> grid, const std::string& path, - WbWriter* const writer, - SPtr<UbScheduler> s, SPtr<Communicator> comm) - : CoProcessor(grid, s), - path(path), - comm(comm), - writer(writer) +TurbulenceIntensityCoProcessor::TurbulenceIntensityCoProcessor(SPtr<Grid3D> grid, const std::string &path, + WbWriter *const writer, SPtr<UbScheduler> s, + SPtr<Communicator> comm) + : CoProcessor(grid, s), path(path), comm(comm), writer(writer) { - init(); + init(); } ////////////////////////////////////////////////////////////////////////// void TurbulenceIntensityCoProcessor::init() { - gridRank = grid->getRank(); - minInitLevel = this->grid->getCoarsestInitializedLevel(); - maxInitLevel = this->grid->getFinestInitializedLevel(); - - blockVector.resize(maxInitLevel+1); - - for(int level = minInitLevel; level<=maxInitLevel;level++) - { - grid->getBlocks(level, gridRank, true, blockVector[level]); - - for(SPtr<Block3D> block : blockVector[level]) - { - UbTupleInt3 nx = grid->getBlockNX(); - SPtr<AverageValuesArray3D> averageValues = SPtr<AverageValuesArray3D>(new AverageValuesArray3D(val<1>(nx)+1, val<2>(nx)+1, val<3>(nx)+1, 4, 0.0)); - block->getKernel()->getDataSet()->setAverageValues(averageValues); - } - } + gridRank = grid->getRank(); + minInitLevel = this->grid->getCoarsestInitializedLevel(); + maxInitLevel = this->grid->getFinestInitializedLevel(); + + blockVector.resize(maxInitLevel + 1); + + for (int level = minInitLevel; level <= maxInitLevel; level++) { + grid->getBlocks(level, gridRank, true, blockVector[level]); + + for (SPtr<Block3D> block : blockVector[level]) { + UbTupleInt3 nx = grid->getBlockNX(); + SPtr<AverageValuesArray3D> averageValues = SPtr<AverageValuesArray3D>( + new AverageValuesArray3D(val<1>(nx) + 1, val<2>(nx) + 1, val<3>(nx) + 1, 4, 0.0)); + block->getKernel()->getDataSet()->setAverageValues(averageValues); + } + } } ////////////////////////////////////////////////////////////////////////// void TurbulenceIntensityCoProcessor::process(double step) { - calculateAverageValues(int(step)); + calculateAverageValues(int(step)); - if(scheduler->isDue(step) ) - collectData(step); + if (scheduler->isDue(step)) + collectData(step); - UBLOG(logDEBUG3, "TurbulenceIntensityCoProcessor::update:" << step); + UBLOG(logDEBUG3, "TurbulenceIntensityCoProcessor::update:" << step); } ////////////////////////////////////////////////////////////////////////// void TurbulenceIntensityCoProcessor::collectData(double step) { - int istep = int(step); - - for(int level = minInitLevel; level<=maxInitLevel;level++) - { - for(SPtr<Block3D> block : blockVector[level]) - { - if (block) - { - addData(block); - } - } - } - - std::string partName = writer->writeOctsWithNodeData(path+ UbSystem::toString(gridRank)+ "_" + UbSystem::toString(istep),nodes,cells,datanames,data); - size_t found=partName.find_last_of("//"); - std::string piece = partName.substr(found+1); - - std::vector<std::string> cellDataNames; - - std::vector<std::string> pieces = comm->gather(piece); - if (comm->getProcessID() == comm->getRoot()) - { - std::string pname = WbWriterVtkXmlASCII::getInstance()->writeParallelFile(path+"_"+UbSystem::toString(istep),pieces,datanames,cellDataNames); - - std::vector<std::string> filenames; - filenames.push_back(pname); - if (step == CoProcessor::scheduler->getMinBegin()) - { - WbWriterVtkXmlASCII::getInstance()->writeCollection(path+"_collection",filenames,istep,false); - } - else - { - WbWriterVtkXmlASCII::getInstance()->addFilesToCollection(path+"_collection",filenames,istep,false); - } - UBLOG(logINFO,"TurbulenceIntensityCoProcessor step: " << istep); - } - - clearData(); + int istep = int(step); + + for (int level = minInitLevel; level <= maxInitLevel; level++) { + for (SPtr<Block3D> block : blockVector[level]) { + if (block) { + addData(block); + } + } + } + + std::string partName = writer->writeOctsWithNodeData( + path + UbSystem::toString(gridRank) + "_" + UbSystem::toString(istep), nodes, cells, datanames, data); + size_t found = partName.find_last_of("//"); + std::string piece = partName.substr(found + 1); + + std::vector<std::string> cellDataNames; + + std::vector<std::string> pieces = comm->gather(piece); + if (comm->getProcessID() == comm->getRoot()) { + std::string pname = WbWriterVtkXmlASCII::getInstance()->writeParallelFile( + path + "_" + UbSystem::toString(istep), pieces, datanames, cellDataNames); + + std::vector<std::string> filenames; + filenames.push_back(pname); + if (step == CoProcessor::scheduler->getMinBegin()) { + WbWriterVtkXmlASCII::getInstance()->writeCollection(path + "_collection", filenames, istep, false); + } else { + WbWriterVtkXmlASCII::getInstance()->addFilesToCollection(path + "_collection", filenames, istep, false); + } + UBLOG(logINFO, "TurbulenceIntensityCoProcessor step: " << istep); + } + + clearData(); } ////////////////////////////////////////////////////////////////////////// void TurbulenceIntensityCoProcessor::clearData() { - nodes.clear(); - cells.clear(); - datanames.clear(); - data.clear(); + nodes.clear(); + cells.clear(); + datanames.clear(); + data.clear(); } ////////////////////////////////////////////////////////////////////////// void TurbulenceIntensityCoProcessor::addData(const SPtr<Block3D> block) { - UbTupleDouble3 org = grid->getBlockWorldCoordinates(block); -// UbTupleDouble3 blockLengths = grid->getBlockLengths(block); - UbTupleDouble3 nodeOffset = grid->getNodeOffset(block); - double dx = grid->getDeltaX(block); - - //Diese Daten werden geschrieben: - datanames.resize(0); - datanames.emplace_back("TI"); - - data.resize(datanames.size()); - - SPtr<ILBMKernel> kernel = block->getKernel(); - SPtr<BCArray3D> bcArray = kernel->getBCProcessor()->getBCArray(); - SPtr<DistributionArray3D> distributions = kernel->getDataSet()->getFdistributions(); - SPtr<AverageValuesArray3D> av = kernel->getDataSet()->getAverageValues(); - //int ghostLayerWidth = kernel->getGhostLayerWidth(); - - //knotennummerierung faengt immer bei 0 an! - unsigned int SWB,SEB,NEB,NWB,SWT,SET,NET,NWT; - - int minX1 = 0; - int minX2 = 0; - int minX3 = 0; - - int maxX1 = int(distributions->getNX1()); - int maxX2 = int(distributions->getNX2()); - int maxX3 = int(distributions->getNX3()); - - //nummern vergeben und node std::vector erstellen + daten sammeln - CbArray3D<int> nodeNumbers((int)maxX1, (int)maxX2, (int)maxX3,-1); - //D3Q27BoundaryConditionPtr bcPtr; - int nr = (int)nodes.size(); - - for(int ix3=minX3; ix3<maxX3-1; ix3++) - { - for(int ix2=minX2; ix2<maxX2-1; ix2++) - { - for(int ix1=minX1; ix1<maxX1-1; ix1++) - { - if(!bcArray->isUndefined(ix1,ix2,ix3) && !bcArray->isSolid(ix1,ix2,ix3)) - { - int index = 0; - nodeNumbers(ix1,ix2,ix3) = nr++; - nodes.push_back( makeUbTuple(float(val<1>(org) - val<1>(nodeOffset) + ix1*dx), - float(val<2>(org) - val<2>(nodeOffset) + ix2*dx), - float(val<3>(org) - val<3>(nodeOffset) + ix3*dx)) ); - - //compute turbulence intensity - double temp = (*av)(ix1,ix2,ix3,AvVxxyyzz)/ - ((*av)(ix1,ix2,ix3,AvVx)*(*av)(ix1,ix2,ix3,AvVx)+ - (*av)(ix1,ix2,ix3,AvVy)*(*av)(ix1,ix2,ix3,AvVy)+ - (*av)(ix1,ix2,ix3,AvVz)*(*av)(ix1,ix2,ix3,AvVz)); - - LBMReal ti = sqrt(temp); - - if (UbMath::isNaN(ti)) UB_THROW( UbException(UB_EXARGS,"TI is not a number (nan or -1.#IND), sqrt(temp), where temp = "+UbSystem::toString(temp)+", AvVx = "+UbSystem::toString((*av)(ix1,ix2,ix3,AvVx))+" AvVy = "+UbSystem::toString((*av)(ix1,ix2,ix3,AvVy))+" AvVz = "+UbSystem::toString((*av)(ix1,ix2,ix3,AvVz)))); - - data[index++].push_back(ti); + UbTupleDouble3 org = grid->getBlockWorldCoordinates(block); + // UbTupleDouble3 blockLengths = grid->getBlockLengths(block); + UbTupleDouble3 nodeOffset = grid->getNodeOffset(block); + double dx = grid->getDeltaX(block); + + // Diese Daten werden geschrieben: + datanames.resize(0); + datanames.emplace_back("TI"); + + data.resize(datanames.size()); + + SPtr<ILBMKernel> kernel = block->getKernel(); + SPtr<BCArray3D> bcArray = kernel->getBCProcessor()->getBCArray(); + SPtr<DistributionArray3D> distributions = kernel->getDataSet()->getFdistributions(); + SPtr<AverageValuesArray3D> av = kernel->getDataSet()->getAverageValues(); + // int ghostLayerWidth = kernel->getGhostLayerWidth(); + + // knotennummerierung faengt immer bei 0 an! + unsigned int SWB, SEB, NEB, NWB, SWT, SET, NET, NWT; + + int minX1 = 0; + int minX2 = 0; + int minX3 = 0; + + int maxX1 = int(distributions->getNX1()); + int maxX2 = int(distributions->getNX2()); + int maxX3 = int(distributions->getNX3()); + + // nummern vergeben und node std::vector erstellen + daten sammeln + CbArray3D<int> nodeNumbers((int)maxX1, (int)maxX2, (int)maxX3, -1); + // D3Q27BoundaryConditionPtr bcPtr; + int nr = (int)nodes.size(); + + for (int ix3 = minX3; ix3 < maxX3 - 1; ix3++) { + for (int ix2 = minX2; ix2 < maxX2 - 1; ix2++) { + for (int ix1 = minX1; ix1 < maxX1 - 1; ix1++) { + if (!bcArray->isUndefined(ix1, ix2, ix3) && !bcArray->isSolid(ix1, ix2, ix3)) { + int index = 0; + nodeNumbers(ix1, ix2, ix3) = nr++; + nodes.push_back(makeUbTuple(float(val<1>(org) - val<1>(nodeOffset) + ix1 * dx), + float(val<2>(org) - val<2>(nodeOffset) + ix2 * dx), + float(val<3>(org) - val<3>(nodeOffset) + ix3 * dx))); + + // compute turbulence intensity + double temp = + (*av)(ix1, ix2, ix3, AvVxxyyzz) / ((*av)(ix1, ix2, ix3, AvVx) * (*av)(ix1, ix2, ix3, AvVx) + + (*av)(ix1, ix2, ix3, AvVy) * (*av)(ix1, ix2, ix3, AvVy) + + (*av)(ix1, ix2, ix3, AvVz) * (*av)(ix1, ix2, ix3, AvVz)); + + LBMReal ti = sqrt(temp); + + if (UbMath::isNaN(ti)) + UB_THROW( + UbException(UB_EXARGS, "TI is not a number (nan or -1.#IND), sqrt(temp), where temp = " + + UbSystem::toString(temp) + + ", AvVx = " + UbSystem::toString((*av)(ix1, ix2, ix3, AvVx)) + + " AvVy = " + UbSystem::toString((*av)(ix1, ix2, ix3, AvVy)) + + " AvVz = " + UbSystem::toString((*av)(ix1, ix2, ix3, AvVz)))); + + data[index++].push_back(ti); + } } - } - } - } - //cell std::vector erstellen - for(int ix3=minX3; ix3<maxX3-1; ix3++) - { - for(int ix2=minX2; ix2<maxX2-1; ix2++) - { - for(int ix1=minX1; ix1<maxX1-1; ix1++) - { - if( (SWB=nodeNumbers( ix1 , ix2, ix3 )) >= 0 - && (SEB=nodeNumbers( ix1+1, ix2, ix3 )) >= 0 - && (NEB=nodeNumbers( ix1+1, ix2+1, ix3 )) >= 0 - && (NWB=nodeNumbers( ix1 , ix2+1, ix3 )) >= 0 - && (SWT=nodeNumbers( ix1 , ix2, ix3+1 )) >= 0 - && (SET=nodeNumbers( ix1+1, ix2, ix3+1 )) >= 0 - && (NET=nodeNumbers( ix1+1, ix2+1, ix3+1 )) >= 0 - && (NWT=nodeNumbers( ix1 , ix2+1, ix3+1 )) >= 0 ) - { - cells.push_back( makeUbTuple(SWB,SEB,NEB,NWB,SWT,SET,NET,NWT) ); + } + } + // cell std::vector erstellen + for (int ix3 = minX3; ix3 < maxX3 - 1; ix3++) { + for (int ix2 = minX2; ix2 < maxX2 - 1; ix2++) { + for (int ix1 = minX1; ix1 < maxX1 - 1; ix1++) { + if ((SWB = nodeNumbers(ix1, ix2, ix3)) >= 0 && (SEB = nodeNumbers(ix1 + 1, ix2, ix3)) >= 0 && + (NEB = nodeNumbers(ix1 + 1, ix2 + 1, ix3)) >= 0 && (NWB = nodeNumbers(ix1, ix2 + 1, ix3)) >= 0 && + (SWT = nodeNumbers(ix1, ix2, ix3 + 1)) >= 0 && (SET = nodeNumbers(ix1 + 1, ix2, ix3 + 1)) >= 0 && + (NET = nodeNumbers(ix1 + 1, ix2 + 1, ix3 + 1)) >= 0 && + (NWT = nodeNumbers(ix1, ix2 + 1, ix3 + 1)) >= 0) { + cells.push_back(makeUbTuple(SWB, SEB, NEB, NWB, SWT, SET, NET, NWT)); + } } - } - } - } + } + } } ////////////////////////////////////////////////////////////////////////// void TurbulenceIntensityCoProcessor::calculateAverageValues(double timeStep) { - using namespace D3Q27System; - - int minInitLevel = this->grid->getCoarsestInitializedLevel(); - int maxInitLevel = this->grid->getFinestInitializedLevel(); - LBMReal f[27]; - LBMReal vx, vy, vz; - - for(int level = minInitLevel; level<=maxInitLevel;level++) - { - for(SPtr<Block3D> block : blockVector[level]) - { - if (block) - { - SPtr<ILBMKernel> kernel = block->getKernel(); - SPtr<BCArray3D> bcArray = kernel->getBCProcessor()->getBCArray(); - SPtr<DistributionArray3D> distributions = kernel->getDataSet()->getFdistributions(); - SPtr<AverageValuesArray3D> av = kernel->getDataSet()->getAverageValues(); - - int minX1 = 0; - int minX2 = 0; - int minX3 = 0; - - int maxX1 = int(distributions->getNX1()); - int maxX2 = int(distributions->getNX2()); - int maxX3 = int(distributions->getNX3()); - - for(int ix3=minX3; ix3<maxX3-1; ix3++) - { - for(int ix2=minX2; ix2<maxX2-1; ix2++) - { - for(int ix1=minX1; ix1<maxX1-1; ix1++) - { - if(!bcArray->isUndefined(ix1,ix2,ix3) && !bcArray->isSolid(ix1,ix2,ix3)) - { - ////////////////////////////////////////////////////////////////////////// - //read distribution - //////////////////////////////////////////////////////////////////////////// - distributions->getDistribution(f, ix1, ix2, ix3); - ////////////////////////////////////////////////////////////////////////// - //compute velocity - ////////////////////////////////////////////////////////////////////////// - vx = f[E] - f[W] + f[NE] - f[SW] + f[SE] - f[NW] + f[TE] - f[BW] - + f[BE] - f[TW] + f[TNE] - f[TSW] + f[TSE] - f[TNW] + f[BNE] - f[BSW] - + f[BSE] - f[BNW]; - - vy = f[N] - f[S] + f[NE] - f[SW] - f[SE] + f[NW] + f[TN] - f[BS] + f[BN] - - f[TS] + f[TNE] - f[TSW] - f[TSE] + f[TNW] + f[BNE] - f[BSW] - f[BSE] - + f[BNW]; - - vz = f[T] - f[B] + f[TE] - f[BW] - f[BE] + f[TW] + f[TN] - f[BS] - f[BN] - + f[TS] + f[TNE] + f[TSW] + f[TSE] + f[TNW] - f[BNE] - f[BSW] - f[BSE] - - f[BNW]; - ////////////////////////////////////////////////////////////////////////// - //compute average values - ////////////////////////////////////////////////////////////////////////// - (*av)(ix1,ix2,ix3,AvVx) = ((*av)(ix1,ix2,ix3,AvVx)*timeStep + vx)/(timeStep+1.0); - (*av)(ix1,ix2,ix3,AvVy) = ((*av)(ix1,ix2,ix3,AvVy)*timeStep + vy)/(timeStep+1.0); - (*av)(ix1,ix2,ix3,AvVz) = ((*av)(ix1,ix2,ix3,AvVz)*timeStep + vz)/(timeStep+1.0); - - (*av)(ix1,ix2,ix3,AvVxxyyzz) = ((vx-(*av)(ix1,ix2,ix3,AvVx))*(vx-(*av)(ix1,ix2,ix3,AvVx)) + - (vy-(*av)(ix1,ix2,ix3,AvVy))*(vy-(*av)(ix1,ix2,ix3,AvVy)) + - (vz-(*av)(ix1,ix2,ix3,AvVz))*(vz-(*av)(ix1,ix2,ix3,AvVz)) + - (*av)(ix1,ix2,ix3,AvVxxyyzz)*timeStep)/(timeStep+1.0); - ////////////////////////////////////////////////////////////////////////// - } - } - } + using namespace D3Q27System; + + int minInitLevel = this->grid->getCoarsestInitializedLevel(); + int maxInitLevel = this->grid->getFinestInitializedLevel(); + LBMReal f[27]; + LBMReal vx, vy, vz; + + for (int level = minInitLevel; level <= maxInitLevel; level++) { + for (SPtr<Block3D> block : blockVector[level]) { + if (block) { + SPtr<ILBMKernel> kernel = block->getKernel(); + SPtr<BCArray3D> bcArray = kernel->getBCProcessor()->getBCArray(); + SPtr<DistributionArray3D> distributions = kernel->getDataSet()->getFdistributions(); + SPtr<AverageValuesArray3D> av = kernel->getDataSet()->getAverageValues(); + + int minX1 = 0; + int minX2 = 0; + int minX3 = 0; + + int maxX1 = int(distributions->getNX1()); + int maxX2 = int(distributions->getNX2()); + int maxX3 = int(distributions->getNX3()); + + for (int ix3 = minX3; ix3 < maxX3 - 1; ix3++) { + for (int ix2 = minX2; ix2 < maxX2 - 1; ix2++) { + for (int ix1 = minX1; ix1 < maxX1 - 1; ix1++) { + if (!bcArray->isUndefined(ix1, ix2, ix3) && !bcArray->isSolid(ix1, ix2, ix3)) { + ////////////////////////////////////////////////////////////////////////// + // read distribution + //////////////////////////////////////////////////////////////////////////// + distributions->getDistribution(f, ix1, ix2, ix3); + ////////////////////////////////////////////////////////////////////////// + // compute velocity + ////////////////////////////////////////////////////////////////////////// + vx = f[E] - f[W] + f[NE] - f[SW] + f[SE] - f[NW] + f[TE] - f[BW] + f[BE] - f[TW] + + f[TNE] - f[TSW] + f[TSE] - f[TNW] + f[BNE] - f[BSW] + f[BSE] - f[BNW]; + + vy = f[N] - f[S] + f[NE] - f[SW] - f[SE] + f[NW] + f[TN] - f[BS] + f[BN] - f[TS] + + f[TNE] - f[TSW] - f[TSE] + f[TNW] + f[BNE] - f[BSW] - f[BSE] + f[BNW]; + + vz = f[T] - f[B] + f[TE] - f[BW] - f[BE] + f[TW] + f[TN] - f[BS] - f[BN] + f[TS] + + f[TNE] + f[TSW] + f[TSE] + f[TNW] - f[BNE] - f[BSW] - f[BSE] - f[BNW]; + ////////////////////////////////////////////////////////////////////////// + // compute average values + ////////////////////////////////////////////////////////////////////////// + (*av)(ix1, ix2, ix3, AvVx) = + ((*av)(ix1, ix2, ix3, AvVx) * timeStep + vx) / (timeStep + 1.0); + (*av)(ix1, ix2, ix3, AvVy) = + ((*av)(ix1, ix2, ix3, AvVy) * timeStep + vy) / (timeStep + 1.0); + (*av)(ix1, ix2, ix3, AvVz) = + ((*av)(ix1, ix2, ix3, AvVz) * timeStep + vz) / (timeStep + 1.0); + + (*av)(ix1, ix2, ix3, AvVxxyyzz) = + ((vx - (*av)(ix1, ix2, ix3, AvVx)) * (vx - (*av)(ix1, ix2, ix3, AvVx)) + + (vy - (*av)(ix1, ix2, ix3, AvVy)) * (vy - (*av)(ix1, ix2, ix3, AvVy)) + + (vz - (*av)(ix1, ix2, ix3, AvVz)) * (vz - (*av)(ix1, ix2, ix3, AvVz)) + + (*av)(ix1, ix2, ix3, AvVxxyyzz) * timeStep) / + (timeStep + 1.0); + ////////////////////////////////////////////////////////////////////////// + } + } + } + } } - } - } - } + } + } } - diff --git a/src/cpu/VirtualFluidsCore/CoProcessors/TurbulenceIntensityCoProcessor.h b/src/cpu/VirtualFluidsCore/CoProcessors/TurbulenceIntensityCoProcessor.h index fe14a4922d808f037dc1eeaab831f869592ae29c..5c389eed8ca84c2a8ec6700af6c33bd8a492eb1c 100644 --- a/src/cpu/VirtualFluidsCore/CoProcessors/TurbulenceIntensityCoProcessor.h +++ b/src/cpu/VirtualFluidsCore/CoProcessors/TurbulenceIntensityCoProcessor.h @@ -17,27 +17,29 @@ class Block3D; class TurbulenceIntensityCoProcessor : public CoProcessor { public: - TurbulenceIntensityCoProcessor(SPtr<Grid3D> grid, const std::string& path, WbWriter* const writer, - SPtr<UbScheduler> s, SPtr<Communicator> comm); - void process(double step) override; + TurbulenceIntensityCoProcessor(SPtr<Grid3D> grid, const std::string &path, WbWriter *const writer, + SPtr<UbScheduler> s, SPtr<Communicator> comm); + void process(double step) override; + protected: - void collectData(double step); - void addData(const SPtr<Block3D> block); - void clearData(); - void calculateAverageValues(double timeStep); + void collectData(double step); + void addData(const SPtr<Block3D> block); + void clearData(); + void calculateAverageValues(double timeStep); + private: - void init(); - std::vector<UbTupleFloat3> nodes; - std::vector<UbTupleUInt8> cells; - std::vector<std::string> datanames; - std::vector<std::vector<double> > data; - std::vector<std::vector<SPtr<Block3D> > > blockVector; - int minInitLevel; - int maxInitLevel; - int gridRank; - std::string path; - WbWriter* writer; - SPtr<Communicator> comm; - enum Values{AvVx = 0, AvVy = 1, AvVz = 2, AvVxxyyzz = 3}; + void init(); + std::vector<UbTupleFloat3> nodes; + std::vector<UbTupleUInt8> cells; + std::vector<std::string> datanames; + std::vector<std::vector<double>> data; + std::vector<std::vector<SPtr<Block3D>>> blockVector; + int minInitLevel; + int maxInitLevel; + int gridRank; + std::string path; + WbWriter *writer; + SPtr<Communicator> comm; + enum Values { AvVx = 0, AvVy = 1, AvVz = 2, AvVxxyyzz = 3 }; }; #endif diff --git a/src/cpu/VirtualFluidsCore/CoProcessors/WriteBlocksCoProcessor.cpp b/src/cpu/VirtualFluidsCore/CoProcessors/WriteBlocksCoProcessor.cpp index 077c10e32a09b2902267ba4dd010dac27a5a15ff..bac7c9c346c24198b56ce8a77cf884c0a660bb1f 100644 --- a/src/cpu/VirtualFluidsCore/CoProcessors/WriteBlocksCoProcessor.cpp +++ b/src/cpu/VirtualFluidsCore/CoProcessors/WriteBlocksCoProcessor.cpp @@ -1,28 +1,28 @@ //======================================================================================= -// ____ ____ __ ______ __________ __ __ __ __ -// \ \ | | | | | _ \ |___ ___| | | | | / \ | | -// \ \ | | | | | |_) | | | | | | | / \ | | -// \ \ | | | | | _ / | | | | | | / /\ \ | | -// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ -// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| -// \ \ | | ________________________________________________________________ -// \ \ | | | ______________________________________________________________| -// \ \| | | | __ __ __ __ ______ _______ -// \ | | |_____ | | | | | | | | | _ \ / _____) -// \ | | _____| | | | | | | | | | | \ \ \_______ +// ____ ____ __ ______ __________ __ __ __ __ +// \ \ | | | | | _ \ |___ ___| | | | | / \ | | +// \ \ | | | | | |_) | | | | | | | / \ | | +// \ \ | | | | | _ / | | | | | | / /\ \ | | +// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ +// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| +// \ \ | | ________________________________________________________________ +// \ \ | | | ______________________________________________________________| +// \ \| | | | __ __ __ __ ______ _______ +// \ | | |_____ | | | | | | | | | _ \ / _____) +// \ | | _____| | | | | | | | | | | \ \ \_______ // \ | | | | |_____ | \_/ | | | | |_/ / _____ | -// \ _____| |__| |________| \_______/ |__| |______/ (_______/ +// \ _____| |__| |________| \_______/ |__| |______/ (_______/ // -// This file is part of VirtualFluids. VirtualFluids is free software: you can +// This file is part of VirtualFluids. VirtualFluids is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of +// License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. -// -// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// +// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License along // with VirtualFluids (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>. // @@ -34,152 +34,152 @@ #include "WriteBlocksCoProcessor.h" #include "basics/writer/WbWriterVtkXmlASCII.h" -#include "D3Q27System.h" #include "Block3D.h" -#include "UbScheduler.h" #include "Communicator.h" +#include "D3Q27System.h" #include "Grid3D.h" +#include "UbScheduler.h" -WriteBlocksCoProcessor::WriteBlocksCoProcessor(SPtr<Grid3D> grid, SPtr<UbScheduler> s, - const std::string& path, WbWriter* const writer, - SPtr<Communicator> comm) : - CoProcessor(grid, s), - path(path), - writer(writer), - comm(comm) +WriteBlocksCoProcessor::WriteBlocksCoProcessor(SPtr<Grid3D> grid, SPtr<UbScheduler> s, const std::string &path, + WbWriter *const writer, SPtr<Communicator> comm) + : CoProcessor(grid, s), path(path), writer(writer), comm(comm) { - } ////////////////////////////////////////////////////////////////////////// -WriteBlocksCoProcessor::~WriteBlocksCoProcessor() -= default; +WriteBlocksCoProcessor::~WriteBlocksCoProcessor() = default; ////////////////////////////////////////////////////////////////////////// void WriteBlocksCoProcessor::process(double step) { - if(scheduler->isDue(step) ) - collectData(step); + if (scheduler->isDue(step)) + collectData(step); } ////////////////////////////////////////////////////////////////////////// void WriteBlocksCoProcessor::collectData(double step) { - if (comm->getProcessID() == comm->getRoot()) - { - int istep = int(step); - std::vector<std::string> filenames; - std::vector< UbTupleFloat3 > nodes; - std::vector< UbTupleInt8 > cells; - std::vector<std::string> celldatanames; - - celldatanames.emplace_back("isActive"); - celldatanames.emplace_back("rank"); - celldatanames.emplace_back("interface"); - celldatanames.emplace_back("ID"); - celldatanames.emplace_back("part"); - celldatanames.emplace_back("level"); - //celldatanames.push_back("connectorCF"); - //celldatanames.push_back("connectorFC"); + if (comm->getProcessID() == comm->getRoot()) { + int istep = int(step); + std::vector<std::string> filenames; + std::vector<UbTupleFloat3> nodes; + std::vector<UbTupleInt8> cells; + std::vector<std::string> celldatanames; + + celldatanames.emplace_back("isActive"); + celldatanames.emplace_back("rank"); + celldatanames.emplace_back("interface"); + celldatanames.emplace_back("ID"); + celldatanames.emplace_back("part"); + celldatanames.emplace_back("level"); + // celldatanames.push_back("connectorCF"); + // celldatanames.push_back("connectorFC"); #if defined VF_FETOL - celldatanames.push_back("bundle"); + celldatanames.push_back("bundle"); #endif - std::vector< std::vector< double > > celldata(celldatanames.size()); - - int nr=0; - int minInitLevel = this->grid->getCoarsestInitializedLevel(); - int maxInitLevel = this->grid->getFinestInitializedLevel(); - - for(int level = minInitLevel; level<=maxInitLevel;level++) - { - std::vector<SPtr<Block3D>> blockVector; - grid->getBlocks(level, blockVector); - for(SPtr<Block3D> block : blockVector) - { - UbTupleDouble3 org = grid->getBlockWorldCoordinates(block); - UbTupleDouble3 blockLength = grid->getBlockLengths(block); - - nodes.push_back(makeUbTuple((float)(val<1>(org)), (float)(val<2>(org)), (float)(val<3>(org)))); - nodes.push_back(makeUbTuple((float)(val<1>(org)+val<1>(blockLength)), (float)(val<2>(org)), (float)(val<3>(org)))); - nodes.push_back(makeUbTuple((float)(val<1>(org)+val<1>(blockLength)), (float)(val<2>(org)+val<2>(blockLength)), (float)(val<3>(org)))); - nodes.push_back(makeUbTuple((float)(val<1>(org)), (float)(val<2>(org)+val<2>(blockLength)), (float)(val<3>(org)))); - nodes.push_back(makeUbTuple((float)(val<1>(org)), (float)(val<2>(org)), (float)(val<3>(org)+val<3>(blockLength)))); - nodes.push_back(makeUbTuple((float)(val<1>(org)+val<1>(blockLength)), (float)(val<2>(org)), (float)(val<3>(org)+val<3>(blockLength)))); - nodes.push_back(makeUbTuple((float)(val<1>(org)+val<1>(blockLength)), (float)(val<2>(org)+val<2>(blockLength)), (float)(val<3>(org)+val<3>(blockLength)))); - nodes.push_back(makeUbTuple((float)(val<1>(org)), (float)(val<2>(org)+val<2>(blockLength)), (float)(val<3>(org)+val<3>(blockLength)))); - cells.push_back(makeUbTuple(nr, nr+1, nr+2, nr+3, nr+4, nr+5, nr+6, nr+7)); - nr += 8; - - //data - celldata[0].push_back((double)block->isActive()); - celldata[1].push_back((double)block->getRank()); - celldata[2].push_back((double)block->hasInterpolationFlag()); - celldata[3].push_back((double)block->getGlobalID()); - celldata[4].push_back((double)block->getPart()); - celldata[5].push_back((double)block->getLevel()); - - //bool flag = false; - //std::vector<SPtr<Block3DConnector>> connectors; - - //block->pushBackLocalInterpolationConnectorsCF(connectors); - //for (std::size_t i = 0; i<connectors.size(); i++) - // if (connectors[i]) - // { - // if (connectors[i]->getSendDir() == D3Q27System::BS) - // { - - // flag = true; - // } - // } - - //if (flag) - //{ - // celldata[6].push_back(1); - // UBLOG(logINFO, "CF: "+block->toString()); - //} - //else - //{ - // celldata[6].push_back(0); - //} - - //flag = false; - //connectors.resize(0); - //block->pushBackLocalInterpolationConnectorsFC(connectors); - //for (std::size_t i = 0; i<connectors.size(); i++) - // if (connectors[i]) - // { - // if (connectors[i]->getSendDir() == D3Q27System::BS) - // { - - // flag = true; - // } - // } - - //if (flag) - //{ - // celldata[7].push_back(1); - // UBLOG(logINFO, "FC: "+block->toString()); - //} - //else - //{ - // celldata[7].push_back(0); - //} - -#ifdef VF_FETOL - celldata[6].push_back( (double)block->getBundle()); + std::vector<std::vector<double>> celldata(celldatanames.size()); + + int nr = 0; + int minInitLevel = this->grid->getCoarsestInitializedLevel(); + int maxInitLevel = this->grid->getFinestInitializedLevel(); + + for (int level = minInitLevel; level <= maxInitLevel; level++) { + std::vector<SPtr<Block3D>> blockVector; + grid->getBlocks(level, blockVector); + for (SPtr<Block3D> block : blockVector) { + UbTupleDouble3 org = grid->getBlockWorldCoordinates(block); + UbTupleDouble3 blockLength = grid->getBlockLengths(block); + + nodes.push_back(makeUbTuple((float)(val<1>(org)), (float)(val<2>(org)), (float)(val<3>(org)))); + nodes.push_back(makeUbTuple((float)(val<1>(org) + val<1>(blockLength)), (float)(val<2>(org)), + (float)(val<3>(org)))); + nodes.push_back(makeUbTuple((float)(val<1>(org) + val<1>(blockLength)), + (float)(val<2>(org) + val<2>(blockLength)), (float)(val<3>(org)))); + nodes.push_back(makeUbTuple((float)(val<1>(org)), (float)(val<2>(org) + val<2>(blockLength)), + (float)(val<3>(org)))); + nodes.push_back(makeUbTuple((float)(val<1>(org)), (float)(val<2>(org)), + (float)(val<3>(org) + val<3>(blockLength)))); + nodes.push_back(makeUbTuple((float)(val<1>(org) + val<1>(blockLength)), (float)(val<2>(org)), + (float)(val<3>(org) + val<3>(blockLength)))); + nodes.push_back(makeUbTuple((float)(val<1>(org) + val<1>(blockLength)), + (float)(val<2>(org) + val<2>(blockLength)), + (float)(val<3>(org) + val<3>(blockLength)))); + nodes.push_back(makeUbTuple((float)(val<1>(org)), (float)(val<2>(org) + val<2>(blockLength)), + (float)(val<3>(org) + val<3>(blockLength)))); + cells.push_back(makeUbTuple(nr, nr + 1, nr + 2, nr + 3, nr + 4, nr + 5, nr + 6, nr + 7)); + nr += 8; + + // data + celldata[0].push_back((double)block->isActive()); + celldata[1].push_back((double)block->getRank()); + celldata[2].push_back((double)block->hasInterpolationFlag()); + celldata[3].push_back((double)block->getGlobalID()); + celldata[4].push_back((double)block->getPart()); + celldata[5].push_back((double)block->getLevel()); + + // bool flag = false; + // std::vector<SPtr<Block3DConnector>> connectors; + + // block->pushBackLocalInterpolationConnectorsCF(connectors); + // for (std::size_t i = 0; i<connectors.size(); i++) + // if (connectors[i]) + // { + // if (connectors[i]->getSendDir() == D3Q27System::BS) + // { + + // flag = true; + // } + // } + + // if (flag) + //{ + // celldata[6].push_back(1); + // UBLOG(logINFO, "CF: "+block->toString()); + //} + // else + //{ + // celldata[6].push_back(0); + //} + + // flag = false; + // connectors.resize(0); + // block->pushBackLocalInterpolationConnectorsFC(connectors); + // for (std::size_t i = 0; i<connectors.size(); i++) + // if (connectors[i]) + // { + // if (connectors[i]->getSendDir() == D3Q27System::BS) + // { + + // flag = true; + // } + // } + + // if (flag) + //{ + // celldata[7].push_back(1); + // UBLOG(logINFO, "FC: "+block->toString()); + //} + // else + //{ + // celldata[7].push_back(0); + //} + +#ifdef VF_FETOL + celldata[6].push_back((double)block->getBundle()); #endif - } - } - - filenames.push_back(writer->writeOctsWithCellData(path+"/blocks/blocks_" + UbSystem::toString(grid->getRank()) + "_" + UbSystem::toString(istep),nodes,cells,celldatanames,celldata)); - - if (istep == CoProcessor::scheduler->getMinBegin()) - { - WbWriterVtkXmlASCII::getInstance()->writeCollection(path+"/blocks/blocks_collection",filenames,istep,false); - } - else - { - WbWriterVtkXmlASCII::getInstance()->addFilesToCollection(path + "/blocks/blocks_collection", filenames, istep, false); - } - - UBLOG(logINFO,"WriteBlocksCoProcessor step: " << istep); - } + } + } + + filenames.push_back(writer->writeOctsWithCellData( + path + "/blocks/blocks_" + UbSystem::toString(grid->getRank()) + "_" + UbSystem::toString(istep), nodes, + cells, celldatanames, celldata)); + + if (istep == CoProcessor::scheduler->getMinBegin()) { + WbWriterVtkXmlASCII::getInstance()->writeCollection(path + "/blocks/blocks_collection", filenames, istep, + false); + } else { + WbWriterVtkXmlASCII::getInstance()->addFilesToCollection(path + "/blocks/blocks_collection", filenames, + istep, false); + } + + UBLOG(logINFO, "WriteBlocksCoProcessor step: " << istep); + } } diff --git a/src/cpu/VirtualFluidsCore/CoProcessors/WriteBlocksCoProcessor.h b/src/cpu/VirtualFluidsCore/CoProcessors/WriteBlocksCoProcessor.h index 30beca56754f7bc74738664ee694e0b21acab146..b26cdeebb29fcb1a9ba5b96f010c3c4af83e4c99 100644 --- a/src/cpu/VirtualFluidsCore/CoProcessors/WriteBlocksCoProcessor.h +++ b/src/cpu/VirtualFluidsCore/CoProcessors/WriteBlocksCoProcessor.h @@ -1,28 +1,28 @@ //======================================================================================= -// ____ ____ __ ______ __________ __ __ __ __ -// \ \ | | | | | _ \ |___ ___| | | | | / \ | | -// \ \ | | | | | |_) | | | | | | | / \ | | -// \ \ | | | | | _ / | | | | | | / /\ \ | | -// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ -// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| -// \ \ | | ________________________________________________________________ -// \ \ | | | ______________________________________________________________| -// \ \| | | | __ __ __ __ ______ _______ -// \ | | |_____ | | | | | | | | | _ \ / _____) -// \ | | _____| | | | | | | | | | | \ \ \_______ +// ____ ____ __ ______ __________ __ __ __ __ +// \ \ | | | | | _ \ |___ ___| | | | | / \ | | +// \ \ | | | | | |_) | | | | | | | / \ | | +// \ \ | | | | | _ / | | | | | | / /\ \ | | +// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ +// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| +// \ \ | | ________________________________________________________________ +// \ \ | | | ______________________________________________________________| +// \ \| | | | __ __ __ __ ______ _______ +// \ | | |_____ | | | | | | | | | _ \ / _____) +// \ | | _____| | | | | | | | | | | \ \ \_______ // \ | | | | |_____ | \_/ | | | | |_/ / _____ | -// \ _____| |__| |________| \_______/ |__| |______/ (_______/ +// \ _____| |__| |________| \_______/ |__| |______/ (_______/ // -// This file is part of VirtualFluids. VirtualFluids is free software: you can +// This file is part of VirtualFluids. VirtualFluids is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of +// License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. -// -// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// +// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License along // with VirtualFluids (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>. // @@ -46,30 +46,30 @@ class WbWriter; //! \class WriteBlocksCoProcessor //! \brief A class writes a block grid to a VTK-file -class WriteBlocksCoProcessor: public CoProcessor +class WriteBlocksCoProcessor : public CoProcessor { public: - //! \brief Construct WriteBlocksCoProcessor object. - //! \pre The Grid3D and UbScheduler objects must exist. - //! \param grid is observable Grid3D object - //! \param s is UbScheduler object for scheduling of observer - //! \param path is path of folder for output - //! \param writer is WbWriter object - //! \param comm is Communicator object - WriteBlocksCoProcessor(SPtr<Grid3D> grid, SPtr<UbScheduler> s, const std::string& path, WbWriter* const writer, SPtr<Communicator> comm); - ~WriteBlocksCoProcessor() override; + //! \brief Construct WriteBlocksCoProcessor object. + //! \pre The Grid3D and UbScheduler objects must exist. + //! \param grid is observable Grid3D object + //! \param s is UbScheduler object for scheduling of observer + //! \param path is path of folder for output + //! \param writer is WbWriter object + //! \param comm is Communicator object + WriteBlocksCoProcessor(SPtr<Grid3D> grid, SPtr<UbScheduler> s, const std::string &path, WbWriter *const writer, + SPtr<Communicator> comm); + ~WriteBlocksCoProcessor() override; - void process(double step) override; + void process(double step) override; protected: - //! Collect data for VTK-file - //! \param step is a time step - void collectData(double step); + //! Collect data for VTK-file + //! \param step is a time step + void collectData(double step); - std::string path; - WbWriter* writer; - SPtr<Communicator> comm; + std::string path; + WbWriter *writer; + SPtr<Communicator> comm; }; - -#endif +#endif diff --git a/src/cpu/VirtualFluidsCore/CoProcessors/WriteBoundaryConditionsCoProcessor.cpp b/src/cpu/VirtualFluidsCore/CoProcessors/WriteBoundaryConditionsCoProcessor.cpp index 4902ea845c4bc76c281f49c9b0db303adcd19dc8..bae45335e4c98bb60b6f67c65de3ec95ec19a3a0 100644 --- a/src/cpu/VirtualFluidsCore/CoProcessors/WriteBoundaryConditionsCoProcessor.cpp +++ b/src/cpu/VirtualFluidsCore/CoProcessors/WriteBoundaryConditionsCoProcessor.cpp @@ -1,28 +1,28 @@ //======================================================================================= -// ____ ____ __ ______ __________ __ __ __ __ -// \ \ | | | | | _ \ |___ ___| | | | | / \ | | -// \ \ | | | | | |_) | | | | | | | / \ | | -// \ \ | | | | | _ / | | | | | | / /\ \ | | -// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ -// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| -// \ \ | | ________________________________________________________________ -// \ \ | | | ______________________________________________________________| -// \ \| | | | __ __ __ __ ______ _______ -// \ | | |_____ | | | | | | | | | _ \ / _____) -// \ | | _____| | | | | | | | | | | \ \ \_______ +// ____ ____ __ ______ __________ __ __ __ __ +// \ \ | | | | | _ \ |___ ___| | | | | / \ | | +// \ \ | | | | | |_) | | | | | | | / \ | | +// \ \ | | | | | _ / | | | | | | / /\ \ | | +// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ +// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| +// \ \ | | ________________________________________________________________ +// \ \ | | | ______________________________________________________________| +// \ \| | | | __ __ __ __ ______ _______ +// \ | | |_____ | | | | | | | | | _ \ / _____) +// \ | | _____| | | | | | | | | | | \ \ \_______ // \ | | | | |_____ | \_/ | | | | |_/ / _____ | -// \ _____| |__| |________| \_______/ |__| |______/ (_______/ +// \ _____| |__| |________| \_______/ |__| |______/ (_______/ // -// This file is part of VirtualFluids. VirtualFluids is free software: you can +// This file is part of VirtualFluids. VirtualFluids is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of +// License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. -// -// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// +// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License along // with VirtualFluids (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>. // @@ -32,234 +32,202 @@ //======================================================================================= #include "WriteBoundaryConditionsCoProcessor.h" -#include "LBMKernel.h" #include "BCProcessor.h" -#include <vector> +#include "LBMKernel.h" #include <string> +#include <vector> -#include "basics/writer/WbWriterVtkXmlASCII.h" -#include "Grid3D.h" +#include "BCArray3D.h" #include "Block3D.h" -#include "LBMUnitConverter.h" +#include "CbArray3D.h" #include "Communicator.h" -#include "WbWriter.h" +#include "Grid3D.h" +#include "LBMUnitConverter.h" #include "UbScheduler.h" -#include "CbArray3D.h" -#include "BCArray3D.h" +#include "WbWriter.h" +#include "basics/writer/WbWriterVtkXmlASCII.h" using namespace std; -WriteBoundaryConditionsCoProcessor::WriteBoundaryConditionsCoProcessor() -= default; +WriteBoundaryConditionsCoProcessor::WriteBoundaryConditionsCoProcessor() = default; ////////////////////////////////////////////////////////////////////////// WriteBoundaryConditionsCoProcessor::WriteBoundaryConditionsCoProcessor(SPtr<Grid3D> grid, SPtr<UbScheduler> s, - const std::string& path, WbWriter* const writer, SPtr<Communicator> comm) - : CoProcessor(grid, s), - path(path), - writer(writer), - comm(comm) + const std::string &path, WbWriter *const writer, + SPtr<Communicator> comm) + : CoProcessor(grid, s), path(path), writer(writer), comm(comm) { - gridRank = comm->getProcessID(); - minInitLevel = this->grid->getCoarsestInitializedLevel(); - maxInitLevel = this->grid->getFinestInitializedLevel(); + gridRank = comm->getProcessID(); + minInitLevel = this->grid->getCoarsestInitializedLevel(); + maxInitLevel = this->grid->getFinestInitializedLevel(); - blockVector.resize(maxInitLevel+1); + blockVector.resize(maxInitLevel + 1); - for (int level = minInitLevel; level<=maxInitLevel; level++) - { - grid->getBlocks(level, gridRank, true, blockVector[level]); - } + for (int level = minInitLevel; level <= maxInitLevel; level++) { + grid->getBlocks(level, gridRank, true, blockVector[level]); + } } ////////////////////////////////////////////////////////////////////////// void WriteBoundaryConditionsCoProcessor::process(double step) { - if (scheduler->isDue(step)) - collectData(step); + if (scheduler->isDue(step)) + collectData(step); - UBLOG(logDEBUG3, "WriteBoundaryConditionsCoProcessor::update:"<<step); + UBLOG(logDEBUG3, "WriteBoundaryConditionsCoProcessor::update:" << step); } ////////////////////////////////////////////////////////////////////////// void WriteBoundaryConditionsCoProcessor::collectData(double step) { - int istep = static_cast<int>(step); - - for (int level = minInitLevel; level<=maxInitLevel; level++) - { - for(SPtr<Block3D> block : blockVector[level]) - { - if (block) - { - addDataGeo(block); - } - } - } - - string pfilePath, partPath, subfolder, cfilePath; - - subfolder = "bc"+UbSystem::toString(istep); - pfilePath = path+"/bc/"+subfolder; - cfilePath = path+"/bc/bc_collection"; - partPath = pfilePath+"/bc"+UbSystem::toString(gridRank)+"_"+UbSystem::toString(istep); - - - string partName = writer->writeOctsWithNodeData(partPath, nodes, cells, datanames, data); - size_t found = partName.find_last_of("/"); - string piece = partName.substr(found+1); - piece = subfolder+"/"+piece; + int istep = static_cast<int>(step); - vector<string> cellDataNames; - vector<string> pieces = comm->gather(piece); - if (comm->getProcessID()==comm->getRoot()) - { - string pname = WbWriterVtkXmlASCII::getInstance()->writeParallelFile(pfilePath, pieces, datanames, cellDataNames); - found = pname.find_last_of("/"); - piece = pname.substr(found+1); - - vector<string> filenames; - filenames.push_back(piece); - if (step==CoProcessor::scheduler->getMinBegin()) - { - WbWriterVtkXmlASCII::getInstance()->writeCollection(cfilePath, filenames, istep, false); - } - else - { - WbWriterVtkXmlASCII::getInstance()->addFilesToCollection(cfilePath, filenames, istep, false); - } - UBLOG(logINFO, "WriteBoundaryConditionsCoProcessor step: "<<istep); - } - - clearData(); + for (int level = minInitLevel; level <= maxInitLevel; level++) { + for (SPtr<Block3D> block : blockVector[level]) { + if (block) { + addDataGeo(block); + } + } + } + + string pfilePath, partPath, subfolder, cfilePath; + + subfolder = "bc" + UbSystem::toString(istep); + pfilePath = path + "/bc/" + subfolder; + cfilePath = path + "/bc/bc_collection"; + partPath = pfilePath + "/bc" + UbSystem::toString(gridRank) + "_" + UbSystem::toString(istep); + + string partName = writer->writeOctsWithNodeData(partPath, nodes, cells, datanames, data); + size_t found = partName.find_last_of("/"); + string piece = partName.substr(found + 1); + piece = subfolder + "/" + piece; + + vector<string> cellDataNames; + vector<string> pieces = comm->gather(piece); + if (comm->getProcessID() == comm->getRoot()) { + string pname = + WbWriterVtkXmlASCII::getInstance()->writeParallelFile(pfilePath, pieces, datanames, cellDataNames); + found = pname.find_last_of("/"); + piece = pname.substr(found + 1); + + vector<string> filenames; + filenames.push_back(piece); + if (step == CoProcessor::scheduler->getMinBegin()) { + WbWriterVtkXmlASCII::getInstance()->writeCollection(cfilePath, filenames, istep, false); + } else { + WbWriterVtkXmlASCII::getInstance()->addFilesToCollection(cfilePath, filenames, istep, false); + } + UBLOG(logINFO, "WriteBoundaryConditionsCoProcessor step: " << istep); + } + + clearData(); } ////////////////////////////////////////////////////////////////////////// void WriteBoundaryConditionsCoProcessor::clearData() { - nodes.clear(); - cells.clear(); - datanames.clear(); - data.clear(); + nodes.clear(); + cells.clear(); + datanames.clear(); + data.clear(); } ////////////////////////////////////////////////////////////////////////// void WriteBoundaryConditionsCoProcessor::addDataGeo(SPtr<Block3D> block) { - UbTupleDouble3 org = grid->getBlockWorldCoordinates(block); - UbTupleDouble3 nodeOffset = grid->getNodeOffset(block); - double dx = grid->getDeltaX(block); - - double level = (double)block->getLevel(); - - //Diese Daten werden geschrieben: - datanames.resize(0); - datanames.emplace_back("Boundary Conditions"); - datanames.emplace_back("Geometry"); - datanames.emplace_back("Level"); - //datanames.emplace_back("Interface CF"); - - data.resize(datanames.size()); - - SPtr<ILBMKernel> kernel = block->getKernel(); - SPtr<BCArray3D> bcArray = kernel->getBCProcessor()->getBCArray(); - - //knotennummerierung faengt immer bei 0 an! - unsigned int SWB, SEB, NEB, NWB, SWT, SET, NET, NWT; - - int minX1 = 0; - int minX2 = 0; - int minX3 = 0; - - int maxX1 = (int)bcArray->getNX1(); - int maxX2 = (int)bcArray->getNX2(); - int maxX3 = (int)bcArray->getNX3(); - - //nummern vergeben und node vector erstellen + daten sammeln - CbArray3D<int> nodeNumbers((int)maxX1, (int)maxX2, (int)maxX3, -1); - //D3Q27BoundaryConditionPtr bcPtr; - int nr = (int)nodes.size(); - - maxX1 -= 1; - maxX2 -= 1; - maxX3 -= 1; - - for (size_t ix3 = minX3; ix3<=maxX3; ix3++) - { - for (size_t ix2 = minX2; ix2<=maxX2; ix2++) - { - for (size_t ix1 = minX1; ix1<=maxX1; ix1++) - { - if (!bcArray->isUndefined(ix1, ix2, ix3)) - { - //int index = 0; - nodeNumbers(ix1, ix2, ix3) = nr++; - nodes.push_back(makeUbTuple(float(val<1>(org)-val<1>(nodeOffset)+ix1*dx), - float(val<2>(org)-val<2>(nodeOffset)+ix2*dx), - float(val<3>(org)-val<3>(nodeOffset)+ix3*dx))); - - - - if (!bcArray->hasBC(ix1, ix2, ix3)) - { - data[0].push_back(0.0); - } - else if (bcArray->getBC(ix1, ix2, ix3)->hasNoSlipBoundary()) - data[0].push_back(1.0); - else if (bcArray->getBC(ix1, ix2, ix3)->hasVelocityBoundary()) - data[0].push_back(2.0); - else if (bcArray->getBC(ix1, ix2, ix3)->hasDensityBoundary()) - data[0].push_back(3.0); - else if (bcArray->getBC(ix1, ix2, ix3)->hasSlipBoundary()) - data[0].push_back(4.0); - //else - // data[0].push_back(5.0); - - - if (bcArray->isSolid(ix1, ix2, ix3)) - { - data[1].push_back(1.0); - } - else - { - data[1].push_back(0.0); - } - - - data[2].push_back(level); - - //if (bcArray->isInterfaceCF(ix1, ix2, ix3)) - //{ - // data[3].push_back(1.0); - //} - //else - //{ - // data[3].push_back(0.0); - //} - + UbTupleDouble3 org = grid->getBlockWorldCoordinates(block); + UbTupleDouble3 nodeOffset = grid->getNodeOffset(block); + double dx = grid->getDeltaX(block); + + double level = (double)block->getLevel(); + + // Diese Daten werden geschrieben: + datanames.resize(0); + datanames.emplace_back("Boundary Conditions"); + datanames.emplace_back("Geometry"); + datanames.emplace_back("Level"); + // datanames.emplace_back("Interface CF"); + + data.resize(datanames.size()); + + SPtr<ILBMKernel> kernel = block->getKernel(); + SPtr<BCArray3D> bcArray = kernel->getBCProcessor()->getBCArray(); + + // knotennummerierung faengt immer bei 0 an! + unsigned int SWB, SEB, NEB, NWB, SWT, SET, NET, NWT; + + int minX1 = 0; + int minX2 = 0; + int minX3 = 0; + + int maxX1 = (int)bcArray->getNX1(); + int maxX2 = (int)bcArray->getNX2(); + int maxX3 = (int)bcArray->getNX3(); + + // nummern vergeben und node vector erstellen + daten sammeln + CbArray3D<int> nodeNumbers((int)maxX1, (int)maxX2, (int)maxX3, -1); + // D3Q27BoundaryConditionPtr bcPtr; + int nr = (int)nodes.size(); + + maxX1 -= 1; + maxX2 -= 1; + maxX3 -= 1; + + for (size_t ix3 = minX3; ix3 <= maxX3; ix3++) { + for (size_t ix2 = minX2; ix2 <= maxX2; ix2++) { + for (size_t ix1 = minX1; ix1 <= maxX1; ix1++) { + if (!bcArray->isUndefined(ix1, ix2, ix3)) { + // int index = 0; + nodeNumbers(ix1, ix2, ix3) = nr++; + nodes.push_back(makeUbTuple(float(val<1>(org) - val<1>(nodeOffset) + ix1 * dx), + float(val<2>(org) - val<2>(nodeOffset) + ix2 * dx), + float(val<3>(org) - val<3>(nodeOffset) + ix3 * dx))); + + if (!bcArray->hasBC(ix1, ix2, ix3)) { + data[0].push_back(0.0); + } else if (bcArray->getBC(ix1, ix2, ix3)->hasNoSlipBoundary()) + data[0].push_back(1.0); + else if (bcArray->getBC(ix1, ix2, ix3)->hasVelocityBoundary()) + data[0].push_back(2.0); + else if (bcArray->getBC(ix1, ix2, ix3)->hasDensityBoundary()) + data[0].push_back(3.0); + else if (bcArray->getBC(ix1, ix2, ix3)->hasSlipBoundary()) + data[0].push_back(4.0); + // else + // data[0].push_back(5.0); + + if (bcArray->isSolid(ix1, ix2, ix3)) { + data[1].push_back(1.0); + } else { + data[1].push_back(0.0); + } + + data[2].push_back(level); + + // if (bcArray->isInterfaceCF(ix1, ix2, ix3)) + //{ + // data[3].push_back(1.0); + //} + // else + //{ + // data[3].push_back(0.0); + //} + } } - } - } - } - - maxX1 -= 1; - maxX2 -= 1; - maxX3 -= 1; - - //cell vector erstellen - for (int ix3 = minX3; ix3<=maxX3; ix3++) - { - for (int ix2 = minX2; ix2<=maxX2; ix2++) - { - for (int ix1 = minX1; ix1<=maxX1; ix1++) - { - if ((SWB = nodeNumbers(ix1, ix2, ix3))>=0 - &&(SEB = nodeNumbers(ix1+1, ix2, ix3))>=0 - &&(NEB = nodeNumbers(ix1+1, ix2+1, ix3))>=0 - &&(NWB = nodeNumbers(ix1, ix2+1, ix3))>=0 - &&(SWT = nodeNumbers(ix1, ix2, ix3+1))>=0 - &&(SET = nodeNumbers(ix1+1, ix2, ix3+1))>=0 - &&(NET = nodeNumbers(ix1+1, ix2+1, ix3+1))>=0 - &&(NWT = nodeNumbers(ix1, ix2+1, ix3+1))>=0) - { - cells.push_back(makeUbTuple(SWB, SEB, NEB, NWB, SWT, SET, NET, NWT)); + } + } + + maxX1 -= 1; + maxX2 -= 1; + maxX3 -= 1; + + // cell vector erstellen + for (int ix3 = minX3; ix3 <= maxX3; ix3++) { + for (int ix2 = minX2; ix2 <= maxX2; ix2++) { + for (int ix1 = minX1; ix1 <= maxX1; ix1++) { + if ((SWB = nodeNumbers(ix1, ix2, ix3)) >= 0 && (SEB = nodeNumbers(ix1 + 1, ix2, ix3)) >= 0 && + (NEB = nodeNumbers(ix1 + 1, ix2 + 1, ix3)) >= 0 && (NWB = nodeNumbers(ix1, ix2 + 1, ix3)) >= 0 && + (SWT = nodeNumbers(ix1, ix2, ix3 + 1)) >= 0 && (SET = nodeNumbers(ix1 + 1, ix2, ix3 + 1)) >= 0 && + (NET = nodeNumbers(ix1 + 1, ix2 + 1, ix3 + 1)) >= 0 && + (NWT = nodeNumbers(ix1, ix2 + 1, ix3 + 1)) >= 0) { + cells.push_back(makeUbTuple(SWB, SEB, NEB, NWB, SWT, SET, NET, NWT)); + } } - } - } - } + } + } } diff --git a/src/cpu/VirtualFluidsCore/CoProcessors/WriteBoundaryConditionsCoProcessor.h b/src/cpu/VirtualFluidsCore/CoProcessors/WriteBoundaryConditionsCoProcessor.h index b89db187db42d4d13a0f3f9b986451e3665e499b..ad29abca5e90c1267d7ab1768c1b3600fbd535c7 100644 --- a/src/cpu/VirtualFluidsCore/CoProcessors/WriteBoundaryConditionsCoProcessor.h +++ b/src/cpu/VirtualFluidsCore/CoProcessors/WriteBoundaryConditionsCoProcessor.h @@ -1,28 +1,28 @@ //======================================================================================= -// ____ ____ __ ______ __________ __ __ __ __ -// \ \ | | | | | _ \ |___ ___| | | | | / \ | | -// \ \ | | | | | |_) | | | | | | | / \ | | -// \ \ | | | | | _ / | | | | | | / /\ \ | | -// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ -// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| -// \ \ | | ________________________________________________________________ -// \ \ | | | ______________________________________________________________| -// \ \| | | | __ __ __ __ ______ _______ -// \ | | |_____ | | | | | | | | | _ \ / _____) -// \ | | _____| | | | | | | | | | | \ \ \_______ +// ____ ____ __ ______ __________ __ __ __ __ +// \ \ | | | | | _ \ |___ ___| | | | | / \ | | +// \ \ | | | | | |_) | | | | | | | / \ | | +// \ \ | | | | | _ / | | | | | | / /\ \ | | +// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ +// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| +// \ \ | | ________________________________________________________________ +// \ \ | | | ______________________________________________________________| +// \ \| | | | __ __ __ __ ______ _______ +// \ | | |_____ | | | | | | | | | _ \ / _____) +// \ | | _____| | | | | | | | | | | \ \ \_______ // \ | | | | |_____ | \_/ | | | | |_/ / _____ | -// \ _____| |__| |________| \_______/ |__| |______/ (_______/ +// \ _____| |__| |________| \_______/ |__| |______/ (_______/ // -// This file is part of VirtualFluids. VirtualFluids is free software: you can +// This file is part of VirtualFluids. VirtualFluids is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of +// License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. -// -// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// +// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License along // with VirtualFluids (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>. // @@ -49,40 +49,41 @@ class Block3D; class LBMUnitConverter; //! \brief A class writes boundary conditions information to a VTK-file -class WriteBoundaryConditionsCoProcessor : public CoProcessor +class WriteBoundaryConditionsCoProcessor : public CoProcessor { public: - WriteBoundaryConditionsCoProcessor(); - //! \brief Construct WriteBoundaryConditionsCoProcessor object - //! \pre The Grid3D and UbScheduler objects must exist - //! \param grid is observable Grid3D object - //! \param s is UbScheduler object for scheduling of observer - //! \param path is path of folder for output - //! \param writer is WbWriter object - //! \param comm is Communicator object - WriteBoundaryConditionsCoProcessor(SPtr<Grid3D> grid, SPtr<UbScheduler> s, const std::string& path, WbWriter* const writer, SPtr<Communicator> comm); - ~WriteBoundaryConditionsCoProcessor() override = default; + WriteBoundaryConditionsCoProcessor(); + //! \brief Construct WriteBoundaryConditionsCoProcessor object + //! \pre The Grid3D and UbScheduler objects must exist + //! \param grid is observable Grid3D object + //! \param s is UbScheduler object for scheduling of observer + //! \param path is path of folder for output + //! \param writer is WbWriter object + //! \param comm is Communicator object + WriteBoundaryConditionsCoProcessor(SPtr<Grid3D> grid, SPtr<UbScheduler> s, const std::string &path, + WbWriter *const writer, SPtr<Communicator> comm); + ~WriteBoundaryConditionsCoProcessor() override = default; - void process(double step) override; + void process(double step) override; protected: - //! Collect data for VTK-file - //! \param step is a time step - void collectData(double step); - void addDataGeo(SPtr<Block3D> block); - void clearData(); + //! Collect data for VTK-file + //! \param step is a time step + void collectData(double step); + void addDataGeo(SPtr<Block3D> block); + void clearData(); private: - std::vector<UbTupleFloat3> nodes; - std::vector<UbTupleUInt8> cells; - std::vector<std::string> datanames; - std::vector<std::vector<double> > data; - std::string path; - WbWriter* writer; - std::vector<std::vector<SPtr<Block3D> > > blockVector; - int minInitLevel; - int maxInitLevel; - int gridRank; - SPtr<Communicator> comm; + std::vector<UbTupleFloat3> nodes; + std::vector<UbTupleUInt8> cells; + std::vector<std::string> datanames; + std::vector<std::vector<double>> data; + std::string path; + WbWriter *writer; + std::vector<std::vector<SPtr<Block3D>>> blockVector; + int minInitLevel; + int maxInitLevel; + int gridRank; + SPtr<Communicator> comm; }; #endif diff --git a/src/cpu/VirtualFluidsCore/CoProcessors/WriteGbObjectsCoProcessor.cpp b/src/cpu/VirtualFluidsCore/CoProcessors/WriteGbObjectsCoProcessor.cpp index 0b66c12875bb7a7174f2f1501ae6c3731a257246..3c1c36a11fcdfc000cc6251130f720baf91607a2 100644 --- a/src/cpu/VirtualFluidsCore/CoProcessors/WriteGbObjectsCoProcessor.cpp +++ b/src/cpu/VirtualFluidsCore/CoProcessors/WriteGbObjectsCoProcessor.cpp @@ -1,80 +1,73 @@ #include "WriteGbObjectsCoProcessor.h" -#include "UbScheduler.h" -#include "WbWriterVtkXmlBinary.h" -#include "WbWriterVtkXmlASCII.h" #include "Communicator.h" #include "GbObject3D.h" +#include "UbScheduler.h" +#include "WbWriterVtkXmlASCII.h" +#include "WbWriterVtkXmlBinary.h" #include <vector> -WriteGbObjectsCoProcessor::WriteGbObjectsCoProcessor(SPtr<Grid3D> grid, SPtr<UbScheduler> s, const std::string& path, WbWriter* const writer, SPtr<Communicator> comm) : CoProcessor(grid, s), path(path), writer(writer), comm(comm) +WriteGbObjectsCoProcessor::WriteGbObjectsCoProcessor(SPtr<Grid3D> grid, SPtr<UbScheduler> s, const std::string &path, + WbWriter *const writer, SPtr<Communicator> comm) + : CoProcessor(grid, s), path(path), writer(writer), comm(comm) { } ////////////////////////////////////////////////////////////////////////// -WriteGbObjectsCoProcessor::~WriteGbObjectsCoProcessor() -= default; +WriteGbObjectsCoProcessor::~WriteGbObjectsCoProcessor() = default; ////////////////////////////////////////////////////////////////////////// void WriteGbObjectsCoProcessor::process(double step) { - if (scheduler->isDue(step)) - collectData(step); + if (scheduler->isDue(step)) + collectData(step); } ////////////////////////////////////////////////////////////////////////// -void WriteGbObjectsCoProcessor::addGbObject(SPtr<GbObject3D> object) -{ - objects.push_back(object); -} +void WriteGbObjectsCoProcessor::addGbObject(SPtr<GbObject3D> object) { objects.push_back(object); } ////////////////////////////////////////////////////////////////////////// void WriteGbObjectsCoProcessor::collectData(double step) { - std::vector<UbTupleFloat3> nodes; - std::vector<UbTupleInt3> triangles; - - int numObjcts = 0; + std::vector<UbTupleFloat3> nodes; + std::vector<UbTupleInt3> triangles; - for (SPtr<GbObject3D>object : objects) - { - object->addSurfaceTriangleSet(nodes, triangles); - numObjcts++; - } + int numObjcts = 0; - int istep = static_cast<int>(step); + for (SPtr<GbObject3D> object : objects) { + object->addSurfaceTriangleSet(nodes, triangles); + numObjcts++; + } - std::string pfilePath, partPath, subfolder, cfilePath; + int istep = static_cast<int>(step); - subfolder = "gob"+UbSystem::toString(istep); - pfilePath = path+"/gob/"+subfolder; - cfilePath = path+"/gob/gob_collection"; - partPath = pfilePath+"/gob"+UbSystem::toString(comm->getProcessID())+ "_" + UbSystem::toString(istep); + std::string pfilePath, partPath, subfolder, cfilePath; + subfolder = "gob" + UbSystem::toString(istep); + pfilePath = path + "/gob/" + subfolder; + cfilePath = path + "/gob/gob_collection"; + partPath = pfilePath + "/gob" + UbSystem::toString(comm->getProcessID()) + "_" + UbSystem::toString(istep); - std::string partName = writer->writeTriangles(partPath, nodes, triangles); + std::string partName = writer->writeTriangles(partPath, nodes, triangles); - size_t found=partName.find_last_of("/"); - std::string piece = partName.substr(found+1); - piece = subfolder + "/" + piece; + size_t found = partName.find_last_of("/"); + std::string piece = partName.substr(found + 1); + piece = subfolder + "/" + piece; - std::vector<std::string> datanames; - std::vector<std::string> cellDataNames; - //std::vector<std::string> pieces = comm->gather(piece); - std::vector<std::string> pieces; - pieces.push_back(piece); - if (comm->isRoot()) - { - std::string pname = WbWriterVtkXmlASCII::getInstance()->writeParallelFile(pfilePath, pieces, datanames, cellDataNames); - found=pname.find_last_of("/"); - piece = pname.substr(found+1); + std::vector<std::string> datanames; + std::vector<std::string> cellDataNames; + // std::vector<std::string> pieces = comm->gather(piece); + std::vector<std::string> pieces; + pieces.push_back(piece); + if (comm->isRoot()) { + std::string pname = + WbWriterVtkXmlASCII::getInstance()->writeParallelFile(pfilePath, pieces, datanames, cellDataNames); + found = pname.find_last_of("/"); + piece = pname.substr(found + 1); - std::vector<std::string> filenames; - filenames.push_back(piece); - if (step == CoProcessor::scheduler->getMinBegin()) - { - WbWriterVtkXmlASCII::getInstance()->writeCollection(cfilePath, filenames, istep, false); - } - else - { - WbWriterVtkXmlASCII::getInstance()->addFilesToCollection(cfilePath, filenames, istep, false); - } - UBLOG(logINFO, "WriteGbObjectsCoProcessor number of objects: " << numObjcts); - UBLOG(logINFO, "WriteGbObjectsCoProcessor step: " << istep); - } + std::vector<std::string> filenames; + filenames.push_back(piece); + if (step == CoProcessor::scheduler->getMinBegin()) { + WbWriterVtkXmlASCII::getInstance()->writeCollection(cfilePath, filenames, istep, false); + } else { + WbWriterVtkXmlASCII::getInstance()->addFilesToCollection(cfilePath, filenames, istep, false); + } + UBLOG(logINFO, "WriteGbObjectsCoProcessor number of objects: " << numObjcts); + UBLOG(logINFO, "WriteGbObjectsCoProcessor step: " << istep); + } } diff --git a/src/cpu/VirtualFluidsCore/CoProcessors/WriteGbObjectsCoProcessor.h b/src/cpu/VirtualFluidsCore/CoProcessors/WriteGbObjectsCoProcessor.h index 6b1c9f24ab7096d171eb35cca035ecf7f5393d92..d1e9925b5eaec20a1319818acb67c662e595e7d3 100644 --- a/src/cpu/VirtualFluidsCore/CoProcessors/WriteGbObjectsCoProcessor.h +++ b/src/cpu/VirtualFluidsCore/CoProcessors/WriteGbObjectsCoProcessor.h @@ -17,22 +17,25 @@ class WbWriter; //! \author Konstantin Kutscher //! \date December 2018 -class WriteGbObjectsCoProcessor :public CoProcessor +class WriteGbObjectsCoProcessor : public CoProcessor { public: - WriteGbObjectsCoProcessor(SPtr<Grid3D> grid, SPtr<UbScheduler> s, const std::string& path, WbWriter* const writer, SPtr<Communicator> comm); - ~WriteGbObjectsCoProcessor() override; - //! calls collectData. - void process(double step) override; - //! adds geometry object - void addGbObject(SPtr<GbObject3D> object); + WriteGbObjectsCoProcessor(SPtr<Grid3D> grid, SPtr<UbScheduler> s, const std::string &path, WbWriter *const writer, + SPtr<Communicator> comm); + ~WriteGbObjectsCoProcessor() override; + //! calls collectData. + void process(double step) override; + //! adds geometry object + void addGbObject(SPtr<GbObject3D> object); + protected: - void collectData(double step); + void collectData(double step); + private: - std::vector< SPtr<GbObject3D> > objects; - std::string path; - WbWriter* writer; - SPtr<Communicator> comm; + std::vector<SPtr<GbObject3D>> objects; + std::string path; + WbWriter *writer; + SPtr<Communicator> comm; }; #endif // WriteGbObjectsCoProcessor_h__ \ No newline at end of file diff --git a/src/cpu/VirtualFluidsCore/CoProcessors/WriteMQFromSelectionCoProcessor.cpp b/src/cpu/VirtualFluidsCore/CoProcessors/WriteMQFromSelectionCoProcessor.cpp index 0f53b97a4acedd5ebc286f3f3e3a596bc40cb211..3d892d561fe64de1b3efb3f94450e36cc6632a0d 100644 --- a/src/cpu/VirtualFluidsCore/CoProcessors/WriteMQFromSelectionCoProcessor.cpp +++ b/src/cpu/VirtualFluidsCore/CoProcessors/WriteMQFromSelectionCoProcessor.cpp @@ -1,235 +1,213 @@ #include "WriteMQFromSelectionCoProcessor.h" -#include "LBMKernel.h" #include "BCProcessor.h" -#include <vector> +#include "LBMKernel.h" #include <string> +#include <vector> -#include "basics/writer/WbWriterVtkXmlASCII.h" +#include "BCArray3D.h" +#include "Block3D.h" +#include "Communicator.h" #include "DataSet3D.h" -#include "UbScheduler.h" +#include "GbObject3D.h" #include "Grid3D.h" -#include "Communicator.h" #include "LBMUnitConverter.h" -#include "Block3D.h" -#include "BCArray3D.h" -#include "GbObject3D.h" +#include "UbScheduler.h" +#include "basics/writer/WbWriterVtkXmlASCII.h" -WriteMQFromSelectionCoProcessor::WriteMQFromSelectionCoProcessor() -= default; +WriteMQFromSelectionCoProcessor::WriteMQFromSelectionCoProcessor() = default; ////////////////////////////////////////////////////////////////////////// WriteMQFromSelectionCoProcessor::WriteMQFromSelectionCoProcessor(SPtr<Grid3D> grid, SPtr<UbScheduler> s, - SPtr<GbObject3D> gbObject, - const std::string& path, WbWriter* const writer, - SPtr<LBMUnitConverter> conv, - SPtr<Communicator> comm) - : CoProcessor(grid, s), - gbObject(gbObject), - path(path), - writer(writer), - conv(conv), - comm(comm) + SPtr<GbObject3D> gbObject, const std::string &path, + WbWriter *const writer, SPtr<LBMUnitConverter> conv, + SPtr<Communicator> comm) + : CoProcessor(grid, s), gbObject(gbObject), path(path), writer(writer), conv(conv), comm(comm) { - gridRank = comm->getProcessID(); - minInitLevel = this->grid->getCoarsestInitializedLevel(); - maxInitLevel = this->grid->getFinestInitializedLevel(); + gridRank = comm->getProcessID(); + minInitLevel = this->grid->getCoarsestInitializedLevel(); + maxInitLevel = this->grid->getFinestInitializedLevel(); - blockVector.resize(maxInitLevel+1); + blockVector.resize(maxInitLevel + 1); - for (int level = minInitLevel; level<=maxInitLevel; level++) - { - grid->getBlocks(level, gridRank, true, blockVector[level]); - } + for (int level = minInitLevel; level <= maxInitLevel; level++) { + grid->getBlocks(level, gridRank, true, blockVector[level]); + } } ////////////////////////////////////////////////////////////////////////// -void WriteMQFromSelectionCoProcessor::init() -{ - -} +void WriteMQFromSelectionCoProcessor::init() {} ////////////////////////////////////////////////////////////////////////// void WriteMQFromSelectionCoProcessor::process(double step) { - if(scheduler->isDue(step) ) - collectData(step); + if (scheduler->isDue(step)) + collectData(step); - UBLOG(logDEBUG3, "WriteMQFromSelectionCoProcessor::update:" << step); + UBLOG(logDEBUG3, "WriteMQFromSelectionCoProcessor::update:" << step); } ////////////////////////////////////////////////////////////////////////// void WriteMQFromSelectionCoProcessor::collectData(double step) { - int istep = static_cast<int>(step); - - for(int level = minInitLevel; level<=maxInitLevel;level++) - { - for(SPtr<Block3D> block : blockVector[level]) - { - if (block) - { - UbTupleDouble3 org = grid->getBlockWorldCoordinates(block); - UbTupleDouble3 blockLengths = grid->getBlockLengths(block); - - double minX1 = val<1>(org); - double minX2 = val<2>(org); - double minX3 = val<3>(org); - double maxX1 = val<1>(org)+val<1>(blockLengths); - double maxX2 = val<2>(org)+val<2>(blockLengths); - double maxX3 = val<3>(org)+val<3>(blockLengths); - - if (gbObject->isCellInsideOrCuttingGbObject3D(minX1, minX2, minX3, maxX1, maxX2, maxX3)) - { - addDataMQ(block); + int istep = static_cast<int>(step); + + for (int level = minInitLevel; level <= maxInitLevel; level++) { + for (SPtr<Block3D> block : blockVector[level]) { + if (block) { + UbTupleDouble3 org = grid->getBlockWorldCoordinates(block); + UbTupleDouble3 blockLengths = grid->getBlockLengths(block); + + double minX1 = val<1>(org); + double minX2 = val<2>(org); + double minX3 = val<3>(org); + double maxX1 = val<1>(org) + val<1>(blockLengths); + double maxX2 = val<2>(org) + val<2>(blockLengths); + double maxX3 = val<3>(org) + val<3>(blockLengths); + + if (gbObject->isCellInsideOrCuttingGbObject3D(minX1, minX2, minX3, maxX1, maxX2, maxX3)) { + addDataMQ(block); + } } - } - } - } - - std::string pfilePath, partPath, subfolder, cfilePath; - - subfolder = "mqSelect"+UbSystem::toString(istep); - pfilePath = path+"/mqSelect/"+subfolder; - cfilePath = path+"/mqSelect/mq_collection"; - partPath = pfilePath+"/mqSelect"+UbSystem::toString(gridRank)+ "_" + UbSystem::toString(istep); - - - std::string partName = writer->writeNodesWithNodeData(partPath,nodes,datanames,data); - size_t found=partName.find_last_of("/"); - std::string piece = partName.substr(found+1); - piece = subfolder + "/" + piece; - - std::vector<std::string> cellDataNames; - SPtr<Communicator> comm = Communicator::getInstance(); - std::vector<std::string> pieces = comm->gather(piece); - if (comm->getProcessID() == comm->getRoot()) - { - std::string pname = WbWriterVtkXmlASCII::getInstance()->writeParallelFile(pfilePath,pieces,datanames,cellDataNames); - found=pname.find_last_of("/"); - piece = pname.substr(found+1); - - std::vector<std::string> filenames; - filenames.push_back(piece); - if (step == CoProcessor::scheduler->getMinBegin()) - { - WbWriterVtkXmlASCII::getInstance()->writeCollection(cfilePath,filenames,istep,false); - } - else - { - WbWriterVtkXmlASCII::getInstance()->addFilesToCollection(cfilePath,filenames,istep,false); - } - UBLOG(logINFO,"WriteMQFromSelectionCoProcessor step: " << istep); - } - - clearData(); + } + } + + std::string pfilePath, partPath, subfolder, cfilePath; + + subfolder = "mqSelect" + UbSystem::toString(istep); + pfilePath = path + "/mqSelect/" + subfolder; + cfilePath = path + "/mqSelect/mq_collection"; + partPath = pfilePath + "/mqSelect" + UbSystem::toString(gridRank) + "_" + UbSystem::toString(istep); + + std::string partName = writer->writeNodesWithNodeData(partPath, nodes, datanames, data); + size_t found = partName.find_last_of("/"); + std::string piece = partName.substr(found + 1); + piece = subfolder + "/" + piece; + + std::vector<std::string> cellDataNames; + SPtr<Communicator> comm = Communicator::getInstance(); + std::vector<std::string> pieces = comm->gather(piece); + if (comm->getProcessID() == comm->getRoot()) { + std::string pname = + WbWriterVtkXmlASCII::getInstance()->writeParallelFile(pfilePath, pieces, datanames, cellDataNames); + found = pname.find_last_of("/"); + piece = pname.substr(found + 1); + + std::vector<std::string> filenames; + filenames.push_back(piece); + if (step == CoProcessor::scheduler->getMinBegin()) { + WbWriterVtkXmlASCII::getInstance()->writeCollection(cfilePath, filenames, istep, false); + } else { + WbWriterVtkXmlASCII::getInstance()->addFilesToCollection(cfilePath, filenames, istep, false); + } + UBLOG(logINFO, "WriteMQFromSelectionCoProcessor step: " << istep); + } + + clearData(); } ////////////////////////////////////////////////////////////////////////// void WriteMQFromSelectionCoProcessor::clearData() { - nodes.clear(); - datanames.clear(); - data.clear(); + nodes.clear(); + datanames.clear(); + data.clear(); } ////////////////////////////////////////////////////////////////////////// void WriteMQFromSelectionCoProcessor::addDataMQ(SPtr<Block3D> block) { - double level = (double)block->getLevel(); -// double blockID = (double)block->getGlobalID(); - - //Diese Daten werden geschrieben: - datanames.resize(0); - datanames.emplace_back("Rho"); - datanames.emplace_back("Vx"); - datanames.emplace_back("Vy"); - datanames.emplace_back("Vz"); - //datanames.push_back("Press"); - datanames.emplace_back("Level"); - //datanames.push_back("BlockID"); - - - - data.resize(datanames.size()); - - SPtr<ILBMKernel> kernel = block->getKernel(); - SPtr<BCArray3D> bcArray = kernel->getBCProcessor()->getBCArray(); - SPtr<DistributionArray3D> distributions = kernel->getDataSet()->getFdistributions(); - LBMReal f[D3Q27System::ENDF+1]; - LBMReal vx1,vx2,vx3,rho; - - if(block->getKernel()->getCompressible()) - { - calcMacros = &D3Q27System::calcCompMacroscopicValues; - } - else - { - calcMacros = &D3Q27System::calcIncompMacroscopicValues; - } - - int minX1 = 1; - int minX2 = 1; - int minX3 = 1; - - int maxX1 = (int)(distributions->getNX1()); - int maxX2 = (int)(distributions->getNX2()); - int maxX3 = (int)(distributions->getNX3()); - - //int minX1 = 1; - //int minX2 = 1; - //int minX3 = 1; - - //int maxX1 = (int)(distributions->getNX1()); - //int maxX2 = (int)(distributions->getNX2()); - //int maxX3 = (int)(distributions->getNX3()); - - //nummern vergeben und node vector erstellen + daten sammeln - CbArray3D<int> nodeNumbers((int)maxX1, (int)maxX2, (int)maxX3,-1); - maxX1 -= 2; - maxX2 -= 2; - maxX3 -= 2; - - //D3Q27BoundaryConditionPtr bcPtr; - int nr = (int)nodes.size(); - - for(int ix3=minX3; ix3<=maxX3; ix3++) - { - for(int ix2=minX2; ix2<=maxX2; ix2++) - { - for(int ix1=minX1; ix1<=maxX1; ix1++) - { - if(!bcArray->isUndefined(ix1,ix2,ix3) && !bcArray->isSolid(ix1,ix2,ix3)) - { - Vector3D worldCoordinates = grid->getNodeCoordinates(block, ix1, ix2, ix3); - if (gbObject->isPointInGbObject3D(worldCoordinates[0], worldCoordinates[1], worldCoordinates[2])) - { - int index = 0; - nodeNumbers(ix1, ix2, ix3) = nr++; - - nodes.emplace_back(float(worldCoordinates[0]), - float(worldCoordinates[1]), - float(worldCoordinates[2])); - - distributions->getDistribution(f, ix1, ix2, ix3); - calcMacros(f, rho, vx1, vx2, vx3); - - if (UbMath::isNaN(rho) || UbMath::isInfinity(rho)) - UB_THROW(UbException(UB_EXARGS, "rho is not a number (nan or -1.#IND) or infinity number -1.#INF in block="+block->toString()+ - ", node="+UbSystem::toString(ix1)+","+UbSystem::toString(ix2)+","+UbSystem::toString(ix3))); - if (UbMath::isNaN(vx1) || UbMath::isInfinity(vx1)) - UB_THROW(UbException(UB_EXARGS, "vx1 is not a number (nan or -1.#IND) or infinity number -1.#INF in block="+block->toString()+ - ", node="+UbSystem::toString(ix1)+","+UbSystem::toString(ix2)+","+UbSystem::toString(ix3))); - //vx1=999.0; - if (UbMath::isNaN(vx2) || UbMath::isInfinity(vx2)) - UB_THROW(UbException(UB_EXARGS, "vx2 is not a number (nan or -1.#IND) or infinity number -1.#INF in block="+block->toString()+ - ", node="+UbSystem::toString(ix1)+","+UbSystem::toString(ix2)+","+UbSystem::toString(ix3))); - //vx2=999.0; - if (UbMath::isNaN(vx3) || UbMath::isInfinity(vx3)) - UB_THROW(UbException(UB_EXARGS, "vx3 is not a number (nan or -1.#IND) or infinity number -1.#INF in block="+block->toString()+ - ", node="+UbSystem::toString(ix1)+","+UbSystem::toString(ix2)+","+UbSystem::toString(ix3))); - - data[index++].push_back(rho); - data[index++].push_back(vx1); - data[index++].push_back(vx2); - data[index++].push_back(vx3); - data[index++].push_back(level); - } + double level = (double)block->getLevel(); + // double blockID = (double)block->getGlobalID(); + + // Diese Daten werden geschrieben: + datanames.resize(0); + datanames.emplace_back("Rho"); + datanames.emplace_back("Vx"); + datanames.emplace_back("Vy"); + datanames.emplace_back("Vz"); + // datanames.push_back("Press"); + datanames.emplace_back("Level"); + // datanames.push_back("BlockID"); + + data.resize(datanames.size()); + + SPtr<ILBMKernel> kernel = block->getKernel(); + SPtr<BCArray3D> bcArray = kernel->getBCProcessor()->getBCArray(); + SPtr<DistributionArray3D> distributions = kernel->getDataSet()->getFdistributions(); + LBMReal f[D3Q27System::ENDF + 1]; + LBMReal vx1, vx2, vx3, rho; + + if (block->getKernel()->getCompressible()) { + calcMacros = &D3Q27System::calcCompMacroscopicValues; + } else { + calcMacros = &D3Q27System::calcIncompMacroscopicValues; + } + + int minX1 = 1; + int minX2 = 1; + int minX3 = 1; + + int maxX1 = (int)(distributions->getNX1()); + int maxX2 = (int)(distributions->getNX2()); + int maxX3 = (int)(distributions->getNX3()); + + // int minX1 = 1; + // int minX2 = 1; + // int minX3 = 1; + + // int maxX1 = (int)(distributions->getNX1()); + // int maxX2 = (int)(distributions->getNX2()); + // int maxX3 = (int)(distributions->getNX3()); + + // nummern vergeben und node vector erstellen + daten sammeln + CbArray3D<int> nodeNumbers((int)maxX1, (int)maxX2, (int)maxX3, -1); + maxX1 -= 2; + maxX2 -= 2; + maxX3 -= 2; + + // D3Q27BoundaryConditionPtr bcPtr; + int nr = (int)nodes.size(); + + for (int ix3 = minX3; ix3 <= maxX3; ix3++) { + for (int ix2 = minX2; ix2 <= maxX2; ix2++) { + for (int ix1 = minX1; ix1 <= maxX1; ix1++) { + if (!bcArray->isUndefined(ix1, ix2, ix3) && !bcArray->isSolid(ix1, ix2, ix3)) { + Vector3D worldCoordinates = grid->getNodeCoordinates(block, ix1, ix2, ix3); + if (gbObject->isPointInGbObject3D(worldCoordinates[0], worldCoordinates[1], worldCoordinates[2])) { + int index = 0; + nodeNumbers(ix1, ix2, ix3) = nr++; + + nodes.emplace_back(float(worldCoordinates[0]), float(worldCoordinates[1]), + float(worldCoordinates[2])); + + distributions->getDistribution(f, ix1, ix2, ix3); + calcMacros(f, rho, vx1, vx2, vx3); + + if (UbMath::isNaN(rho) || UbMath::isInfinity(rho)) + UB_THROW(UbException( + UB_EXARGS, "rho is not a number (nan or -1.#IND) or infinity number -1.#INF in block=" + + block->toString() + ", node=" + UbSystem::toString(ix1) + "," + + UbSystem::toString(ix2) + "," + UbSystem::toString(ix3))); + if (UbMath::isNaN(vx1) || UbMath::isInfinity(vx1)) + UB_THROW(UbException( + UB_EXARGS, "vx1 is not a number (nan or -1.#IND) or infinity number -1.#INF in block=" + + block->toString() + ", node=" + UbSystem::toString(ix1) + "," + + UbSystem::toString(ix2) + "," + UbSystem::toString(ix3))); + // vx1=999.0; + if (UbMath::isNaN(vx2) || UbMath::isInfinity(vx2)) + UB_THROW(UbException( + UB_EXARGS, "vx2 is not a number (nan or -1.#IND) or infinity number -1.#INF in block=" + + block->toString() + ", node=" + UbSystem::toString(ix1) + "," + + UbSystem::toString(ix2) + "," + UbSystem::toString(ix3))); + // vx2=999.0; + if (UbMath::isNaN(vx3) || UbMath::isInfinity(vx3)) + UB_THROW(UbException( + UB_EXARGS, "vx3 is not a number (nan or -1.#IND) or infinity number -1.#INF in block=" + + block->toString() + ", node=" + UbSystem::toString(ix1) + "," + + UbSystem::toString(ix2) + "," + UbSystem::toString(ix3))); + + data[index++].push_back(rho); + data[index++].push_back(vx1); + data[index++].push_back(vx2); + data[index++].push_back(vx3); + data[index++].push_back(level); + } + } } - } - } - } + } + } } diff --git a/src/cpu/VirtualFluidsCore/CoProcessors/WriteMQFromSelectionCoProcessor.h b/src/cpu/VirtualFluidsCore/CoProcessors/WriteMQFromSelectionCoProcessor.h index a10ab7f2707b71daf4468523f10c92ddc6f04826..0e52856cb32360a706b77fdcea8935037664b542 100644 --- a/src/cpu/VirtualFluidsCore/CoProcessors/WriteMQFromSelectionCoProcessor.h +++ b/src/cpu/VirtualFluidsCore/CoProcessors/WriteMQFromSelectionCoProcessor.h @@ -10,7 +10,6 @@ #include "LBMSystem.h" #include "UbTuple.h" - class Communicator; class Grid3D; class UbScheduler; @@ -19,41 +18,40 @@ class WbWriter; class Block3D; class GbObject3D; -class WriteMQFromSelectionCoProcessor : public CoProcessor +class WriteMQFromSelectionCoProcessor : public CoProcessor { public: - WriteMQFromSelectionCoProcessor(); - WriteMQFromSelectionCoProcessor(SPtr<Grid3D> grid, SPtr<UbScheduler> s, - SPtr<GbObject3D> gbObject, - const std::string& path, WbWriter* const writer, - SPtr<LBMUnitConverter> conv, SPtr<Communicator> comm); - ~WriteMQFromSelectionCoProcessor() override= default; + WriteMQFromSelectionCoProcessor(); + WriteMQFromSelectionCoProcessor(SPtr<Grid3D> grid, SPtr<UbScheduler> s, SPtr<GbObject3D> gbObject, + const std::string &path, WbWriter *const writer, SPtr<LBMUnitConverter> conv, + SPtr<Communicator> comm); + ~WriteMQFromSelectionCoProcessor() override = default; - void process(double step) override; + void process(double step) override; protected: - void collectData(double step); - void addDataMQ(SPtr<Block3D> block); - void clearData(); + void collectData(double step); + void addDataMQ(SPtr<Block3D> block); + void clearData(); private: - void init(); - std::vector<UbTupleFloat3> nodes; - std::vector<std::string> datanames; - std::vector<std::vector<double> > data; - std::string path; - WbWriter* writer; - SPtr<LBMUnitConverter> conv; -// bool bcInformation; - std::vector<std::vector<SPtr<Block3D> > > blockVector; - int minInitLevel; - int maxInitLevel; - int gridRank; - SPtr<Communicator> comm; - SPtr<GbObject3D> gbObject; - - using CalcMacrosFct = void (*)(const LBMReal *const &, LBMReal &, LBMReal &, LBMReal &, LBMReal &); - CalcMacrosFct calcMacros; + void init(); + std::vector<UbTupleFloat3> nodes; + std::vector<std::string> datanames; + std::vector<std::vector<double>> data; + std::string path; + WbWriter *writer; + SPtr<LBMUnitConverter> conv; + // bool bcInformation; + std::vector<std::vector<SPtr<Block3D>>> blockVector; + int minInitLevel; + int maxInitLevel; + int gridRank; + SPtr<Communicator> comm; + SPtr<GbObject3D> gbObject; + + using CalcMacrosFct = void (*)(const LBMReal *const &, LBMReal &, LBMReal &, LBMReal &, LBMReal &); + CalcMacrosFct calcMacros; }; #endif diff --git a/src/cpu/VirtualFluidsCore/CoProcessors/WriteMacroscopicQuantitiesCoProcessor.cpp b/src/cpu/VirtualFluidsCore/CoProcessors/WriteMacroscopicQuantitiesCoProcessor.cpp index d621d551561991fa2edde46152a1ce96cc9db264..c34dccf9feefee287106e04f7bbeee4b3a6b13b7 100644 --- a/src/cpu/VirtualFluidsCore/CoProcessors/WriteMacroscopicQuantitiesCoProcessor.cpp +++ b/src/cpu/VirtualFluidsCore/CoProcessors/WriteMacroscopicQuantitiesCoProcessor.cpp @@ -1,28 +1,28 @@ //======================================================================================= -// ____ ____ __ ______ __________ __ __ __ __ -// \ \ | | | | | _ \ |___ ___| | | | | / \ | | -// \ \ | | | | | |_) | | | | | | | / \ | | -// \ \ | | | | | _ / | | | | | | / /\ \ | | -// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ -// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| -// \ \ | | ________________________________________________________________ -// \ \ | | | ______________________________________________________________| -// \ \| | | | __ __ __ __ ______ _______ -// \ | | |_____ | | | | | | | | | _ \ / _____) -// \ | | _____| | | | | | | | | | | \ \ \_______ +// ____ ____ __ ______ __________ __ __ __ __ +// \ \ | | | | | _ \ |___ ___| | | | | / \ | | +// \ \ | | | | | |_) | | | | | | | / \ | | +// \ \ | | | | | _ / | | | | | | / /\ \ | | +// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ +// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| +// \ \ | | ________________________________________________________________ +// \ \ | | | ______________________________________________________________| +// \ \| | | | __ __ __ __ ______ _______ +// \ | | |_____ | | | | | | | | | _ \ / _____) +// \ | | _____| | | | | | | | | | | \ \ \_______ // \ | | | | |_____ | \_/ | | | | |_/ / _____ | -// \ _____| |__| |________| \_______/ |__| |______/ (_______/ +// \ _____| |__| |________| \_______/ |__| |______/ (_______/ // -// This file is part of VirtualFluids. VirtualFluids is free software: you can +// This file is part of VirtualFluids. VirtualFluids is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of +// License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. -// -// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// +// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License along // with VirtualFluids (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>. // @@ -32,257 +32,234 @@ //======================================================================================= #include "WriteMacroscopicQuantitiesCoProcessor.h" -#include "LBMKernel.h" #include "BCProcessor.h" -#include <vector> +#include "LBMKernel.h" #include <string> +#include <vector> -#include "basics/writer/WbWriterVtkXmlASCII.h" +#include "BCArray3D.h" +#include "Block3D.h" +#include "Communicator.h" #include "DataSet3D.h" -#include "UbScheduler.h" #include "Grid3D.h" -#include "Communicator.h" #include "LBMUnitConverter.h" -#include "Block3D.h" -#include "BCArray3D.h" +#include "UbScheduler.h" +#include "basics/writer/WbWriterVtkXmlASCII.h" -WriteMacroscopicQuantitiesCoProcessor::WriteMacroscopicQuantitiesCoProcessor() -= default; +WriteMacroscopicQuantitiesCoProcessor::WriteMacroscopicQuantitiesCoProcessor() = default; ////////////////////////////////////////////////////////////////////////// WriteMacroscopicQuantitiesCoProcessor::WriteMacroscopicQuantitiesCoProcessor(SPtr<Grid3D> grid, SPtr<UbScheduler> s, - const std::string& path, WbWriter* const writer, - SPtr<LBMUnitConverter> conv, - SPtr<Communicator> comm) - : CoProcessor(grid, s), - path(path), - writer(writer), - conv(conv), - comm(comm) + const std::string &path, + WbWriter *const writer, + SPtr<LBMUnitConverter> conv, + SPtr<Communicator> comm) + : CoProcessor(grid, s), path(path), writer(writer), conv(conv), comm(comm) { - gridRank = comm->getProcessID(); - minInitLevel = this->grid->getCoarsestInitializedLevel(); - maxInitLevel = this->grid->getFinestInitializedLevel(); + gridRank = comm->getProcessID(); + minInitLevel = this->grid->getCoarsestInitializedLevel(); + maxInitLevel = this->grid->getFinestInitializedLevel(); - blockVector.resize(maxInitLevel+1); + blockVector.resize(maxInitLevel + 1); - for (int level = minInitLevel; level<=maxInitLevel; level++) - { - grid->getBlocks(level, gridRank, true, blockVector[level]); - } + for (int level = minInitLevel; level <= maxInitLevel; level++) { + grid->getBlocks(level, gridRank, true, blockVector[level]); + } } ////////////////////////////////////////////////////////////////////////// -void WriteMacroscopicQuantitiesCoProcessor::init() -{ - -} +void WriteMacroscopicQuantitiesCoProcessor::init() {} ////////////////////////////////////////////////////////////////////////// void WriteMacroscopicQuantitiesCoProcessor::process(double step) { - if(scheduler->isDue(step) ) - collectData(step); + if (scheduler->isDue(step)) + collectData(step); - UBLOG(logDEBUG3, "WriteMacroscopicQuantitiesCoProcessor::update:" << step); + UBLOG(logDEBUG3, "WriteMacroscopicQuantitiesCoProcessor::update:" << step); } ////////////////////////////////////////////////////////////////////////// void WriteMacroscopicQuantitiesCoProcessor::collectData(double step) { - int istep = static_cast<int>(step); - - for(int level = minInitLevel; level<=maxInitLevel;level++) - { - for(SPtr<Block3D> block : blockVector[level]) - { - if (block) - { - addDataMQ(block); - } - } - } + int istep = static_cast<int>(step); - std::string pfilePath, partPath, subfolder, cfilePath; + for (int level = minInitLevel; level <= maxInitLevel; level++) { + for (SPtr<Block3D> block : blockVector[level]) { + if (block) { + addDataMQ(block); + } + } + } - subfolder = "mq"+UbSystem::toString(istep); - pfilePath = path+"/mq/"+subfolder; - cfilePath = path+"/mq/mq_collection"; - partPath = pfilePath+"/mq"+UbSystem::toString(gridRank)+ "_" + UbSystem::toString(istep); + std::string pfilePath, partPath, subfolder, cfilePath; + subfolder = "mq" + UbSystem::toString(istep); + pfilePath = path + "/mq/" + subfolder; + cfilePath = path + "/mq/mq_collection"; + partPath = pfilePath + "/mq" + UbSystem::toString(gridRank) + "_" + UbSystem::toString(istep); - std::string partName = writer->writeOctsWithNodeData(partPath,nodes,cells,datanames,data); - size_t found=partName.find_last_of("/"); - std::string piece = partName.substr(found+1); - piece = subfolder + "/" + piece; + std::string partName = writer->writeOctsWithNodeData(partPath, nodes, cells, datanames, data); + size_t found = partName.find_last_of("/"); + std::string piece = partName.substr(found + 1); + piece = subfolder + "/" + piece; - std::vector<std::string> cellDataNames; - std::vector<std::string> pieces = comm->gather(piece); - if (comm->getProcessID() == comm->getRoot()) - { - std::string pname = WbWriterVtkXmlASCII::getInstance()->writeParallelFile(pfilePath,pieces,datanames,cellDataNames); - found=pname.find_last_of("/"); - piece = pname.substr(found+1); + std::vector<std::string> cellDataNames; + std::vector<std::string> pieces = comm->gather(piece); + if (comm->getProcessID() == comm->getRoot()) { + std::string pname = + WbWriterVtkXmlASCII::getInstance()->writeParallelFile(pfilePath, pieces, datanames, cellDataNames); + found = pname.find_last_of("/"); + piece = pname.substr(found + 1); - std::vector<std::string> filenames; - filenames.push_back(piece); - if (step == CoProcessor::scheduler->getMinBegin()) - { - WbWriterVtkXmlASCII::getInstance()->writeCollection(cfilePath,filenames,istep,false); - } - else - { - WbWriterVtkXmlASCII::getInstance()->addFilesToCollection(cfilePath,filenames,istep,false); - } - UBLOG(logINFO,"WriteMacroscopicQuantitiesCoProcessor step: " << istep); - } + std::vector<std::string> filenames; + filenames.push_back(piece); + if (step == CoProcessor::scheduler->getMinBegin()) { + WbWriterVtkXmlASCII::getInstance()->writeCollection(cfilePath, filenames, istep, false); + } else { + WbWriterVtkXmlASCII::getInstance()->addFilesToCollection(cfilePath, filenames, istep, false); + } + UBLOG(logINFO, "WriteMacroscopicQuantitiesCoProcessor step: " << istep); + } - clearData(); + clearData(); } ////////////////////////////////////////////////////////////////////////// void WriteMacroscopicQuantitiesCoProcessor::clearData() { - nodes.clear(); - cells.clear(); - datanames.clear(); - data.clear(); + nodes.clear(); + cells.clear(); + datanames.clear(); + data.clear(); } ////////////////////////////////////////////////////////////////////////// void WriteMacroscopicQuantitiesCoProcessor::addDataMQ(SPtr<Block3D> block) { - double level = (double)block->getLevel(); -// double blockID = (double)block->getGlobalID(); + double level = (double)block->getLevel(); + // double blockID = (double)block->getGlobalID(); + + // Diese Daten werden geschrieben: + datanames.resize(0); + datanames.emplace_back("Rho"); + datanames.emplace_back("Vx"); + datanames.emplace_back("Vy"); + datanames.emplace_back("Vz"); + // datanames.emplace_back("Press"); + datanames.emplace_back("Level"); + // datanames.emplace_back("BlockID"); - //Diese Daten werden geschrieben: - datanames.resize(0); - datanames.emplace_back("Rho"); - datanames.emplace_back("Vx"); - datanames.emplace_back("Vy"); - datanames.emplace_back("Vz"); - //datanames.emplace_back("Press"); - datanames.emplace_back("Level"); - //datanames.emplace_back("BlockID"); + data.resize(datanames.size()); - + SPtr<ILBMKernel> kernel = block->getKernel(); + SPtr<BCArray3D> bcArray = kernel->getBCProcessor()->getBCArray(); + SPtr<DistributionArray3D> distributions = kernel->getDataSet()->getFdistributions(); + LBMReal f[D3Q27System::ENDF + 1]; + LBMReal vx1, vx2, vx3, rho; - data.resize(datanames.size()); + // knotennummerierung faengt immer bei 0 an! + unsigned int SWB, SEB, NEB, NWB, SWT, SET, NET, NWT; - SPtr<ILBMKernel> kernel = block->getKernel(); - SPtr<BCArray3D> bcArray = kernel->getBCProcessor()->getBCArray(); - SPtr<DistributionArray3D> distributions = kernel->getDataSet()->getFdistributions(); - LBMReal f[D3Q27System::ENDF+1]; - LBMReal vx1,vx2,vx3,rho; + if (block->getKernel()->getCompressible()) { + calcMacros = &D3Q27System::calcCompMacroscopicValues; + } else { + calcMacros = &D3Q27System::calcIncompMacroscopicValues; + } - //knotennummerierung faengt immer bei 0 an! - unsigned int SWB,SEB,NEB,NWB,SWT,SET,NET,NWT; + int minX1 = 0; + int minX2 = 0; + int minX3 = 0; - if(block->getKernel()->getCompressible()) - { - calcMacros = &D3Q27System::calcCompMacroscopicValues; - } - else - { - calcMacros = &D3Q27System::calcIncompMacroscopicValues; - } + int maxX1 = (int)(distributions->getNX1()); + int maxX2 = (int)(distributions->getNX2()); + int maxX3 = (int)(distributions->getNX3()); - int minX1 = 0; - int minX2 = 0; - int minX3 = 0; + // int minX1 = 1; + // int minX2 = 1; + // int minX3 = 1; - int maxX1 = (int)(distributions->getNX1()); - int maxX2 = (int)(distributions->getNX2()); - int maxX3 = (int)(distributions->getNX3()); + // int maxX1 = (int)(distributions->getNX1()); + // int maxX2 = (int)(distributions->getNX2()); + // int maxX3 = (int)(distributions->getNX3()); - //int minX1 = 1; - //int minX2 = 1; - //int minX3 = 1; + // nummern vergeben und node vector erstellen + daten sammeln + CbArray3D<int> nodeNumbers((int)maxX1, (int)maxX2, (int)maxX3, -1); + maxX1 -= 2; + maxX2 -= 2; + maxX3 -= 2; - //int maxX1 = (int)(distributions->getNX1()); - //int maxX2 = (int)(distributions->getNX2()); - //int maxX3 = (int)(distributions->getNX3()); + // D3Q27BoundaryConditionPtr bcPtr; + int nr = (int)nodes.size(); - //nummern vergeben und node vector erstellen + daten sammeln - CbArray3D<int> nodeNumbers((int)maxX1, (int)maxX2, (int)maxX3,-1); - maxX1 -= 2; - maxX2 -= 2; - maxX3 -= 2; + for (int ix3 = minX3; ix3 <= maxX3; ix3++) { + for (int ix2 = minX2; ix2 <= maxX2; ix2++) { + for (int ix1 = minX1; ix1 <= maxX1; ix1++) { + if (!bcArray->isUndefined(ix1, ix2, ix3) && !bcArray->isSolid(ix1, ix2, ix3)) { + int index = 0; + nodeNumbers(ix1, ix2, ix3) = nr++; + Vector3D worldCoordinates = grid->getNodeCoordinates(block, ix1, ix2, ix3); + nodes.emplace_back(float(worldCoordinates[0]), float(worldCoordinates[1]), + float(worldCoordinates[2])); - //D3Q27BoundaryConditionPtr bcPtr; - int nr = (int)nodes.size(); - - for(int ix3=minX3; ix3<=maxX3; ix3++) - { - for(int ix2=minX2; ix2<=maxX2; ix2++) - { - for(int ix1=minX1; ix1<=maxX1; ix1++) - { - if(!bcArray->isUndefined(ix1,ix2,ix3) && !bcArray->isSolid(ix1,ix2,ix3)) - { - int index = 0; - nodeNumbers(ix1,ix2,ix3) = nr++; - Vector3D worldCoordinates = grid->getNodeCoordinates(block, ix1, ix2, ix3); - nodes.emplace_back(float(worldCoordinates[0]), - float(worldCoordinates[1]), - float(worldCoordinates[2]) ); + distributions->getDistribution(f, ix1, ix2, ix3); + calcMacros(f, rho, vx1, vx2, vx3); + // double press = D3Q27System::calcPress(f,rho,vx1,vx2,vx3); - distributions->getDistribution(f, ix1, ix2, ix3); - calcMacros(f,rho,vx1,vx2,vx3); - //double press = D3Q27System::calcPress(f,rho,vx1,vx2,vx3); + if (UbMath::isNaN(rho) || UbMath::isInfinity(rho)) + UB_THROW(UbException( + UB_EXARGS, "rho is not a number (nan or -1.#IND) or infinity number -1.#INF in block=" + + block->toString() + ", node=" + UbSystem::toString(ix1) + "," + + UbSystem::toString(ix2) + "," + UbSystem::toString(ix3))); + // rho=999.0; + // if (UbMath::isNaN(press) || UbMath::isInfinity(press)) + // UB_THROW( UbException(UB_EXARGS,"press is not a number (nan or -1.#IND) or infinity number + // -1.#INF in block="+block->toString()+ + // ", node="+UbSystem::toString(ix1)+","+UbSystem::toString(ix2)+","+UbSystem::toString(ix3))); + // press=999.0; + if (UbMath::isNaN(vx1) || UbMath::isInfinity(vx1)) + UB_THROW(UbException( + UB_EXARGS, "vx1 is not a number (nan or -1.#IND) or infinity number -1.#INF in block=" + + block->toString() + ", node=" + UbSystem::toString(ix1) + "," + + UbSystem::toString(ix2) + "," + UbSystem::toString(ix3))); + // vx1=999.0; + if (UbMath::isNaN(vx2) || UbMath::isInfinity(vx2)) + UB_THROW(UbException( + UB_EXARGS, "vx2 is not a number (nan or -1.#IND) or infinity number -1.#INF in block=" + + block->toString() + ", node=" + UbSystem::toString(ix1) + "," + + UbSystem::toString(ix2) + "," + UbSystem::toString(ix3))); + // vx2=999.0; + if (UbMath::isNaN(vx3) || UbMath::isInfinity(vx3)) + UB_THROW(UbException( + UB_EXARGS, "vx3 is not a number (nan or -1.#IND) or infinity number -1.#INF in block=" + + block->toString() + ", node=" + UbSystem::toString(ix1) + "," + + UbSystem::toString(ix2) + "," + UbSystem::toString(ix3))); - if (UbMath::isNaN(rho) || UbMath::isInfinity(rho)) - UB_THROW( UbException(UB_EXARGS,"rho is not a number (nan or -1.#IND) or infinity number -1.#INF in block="+block->toString()+ - ", node="+UbSystem::toString(ix1)+","+UbSystem::toString(ix2)+","+UbSystem::toString(ix3))); - //rho=999.0; - //if (UbMath::isNaN(press) || UbMath::isInfinity(press)) - // UB_THROW( UbException(UB_EXARGS,"press is not a number (nan or -1.#IND) or infinity number -1.#INF in block="+block->toString()+ - // ", node="+UbSystem::toString(ix1)+","+UbSystem::toString(ix2)+","+UbSystem::toString(ix3))); - //press=999.0; - if (UbMath::isNaN(vx1) || UbMath::isInfinity(vx1)) - UB_THROW( UbException(UB_EXARGS,"vx1 is not a number (nan or -1.#IND) or infinity number -1.#INF in block="+block->toString()+ - ", node="+UbSystem::toString(ix1)+","+UbSystem::toString(ix2)+","+UbSystem::toString(ix3))); - //vx1=999.0; - if (UbMath::isNaN(vx2) || UbMath::isInfinity(vx2)) - UB_THROW( UbException(UB_EXARGS,"vx2 is not a number (nan or -1.#IND) or infinity number -1.#INF in block="+block->toString()+ - ", node="+UbSystem::toString(ix1)+","+UbSystem::toString(ix2)+","+UbSystem::toString(ix3))); - //vx2=999.0; - if (UbMath::isNaN(vx3) || UbMath::isInfinity(vx3)) - UB_THROW( UbException(UB_EXARGS,"vx3 is not a number (nan or -1.#IND) or infinity number -1.#INF in block="+block->toString()+ - ", node="+UbSystem::toString(ix1)+","+UbSystem::toString(ix2)+","+UbSystem::toString(ix3))); + data[index++].push_back(rho); + data[index++].push_back(vx1); + data[index++].push_back(vx2); + data[index++].push_back(vx3); - data[index++].push_back(rho); - data[index++].push_back(vx1); - data[index++].push_back(vx2); - data[index++].push_back(vx3); - - //data[index++].push_back(rho * conv->getFactorDensityLbToW2() ); - //data[index++].push_back(vx1 * conv->getFactorVelocityLbToW2()); - //data[index++].push_back(vx2 * conv->getFactorVelocityLbToW2()); - //data[index++].push_back(vx3 * conv->getFactorVelocityLbToW2()); - //data[index++].push_back(press * conv->getFactorPressureLbToW2()); - data[index++].push_back(level); - //data[index++].push_back(blockID); + // data[index++].push_back(rho * conv->getFactorDensityLbToW2() ); + // data[index++].push_back(vx1 * conv->getFactorVelocityLbToW2()); + // data[index++].push_back(vx2 * conv->getFactorVelocityLbToW2()); + // data[index++].push_back(vx3 * conv->getFactorVelocityLbToW2()); + // data[index++].push_back(press * conv->getFactorPressureLbToW2()); + data[index++].push_back(level); + // data[index++].push_back(blockID); + } } - } - } - } - maxX1 -= 1; - maxX2 -= 1; - maxX3 -= 1; - //cell vector erstellen - for(int ix3=minX3; ix3<=maxX3; ix3++) - { - for(int ix2=minX2; ix2<=maxX2; ix2++) - { - for(int ix1=minX1; ix1<=maxX1; ix1++) - { - if( (SWB=nodeNumbers( ix1 , ix2, ix3 )) >= 0 - && (SEB=nodeNumbers( ix1+1, ix2, ix3 )) >= 0 - && (NEB=nodeNumbers( ix1+1, ix2+1, ix3 )) >= 0 - && (NWB=nodeNumbers( ix1 , ix2+1, ix3 )) >= 0 - && (SWT=nodeNumbers( ix1 , ix2, ix3+1 )) >= 0 - && (SET=nodeNumbers( ix1+1, ix2, ix3+1 )) >= 0 - && (NET=nodeNumbers( ix1+1, ix2+1, ix3+1 )) >= 0 - && (NWT=nodeNumbers( ix1 , ix2+1, ix3+1 )) >= 0 ) - { - cells.push_back( makeUbTuple(SWB,SEB,NEB,NWB,SWT,SET,NET,NWT) ); + } + } + maxX1 -= 1; + maxX2 -= 1; + maxX3 -= 1; + // cell vector erstellen + for (int ix3 = minX3; ix3 <= maxX3; ix3++) { + for (int ix2 = minX2; ix2 <= maxX2; ix2++) { + for (int ix1 = minX1; ix1 <= maxX1; ix1++) { + if ((SWB = nodeNumbers(ix1, ix2, ix3)) >= 0 && (SEB = nodeNumbers(ix1 + 1, ix2, ix3)) >= 0 && + (NEB = nodeNumbers(ix1 + 1, ix2 + 1, ix3)) >= 0 && (NWB = nodeNumbers(ix1, ix2 + 1, ix3)) >= 0 && + (SWT = nodeNumbers(ix1, ix2, ix3 + 1)) >= 0 && (SET = nodeNumbers(ix1 + 1, ix2, ix3 + 1)) >= 0 && + (NET = nodeNumbers(ix1 + 1, ix2 + 1, ix3 + 1)) >= 0 && + (NWT = nodeNumbers(ix1, ix2 + 1, ix3 + 1)) >= 0) { + cells.push_back(makeUbTuple(SWB, SEB, NEB, NWB, SWT, SET, NET, NWT)); + } } - } - } - } + } + } } diff --git a/src/cpu/VirtualFluidsCore/CoProcessors/WriteMacroscopicQuantitiesCoProcessor.h b/src/cpu/VirtualFluidsCore/CoProcessors/WriteMacroscopicQuantitiesCoProcessor.h index 816999a71d92219f11d59fd2d9450e46531d427e..91df3acf3dc3f584516820e45ca000365dc5d94f 100644 --- a/src/cpu/VirtualFluidsCore/CoProcessors/WriteMacroscopicQuantitiesCoProcessor.h +++ b/src/cpu/VirtualFluidsCore/CoProcessors/WriteMacroscopicQuantitiesCoProcessor.h @@ -1,28 +1,28 @@ //======================================================================================= -// ____ ____ __ ______ __________ __ __ __ __ -// \ \ | | | | | _ \ |___ ___| | | | | / \ | | -// \ \ | | | | | |_) | | | | | | | / \ | | -// \ \ | | | | | _ / | | | | | | / /\ \ | | -// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ -// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| -// \ \ | | ________________________________________________________________ -// \ \ | | | ______________________________________________________________| -// \ \| | | | __ __ __ __ ______ _______ -// \ | | |_____ | | | | | | | | | _ \ / _____) -// \ | | _____| | | | | | | | | | | \ \ \_______ +// ____ ____ __ ______ __________ __ __ __ __ +// \ \ | | | | | _ \ |___ ___| | | | | / \ | | +// \ \ | | | | | |_) | | | | | | | / \ | | +// \ \ | | | | | _ / | | | | | | / /\ \ | | +// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ +// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| +// \ \ | | ________________________________________________________________ +// \ \ | | | ______________________________________________________________| +// \ \| | | | __ __ __ __ ______ _______ +// \ | | |_____ | | | | | | | | | _ \ / _____) +// \ | | _____| | | | | | | | | | | \ \ \_______ // \ | | | | |_____ | \_/ | | | | |_/ / _____ | -// \ _____| |__| |________| \_______/ |__| |______/ (_______/ +// \ _____| |__| |________| \_______/ |__| |______/ (_______/ // -// This file is part of VirtualFluids. VirtualFluids is free software: you can +// This file is part of VirtualFluids. VirtualFluids is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of +// License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. -// -// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// +// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License along // with VirtualFluids (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>. // @@ -39,8 +39,8 @@ #include <vector> #include "CoProcessor.h" -#include "UbTuple.h" #include "LBMSystem.h" +#include "UbTuple.h" class Communicator; class Grid3D; @@ -49,53 +49,51 @@ class LBMUnitConverter; class WbWriter; class Block3D; - //! \brief A class writes macroscopic quantities information to a VTK-file -class WriteMacroscopicQuantitiesCoProcessor : public CoProcessor +class WriteMacroscopicQuantitiesCoProcessor : public CoProcessor { public: - WriteMacroscopicQuantitiesCoProcessor(); - //! \brief Construct WriteMacroscopicQuantitiesCoProcessor object - //! \pre The Grid3D and UbScheduler objects must exist - //! \param grid is observable Grid3D object - //! \param s is UbScheduler object for scheduling of observer - //! \param path is path of folder for output - //! \param writer is WbWriter object - //! \param conv is LBMUnitConverter object - //! \param comm is Communicator object - WriteMacroscopicQuantitiesCoProcessor(SPtr<Grid3D> grid, SPtr<UbScheduler> s, - const std::string& path, WbWriter* const writer, - SPtr<LBMUnitConverter> conv, SPtr<Communicator> comm); - ~WriteMacroscopicQuantitiesCoProcessor() override= default; + WriteMacroscopicQuantitiesCoProcessor(); + //! \brief Construct WriteMacroscopicQuantitiesCoProcessor object + //! \pre The Grid3D and UbScheduler objects must exist + //! \param grid is observable Grid3D object + //! \param s is UbScheduler object for scheduling of observer + //! \param path is path of folder for output + //! \param writer is WbWriter object + //! \param conv is LBMUnitConverter object + //! \param comm is Communicator object + WriteMacroscopicQuantitiesCoProcessor(SPtr<Grid3D> grid, SPtr<UbScheduler> s, const std::string &path, + WbWriter *const writer, SPtr<LBMUnitConverter> conv, SPtr<Communicator> comm); + ~WriteMacroscopicQuantitiesCoProcessor() override = default; - void process(double step) override; + void process(double step) override; protected: - //! Collect data for VTK-file - //! \param step is a time step - void collectData(double step); - //! Collect data for VTK-file - //! \param block is a time step - void addDataMQ(SPtr<Block3D> block); - void clearData(); + //! Collect data for VTK-file + //! \param step is a time step + void collectData(double step); + //! Collect data for VTK-file + //! \param block is a time step + void addDataMQ(SPtr<Block3D> block); + void clearData(); private: - void init(); - std::vector<UbTupleFloat3> nodes; - std::vector<UbTupleUInt8> cells; - std::vector<std::string> datanames; - std::vector<std::vector<double> > data; - std::string path; - WbWriter* writer; - SPtr<LBMUnitConverter> conv; - std::vector<std::vector<SPtr<Block3D> > > blockVector; - int minInitLevel; - int maxInitLevel; - int gridRank; - SPtr<Communicator> comm; + void init(); + std::vector<UbTupleFloat3> nodes; + std::vector<UbTupleUInt8> cells; + std::vector<std::string> datanames; + std::vector<std::vector<double>> data; + std::string path; + WbWriter *writer; + SPtr<LBMUnitConverter> conv; + std::vector<std::vector<SPtr<Block3D>>> blockVector; + int minInitLevel; + int maxInitLevel; + int gridRank; + SPtr<Communicator> comm; - using CalcMacrosFct = void (*)(const LBMReal *const &, LBMReal &, LBMReal &, LBMReal &, LBMReal &); - CalcMacrosFct calcMacros; + using CalcMacrosFct = void (*)(const LBMReal *const &, LBMReal &, LBMReal &, LBMReal &, LBMReal &); + CalcMacrosFct calcMacros; }; #endif diff --git a/src/cpu/VirtualFluidsCore/Connectors/Block3DConnector.h b/src/cpu/VirtualFluidsCore/Connectors/Block3DConnector.h index 1bef6737422efa711f15bb1f78b87312ea0032e2..1b737141a4d2f6675613a9b1f3b2fe4bf52d8562 100644 --- a/src/cpu/VirtualFluidsCore/Connectors/Block3DConnector.h +++ b/src/cpu/VirtualFluidsCore/Connectors/Block3DConnector.h @@ -1,28 +1,28 @@ //======================================================================================= -// ____ ____ __ ______ __________ __ __ __ __ -// \ \ | | | | | _ \ |___ ___| | | | | / \ | | -// \ \ | | | | | |_) | | | | | | | / \ | | -// \ \ | | | | | _ / | | | | | | / /\ \ | | -// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ -// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| -// \ \ | | ________________________________________________________________ -// \ \ | | | ______________________________________________________________| -// \ \| | | | __ __ __ __ ______ _______ -// \ | | |_____ | | | | | | | | | _ \ / _____) -// \ | | _____| | | | | | | | | | | \ \ \_______ +// ____ ____ __ ______ __________ __ __ __ __ +// \ \ | | | | | _ \ |___ ___| | | | | / \ | | +// \ \ | | | | | |_) | | | | | | | / \ | | +// \ \ | | | | | _ / | | | | | | / /\ \ | | +// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ +// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| +// \ \ | | ________________________________________________________________ +// \ \ | | | ______________________________________________________________| +// \ \| | | | __ __ __ __ ______ _______ +// \ | | |_____ | | | | | | | | | _ \ / _____) +// \ | | _____| | | | | | | | | | | \ \ \_______ // \ | | | | |_____ | \_/ | | | | |_/ / _____ | -// \ _____| |__| |________| \_______/ |__| |______/ (_______/ +// \ _____| |__| |________| \_______/ |__| |______/ (_______/ // -// This file is part of VirtualFluids. VirtualFluids is free software: you can +// This file is part of VirtualFluids. VirtualFluids is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of +// License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. -// -// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// +// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License along // with VirtualFluids (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>. // @@ -34,67 +34,67 @@ #ifndef BLOCK2DCONNECTOR_H #define BLOCK2DCONNECTOR_H -#include <vector> #include <string> +#include <vector> #include <basics/utilities/UbTuple.h> #include <PointerDefinitions.h> -//! \brief Abstract class of connectors +//! \brief Abstract class of connectors //! \details Connector send and receive full distributions between two blocks in shared memory. class Block3DConnector { public: - Block3DConnector() = default; - Block3DConnector(const int& sendDir) : sendDir(sendDir) {} - virtual ~Block3DConnector() = default; - //!Iniitializes connector - virtual void init()=0; - //!Synchronizes the send-buffer length - virtual void sendTransmitterDataSize()=0; - //!Synchronizes the receive-buffer length - virtual void receiveTransmitterDataSize()=0; - - //Send (should be called in given order!!!) - virtual void prepareForSend()=0; - virtual void fillSendVectors()=0; - virtual void sendVectors()=0; - - //Receive (should be called in given order!!!) - virtual void prepareForReceive()=0; - virtual void receiveVectors()=0; - virtual void distributeReceiveVectors()=0; - - //info section - virtual bool isLocalConnector() = 0; - virtual bool isRemoteConnector() = 0; - virtual bool isInterpolationConnectorCF() = 0; - virtual bool isInterpolationConnectorFC() = 0; - - //grid refinement - virtual int getSendDir() const { return sendDir; } - - //virtual double getSendRecieveTime() = 0; - - virtual void prepareForSendX1() = 0; - virtual void prepareForSendX2() = 0; - virtual void prepareForSendX3() = 0; - - virtual void sendVectorsX1() = 0; - virtual void sendVectorsX2() = 0; - virtual void sendVectorsX3() = 0; - - virtual void prepareForReceiveX1() = 0; - virtual void prepareForReceiveX2() = 0; - virtual void prepareForReceiveX3() = 0; - - virtual void receiveVectorsX1() = 0; - virtual void receiveVectorsX2() = 0; - virtual void receiveVectorsX3() = 0; + Block3DConnector() = default; + Block3DConnector(const int &sendDir) : sendDir(sendDir) {} + virtual ~Block3DConnector() = default; + //! Iniitializes connector + virtual void init() = 0; + //! Synchronizes the send-buffer length + virtual void sendTransmitterDataSize() = 0; + //! Synchronizes the receive-buffer length + virtual void receiveTransmitterDataSize() = 0; + + // Send (should be called in given order!!!) + virtual void prepareForSend() = 0; + virtual void fillSendVectors() = 0; + virtual void sendVectors() = 0; + + // Receive (should be called in given order!!!) + virtual void prepareForReceive() = 0; + virtual void receiveVectors() = 0; + virtual void distributeReceiveVectors() = 0; + + // info section + virtual bool isLocalConnector() = 0; + virtual bool isRemoteConnector() = 0; + virtual bool isInterpolationConnectorCF() = 0; + virtual bool isInterpolationConnectorFC() = 0; + + // grid refinement + virtual int getSendDir() const { return sendDir; } + + // virtual double getSendRecieveTime() = 0; + + virtual void prepareForSendX1() = 0; + virtual void prepareForSendX2() = 0; + virtual void prepareForSendX3() = 0; + + virtual void sendVectorsX1() = 0; + virtual void sendVectorsX2() = 0; + virtual void sendVectorsX3() = 0; + + virtual void prepareForReceiveX1() = 0; + virtual void prepareForReceiveX2() = 0; + virtual void prepareForReceiveX3() = 0; + + virtual void receiveVectorsX1() = 0; + virtual void receiveVectorsX2() = 0; + virtual void receiveVectorsX3() = 0; protected: - int sendDir{-1}; + int sendDir{ -1 }; }; -#endif //BLOCK3DCONNECTOR_H +#endif // BLOCK3DCONNECTOR_H diff --git a/src/cpu/VirtualFluidsCore/Connectors/Block3DConnectorFactory.cpp b/src/cpu/VirtualFluidsCore/Connectors/Block3DConnectorFactory.cpp index af4cefa6778fdf130a530b125ec2a321eae6664b..e30da27cd88b759b2f0df44774c388504d303355 100644 --- a/src/cpu/VirtualFluidsCore/Connectors/Block3DConnectorFactory.cpp +++ b/src/cpu/VirtualFluidsCore/Connectors/Block3DConnectorFactory.cpp @@ -1,48 +1,41 @@ #include "Block3DConnectorFactory.h" +#include "CoarseToFineNodeSetBlock3DConnector.h" #include "D3Q27ETFullDirectConnector.h" #include "D3Q27ETFullVectorConnector.h" -#include "CoarseToFineNodeSetBlock3DConnector.h" #include "FineToCoarseNodeSetBlock3DConnector.h" -Block3DConnectorFactory::Block3DConnectorFactory() -= default; +Block3DConnectorFactory::Block3DConnectorFactory() = default; ////////////////////////////////////////////////////////////////////////// -Block3DConnectorFactory::~Block3DConnectorFactory() -= default; +Block3DConnectorFactory::~Block3DConnectorFactory() = default; ////////////////////////////////////////////////////////////////////////// -SPtr<Block3DConnector> Block3DConnectorFactory::createSameLevelDirectConnector(SPtr<Block3D> from, SPtr<Block3D> to, int sendDir) +SPtr<Block3DConnector> Block3DConnectorFactory::createSameLevelDirectConnector(SPtr<Block3D> from, SPtr<Block3D> to, + int sendDir) { - return SPtr<Block3DConnector>(new D3Q27ETFullDirectConnector(from, to, sendDir)); + return SPtr<Block3DConnector>(new D3Q27ETFullDirectConnector(from, to, sendDir)); } ////////////////////////////////////////////////////////////////////////// SPtr<Block3DConnector> Block3DConnectorFactory::createSameLevelVectorConnector(SPtr<Block3D> block, - VectorTransmitterPtr sender, - VectorTransmitterPtr receiver, - int sendDir) + VectorTransmitterPtr sender, + VectorTransmitterPtr receiver, + int sendDir) { - return SPtr<Block3DConnector>(new D3Q27ETFullVectorConnector(block, sender, receiver, sendDir)); + return SPtr<Block3DConnector>(new D3Q27ETFullVectorConnector(block, sender, receiver, sendDir)); } ////////////////////////////////////////////////////////////////////////// -SPtr<Block3DConnector> Block3DConnectorFactory::createCoarseToFineConnector(SPtr<Block3D> block, - VectorTransmitterPtr sender00, VectorTransmitterPtr receiver00, - VectorTransmitterPtr sender01, VectorTransmitterPtr receiver01, - VectorTransmitterPtr sender10, VectorTransmitterPtr receiver10, - VectorTransmitterPtr sender11, VectorTransmitterPtr receiver11, - int sendDir, InterpolationProcessorPtr iprocessor) +SPtr<Block3DConnector> Block3DConnectorFactory::createCoarseToFineConnector( + SPtr<Block3D> block, VectorTransmitterPtr sender00, VectorTransmitterPtr receiver00, VectorTransmitterPtr sender01, + VectorTransmitterPtr receiver01, VectorTransmitterPtr sender10, VectorTransmitterPtr receiver10, + VectorTransmitterPtr sender11, VectorTransmitterPtr receiver11, int sendDir, InterpolationProcessorPtr iprocessor) { - return SPtr<Block3DConnector> (new CoarseToFineNodeSetBlock3DConnector(block, - sender00, receiver00, sender01, receiver01, - sender10, receiver10, sender11, receiver11, - sendDir, iprocessor)); + return SPtr<Block3DConnector>(new CoarseToFineNodeSetBlock3DConnector(block, sender00, receiver00, sender01, + receiver01, sender10, receiver10, sender11, + receiver11, sendDir, iprocessor)); } ////////////////////////////////////////////////////////////////////////// -SPtr<Block3DConnector> Block3DConnectorFactory::createFineToCoarseConnector(SPtr<Block3D> block, - VectorTransmitterPtr sender, - VectorTransmitterPtr receiver, - int sendDir, - InterpolationProcessorPtr iprocessor, - FineToCoarseBlock3DConnector::CFconnectorType connType) +SPtr<Block3DConnector> Block3DConnectorFactory::createFineToCoarseConnector( + SPtr<Block3D> block, VectorTransmitterPtr sender, VectorTransmitterPtr receiver, int sendDir, + InterpolationProcessorPtr iprocessor, FineToCoarseBlock3DConnector::CFconnectorType connType) { - return SPtr<Block3DConnector>(new FineToCoarseNodeSetBlock3DConnector(block, - sender, receiver, sendDir, iprocessor, connType)); + return SPtr<Block3DConnector>( + new FineToCoarseNodeSetBlock3DConnector(block, sender, receiver, sendDir, iprocessor, connType)); } diff --git a/src/cpu/VirtualFluidsCore/Connectors/Block3DConnectorFactory.h b/src/cpu/VirtualFluidsCore/Connectors/Block3DConnectorFactory.h index 4e2ae44a04429e199c23bc629b6ee9f9e295a541..687f787cd3efb2c7ba64bb2e722cede59ce77f48 100644 --- a/src/cpu/VirtualFluidsCore/Connectors/Block3DConnectorFactory.h +++ b/src/cpu/VirtualFluidsCore/Connectors/Block3DConnectorFactory.h @@ -8,32 +8,26 @@ class Block3DConnectorFactory : public ConnectorFactory { public: - Block3DConnectorFactory(); - ~Block3DConnectorFactory() override; - - SPtr<Block3DConnector> createSameLevelDirectConnector(SPtr<Block3D> from, SPtr<Block3D> to, int sendDir) override; - - SPtr<Block3DConnector> createSameLevelVectorConnector(SPtr<Block3D> block, - VectorTransmitterPtr sender, - VectorTransmitterPtr receiver, - int sendDir) override; - - SPtr<Block3DConnector> createCoarseToFineConnector(SPtr<Block3D> block, - VectorTransmitterPtr sender00, VectorTransmitterPtr receiver00, - VectorTransmitterPtr sender01, VectorTransmitterPtr receiver01, - VectorTransmitterPtr sender10, VectorTransmitterPtr receiver10, - VectorTransmitterPtr sender11, VectorTransmitterPtr receiver11, - int sendDir, InterpolationProcessorPtr iprocessor) override; - - SPtr<Block3DConnector> createFineToCoarseConnector(SPtr<Block3D> block, - VectorTransmitterPtr sender, - VectorTransmitterPtr receiver, - int sendDir, - InterpolationProcessorPtr iprocessor, - FineToCoarseBlock3DConnector::CFconnectorType connType) override; + Block3DConnectorFactory(); + ~Block3DConnectorFactory() override; -private: + SPtr<Block3DConnector> createSameLevelDirectConnector(SPtr<Block3D> from, SPtr<Block3D> to, int sendDir) override; + + SPtr<Block3DConnector> createSameLevelVectorConnector(SPtr<Block3D> block, VectorTransmitterPtr sender, + VectorTransmitterPtr receiver, int sendDir) override; + + SPtr<Block3DConnector> createCoarseToFineConnector(SPtr<Block3D> block, VectorTransmitterPtr sender00, + VectorTransmitterPtr receiver00, VectorTransmitterPtr sender01, + VectorTransmitterPtr receiver01, VectorTransmitterPtr sender10, + VectorTransmitterPtr receiver10, VectorTransmitterPtr sender11, + VectorTransmitterPtr receiver11, int sendDir, + InterpolationProcessorPtr iprocessor) override; + SPtr<Block3DConnector> createFineToCoarseConnector(SPtr<Block3D> block, VectorTransmitterPtr sender, + VectorTransmitterPtr receiver, int sendDir, + InterpolationProcessorPtr iprocessor, + FineToCoarseBlock3DConnector::CFconnectorType connType) override; + +private: }; #endif // Block3DConnectorFactory_h__ - diff --git a/src/cpu/VirtualFluidsCore/Connectors/CoarseToFineBlock3DConnector.cpp b/src/cpu/VirtualFluidsCore/Connectors/CoarseToFineBlock3DConnector.cpp index dadbd0c9677105204c52f3ae976b4f4611082c8f..d9c493e5d4cf88a66e4bc26090cd6d98aa68b4a7 100644 --- a/src/cpu/VirtualFluidsCore/Connectors/CoarseToFineBlock3DConnector.cpp +++ b/src/cpu/VirtualFluidsCore/Connectors/CoarseToFineBlock3DConnector.cpp @@ -1,135 +1,138 @@ #include "CoarseToFineBlock3DConnector.h" - - //////////////////////////////////////////////////////////////////////////// -CoarseToFineBlock3DConnector::CoarseToFineBlock3DConnector(SPtr<Block3D> block, - VectorTransmitterPtr sender00, VectorTransmitterPtr receiver00, - VectorTransmitterPtr sender01, VectorTransmitterPtr receiver01, - VectorTransmitterPtr sender10, VectorTransmitterPtr receiver10, - VectorTransmitterPtr sender11, VectorTransmitterPtr receiver11, - int sendDir, InterpolationProcessorPtr iprocessor) : Block3DConnector(sendDir) - , block(block) - , sender00(sender00) - , sender01(sender01) - , sender10(sender10) - , sender11(sender11) - , receiver00(receiver00) - , receiver01(receiver01) - , receiver10(receiver10) - , receiver11(receiver11) - , iprocessor(iprocessor) +CoarseToFineBlock3DConnector::CoarseToFineBlock3DConnector( + SPtr<Block3D> block, VectorTransmitterPtr sender00, VectorTransmitterPtr receiver00, VectorTransmitterPtr sender01, + VectorTransmitterPtr receiver01, VectorTransmitterPtr sender10, VectorTransmitterPtr receiver10, + VectorTransmitterPtr sender11, VectorTransmitterPtr receiver11, int sendDir, InterpolationProcessorPtr iprocessor) + : Block3DConnector(sendDir), block(block), sender00(sender00), sender01(sender01), sender10(sender10), + sender11(sender11), receiver00(receiver00), receiver01(receiver01), receiver10(receiver10), + receiver11(receiver11), iprocessor(iprocessor) { - if (!(sendDir==D3Q27System::E || sendDir==D3Q27System::W || sendDir==D3Q27System::N || sendDir==D3Q27System::S || sendDir==D3Q27System::T || sendDir==D3Q27System::B - || sendDir==D3Q27System::NE || sendDir==D3Q27System::SW || sendDir==D3Q27System::SE || sendDir==D3Q27System::NW - || sendDir==D3Q27System::TE || sendDir==D3Q27System::BW || sendDir==D3Q27System::BE || sendDir==D3Q27System::TW - || sendDir==D3Q27System::TN || sendDir==D3Q27System::BS || sendDir==D3Q27System::BN || sendDir==D3Q27System::TS - || sendDir==D3Q27System::TNE || sendDir==D3Q27System::TNW || sendDir==D3Q27System::TSE || sendDir==D3Q27System::TSW - || sendDir==D3Q27System::BNE || sendDir==D3Q27System::BNW || sendDir==D3Q27System::BSE || sendDir==D3Q27System::BSW - )) - { - throw UbException(UB_EXARGS, "invalid constructor for this direction"); - } + if (!(sendDir == D3Q27System::E || sendDir == D3Q27System::W || sendDir == D3Q27System::N || + sendDir == D3Q27System::S || sendDir == D3Q27System::T || sendDir == D3Q27System::B || + sendDir == D3Q27System::NE || sendDir == D3Q27System::SW || sendDir == D3Q27System::SE || + sendDir == D3Q27System::NW || sendDir == D3Q27System::TE || sendDir == D3Q27System::BW || + sendDir == D3Q27System::BE || sendDir == D3Q27System::TW || sendDir == D3Q27System::TN || + sendDir == D3Q27System::BS || sendDir == D3Q27System::BN || sendDir == D3Q27System::TS || + sendDir == D3Q27System::TNE || sendDir == D3Q27System::TNW || sendDir == D3Q27System::TSE || + sendDir == D3Q27System::TSW || sendDir == D3Q27System::BNE || sendDir == D3Q27System::BNW || + sendDir == D3Q27System::BSE || sendDir == D3Q27System::BSW)) { + throw UbException(UB_EXARGS, "invalid constructor for this direction"); + } } ////////////////////////////////////////////////////////////////////////// -bool CoarseToFineBlock3DConnector::isLocalConnector() -{ - return !this->isRemoteConnector(); -} +bool CoarseToFineBlock3DConnector::isLocalConnector() { return !this->isRemoteConnector(); } ////////////////////////////////////////////////////////////////////////// bool CoarseToFineBlock3DConnector::isRemoteConnector() { - return ((sender11 && sender11->isRemoteTransmitter()) || (receiver11 && receiver11->isRemoteTransmitter()) - || (sender00 && sender00->isRemoteTransmitter()) || (receiver00 && receiver00->isRemoteTransmitter()) - || (sender01 && sender01->isRemoteTransmitter()) || (receiver01 && receiver01->isRemoteTransmitter()) - || (sender10 && sender10->isRemoteTransmitter()) || (receiver10 && receiver10->isRemoteTransmitter())); + return ((sender11 && sender11->isRemoteTransmitter()) || (receiver11 && receiver11->isRemoteTransmitter()) || + (sender00 && sender00->isRemoteTransmitter()) || (receiver00 && receiver00->isRemoteTransmitter()) || + (sender01 && sender01->isRemoteTransmitter()) || (receiver01 && receiver01->isRemoteTransmitter()) || + (sender10 && sender10->isRemoteTransmitter()) || (receiver10 && receiver10->isRemoteTransmitter())); } ////////////////////////////////////////////////////////////////////////// void CoarseToFineBlock3DConnector::sendTransmitterDataSize() { - if (sender00) - { - UBLOG(logDEBUG5, "CoarseToFineBlock3DConnector<VectorTransmitter>::sendTransmitterDataSize()-sender00 "<<block.lock()->toString()<<" sendDir="<<sendDir); - sender00->sendDataSize(); - } - if (sender01) - { - UBLOG(logDEBUG5, "CoarseToFineBlock3DConnector<VectorTransmitter>::sendTransmitterDataSize()-sender01 "<<block.lock()->toString()<<"sendDir="<<sendDir); - sender01->sendDataSize(); - } - if (sender10) - { - UBLOG(logDEBUG5, "CoarseToFineBlock3DConnector<VectorTransmitter>::sendTransmitterDataSize()-sender10 "<<block.lock()->toString()+"sendDir="<<sendDir); - sender10->sendDataSize(); - } - if (sender11) - { - UBLOG(logDEBUG5, "CoarseToFineBlock3DConnector<VectorTransmitter>::sendTransmitterDataSize()-sender11 "<<block.lock()->toString()<<"sendDir="<<sendDir); - sender11->sendDataSize(); - } + if (sender00) { + UBLOG(logDEBUG5, "CoarseToFineBlock3DConnector<VectorTransmitter>::sendTransmitterDataSize()-sender00 " + << block.lock()->toString() << " sendDir=" << sendDir); + sender00->sendDataSize(); + } + if (sender01) { + UBLOG(logDEBUG5, "CoarseToFineBlock3DConnector<VectorTransmitter>::sendTransmitterDataSize()-sender01 " + << block.lock()->toString() << "sendDir=" << sendDir); + sender01->sendDataSize(); + } + if (sender10) { + UBLOG(logDEBUG5, "CoarseToFineBlock3DConnector<VectorTransmitter>::sendTransmitterDataSize()-sender10 " + << block.lock()->toString() + "sendDir=" << sendDir); + sender10->sendDataSize(); + } + if (sender11) { + UBLOG(logDEBUG5, "CoarseToFineBlock3DConnector<VectorTransmitter>::sendTransmitterDataSize()-sender11 " + << block.lock()->toString() << "sendDir=" << sendDir); + sender11->sendDataSize(); + } } ////////////////////////////////////////////////////////////////////////// void CoarseToFineBlock3DConnector::receiveTransmitterDataSize() { - if (receiver00) - { - UBLOG(logDEBUG5, "CoarseToFineBlock3DConnector<VectorTransmitter>::receiveTransmitterDataSize()-receiver00 "<<block.lock()->toString()<<"sendDir="<<sendDir); - receiver00->receiveDataSize(); - } - if (receiver01) - { - UBLOG(logDEBUG5, "CoarseToFineBlock3DConnector<VectorTransmitter>::receiveTransmitterDataSize()-receiver01 "<<block.lock()->toString()<<"sendDir="<<sendDir); - receiver01->receiveDataSize(); - } - if (receiver10) - { - UBLOG(logDEBUG5, "CoarseToFineBlock3DConnector<VectorTransmitter>::receiveTransmitterDataSize()-receiver10 "<<block.lock()->toString()<<"sendDir="<<sendDir); - receiver10->receiveDataSize(); - } - if (receiver11) - { - UBLOG(logDEBUG5, "CoarseToFineBlock3DConnector<VectorTransmitter>::receiveTransmitterDataSize()-receiver11 "<<block.lock()->toString()<<"sendDir="<<sendDir); - receiver11->receiveDataSize(); - } + if (receiver00) { + UBLOG(logDEBUG5, "CoarseToFineBlock3DConnector<VectorTransmitter>::receiveTransmitterDataSize()-receiver00 " + << block.lock()->toString() << "sendDir=" << sendDir); + receiver00->receiveDataSize(); + } + if (receiver01) { + UBLOG(logDEBUG5, "CoarseToFineBlock3DConnector<VectorTransmitter>::receiveTransmitterDataSize()-receiver01 " + << block.lock()->toString() << "sendDir=" << sendDir); + receiver01->receiveDataSize(); + } + if (receiver10) { + UBLOG(logDEBUG5, "CoarseToFineBlock3DConnector<VectorTransmitter>::receiveTransmitterDataSize()-receiver10 " + << block.lock()->toString() << "sendDir=" << sendDir); + receiver10->receiveDataSize(); + } + if (receiver11) { + UBLOG(logDEBUG5, "CoarseToFineBlock3DConnector<VectorTransmitter>::receiveTransmitterDataSize()-receiver11 " + << block.lock()->toString() << "sendDir=" << sendDir); + receiver11->receiveDataSize(); + } } ////////////////////////////////////////////////////////////////////////// void CoarseToFineBlock3DConnector::prepareForSend() { - if (sender00) sender00->prepareForSend(); - if (sender01) sender01->prepareForSend(); - if (sender10) sender10->prepareForSend(); - if (sender11) sender11->prepareForSend(); + if (sender00) + sender00->prepareForSend(); + if (sender01) + sender01->prepareForSend(); + if (sender10) + sender10->prepareForSend(); + if (sender11) + sender11->prepareForSend(); } ////////////////////////////////////////////////////////////////////////// void CoarseToFineBlock3DConnector::sendVectors() { - if (sender00) sender00->sendData(); - if (sender01) sender01->sendData(); - if (sender10) sender10->sendData(); - if (sender11) sender11->sendData(); + if (sender00) + sender00->sendData(); + if (sender01) + sender01->sendData(); + if (sender10) + sender10->sendData(); + if (sender11) + sender11->sendData(); } ////////////////////////////////////////////////////////////////////////// void CoarseToFineBlock3DConnector::prepareForReceive() { - if (receiver00) receiver00->prepareForReceive(); - if (receiver01) receiver01->prepareForReceive(); - if (receiver10) receiver10->prepareForReceive(); - if (receiver11) receiver11->prepareForReceive(); + if (receiver00) + receiver00->prepareForReceive(); + if (receiver01) + receiver01->prepareForReceive(); + if (receiver10) + receiver10->prepareForReceive(); + if (receiver11) + receiver11->prepareForReceive(); } ////////////////////////////////////////////////////////////////////////// void CoarseToFineBlock3DConnector::receiveVectors() { - if (receiver00) receiver00->receiveData(); - if (receiver01) receiver01->receiveData(); - if (receiver10) receiver10->receiveData(); - if (receiver11) receiver11->receiveData(); + if (receiver00) + receiver00->receiveData(); + if (receiver01) + receiver01->receiveData(); + if (receiver10) + receiver10->receiveData(); + if (receiver11) + receiver11->receiveData(); } diff --git a/src/cpu/VirtualFluidsCore/Connectors/CoarseToFineBlock3DConnector.h b/src/cpu/VirtualFluidsCore/Connectors/CoarseToFineBlock3DConnector.h index 54798eaf848c9e2550ff5c2bbc4de3b6888c8f60..6ca7c40bfaf22ebfed0c13b23e7973926a805427 100644 --- a/src/cpu/VirtualFluidsCore/Connectors/CoarseToFineBlock3DConnector.h +++ b/src/cpu/VirtualFluidsCore/Connectors/CoarseToFineBlock3DConnector.h @@ -1,36 +1,35 @@ //! \file CoarseToFineBlock3DConnector.h -//! \brief Base class for connectors that interpolates and sends data from coarse level to fine. +//! \brief Base class for connectors that interpolates and sends data from coarse level to fine. //! \author Konstantin Kutscher //! \date 18.05.2015 #ifndef CoarseToFineBlock3DConnector_H #define CoarseToFineBlock3DConnector_H -#include "TransmitterType.h" +#include "Block3D.h" #include "Block3DConnector.h" #include "D3Q27System.h" -#include "Block3D.h" #include "InterpolationProcessor.h" +#include "TransmitterType.h" #include <PointerDefinitions.h> - class Block3D; //! \class CoarseToFineBlock3DConnector -//! \brief Base class for connectors that interpolates and sends data from coarse level to fine. -//! \details The data is copied in a vector (this is located in the transmitter). -//! The vector is transmitted via transmitter. -//! The transmitter can be a local, MPI, RCG, CTL or whatever +//! \brief Base class for connectors that interpolates and sends data from coarse level to fine. +//! \details The data is copied in a vector (this is located in the transmitter). +//! The vector is transmitted via transmitter. +//! The transmitter can be a local, MPI, RCG, CTL or whatever //! which a transmitter that is derived from transmitter base class. //! //! four fine blocks inside a coarse block: //! //! | | | -//! |:--:|:---| -//! | 01 | 11 | -//! | 00 | 10 | +//! |:--:|:---| +//! | 01 | 11 | +//! | 00 | 10 | //! -//! send direction: +//! send direction: //! //! |E<->W | N<->S | T<->B | //! |--------|---------|--------| @@ -38,68 +37,58 @@ class Block3D; //! | ^ | ^ | ^ | //! | +->x2 | +->x1 | +->x1| - class CoarseToFineBlock3DConnector : public Block3DConnector { public: - CoarseToFineBlock3DConnector(SPtr<Block3D> block, - VectorTransmitterPtr sender00, VectorTransmitterPtr receiver00, - VectorTransmitterPtr sender01, VectorTransmitterPtr receiver01, - VectorTransmitterPtr sender10, VectorTransmitterPtr receiver10, - VectorTransmitterPtr sender11, VectorTransmitterPtr receiver11, - int sendDir, InterpolationProcessorPtr iprocessor); + CoarseToFineBlock3DConnector(SPtr<Block3D> block, VectorTransmitterPtr sender00, VectorTransmitterPtr receiver00, + VectorTransmitterPtr sender01, VectorTransmitterPtr receiver01, + VectorTransmitterPtr sender10, VectorTransmitterPtr receiver10, + VectorTransmitterPtr sender11, VectorTransmitterPtr receiver11, int sendDir, + InterpolationProcessorPtr iprocessor); - ~CoarseToFineBlock3DConnector() override = default; + ~CoarseToFineBlock3DConnector() override = default; - bool isLocalConnector() override; - bool isRemoteConnector() override; + bool isLocalConnector() override; + bool isRemoteConnector() override; - void init() override =0; + void init() override = 0; - void sendTransmitterDataSize() override; - void receiveTransmitterDataSize() override; + void sendTransmitterDataSize() override; + void receiveTransmitterDataSize() override; - void prepareForSend() override; - void sendVectors() override; + void prepareForSend() override; + void sendVectors() override; - void prepareForReceive() override; - void receiveVectors() override; + void prepareForReceive() override; + void receiveVectors() override; - void fillSendVectors() override =0; - void distributeReceiveVectors() override = 0; + void fillSendVectors() override = 0; + void distributeReceiveVectors() override = 0; - bool isInterpolationConnectorCF() override { return true; } - bool isInterpolationConnectorFC() override { return false; } + bool isInterpolationConnectorCF() override { return true; } + bool isInterpolationConnectorFC() override { return false; } - void prepareForSendX1() override {} - void prepareForSendX2() override {} - void prepareForSendX3() override {} + void prepareForSendX1() override {} + void prepareForSendX2() override {} + void prepareForSendX3() override {} - void sendVectorsX1() override {} - void sendVectorsX2() override {} - void sendVectorsX3() override {} + void sendVectorsX1() override {} + void sendVectorsX2() override {} + void sendVectorsX3() override {} - void prepareForReceiveX1() override {} - void prepareForReceiveX2() override {} - void prepareForReceiveX3() override {} + void prepareForReceiveX1() override {} + void prepareForReceiveX2() override {} + void prepareForReceiveX3() override {} - void receiveVectorsX1() override {} - void receiveVectorsX2() override {} - void receiveVectorsX3() override {} + void receiveVectorsX1() override {} + void receiveVectorsX2() override {} + void receiveVectorsX3() override {} protected: - WPtr<Block3D> block; //dieser nvd sendet daten und die empfangenen werden diesem nvd zugeordnet - VectorTransmitterPtr sender00, receiver00, - sender01, receiver01, - sender10, receiver10, - sender11, receiver11; - - InterpolationProcessorPtr iprocessor; + WPtr<Block3D> block; // dieser nvd sendet daten und die empfangenen werden diesem nvd zugeordnet + VectorTransmitterPtr sender00, receiver00, sender01, receiver01, sender10, receiver10, sender11, receiver11; + InterpolationProcessorPtr iprocessor; }; - - - -#endif - +#endif diff --git a/src/cpu/VirtualFluidsCore/Connectors/CoarseToFineNodeSetBlock3DConnector.cpp b/src/cpu/VirtualFluidsCore/Connectors/CoarseToFineNodeSetBlock3DConnector.cpp index e39ad41277c09f5874b6c6798dbbe02723e6d693..36553307d937c07c19f792a7a6e40166d5d04723 100644 --- a/src/cpu/VirtualFluidsCore/Connectors/CoarseToFineNodeSetBlock3DConnector.cpp +++ b/src/cpu/VirtualFluidsCore/Connectors/CoarseToFineNodeSetBlock3DConnector.cpp @@ -1,1384 +1,1293 @@ #include "CoarseToFineNodeSetBlock3DConnector.h" #include "DataSet3D.h" - //////////////////////////////////////////////////////////////////////////// -CoarseToFineNodeSetBlock3DConnector::CoarseToFineNodeSetBlock3DConnector(SPtr<Block3D> block, - VectorTransmitterPtr sender00, VectorTransmitterPtr receiver00, - VectorTransmitterPtr sender01, VectorTransmitterPtr receiver01, - VectorTransmitterPtr sender10, VectorTransmitterPtr receiver10, - VectorTransmitterPtr sender11, VectorTransmitterPtr receiver11, - int sendDir, InterpolationProcessorPtr iprocessor) : CoarseToFineBlock3DConnector(block, sender00, receiver00, - sender01, receiver01, - sender10, receiver10, - sender11, receiver11, - sendDir, iprocessor) +CoarseToFineNodeSetBlock3DConnector::CoarseToFineNodeSetBlock3DConnector( + SPtr<Block3D> block, VectorTransmitterPtr sender00, VectorTransmitterPtr receiver00, VectorTransmitterPtr sender01, + VectorTransmitterPtr receiver01, VectorTransmitterPtr sender10, VectorTransmitterPtr receiver10, + VectorTransmitterPtr sender11, VectorTransmitterPtr receiver11, int sendDir, InterpolationProcessorPtr iprocessor) + : CoarseToFineBlock3DConnector(block, sender00, receiver00, sender01, receiver01, sender10, receiver10, sender11, + receiver11, sendDir, iprocessor) { } ////////////////////////////////////////////////////////////////////////// void CoarseToFineNodeSetBlock3DConnector::init() { - bMaxX1 = (int)block.lock()->getKernel()->getDataSet()->getFdistributions()->getNX1(); - bMaxX2 = (int)block.lock()->getKernel()->getDataSet()->getFdistributions()->getNX2(); - bMaxX3 = (int)block.lock()->getKernel()->getDataSet()->getFdistributions()->getNX3(); - - minX1 = 0; - minX2 = 0; - minX3 = 0; - maxX1 = bMaxX1 - 1; - maxX2 = bMaxX2 - 1; - maxX3 = bMaxX3 - 1; - - minHalfX1 = 0; - minHalfX2 = 0; - minHalfX3 = 0; - - maxHalfX1 = 0; - maxHalfX2 = 0; - maxHalfX3 = 0; - - if (Utilities::isEven(bMaxX1)) - { - minHalfX1 = bMaxX1 / 2 - 1; - maxHalfX1 = bMaxX1 / 2 - 1; - } - else if (Utilities::isOdd(bMaxX1)) - { - minHalfX1 = bMaxX1 / 2; - maxHalfX1 = bMaxX1 / 2 - 1; - } - - if (Utilities::isEven(bMaxX2)) - { - minHalfX2 = bMaxX2 / 2 - 1; - maxHalfX2 = bMaxX2 / 2 - 1; - } - else if (Utilities::isOdd(bMaxX2)) - { - minHalfX2 = bMaxX2 / 2; - maxHalfX2 = bMaxX2 / 2 - 1; - } - - if (Utilities::isEven(bMaxX3)) - { - minHalfX3 = bMaxX3 / 2 - 1; - maxHalfX3 = bMaxX3 / 2 - 1; - } - else if (Utilities::isOdd(bMaxX3)) - { - minHalfX3 = bMaxX3 / 2; - maxHalfX3 = bMaxX3 / 2 - 1; - } - - //int sendSize = 0; - LBMReal initValue = -999.0; - - int sendDataPerNode = 27/*f*/; - int iCellSize = 8; //size of interpolation cell - - findCFCells(); - findFCCells(); - - ////////////////////////////////////////////////////// - //Debug - ////////////////////////////////////////////////////// -// if (block.lock()->getGlobalID() == 2234) -// { -// int test = 0; -// } - - if (sender00) sender00->getData().resize(iNodeSetSender00.size()*iCellSize*sendDataPerNode, initValue); - else sender00 = VectorTransmitterPtr(new TbLocalTransmitter< CbVector< LBMReal > >()); - if (sender01) sender01->getData().resize(iNodeSetSender01.size()*iCellSize*sendDataPerNode, initValue); - else sender01 = VectorTransmitterPtr(new TbLocalTransmitter< CbVector< LBMReal > >()); - if (sender10) sender10->getData().resize(iNodeSetSender10.size()*iCellSize*sendDataPerNode, initValue); - else sender10 = VectorTransmitterPtr(new TbLocalTransmitter< CbVector< LBMReal > >()); - if (sender11) sender11->getData().resize(iNodeSetSender11.size()*iCellSize*sendDataPerNode, initValue); - else sender11 = VectorTransmitterPtr(new TbLocalTransmitter< CbVector< LBMReal > >()); - - if (!receiver00) receiver00 = VectorTransmitterPtr(new TbLocalTransmitter< CbVector< LBMReal > >()); - if (!receiver01) receiver01 = VectorTransmitterPtr(new TbLocalTransmitter< CbVector< LBMReal > >()); - if (!receiver10) receiver10 = VectorTransmitterPtr(new TbLocalTransmitter< CbVector< LBMReal > >()); - if (!receiver11) receiver11 = VectorTransmitterPtr(new TbLocalTransmitter< CbVector< LBMReal > >()); + bMaxX1 = (int)block.lock()->getKernel()->getDataSet()->getFdistributions()->getNX1(); + bMaxX2 = (int)block.lock()->getKernel()->getDataSet()->getFdistributions()->getNX2(); + bMaxX3 = (int)block.lock()->getKernel()->getDataSet()->getFdistributions()->getNX3(); + + minX1 = 0; + minX2 = 0; + minX3 = 0; + maxX1 = bMaxX1 - 1; + maxX2 = bMaxX2 - 1; + maxX3 = bMaxX3 - 1; + + minHalfX1 = 0; + minHalfX2 = 0; + minHalfX3 = 0; + + maxHalfX1 = 0; + maxHalfX2 = 0; + maxHalfX3 = 0; + + if (Utilities::isEven(bMaxX1)) { + minHalfX1 = bMaxX1 / 2 - 1; + maxHalfX1 = bMaxX1 / 2 - 1; + } else if (Utilities::isOdd(bMaxX1)) { + minHalfX1 = bMaxX1 / 2; + maxHalfX1 = bMaxX1 / 2 - 1; + } + + if (Utilities::isEven(bMaxX2)) { + minHalfX2 = bMaxX2 / 2 - 1; + maxHalfX2 = bMaxX2 / 2 - 1; + } else if (Utilities::isOdd(bMaxX2)) { + minHalfX2 = bMaxX2 / 2; + maxHalfX2 = bMaxX2 / 2 - 1; + } + + if (Utilities::isEven(bMaxX3)) { + minHalfX3 = bMaxX3 / 2 - 1; + maxHalfX3 = bMaxX3 / 2 - 1; + } else if (Utilities::isOdd(bMaxX3)) { + minHalfX3 = bMaxX3 / 2; + maxHalfX3 = bMaxX3 / 2 - 1; + } + + // int sendSize = 0; + LBMReal initValue = -999.0; + + int sendDataPerNode = 27 /*f*/; + int iCellSize = 8; // size of interpolation cell + + findCFCells(); + findFCCells(); + + ////////////////////////////////////////////////////// + // Debug + ////////////////////////////////////////////////////// + // if (block.lock()->getGlobalID() == 2234) + // { + // int test = 0; + // } + + if (sender00) + sender00->getData().resize(iNodeSetSender00.size() * iCellSize * sendDataPerNode, initValue); + else + sender00 = VectorTransmitterPtr(new TbLocalTransmitter<CbVector<LBMReal>>()); + if (sender01) + sender01->getData().resize(iNodeSetSender01.size() * iCellSize * sendDataPerNode, initValue); + else + sender01 = VectorTransmitterPtr(new TbLocalTransmitter<CbVector<LBMReal>>()); + if (sender10) + sender10->getData().resize(iNodeSetSender10.size() * iCellSize * sendDataPerNode, initValue); + else + sender10 = VectorTransmitterPtr(new TbLocalTransmitter<CbVector<LBMReal>>()); + if (sender11) + sender11->getData().resize(iNodeSetSender11.size() * iCellSize * sendDataPerNode, initValue); + else + sender11 = VectorTransmitterPtr(new TbLocalTransmitter<CbVector<LBMReal>>()); + + if (!receiver00) + receiver00 = VectorTransmitterPtr(new TbLocalTransmitter<CbVector<LBMReal>>()); + if (!receiver01) + receiver01 = VectorTransmitterPtr(new TbLocalTransmitter<CbVector<LBMReal>>()); + if (!receiver10) + receiver10 = VectorTransmitterPtr(new TbLocalTransmitter<CbVector<LBMReal>>()); + if (!receiver11) + receiver11 = VectorTransmitterPtr(new TbLocalTransmitter<CbVector<LBMReal>>()); } ////////////////////////////////////////////////////////////////////////// -void CoarseToFineNodeSetBlock3DConnector::findCFCells(int lMinX1, int lMinX2, int lMinX3, int lMaxX1, int lMaxX2, int lMaxX3, INodeSet &inodes) +void CoarseToFineNodeSetBlock3DConnector::findCFCells(int lMinX1, int lMinX2, int lMinX3, int lMaxX1, int lMaxX2, + int lMaxX3, INodeSet &inodes) { - int ix1, ix2, ix3; - LBMReal x1off, x2off, x3off; - - SPtr<DistributionArray3D> fFrom = block.lock()->getKernel()->getDataSet()->getFdistributions(); - SPtr<BCArray3D> bcArray = block.lock()->getKernel()->getBCProcessor()->getBCArray(); - - for (ix3 = lMinX3; ix3<=lMaxX3; ix3++) - { - for (ix2 = lMinX2; ix2<=lMaxX2; ix2++) - { - for (ix1 = lMinX1; ix1<=lMaxX1; ix1++) - { - D3Q27ICell icellC; - - int howManySolids = iprocessor->iCellHowManySolids(bcArray, ix1, ix2, ix3); - - if (howManySolids == 0 || howManySolids == 8) - { - x1off = 0.0; - x2off = 0.0; - x3off = 0.0; - } - else - { - if (!iprocessor->findNeighborICell(bcArray, fFrom, icellC, bMaxX1, bMaxX2, bMaxX3, ix1, ix2, ix3, x1off, x2off, x3off)) - { - std::string err = "For "+block.lock()->toString()+" x1="+UbSystem::toString(ix1)+", x2=" + UbSystem::toString(ix2)+", x3=" + UbSystem::toString(ix3)+ - " interpolation is not implemented for other direction"+ - " by using in: "+(std::string)typeid(*this).name()+ - " or maybe you have a solid on the block boundary"; - UB_THROW(UbException(UB_EXARGS, err)); - } + int ix1, ix2, ix3; + LBMReal x1off, x2off, x3off; + + SPtr<DistributionArray3D> fFrom = block.lock()->getKernel()->getDataSet()->getFdistributions(); + SPtr<BCArray3D> bcArray = block.lock()->getKernel()->getBCProcessor()->getBCArray(); + + for (ix3 = lMinX3; ix3 <= lMaxX3; ix3++) { + for (ix2 = lMinX2; ix2 <= lMaxX2; ix2++) { + for (ix1 = lMinX1; ix1 <= lMaxX1; ix1++) { + D3Q27ICell icellC; + + int howManySolids = iprocessor->iCellHowManySolids(bcArray, ix1, ix2, ix3); + + if (howManySolids == 0 || howManySolids == 8) { + x1off = 0.0; + x2off = 0.0; + x3off = 0.0; + } else { + if (!iprocessor->findNeighborICell(bcArray, fFrom, icellC, bMaxX1, bMaxX2, bMaxX3, ix1, ix2, ix3, + x1off, x2off, x3off)) { + std::string err = "For " + block.lock()->toString() + " x1=" + UbSystem::toString(ix1) + + ", x2=" + UbSystem::toString(ix2) + ", x3=" + UbSystem::toString(ix3) + + " interpolation is not implemented for other direction" + + " by using in: " + (std::string) typeid(*this).name() + + " or maybe you have a solid on the block boundary"; + UB_THROW(UbException(UB_EXARGS, err)); + } + } + + INodeVector inv; + inv.push_back(ix1 + (int)x1off); + inv.push_back(ix2 + (int)x2off); + inv.push_back(ix3 + (int)x3off); + inv.push_back((int)x1off); + inv.push_back((int)x2off); + inv.push_back((int)x3off); + // inodes.insert(inv); + inodes.push_back(inv); } - - INodeVector inv; - inv.push_back(ix1 + (int)x1off); - inv.push_back(ix2 + (int)x2off); - inv.push_back(ix3 + (int)x3off); - inv.push_back((int)x1off); - inv.push_back((int)x2off); - inv.push_back((int)x3off); - //inodes.insert(inv); - inodes.push_back(inv); - } - } - } + } + } } ////////////////////////////////////////////////////////////////////////// -//template< typename VectorTransmitter > +// template< typename VectorTransmitter > void CoarseToFineNodeSetBlock3DConnector::findCFCells() { - using namespace D3Q27System; - - int lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3; - - switch (sendDir) - { - //faces - case E: case W: - if (sendDir == E) - { - lMinX1 = maxX1 - 2; - lMaxX1 = lMinX1; - } - else if (sendDir == W) - { - lMinX1 = 1; - lMaxX1 = lMinX1; - } - - if (sender00) - { - lMinX2 = minX2; - lMaxX2 = maxHalfX2; - lMinX3 = minX3; - lMaxX3 = maxHalfX3; - findCFCells(lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, iNodeSetSender00); - } - if (sender10) - { - lMinX2 = minHalfX2; - lMaxX2 = maxX2 - 1; - lMinX3 = minX3; - lMaxX3 = maxHalfX3; - findCFCells(lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, iNodeSetSender10); - } - if (sender01) - { - lMinX2 = minX2; - lMaxX2 = maxHalfX2; - lMinX3 = minHalfX3; - lMaxX3 = maxX3 - 1; - findCFCells(lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, iNodeSetSender01); - } - if (sender11) - { - lMinX2 = minHalfX2; - lMaxX2 = maxX2 - 1; - lMinX3 = minHalfX3; - lMaxX3 = maxX3 - 1; - findCFCells(lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, iNodeSetSender11); - } - break; - case N: case S: - if (sendDir == N) - { - lMinX2 = maxX2 - 2; - lMaxX2 = lMinX2; - } - else if (sendDir == S) - { - lMinX2 = 1; - lMaxX2 = lMinX2; - } - - if (sender00) - { - lMinX1 = minX1; - lMaxX1 = maxHalfX1; - lMinX3 = minX3; - lMaxX3 = maxHalfX3; - findCFCells(lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, iNodeSetSender00); - } - if (sender10) - { - lMinX1 = minHalfX1; - lMaxX1 = maxX1 - 1; - lMinX3 = minX3; - lMaxX3 = maxHalfX3; - findCFCells(lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, iNodeSetSender10); - } - if (sender01) - { - lMinX1 = minX1; - lMaxX1 = maxHalfX1; - lMinX3 = minHalfX3; - lMaxX3 = maxX3 - 1; - findCFCells(lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, iNodeSetSender01); - } - if (sender11) - { - lMinX1 = minHalfX1; - lMaxX1 = maxX1 - 1; - lMinX3 = minHalfX3; - lMaxX3 = maxX3 - 1; - findCFCells(lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, iNodeSetSender11); - } - break; - case T: case B: - if (sendDir == T) - { - lMinX3 = maxX3 - 2; - lMaxX3 = lMinX3; - } - else if (sendDir == B) - { - lMinX3 = 1; - lMaxX3 = lMinX3; - } - - if (sender00) - { - lMinX1 = minX1; - lMaxX1 = maxHalfX1; - lMinX2 = minX2; - lMaxX2 = maxHalfX2; - findCFCells(lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, iNodeSetSender00); - } - if (sender10) - { - lMinX1 = minHalfX1; - lMaxX1 = maxX1 - 1; - lMinX2 = minX2; - lMaxX2 = maxHalfX2; - findCFCells(lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, iNodeSetSender10); - } - if (sender01) - { - lMinX1 = minX1; - lMaxX1 = maxHalfX1; - lMinX2 = minHalfX2; - lMaxX2 = maxX2 - 1; - findCFCells(lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, iNodeSetSender01); - } - if (sender11) - { - lMinX1 = minHalfX1; - lMaxX1 = maxX1 - 1; - lMinX2 = minHalfX2; - lMaxX2 = maxX2 - 1; - findCFCells(lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, iNodeSetSender11); - } - break; - //edges - //N-S-E-W - case NE: case SW: case SE: case NW: - if (sendDir == NE) - { - lMinX1 = maxX1 - 2; - lMaxX1 = lMinX1 + 1; - lMinX2 = maxX2 - 2; - lMaxX2 = lMinX2 + 1; - } - else if (sendDir == SW) - { - lMinX1 = 0; - lMaxX1 = lMinX1 + 1; - lMinX2 = 0; - lMaxX2 = lMinX2 + 1; - } - else if (sendDir == SE) - { - lMinX1 = maxX1 - 2; - lMaxX1 = lMinX1 + 1; - lMinX2 = 0; - lMaxX2 = lMinX2 + 1; - } - else if (sendDir == NW) - { - lMinX1 = 0; - lMaxX1 = lMinX1 + 1; - lMinX2 = maxX2 - 2; - lMaxX2 = lMinX2 + 1; - } - - if (sender00) - { - lMinX3 = minX3; - lMaxX3 = maxHalfX3; - findCFCells(lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, iNodeSetSender00); - } - if (sender10) - { - lMinX3 = minHalfX3; - lMaxX3 = maxX3 - 1; - findCFCells(lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, iNodeSetSender10); - } - break; - //T-B-E-W - case TE: case BW: case BE: case TW: - if (sendDir == TE) - { - lMinX1 = maxX1 - 2; - lMaxX1 = lMinX1 + 1; - lMinX3 = maxX3 - 2; - lMaxX3 = lMinX3 + 1; - } - else if (sendDir == BW) - { - lMinX1 = 0; - lMaxX1 = lMinX1 + 2; - lMinX3 = 0; - lMaxX3 = lMinX3 + 2; - } - else if (sendDir == BE) - { - lMinX1 = maxX1 - 2; - lMaxX1 = lMinX1 + 1; - lMinX3 = 0; - lMaxX3 = lMinX3 + 1; - } - else if (sendDir == TW) - { - lMinX1 = 0; - lMaxX1 = lMinX1 + 1; - lMinX3 = maxX3 - 2; - lMaxX3 = lMinX3 + 1; - } - - if (sender00) - { - lMinX2 = minX2; - lMaxX2 = maxHalfX2; - findCFCells(lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, iNodeSetSender00); - } - if (sender10) - { - lMinX2 = minHalfX2; - lMaxX2 = maxX2 - 1; - findCFCells(lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, iNodeSetSender10); - } - break; - //T-B-N-S - case TN: case BS: case BN: case TS: - if (sendDir == TN) - { - lMinX2 = maxX2 - 2; - lMaxX2 = lMinX2 + 1; - lMinX3 = maxX3 - 3; - lMaxX3 = lMinX3 + 1; - } - else if (sendDir == BS) - { - lMinX2 = 0; - lMaxX2 = lMinX2 + 1; - lMinX3 = 0; - lMaxX3 = lMinX3 + 1; - } - else if (sendDir == BN) - { - lMinX2 = maxX2 - 2; - lMaxX2 = lMinX2 + 1; - lMinX3 = 0; - lMaxX3 = lMinX3 + 1; - } - else if (sendDir == TS) - { - lMinX2 = 0; - lMaxX2 = lMinX2 + 1; - lMinX3 = maxX3 - 2; - lMaxX3 = lMinX3 + 1; - } - - if (sender00) - { - lMinX1 = minX1; - lMaxX1 = maxHalfX1; - findCFCells(lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, iNodeSetSender00); - } - if (sender10) - { - lMinX1 = minHalfX1; - lMaxX1 = maxX1 - 1; - findCFCells(lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, iNodeSetSender10); - } - break; - //corners - case TNE: case TNW: case TSE: case TSW: case BNE: case BNW: case BSE: case BSW: - if (sendDir == TNE) - { - lMinX1 = maxX1-2; - lMaxX1 = maxX1-1; - lMinX2 = maxX2-2; - lMaxX2 = maxX2-1; - lMinX3 = maxX3-2; - lMaxX3 = maxX3-1; - } - else if (sendDir == TNW) - { - lMinX1 = 0; - lMaxX1 = 1; - lMinX2 = maxX2-2; - lMaxX2 = maxX2-1; - lMinX3 = maxX3-2; - lMaxX3 = maxX3-1; - } - else if (sendDir == TSE) - { - lMinX1 = maxX1-2; - lMaxX1 = maxX1-1; - lMinX2 = 0; - lMaxX2 = 1; - lMinX3 = maxX3-2; - lMaxX3 = maxX3-1; - } - else if (sendDir == TSW) - { - lMinX1 = 0; - lMaxX1 = 1; - lMinX2 = 0; - lMaxX2 = 1; - lMinX3 = maxX3-2; - lMaxX3 = maxX3-1; - } - else if (sendDir == BNE) - { - lMinX1 = maxX1-2; - lMaxX1 = maxX1-1; - lMinX2 = maxX2-2; - lMaxX2 = maxX2-1; - lMinX3 = 0; - lMaxX3 = 1; - } - else if (sendDir == BNW) - { - lMinX1 = 0; - lMaxX1 = 1; - lMinX2 = maxX2-2; - lMaxX2 = maxX2-1; - lMinX3 = 0; - lMaxX3 = 1; - } - else if (sendDir == BSE) - { - lMinX1 = maxX1-2; - lMaxX1 = maxX1-1; - lMinX2 = 0; - lMaxX2 = 1; - lMinX3 = 0; - lMaxX3 = 1; - } - else if (sendDir == BSW) - { - lMinX1 = 0; - lMaxX1 = 1; - lMinX2 = 0; - lMaxX2 = 1; - lMinX3 = 0; - lMaxX3 = 1; - } - if (sender00) - { - findCFCells(lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, iNodeSetSender00); - } - break; - } + using namespace D3Q27System; + + int lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3; + + switch (sendDir) { + // faces + case E: + case W: + if (sendDir == E) { + lMinX1 = maxX1 - 2; + lMaxX1 = lMinX1; + } else if (sendDir == W) { + lMinX1 = 1; + lMaxX1 = lMinX1; + } + + if (sender00) { + lMinX2 = minX2; + lMaxX2 = maxHalfX2; + lMinX3 = minX3; + lMaxX3 = maxHalfX3; + findCFCells(lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, iNodeSetSender00); + } + if (sender10) { + lMinX2 = minHalfX2; + lMaxX2 = maxX2 - 1; + lMinX3 = minX3; + lMaxX3 = maxHalfX3; + findCFCells(lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, iNodeSetSender10); + } + if (sender01) { + lMinX2 = minX2; + lMaxX2 = maxHalfX2; + lMinX3 = minHalfX3; + lMaxX3 = maxX3 - 1; + findCFCells(lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, iNodeSetSender01); + } + if (sender11) { + lMinX2 = minHalfX2; + lMaxX2 = maxX2 - 1; + lMinX3 = minHalfX3; + lMaxX3 = maxX3 - 1; + findCFCells(lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, iNodeSetSender11); + } + break; + case N: + case S: + if (sendDir == N) { + lMinX2 = maxX2 - 2; + lMaxX2 = lMinX2; + } else if (sendDir == S) { + lMinX2 = 1; + lMaxX2 = lMinX2; + } + + if (sender00) { + lMinX1 = minX1; + lMaxX1 = maxHalfX1; + lMinX3 = minX3; + lMaxX3 = maxHalfX3; + findCFCells(lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, iNodeSetSender00); + } + if (sender10) { + lMinX1 = minHalfX1; + lMaxX1 = maxX1 - 1; + lMinX3 = minX3; + lMaxX3 = maxHalfX3; + findCFCells(lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, iNodeSetSender10); + } + if (sender01) { + lMinX1 = minX1; + lMaxX1 = maxHalfX1; + lMinX3 = minHalfX3; + lMaxX3 = maxX3 - 1; + findCFCells(lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, iNodeSetSender01); + } + if (sender11) { + lMinX1 = minHalfX1; + lMaxX1 = maxX1 - 1; + lMinX3 = minHalfX3; + lMaxX3 = maxX3 - 1; + findCFCells(lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, iNodeSetSender11); + } + break; + case T: + case B: + if (sendDir == T) { + lMinX3 = maxX3 - 2; + lMaxX3 = lMinX3; + } else if (sendDir == B) { + lMinX3 = 1; + lMaxX3 = lMinX3; + } + + if (sender00) { + lMinX1 = minX1; + lMaxX1 = maxHalfX1; + lMinX2 = minX2; + lMaxX2 = maxHalfX2; + findCFCells(lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, iNodeSetSender00); + } + if (sender10) { + lMinX1 = minHalfX1; + lMaxX1 = maxX1 - 1; + lMinX2 = minX2; + lMaxX2 = maxHalfX2; + findCFCells(lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, iNodeSetSender10); + } + if (sender01) { + lMinX1 = minX1; + lMaxX1 = maxHalfX1; + lMinX2 = minHalfX2; + lMaxX2 = maxX2 - 1; + findCFCells(lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, iNodeSetSender01); + } + if (sender11) { + lMinX1 = minHalfX1; + lMaxX1 = maxX1 - 1; + lMinX2 = minHalfX2; + lMaxX2 = maxX2 - 1; + findCFCells(lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, iNodeSetSender11); + } + break; + // edges + // N-S-E-W + case NE: + case SW: + case SE: + case NW: + if (sendDir == NE) { + lMinX1 = maxX1 - 2; + lMaxX1 = lMinX1 + 1; + lMinX2 = maxX2 - 2; + lMaxX2 = lMinX2 + 1; + } else if (sendDir == SW) { + lMinX1 = 0; + lMaxX1 = lMinX1 + 1; + lMinX2 = 0; + lMaxX2 = lMinX2 + 1; + } else if (sendDir == SE) { + lMinX1 = maxX1 - 2; + lMaxX1 = lMinX1 + 1; + lMinX2 = 0; + lMaxX2 = lMinX2 + 1; + } else if (sendDir == NW) { + lMinX1 = 0; + lMaxX1 = lMinX1 + 1; + lMinX2 = maxX2 - 2; + lMaxX2 = lMinX2 + 1; + } + + if (sender00) { + lMinX3 = minX3; + lMaxX3 = maxHalfX3; + findCFCells(lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, iNodeSetSender00); + } + if (sender10) { + lMinX3 = minHalfX3; + lMaxX3 = maxX3 - 1; + findCFCells(lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, iNodeSetSender10); + } + break; + // T-B-E-W + case TE: + case BW: + case BE: + case TW: + if (sendDir == TE) { + lMinX1 = maxX1 - 2; + lMaxX1 = lMinX1 + 1; + lMinX3 = maxX3 - 2; + lMaxX3 = lMinX3 + 1; + } else if (sendDir == BW) { + lMinX1 = 0; + lMaxX1 = lMinX1 + 2; + lMinX3 = 0; + lMaxX3 = lMinX3 + 2; + } else if (sendDir == BE) { + lMinX1 = maxX1 - 2; + lMaxX1 = lMinX1 + 1; + lMinX3 = 0; + lMaxX3 = lMinX3 + 1; + } else if (sendDir == TW) { + lMinX1 = 0; + lMaxX1 = lMinX1 + 1; + lMinX3 = maxX3 - 2; + lMaxX3 = lMinX3 + 1; + } + + if (sender00) { + lMinX2 = minX2; + lMaxX2 = maxHalfX2; + findCFCells(lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, iNodeSetSender00); + } + if (sender10) { + lMinX2 = minHalfX2; + lMaxX2 = maxX2 - 1; + findCFCells(lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, iNodeSetSender10); + } + break; + // T-B-N-S + case TN: + case BS: + case BN: + case TS: + if (sendDir == TN) { + lMinX2 = maxX2 - 2; + lMaxX2 = lMinX2 + 1; + lMinX3 = maxX3 - 3; + lMaxX3 = lMinX3 + 1; + } else if (sendDir == BS) { + lMinX2 = 0; + lMaxX2 = lMinX2 + 1; + lMinX3 = 0; + lMaxX3 = lMinX3 + 1; + } else if (sendDir == BN) { + lMinX2 = maxX2 - 2; + lMaxX2 = lMinX2 + 1; + lMinX3 = 0; + lMaxX3 = lMinX3 + 1; + } else if (sendDir == TS) { + lMinX2 = 0; + lMaxX2 = lMinX2 + 1; + lMinX3 = maxX3 - 2; + lMaxX3 = lMinX3 + 1; + } + + if (sender00) { + lMinX1 = minX1; + lMaxX1 = maxHalfX1; + findCFCells(lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, iNodeSetSender00); + } + if (sender10) { + lMinX1 = minHalfX1; + lMaxX1 = maxX1 - 1; + findCFCells(lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, iNodeSetSender10); + } + break; + // corners + case TNE: + case TNW: + case TSE: + case TSW: + case BNE: + case BNW: + case BSE: + case BSW: + if (sendDir == TNE) { + lMinX1 = maxX1 - 2; + lMaxX1 = maxX1 - 1; + lMinX2 = maxX2 - 2; + lMaxX2 = maxX2 - 1; + lMinX3 = maxX3 - 2; + lMaxX3 = maxX3 - 1; + } else if (sendDir == TNW) { + lMinX1 = 0; + lMaxX1 = 1; + lMinX2 = maxX2 - 2; + lMaxX2 = maxX2 - 1; + lMinX3 = maxX3 - 2; + lMaxX3 = maxX3 - 1; + } else if (sendDir == TSE) { + lMinX1 = maxX1 - 2; + lMaxX1 = maxX1 - 1; + lMinX2 = 0; + lMaxX2 = 1; + lMinX3 = maxX3 - 2; + lMaxX3 = maxX3 - 1; + } else if (sendDir == TSW) { + lMinX1 = 0; + lMaxX1 = 1; + lMinX2 = 0; + lMaxX2 = 1; + lMinX3 = maxX3 - 2; + lMaxX3 = maxX3 - 1; + } else if (sendDir == BNE) { + lMinX1 = maxX1 - 2; + lMaxX1 = maxX1 - 1; + lMinX2 = maxX2 - 2; + lMaxX2 = maxX2 - 1; + lMinX3 = 0; + lMaxX3 = 1; + } else if (sendDir == BNW) { + lMinX1 = 0; + lMaxX1 = 1; + lMinX2 = maxX2 - 2; + lMaxX2 = maxX2 - 1; + lMinX3 = 0; + lMaxX3 = 1; + } else if (sendDir == BSE) { + lMinX1 = maxX1 - 2; + lMaxX1 = maxX1 - 1; + lMinX2 = 0; + lMaxX2 = 1; + lMinX3 = 0; + lMaxX3 = 1; + } else if (sendDir == BSW) { + lMinX1 = 0; + lMaxX1 = 1; + lMinX2 = 0; + lMaxX2 = 1; + lMinX3 = 0; + lMaxX3 = 1; + } + if (sender00) { + findCFCells(lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, iNodeSetSender00); + } + break; + } } ////////////////////////////////////////////////////////////////////////// -//template< typename VectorTransmitter > +// template< typename VectorTransmitter > void CoarseToFineNodeSetBlock3DConnector::fillSendVectors() { - using namespace D3Q27System; - - SPtr<DistributionArray3D> fFrom = block.lock()->getKernel()->getDataSet()->getFdistributions(); - - int index00 = 0; - int index01 = 0; - int index10 = 0; - int index11 = 0; - - vector_type& data00 = this->sender00->getData(); - vector_type& data01 = this->sender01->getData(); - vector_type& data10 = this->sender10->getData(); - vector_type& data11 = this->sender11->getData(); - - for(INodeVector inode : iNodeSetSender00) - { - D3Q27ICell icellC; - D3Q27ICell icellF; - iprocessor->readICell(fFrom, icellC, inode[0], inode[1], inode[2]); - iprocessor->interpolateCoarseToFine(icellC, icellF, inode[3], inode[4], inode[5]); - writeICellFtoData(data00, index00, icellF); - } - for(INodeVector inode : iNodeSetSender01) - { - D3Q27ICell icellC; - D3Q27ICell icellF; - iprocessor->readICell(fFrom, icellC, inode[0], inode[1], inode[2]); - iprocessor->interpolateCoarseToFine(icellC, icellF, inode[3], inode[4], inode[5]); - writeICellFtoData(data01, index01, icellF); - } - for(INodeVector inode : iNodeSetSender10) - { - D3Q27ICell icellC; - D3Q27ICell icellF; - iprocessor->readICell(fFrom, icellC, inode[0], inode[1], inode[2]); - iprocessor->interpolateCoarseToFine(icellC, icellF, inode[3], inode[4], inode[5]); - writeICellFtoData(data10, index10, icellF); - } - for(INodeVector inode : iNodeSetSender11) - { - D3Q27ICell icellC; - D3Q27ICell icellF; - iprocessor->readICell(fFrom, icellC, inode[0], inode[1], inode[2]); - iprocessor->interpolateCoarseToFine(icellC, icellF, inode[3], inode[4], inode[5]); - writeICellFtoData(data11, index11, icellF); - } + using namespace D3Q27System; + + SPtr<DistributionArray3D> fFrom = block.lock()->getKernel()->getDataSet()->getFdistributions(); + + int index00 = 0; + int index01 = 0; + int index10 = 0; + int index11 = 0; + + vector_type &data00 = this->sender00->getData(); + vector_type &data01 = this->sender01->getData(); + vector_type &data10 = this->sender10->getData(); + vector_type &data11 = this->sender11->getData(); + + for (INodeVector inode : iNodeSetSender00) { + D3Q27ICell icellC; + D3Q27ICell icellF; + iprocessor->readICell(fFrom, icellC, inode[0], inode[1], inode[2]); + iprocessor->interpolateCoarseToFine(icellC, icellF, inode[3], inode[4], inode[5]); + writeICellFtoData(data00, index00, icellF); + } + for (INodeVector inode : iNodeSetSender01) { + D3Q27ICell icellC; + D3Q27ICell icellF; + iprocessor->readICell(fFrom, icellC, inode[0], inode[1], inode[2]); + iprocessor->interpolateCoarseToFine(icellC, icellF, inode[3], inode[4], inode[5]); + writeICellFtoData(data01, index01, icellF); + } + for (INodeVector inode : iNodeSetSender10) { + D3Q27ICell icellC; + D3Q27ICell icellF; + iprocessor->readICell(fFrom, icellC, inode[0], inode[1], inode[2]); + iprocessor->interpolateCoarseToFine(icellC, icellF, inode[3], inode[4], inode[5]); + writeICellFtoData(data10, index10, icellF); + } + for (INodeVector inode : iNodeSetSender11) { + D3Q27ICell icellC; + D3Q27ICell icellF; + iprocessor->readICell(fFrom, icellC, inode[0], inode[1], inode[2]); + iprocessor->interpolateCoarseToFine(icellC, icellF, inode[3], inode[4], inode[5]); + writeICellFtoData(data11, index11, icellF); + } } ////////////////////////////////////////////////////////////////////////// -void CoarseToFineNodeSetBlock3DConnector::writeICellFtoData(vector_type& data, int& index, D3Q27ICell& icellF) +void CoarseToFineNodeSetBlock3DConnector::writeICellFtoData(vector_type &data, int &index, D3Q27ICell &icellF) { - writeNodeToVector(data, index, icellF.BSW); - writeNodeToVector(data, index, icellF.BSE); - writeNodeToVector(data, index, icellF.BNW); - writeNodeToVector(data, index, icellF.BNE); - writeNodeToVector(data, index, icellF.TSW); - writeNodeToVector(data, index, icellF.TSE); - writeNodeToVector(data, index, icellF.TNW); - writeNodeToVector(data, index, icellF.TNE); + writeNodeToVector(data, index, icellF.BSW); + writeNodeToVector(data, index, icellF.BSE); + writeNodeToVector(data, index, icellF.BNW); + writeNodeToVector(data, index, icellF.BNE); + writeNodeToVector(data, index, icellF.TSW); + writeNodeToVector(data, index, icellF.TSE); + writeNodeToVector(data, index, icellF.TNW); + writeNodeToVector(data, index, icellF.TNE); } ////////////////////////////////////////////////////////////////////////// -void CoarseToFineNodeSetBlock3DConnector::writeNodeToVector(vector_type& data, int& index, LBMReal* inode) +void CoarseToFineNodeSetBlock3DConnector::writeNodeToVector(vector_type &data, int &index, LBMReal *inode) { - for (int i = D3Q27System::STARTF; i < D3Q27System::ENDF+1; i++) - { - data[index++] = inode[i]; - } + for (int i = D3Q27System::STARTF; i < D3Q27System::ENDF + 1; i++) { + data[index++] = inode[i]; + } } ////////////////////////////////////////////////////////////////////////// -void CoarseToFineNodeSetBlock3DConnector::findFCCells(int lMinX1, int lMinX2, int lMinX3, int lMaxX1, int lMaxX2, int lMaxX3, INodeSet &inodes) +void CoarseToFineNodeSetBlock3DConnector::findFCCells(int lMinX1, int lMinX2, int lMinX3, int lMaxX1, int lMaxX2, + int lMaxX3, INodeSet &inodes) { - int ix1, ix2, ix3; - - for (ix3 = lMinX3; ix3<=lMaxX3; ix3++) - { - for (ix2 = lMinX2; ix2<=lMaxX2; ix2++) - { - for (ix1 = lMinX1; ix1<=lMaxX1; ix1++) - { - INodeVector inv; - inv.push_back(ix1); - inv.push_back(ix2); - inv.push_back(ix3); - //inodes.insert(inv); - inodes.push_back(inv); - } - } - } + int ix1, ix2, ix3; + + for (ix3 = lMinX3; ix3 <= lMaxX3; ix3++) { + for (ix2 = lMinX2; ix2 <= lMaxX2; ix2++) { + for (ix1 = lMinX1; ix1 <= lMaxX1; ix1++) { + INodeVector inv; + inv.push_back(ix1); + inv.push_back(ix2); + inv.push_back(ix3); + // inodes.insert(inv); + inodes.push_back(inv); + } + } + } } ////////////////////////////////////////////////////////////////////////// -//template< typename VectorTransmitter > +// template< typename VectorTransmitter > void CoarseToFineNodeSetBlock3DConnector::findFCCells() { - using namespace D3Q27System; - - int lMin1X1, lMin1X2, lMin1X3, lMax1X1, lMax1X2, lMax1X3; - int lMin2X1, lMin2X2, lMin2X3, lMax2X1, lMax2X2, lMax2X3; - int lMin3X1, lMin3X2, lMin3X3, lMax3X1, lMax3X2, lMax3X3; - int dummy; - - switch (sendDir) - { - - ////////////////////////////////////////////////////// - //Debug - ////////////////////////////////////////////////////// - // if (block.lock()->getGlobalID() == 2234) - // { - // int test = 0; - // } - - //faces - case E: case W: - if (sendDir == E) - { - lMin1X1 = maxX1 - 3; - lMax1X1 = lMin1X1; - } - else if (sendDir == W) - { - lMin1X1 = 3; - lMax1X1 = lMin1X1; - } - - //int TminX1 = lMinX1; int TminX2 = lMinX2; int TminX3 = lMinX3; int TmaxX1 = lMaxX1; int TmaxX2 = lMaxX2; int TmaxX3 = lMaxX3; - - //if (block.lock()->hasInterpolationFlagCF(E)) - //{ - // if (maxX1==TmaxX1) maxX1 -= 2; - //} - //if (block.lock()->hasInterpolationFlagCF(W)) - //{ - // if (minX1==TminX1) minX1 += 2; - //} - //if (block.lock()->hasInterpolationFlagCF(N)) - //{ - // if (maxX2==TmaxX2) maxX2 -= 2; - //} - //if (block.lock()->hasInterpolationFlagCF(S)) - //{ - // if (minX2==TminX2) minX2 += 2; - //} - //if (block.lock()->hasInterpolationFlagCF(T)) - //{ - // if (maxX3==TmaxX3) maxX3 -= 2; - //} - //if (block.lock()->hasInterpolationFlagCF(B)) - //{ - // if (minX3==TminX3) minX3 += 2; - //} - if (receiver00) - { - lMin1X2 = minX2; - lMax1X2 = maxHalfX2; - lMin1X3 = minX3; - lMax1X3 = maxHalfX3; - getLocalMinMax(dummy, lMin1X2, lMin1X3, dummy, dummy, dummy); - findFCCells(lMin1X1, lMin1X2, lMin1X3, lMax1X1, lMax1X2, lMax1X3, iNodeSetReceiver00); - } - if (receiver10) - { - lMin1X2 = minHalfX2; - lMax1X2 = maxX2 - 1; - lMin1X3 = minX3; - lMax1X3 = maxHalfX3; - getLocalMinMax(dummy, dummy, lMin1X3, dummy, lMax1X2, dummy); - findFCCells(lMin1X1, lMin1X2, lMin1X3, lMax1X1, lMax1X2, lMax1X3, iNodeSetReceiver10); - } - if (receiver01) - { - lMin1X2 = minX2; - lMax1X2 = maxHalfX2; - lMin1X3 = minHalfX3; - lMax1X3 = maxX3 - 1; - getLocalMinMax(dummy, lMin1X2, dummy, dummy, dummy, lMax1X3); - findFCCells(lMin1X1, lMin1X2, lMin1X3, lMax1X1, lMax1X2, lMax1X3, iNodeSetReceiver01); - } - if (receiver11) - { - lMin1X2 = minHalfX2; - lMax1X2 = maxX2 - 1; - lMin1X3 = minHalfX3; - lMax1X3 = maxX3 - 1; - getLocalMinMax(dummy, dummy, dummy, dummy, lMax1X2, lMax1X3); - findFCCells(lMin1X1, lMin1X2, lMin1X3, lMax1X1, lMax1X2, lMax1X3, iNodeSetReceiver11); - } - break; - case N: case S: - if (sendDir == N) - { - lMin1X2 = maxX2 - 3; - lMax1X2 = lMin1X2; - } - else if (sendDir == S) - { - lMin1X2 = 3; - lMax1X2 = lMin1X2; - } - - if (receiver00) - { - lMin1X1 = minX1; - lMax1X1 = maxHalfX1; - lMin1X3 = minX3; - lMax1X3 = maxHalfX3; - findFCCells(lMin1X1, lMin1X2, lMin1X3, lMax1X1, lMax1X2, lMax1X3, iNodeSetReceiver00); - } - if (receiver10) - { - lMin1X1 = minHalfX1; - lMax1X1 = maxX1 - 1; - lMin1X3 = minX3; - lMax1X3 = maxHalfX3; - findFCCells(lMin1X1, lMin1X2, lMin1X3, lMax1X1, lMax1X2, lMax1X3, iNodeSetReceiver10); - } - if (receiver01) - { - lMin1X1 = minX1; - lMax1X1 = maxHalfX1; - lMin1X3 = minHalfX3; - lMax1X3 = maxX3 - 1; - findFCCells(lMin1X1, lMin1X2, lMin1X3, lMax1X1, lMax1X2, lMax1X3, iNodeSetReceiver01); - } - if (receiver11) - { - lMin1X1 = minHalfX1; - lMax1X1 = maxX1 - 1; - lMin1X3 = minHalfX3; - lMax1X3 = maxX3 - 1; - findFCCells(lMin1X1, lMin1X2, lMin1X3, lMax1X1, lMax1X2, lMax1X3, iNodeSetReceiver11); - } - break; - case T: case B: - if (sendDir == T) - { - lMin1X3 = maxX3 - 3; - lMax1X3 = lMin1X3; - } - else if (sendDir == B) - { - lMin1X3 = 3; - lMax1X3 = lMin1X3; - } - - if (receiver00) - { - lMin1X1 = minX1; - lMax1X1 = maxHalfX1; - lMin1X2 = minX2; - lMax1X2 = maxHalfX2; - findFCCells(lMin1X1, lMin1X2, lMin1X3, lMax1X1, lMax1X2, lMax1X3, iNodeSetReceiver00); - } - if (receiver10) - { - lMin1X1 = minHalfX1; - lMax1X1 = maxX1 - 1; - lMin1X2 = minX2; - lMax1X2 = maxHalfX2; - findFCCells(lMin1X1, lMin1X2, lMin1X3, lMax1X1, lMax1X2, lMax1X3, iNodeSetReceiver10); - } - if (receiver01) - { - lMin1X1 = minX1; - lMax1X1 = maxHalfX1; - lMin1X2 = minHalfX2; - lMax1X2 = maxX2 - 1; - findFCCells(lMin1X1, lMin1X2, lMin1X3, lMax1X1, lMax1X2, lMax1X3, iNodeSetReceiver01); - } - if (receiver11) - { - lMin1X1 = minHalfX1; - lMax1X1 = maxX1 - 1; - lMin1X2 = minHalfX2; - lMax1X2 = maxX2 - 1; - findFCCells(lMin1X1, lMin1X2, lMin1X3, lMax1X1, lMax1X2, lMax1X3, iNodeSetReceiver11); - } - break; - //edges - //N-S-E-W - case NE: case SW: case SE: case NW: - if (sendDir == NE) - { - lMin1X1 = maxX1 - 3; - lMax1X1 = lMin1X1 + 2; - lMin1X2 = maxX2 - 3; - lMax1X2 = lMin1X2; - - lMin2X1 = maxX1 - 3; - lMax2X1 = lMin2X1; - lMin2X2 = maxX2 - 3; - lMax2X2 = lMin2X2 + 2; - } - else if (sendDir == SW) - { - lMin1X1 = 1; - lMax1X1 = lMin1X1 + 2; - lMin1X2 = 3; - lMax1X2 = lMin1X2; - - lMin2X1 = 3; - lMax2X1 = lMin2X1; - lMin2X2 = 1; - lMax2X2 = lMin2X2 + 2; - } - else if (sendDir == SE) - { - lMin1X1 = maxX1 - 3; - lMax1X1 = lMin1X1 + 2; - lMin1X2 = 3; - lMax1X2 = lMin1X2; - - lMin2X1 = maxX1 - 3; - lMax2X1 = lMin2X1; - lMin2X2 = 1; - lMax2X2 = lMin2X2 + 2; - } - else if (sendDir == NW) - { - lMin1X1 = 1; - lMax1X1 = lMin1X1 + 2; - lMin1X2 = maxX2 - 3; - lMax1X2 = lMin1X2; - - lMin2X1 = 3; - lMax2X1 = lMin2X1; - lMin2X2 = maxX2 - 3; - lMax2X2 = lMin2X2 + 2; - } - - if (receiver00) - { - lMin1X3 = minX3; - lMax1X3 = maxHalfX3; - findFCCells(lMin1X1, lMin1X2, lMin1X3, lMax1X1, lMax1X2, lMax1X3, iNodeSetReceiver00); - } - if (receiver10) - { - lMin1X3 = minHalfX3; - lMax1X3 = maxX3 - 1; - findFCCells(lMin1X1, lMin1X2, lMin1X3, lMax1X1, lMax1X2, lMax1X3, iNodeSetReceiver10); - } - - if (receiver00) - { - lMin2X3 = minX3; - lMax2X3 = maxHalfX3; - findFCCells(lMin2X1, lMin2X2, lMin2X3, lMax2X1, lMax2X2, lMax2X3, iNodeSetReceiver00); - } - if (receiver10) - { - lMin2X3 = minHalfX3; - lMax2X3 = maxX3 - 1; - findFCCells(lMin2X1, lMin2X2, lMin2X3, lMax2X1, lMax2X2, lMax2X3, iNodeSetReceiver10); - } - break; - //T-B-E-W - case TE: case BW: case BE: case TW: - if (sendDir == TE) - { - lMin1X1 = maxX1 - 3; - lMax1X1 = lMin1X1 + 2; - lMin1X3 = maxX3 - 3; - lMax1X3 = lMin1X3; - - lMin2X1 = maxX1 - 3; - lMax2X1 = lMin2X1; - lMin2X3 = maxX3 - 3; - lMax2X3 = lMin2X3 + 2; - } - else if (sendDir == BW) - { - lMin1X1 = 1; - lMax1X1 = lMin1X1 + 2; - lMin1X3 = 3; - lMax1X3 = lMin1X3; - - lMin2X1 = 3; - lMax2X1 = lMin2X1; - lMin2X3 = 1; - lMax2X3 = lMin2X3 + 2; - } - else if (sendDir == BE) - { - lMin1X1 = maxX1 - 3; - lMax1X1 = lMin1X1 + 2; - lMin1X3 = 3; - lMax1X3 = lMin1X3; - - - lMin2X1 = maxX1 - 3; - lMax2X1 = lMin2X1; - lMin2X3 = 1; - lMax2X3 = lMin2X3 + 2; - } - else if (sendDir == TW) - { - lMin1X1 = 1; - lMax1X1 = lMin1X1 + 2; - lMin1X3 = maxX3 - 3; - lMax1X3 = lMin1X3; - - lMin2X1 = 3; - lMax2X1 = lMin2X1; - lMin2X3 = maxX3 - 3; - lMax2X3 = lMin2X3 + 2; - } - - if (receiver00) - { - lMin1X2 = minX2; - lMax1X2 = maxHalfX2; - findFCCells(lMin1X1, lMin1X2, lMin1X3, lMax1X1, lMax1X2, lMax1X3, iNodeSetReceiver00); - } - if (receiver10) - { - lMin1X2 = minHalfX2; - lMax1X2 = maxX2 - 1; - findFCCells(lMin1X1, lMin1X2, lMin1X3, lMax1X1, lMax1X2, lMax1X3, iNodeSetReceiver10); - } - - if (receiver00) - { - lMin2X2 = minX2; - lMax2X2 = maxHalfX2; - findFCCells(lMin2X1, lMin2X2, lMin2X3, lMax2X1, lMax2X2, lMax2X3, iNodeSetReceiver00); - } - if (receiver10) - { - lMin2X2 = minHalfX2; - lMax2X2 = maxX2 - 1; - findFCCells(lMin2X1, lMin2X2, lMin2X3, lMax2X1, lMax2X2, lMax2X3, iNodeSetReceiver10); - } - break; - //T-B-N-S - case TN: case BS: case BN: case TS: - if (sendDir == TN) - { - lMin1X2 = maxX2 - 3; - lMax1X2 = lMin1X2 + 2; - lMin1X3 = maxX3 - 3; - lMax1X3 = lMin1X3; - - lMin2X2 = maxX2 - 3; - lMax2X2 = lMin2X2; - lMin2X3 = maxX3 - 3; - lMax2X3 = lMin2X3 + 2; - } - else if (sendDir == BS) - { - lMin1X2 = 1; - lMax1X2 = lMin1X2 + 2; - lMin1X3 = 3; - lMax1X3 = lMin1X3; - - lMin2X2 = 3; - lMax2X2 = lMin2X2; - lMin2X3 = 1; - lMax2X3 = lMin2X3 + 2; - } - else if (sendDir == BN) - { - lMin1X2 = maxX2 - 3; - lMax1X2 = lMin1X2 + 2; - lMin1X3 = 3; - lMax1X3 = lMin1X3; - - lMin2X2 = maxX2 - 3; - lMax2X2 = lMin2X2; - lMin2X3 = 1; - lMax2X3 = lMin2X3 + 2; - } - else if (sendDir == TS) - { - lMin1X2 = 1; - lMax1X2 = lMin1X2 + 2; - lMin1X3 = maxX3 - 3; - lMax1X3 = lMin1X3; - - lMin2X2 = 3; - lMax2X2 = lMin2X2; - lMin2X3 = maxX3 - 3; - lMax2X3 = lMin2X3 + 2; - } - - if (receiver00) - { - lMin1X1 = minX1; - lMax1X1 = maxHalfX1; - findFCCells(lMin1X1, lMin1X2, lMin1X3, lMax1X1, lMax1X2, lMax1X3, iNodeSetReceiver00); - } - if (receiver10) - { - lMin1X1 = minHalfX1; - lMax1X1 = maxX1 - 1; - findFCCells(lMin1X1, lMin1X2, lMin1X3, lMax1X1, lMax1X2, lMax1X3, iNodeSetReceiver10); - } - - if (receiver00) - { - lMin2X1 = minX1; - lMax2X1 = maxHalfX1; - findFCCells(lMin2X1, lMin2X2, lMin2X3, lMax2X1, lMax2X2, lMax2X3, iNodeSetReceiver00); - } - if (receiver10) - { - lMin2X1 = minHalfX1; - lMax2X1 = maxX1 - 1; - findFCCells(lMin2X1, lMin2X2, lMin2X3, lMax2X1, lMax2X2, lMax2X3, iNodeSetReceiver10); - } - break; - //corners - case TNE: case TNW: case TSE: case TSW: case BNE: case BNW: case BSE: case BSW: - if (sendDir == TNE) - { - lMin1X1 = maxX1 - 3; - lMax1X1 = maxX1 - 2; - lMin1X2 = maxX2 - 3; - lMax1X2 = maxX2 - 1; - lMin1X3 = maxX3 - 3; - lMax1X3 = maxX3 - 1; - - lMin2X1 = maxX1 - 3; - lMax2X1 = maxX1 - 1; - lMin2X2 = maxX2 - 3; - lMax2X2 = maxX2 - 2; - lMin2X3 = maxX3 - 3; - lMax2X3 = maxX3 - 1; - - lMin3X1 = maxX1 - 3; - lMax3X1 = maxX1 - 1; - lMin3X2 = maxX2 - 3; - lMax3X2 = maxX2 - 1; - lMin3X3 = maxX3 - 3; - lMax3X3 = maxX3 - 2; - } - else if (sendDir == TNW) - { - lMin1X1 = 3; - lMax1X1 = 3; - lMin1X2 = maxX2 - 3; - lMax1X2 = maxX2 - 1; - lMin1X3 = maxX3 - 3; - lMax1X3 = maxX3 - 1; - - lMin2X1 = 1; - lMax2X1 = 3; - lMin2X2 = maxX2 - 3; - lMax2X2 = maxX2 - 2; - lMin2X3 = maxX3 - 3; - lMax2X3 = maxX3; - - lMin3X1 = 1; - lMax3X1 = 3; - lMin3X2 = maxX2 - 3; - lMax3X2 = maxX2 - 1; - lMin3X3 = maxX3 - 3; - lMax3X3 = maxX3 - 2; - } - else if (sendDir == TSE) - { - lMin1X1 = maxX1 - 3; - lMax1X1 = maxX1 - 2; - lMin1X2 = 1; - lMax1X2 = 3; - lMin1X3 = maxX3 - 3; - lMax1X3 = maxX3; - - lMin2X1 = maxX1 - 3; - lMax2X1 = maxX1 - 1; - lMin2X2 = 3; - lMax2X2 = 3; - lMin2X3 = maxX3 - 3; - lMax2X3 = maxX3; - - lMin3X1 = maxX1 - 3; - lMax3X1 = maxX1 - 1; - lMin3X2 = 1; - lMax3X2 = 3; - lMin3X3 = maxX3 - 3; - lMax3X3 = maxX3 - 2; - } - else if (sendDir == TSW) - { - lMin1X1 = 3; - lMax1X1 = 3; - lMin1X2 = 1; - lMax1X2 = 3; - lMin1X3 = maxX3 - 3; - lMax1X3 = maxX3 - 1; - - lMin2X1 = 1; - lMax2X1 = 3; - lMin2X2 = 3; - lMax2X2 = 3; - lMin2X3 = maxX3 - 3; - lMax2X3 = maxX3 - 1; - - lMin3X1 = 1; - lMax3X1 = 3; - lMin3X2 = 1; - lMax3X2 = 3; - lMin3X3 = maxX3 - 3; - lMax3X3 = maxX3 - 2; - } - else if (sendDir == BNE) - { - lMin1X1 = maxX1 - 3; - lMax1X1 = maxX1 - 2; - lMin1X2 = maxX2 - 3; - lMax1X2 = maxX2 - 1; - lMin1X3 = 1; - lMax1X3 = 3; - - lMin2X1 = maxX1 - 3; - lMax2X1 = maxX1 - 1; - lMin2X2 = maxX2 - 3; - lMax2X2 = maxX2 - 2; - lMin2X3 = 1; - lMax2X3 = 3; - - lMin3X1 = maxX1 - 3; - lMax3X1 = maxX1 - 1; - lMin3X2 = maxX2 - 3; - lMax3X2 = maxX2 - 1; - lMin3X3 = 3; - lMax3X3 = 3; - } - else if (sendDir == BNW) - { - lMin1X1 = 3; - lMax1X1 = 3; - lMin1X2 = maxX2 - 3; - lMax1X2 = maxX2 - 1; - lMin1X3 = 1; - lMax1X3 = 3; - - lMin2X1 = 1; - lMax2X1 = 3; - lMin2X2 = maxX2 - 3; - lMax2X2 = maxX2 - 2; - lMin2X3 = 1; - lMax2X3 = 3; - - lMin3X1 = 1; - lMax3X1 = 3; - lMin3X2 = maxX2 - 3; - lMax3X2 = maxX2 - 1; - lMin3X3 = 3; - lMax3X3 = 3; - } - else if (sendDir == BSE) - { - lMin1X1 = maxX1 - 3; - lMax1X1 = maxX1 - 2; - lMin1X2 = 1; - lMax1X2 = 3; - lMin1X3 = 1; - lMax1X3 = 3; - - lMin2X1 = maxX1 - 3; - lMax2X1 = maxX1 - 1; - lMin2X2 = 3; - lMax2X2 = 3; - lMin2X3 = 1; - lMax2X3 = 3; - - lMin3X1 = maxX1 - 3; - lMax3X1 = maxX1 - 1; - lMin3X2 = 1; - lMax3X2 = 3; - lMin3X3 = 3; - lMax3X3 = 3; - } - else if (sendDir == BSW) - { - lMin1X1 = 3; - lMax1X1 = 3; - lMin1X2 = 1; - lMax1X2 = 3; - lMin1X3 = 1; - lMax1X3 = 3; - - lMin2X1 = 1; - lMax2X1 = 3; - lMin2X2 = 3; - lMax2X2 = 3; - lMin2X3 = 1; - lMax2X3 = 3; - - lMin3X1 = 1; - lMax3X1 = 3; - lMin3X2 = 1; - lMax3X2 = 3; - lMin3X3 = 3; - lMax3X3 = 3; - } - if (receiver00) - { - findFCCells(lMin1X1, lMin1X2, lMin1X3, lMax1X1, lMax1X2, lMax1X3, iNodeSetReceiver00); - } - if (receiver00) - { - findFCCells(lMin2X1, lMin2X2, lMin2X3, lMax2X1, lMax2X2, lMax2X3, iNodeSetReceiver00); - } - if (receiver00) - { - findFCCells(lMin3X1, lMin3X2, lMin3X3, lMax3X1, lMax3X2, lMax3X3, iNodeSetReceiver00); - } - break; - } + using namespace D3Q27System; + + int lMin1X1, lMin1X2, lMin1X3, lMax1X1, lMax1X2, lMax1X3; + int lMin2X1, lMin2X2, lMin2X3, lMax2X1, lMax2X2, lMax2X3; + int lMin3X1, lMin3X2, lMin3X3, lMax3X1, lMax3X2, lMax3X3; + int dummy; + + switch (sendDir) { + + ////////////////////////////////////////////////////// + // Debug + ////////////////////////////////////////////////////// + // if (block.lock()->getGlobalID() == 2234) + // { + // int test = 0; + // } + + // faces + case E: + case W: + if (sendDir == E) { + lMin1X1 = maxX1 - 3; + lMax1X1 = lMin1X1; + } else if (sendDir == W) { + lMin1X1 = 3; + lMax1X1 = lMin1X1; + } + + // int TminX1 = lMinX1; int TminX2 = lMinX2; int TminX3 = lMinX3; int TmaxX1 = lMaxX1; int TmaxX2 = lMaxX2; + // int TmaxX3 = lMaxX3; + + // if (block.lock()->hasInterpolationFlagCF(E)) + //{ + // if (maxX1==TmaxX1) maxX1 -= 2; + //} + // if (block.lock()->hasInterpolationFlagCF(W)) + //{ + // if (minX1==TminX1) minX1 += 2; + //} + // if (block.lock()->hasInterpolationFlagCF(N)) + //{ + // if (maxX2==TmaxX2) maxX2 -= 2; + //} + // if (block.lock()->hasInterpolationFlagCF(S)) + //{ + // if (minX2==TminX2) minX2 += 2; + //} + // if (block.lock()->hasInterpolationFlagCF(T)) + //{ + // if (maxX3==TmaxX3) maxX3 -= 2; + //} + // if (block.lock()->hasInterpolationFlagCF(B)) + //{ + // if (minX3==TminX3) minX3 += 2; + //} + if (receiver00) { + lMin1X2 = minX2; + lMax1X2 = maxHalfX2; + lMin1X3 = minX3; + lMax1X3 = maxHalfX3; + getLocalMinMax(dummy, lMin1X2, lMin1X3, dummy, dummy, dummy); + findFCCells(lMin1X1, lMin1X2, lMin1X3, lMax1X1, lMax1X2, lMax1X3, iNodeSetReceiver00); + } + if (receiver10) { + lMin1X2 = minHalfX2; + lMax1X2 = maxX2 - 1; + lMin1X3 = minX3; + lMax1X3 = maxHalfX3; + getLocalMinMax(dummy, dummy, lMin1X3, dummy, lMax1X2, dummy); + findFCCells(lMin1X1, lMin1X2, lMin1X3, lMax1X1, lMax1X2, lMax1X3, iNodeSetReceiver10); + } + if (receiver01) { + lMin1X2 = minX2; + lMax1X2 = maxHalfX2; + lMin1X3 = minHalfX3; + lMax1X3 = maxX3 - 1; + getLocalMinMax(dummy, lMin1X2, dummy, dummy, dummy, lMax1X3); + findFCCells(lMin1X1, lMin1X2, lMin1X3, lMax1X1, lMax1X2, lMax1X3, iNodeSetReceiver01); + } + if (receiver11) { + lMin1X2 = minHalfX2; + lMax1X2 = maxX2 - 1; + lMin1X3 = minHalfX3; + lMax1X3 = maxX3 - 1; + getLocalMinMax(dummy, dummy, dummy, dummy, lMax1X2, lMax1X3); + findFCCells(lMin1X1, lMin1X2, lMin1X3, lMax1X1, lMax1X2, lMax1X3, iNodeSetReceiver11); + } + break; + case N: + case S: + if (sendDir == N) { + lMin1X2 = maxX2 - 3; + lMax1X2 = lMin1X2; + } else if (sendDir == S) { + lMin1X2 = 3; + lMax1X2 = lMin1X2; + } + + if (receiver00) { + lMin1X1 = minX1; + lMax1X1 = maxHalfX1; + lMin1X3 = minX3; + lMax1X3 = maxHalfX3; + findFCCells(lMin1X1, lMin1X2, lMin1X3, lMax1X1, lMax1X2, lMax1X3, iNodeSetReceiver00); + } + if (receiver10) { + lMin1X1 = minHalfX1; + lMax1X1 = maxX1 - 1; + lMin1X3 = minX3; + lMax1X3 = maxHalfX3; + findFCCells(lMin1X1, lMin1X2, lMin1X3, lMax1X1, lMax1X2, lMax1X3, iNodeSetReceiver10); + } + if (receiver01) { + lMin1X1 = minX1; + lMax1X1 = maxHalfX1; + lMin1X3 = minHalfX3; + lMax1X3 = maxX3 - 1; + findFCCells(lMin1X1, lMin1X2, lMin1X3, lMax1X1, lMax1X2, lMax1X3, iNodeSetReceiver01); + } + if (receiver11) { + lMin1X1 = minHalfX1; + lMax1X1 = maxX1 - 1; + lMin1X3 = minHalfX3; + lMax1X3 = maxX3 - 1; + findFCCells(lMin1X1, lMin1X2, lMin1X3, lMax1X1, lMax1X2, lMax1X3, iNodeSetReceiver11); + } + break; + case T: + case B: + if (sendDir == T) { + lMin1X3 = maxX3 - 3; + lMax1X3 = lMin1X3; + } else if (sendDir == B) { + lMin1X3 = 3; + lMax1X3 = lMin1X3; + } + + if (receiver00) { + lMin1X1 = minX1; + lMax1X1 = maxHalfX1; + lMin1X2 = minX2; + lMax1X2 = maxHalfX2; + findFCCells(lMin1X1, lMin1X2, lMin1X3, lMax1X1, lMax1X2, lMax1X3, iNodeSetReceiver00); + } + if (receiver10) { + lMin1X1 = minHalfX1; + lMax1X1 = maxX1 - 1; + lMin1X2 = minX2; + lMax1X2 = maxHalfX2; + findFCCells(lMin1X1, lMin1X2, lMin1X3, lMax1X1, lMax1X2, lMax1X3, iNodeSetReceiver10); + } + if (receiver01) { + lMin1X1 = minX1; + lMax1X1 = maxHalfX1; + lMin1X2 = minHalfX2; + lMax1X2 = maxX2 - 1; + findFCCells(lMin1X1, lMin1X2, lMin1X3, lMax1X1, lMax1X2, lMax1X3, iNodeSetReceiver01); + } + if (receiver11) { + lMin1X1 = minHalfX1; + lMax1X1 = maxX1 - 1; + lMin1X2 = minHalfX2; + lMax1X2 = maxX2 - 1; + findFCCells(lMin1X1, lMin1X2, lMin1X3, lMax1X1, lMax1X2, lMax1X3, iNodeSetReceiver11); + } + break; + // edges + // N-S-E-W + case NE: + case SW: + case SE: + case NW: + if (sendDir == NE) { + lMin1X1 = maxX1 - 3; + lMax1X1 = lMin1X1 + 2; + lMin1X2 = maxX2 - 3; + lMax1X2 = lMin1X2; + + lMin2X1 = maxX1 - 3; + lMax2X1 = lMin2X1; + lMin2X2 = maxX2 - 3; + lMax2X2 = lMin2X2 + 2; + } else if (sendDir == SW) { + lMin1X1 = 1; + lMax1X1 = lMin1X1 + 2; + lMin1X2 = 3; + lMax1X2 = lMin1X2; + + lMin2X1 = 3; + lMax2X1 = lMin2X1; + lMin2X2 = 1; + lMax2X2 = lMin2X2 + 2; + } else if (sendDir == SE) { + lMin1X1 = maxX1 - 3; + lMax1X1 = lMin1X1 + 2; + lMin1X2 = 3; + lMax1X2 = lMin1X2; + + lMin2X1 = maxX1 - 3; + lMax2X1 = lMin2X1; + lMin2X2 = 1; + lMax2X2 = lMin2X2 + 2; + } else if (sendDir == NW) { + lMin1X1 = 1; + lMax1X1 = lMin1X1 + 2; + lMin1X2 = maxX2 - 3; + lMax1X2 = lMin1X2; + + lMin2X1 = 3; + lMax2X1 = lMin2X1; + lMin2X2 = maxX2 - 3; + lMax2X2 = lMin2X2 + 2; + } + + if (receiver00) { + lMin1X3 = minX3; + lMax1X3 = maxHalfX3; + findFCCells(lMin1X1, lMin1X2, lMin1X3, lMax1X1, lMax1X2, lMax1X3, iNodeSetReceiver00); + } + if (receiver10) { + lMin1X3 = minHalfX3; + lMax1X3 = maxX3 - 1; + findFCCells(lMin1X1, lMin1X2, lMin1X3, lMax1X1, lMax1X2, lMax1X3, iNodeSetReceiver10); + } + + if (receiver00) { + lMin2X3 = minX3; + lMax2X3 = maxHalfX3; + findFCCells(lMin2X1, lMin2X2, lMin2X3, lMax2X1, lMax2X2, lMax2X3, iNodeSetReceiver00); + } + if (receiver10) { + lMin2X3 = minHalfX3; + lMax2X3 = maxX3 - 1; + findFCCells(lMin2X1, lMin2X2, lMin2X3, lMax2X1, lMax2X2, lMax2X3, iNodeSetReceiver10); + } + break; + // T-B-E-W + case TE: + case BW: + case BE: + case TW: + if (sendDir == TE) { + lMin1X1 = maxX1 - 3; + lMax1X1 = lMin1X1 + 2; + lMin1X3 = maxX3 - 3; + lMax1X3 = lMin1X3; + + lMin2X1 = maxX1 - 3; + lMax2X1 = lMin2X1; + lMin2X3 = maxX3 - 3; + lMax2X3 = lMin2X3 + 2; + } else if (sendDir == BW) { + lMin1X1 = 1; + lMax1X1 = lMin1X1 + 2; + lMin1X3 = 3; + lMax1X3 = lMin1X3; + + lMin2X1 = 3; + lMax2X1 = lMin2X1; + lMin2X3 = 1; + lMax2X3 = lMin2X3 + 2; + } else if (sendDir == BE) { + lMin1X1 = maxX1 - 3; + lMax1X1 = lMin1X1 + 2; + lMin1X3 = 3; + lMax1X3 = lMin1X3; + + lMin2X1 = maxX1 - 3; + lMax2X1 = lMin2X1; + lMin2X3 = 1; + lMax2X3 = lMin2X3 + 2; + } else if (sendDir == TW) { + lMin1X1 = 1; + lMax1X1 = lMin1X1 + 2; + lMin1X3 = maxX3 - 3; + lMax1X3 = lMin1X3; + + lMin2X1 = 3; + lMax2X1 = lMin2X1; + lMin2X3 = maxX3 - 3; + lMax2X3 = lMin2X3 + 2; + } + + if (receiver00) { + lMin1X2 = minX2; + lMax1X2 = maxHalfX2; + findFCCells(lMin1X1, lMin1X2, lMin1X3, lMax1X1, lMax1X2, lMax1X3, iNodeSetReceiver00); + } + if (receiver10) { + lMin1X2 = minHalfX2; + lMax1X2 = maxX2 - 1; + findFCCells(lMin1X1, lMin1X2, lMin1X3, lMax1X1, lMax1X2, lMax1X3, iNodeSetReceiver10); + } + + if (receiver00) { + lMin2X2 = minX2; + lMax2X2 = maxHalfX2; + findFCCells(lMin2X1, lMin2X2, lMin2X3, lMax2X1, lMax2X2, lMax2X3, iNodeSetReceiver00); + } + if (receiver10) { + lMin2X2 = minHalfX2; + lMax2X2 = maxX2 - 1; + findFCCells(lMin2X1, lMin2X2, lMin2X3, lMax2X1, lMax2X2, lMax2X3, iNodeSetReceiver10); + } + break; + // T-B-N-S + case TN: + case BS: + case BN: + case TS: + if (sendDir == TN) { + lMin1X2 = maxX2 - 3; + lMax1X2 = lMin1X2 + 2; + lMin1X3 = maxX3 - 3; + lMax1X3 = lMin1X3; + + lMin2X2 = maxX2 - 3; + lMax2X2 = lMin2X2; + lMin2X3 = maxX3 - 3; + lMax2X3 = lMin2X3 + 2; + } else if (sendDir == BS) { + lMin1X2 = 1; + lMax1X2 = lMin1X2 + 2; + lMin1X3 = 3; + lMax1X3 = lMin1X3; + + lMin2X2 = 3; + lMax2X2 = lMin2X2; + lMin2X3 = 1; + lMax2X3 = lMin2X3 + 2; + } else if (sendDir == BN) { + lMin1X2 = maxX2 - 3; + lMax1X2 = lMin1X2 + 2; + lMin1X3 = 3; + lMax1X3 = lMin1X3; + + lMin2X2 = maxX2 - 3; + lMax2X2 = lMin2X2; + lMin2X3 = 1; + lMax2X3 = lMin2X3 + 2; + } else if (sendDir == TS) { + lMin1X2 = 1; + lMax1X2 = lMin1X2 + 2; + lMin1X3 = maxX3 - 3; + lMax1X3 = lMin1X3; + + lMin2X2 = 3; + lMax2X2 = lMin2X2; + lMin2X3 = maxX3 - 3; + lMax2X3 = lMin2X3 + 2; + } + + if (receiver00) { + lMin1X1 = minX1; + lMax1X1 = maxHalfX1; + findFCCells(lMin1X1, lMin1X2, lMin1X3, lMax1X1, lMax1X2, lMax1X3, iNodeSetReceiver00); + } + if (receiver10) { + lMin1X1 = minHalfX1; + lMax1X1 = maxX1 - 1; + findFCCells(lMin1X1, lMin1X2, lMin1X3, lMax1X1, lMax1X2, lMax1X3, iNodeSetReceiver10); + } + + if (receiver00) { + lMin2X1 = minX1; + lMax2X1 = maxHalfX1; + findFCCells(lMin2X1, lMin2X2, lMin2X3, lMax2X1, lMax2X2, lMax2X3, iNodeSetReceiver00); + } + if (receiver10) { + lMin2X1 = minHalfX1; + lMax2X1 = maxX1 - 1; + findFCCells(lMin2X1, lMin2X2, lMin2X3, lMax2X1, lMax2X2, lMax2X3, iNodeSetReceiver10); + } + break; + // corners + case TNE: + case TNW: + case TSE: + case TSW: + case BNE: + case BNW: + case BSE: + case BSW: + if (sendDir == TNE) { + lMin1X1 = maxX1 - 3; + lMax1X1 = maxX1 - 2; + lMin1X2 = maxX2 - 3; + lMax1X2 = maxX2 - 1; + lMin1X3 = maxX3 - 3; + lMax1X3 = maxX3 - 1; + + lMin2X1 = maxX1 - 3; + lMax2X1 = maxX1 - 1; + lMin2X2 = maxX2 - 3; + lMax2X2 = maxX2 - 2; + lMin2X3 = maxX3 - 3; + lMax2X3 = maxX3 - 1; + + lMin3X1 = maxX1 - 3; + lMax3X1 = maxX1 - 1; + lMin3X2 = maxX2 - 3; + lMax3X2 = maxX2 - 1; + lMin3X3 = maxX3 - 3; + lMax3X3 = maxX3 - 2; + } else if (sendDir == TNW) { + lMin1X1 = 3; + lMax1X1 = 3; + lMin1X2 = maxX2 - 3; + lMax1X2 = maxX2 - 1; + lMin1X3 = maxX3 - 3; + lMax1X3 = maxX3 - 1; + + lMin2X1 = 1; + lMax2X1 = 3; + lMin2X2 = maxX2 - 3; + lMax2X2 = maxX2 - 2; + lMin2X3 = maxX3 - 3; + lMax2X3 = maxX3; + + lMin3X1 = 1; + lMax3X1 = 3; + lMin3X2 = maxX2 - 3; + lMax3X2 = maxX2 - 1; + lMin3X3 = maxX3 - 3; + lMax3X3 = maxX3 - 2; + } else if (sendDir == TSE) { + lMin1X1 = maxX1 - 3; + lMax1X1 = maxX1 - 2; + lMin1X2 = 1; + lMax1X2 = 3; + lMin1X3 = maxX3 - 3; + lMax1X3 = maxX3; + + lMin2X1 = maxX1 - 3; + lMax2X1 = maxX1 - 1; + lMin2X2 = 3; + lMax2X2 = 3; + lMin2X3 = maxX3 - 3; + lMax2X3 = maxX3; + + lMin3X1 = maxX1 - 3; + lMax3X1 = maxX1 - 1; + lMin3X2 = 1; + lMax3X2 = 3; + lMin3X3 = maxX3 - 3; + lMax3X3 = maxX3 - 2; + } else if (sendDir == TSW) { + lMin1X1 = 3; + lMax1X1 = 3; + lMin1X2 = 1; + lMax1X2 = 3; + lMin1X3 = maxX3 - 3; + lMax1X3 = maxX3 - 1; + + lMin2X1 = 1; + lMax2X1 = 3; + lMin2X2 = 3; + lMax2X2 = 3; + lMin2X3 = maxX3 - 3; + lMax2X3 = maxX3 - 1; + + lMin3X1 = 1; + lMax3X1 = 3; + lMin3X2 = 1; + lMax3X2 = 3; + lMin3X3 = maxX3 - 3; + lMax3X3 = maxX3 - 2; + } else if (sendDir == BNE) { + lMin1X1 = maxX1 - 3; + lMax1X1 = maxX1 - 2; + lMin1X2 = maxX2 - 3; + lMax1X2 = maxX2 - 1; + lMin1X3 = 1; + lMax1X3 = 3; + + lMin2X1 = maxX1 - 3; + lMax2X1 = maxX1 - 1; + lMin2X2 = maxX2 - 3; + lMax2X2 = maxX2 - 2; + lMin2X3 = 1; + lMax2X3 = 3; + + lMin3X1 = maxX1 - 3; + lMax3X1 = maxX1 - 1; + lMin3X2 = maxX2 - 3; + lMax3X2 = maxX2 - 1; + lMin3X3 = 3; + lMax3X3 = 3; + } else if (sendDir == BNW) { + lMin1X1 = 3; + lMax1X1 = 3; + lMin1X2 = maxX2 - 3; + lMax1X2 = maxX2 - 1; + lMin1X3 = 1; + lMax1X3 = 3; + + lMin2X1 = 1; + lMax2X1 = 3; + lMin2X2 = maxX2 - 3; + lMax2X2 = maxX2 - 2; + lMin2X3 = 1; + lMax2X3 = 3; + + lMin3X1 = 1; + lMax3X1 = 3; + lMin3X2 = maxX2 - 3; + lMax3X2 = maxX2 - 1; + lMin3X3 = 3; + lMax3X3 = 3; + } else if (sendDir == BSE) { + lMin1X1 = maxX1 - 3; + lMax1X1 = maxX1 - 2; + lMin1X2 = 1; + lMax1X2 = 3; + lMin1X3 = 1; + lMax1X3 = 3; + + lMin2X1 = maxX1 - 3; + lMax2X1 = maxX1 - 1; + lMin2X2 = 3; + lMax2X2 = 3; + lMin2X3 = 1; + lMax2X3 = 3; + + lMin3X1 = maxX1 - 3; + lMax3X1 = maxX1 - 1; + lMin3X2 = 1; + lMax3X2 = 3; + lMin3X3 = 3; + lMax3X3 = 3; + } else if (sendDir == BSW) { + lMin1X1 = 3; + lMax1X1 = 3; + lMin1X2 = 1; + lMax1X2 = 3; + lMin1X3 = 1; + lMax1X3 = 3; + + lMin2X1 = 1; + lMax2X1 = 3; + lMin2X2 = 3; + lMax2X2 = 3; + lMin2X3 = 1; + lMax2X3 = 3; + + lMin3X1 = 1; + lMax3X1 = 3; + lMin3X2 = 1; + lMax3X2 = 3; + lMin3X3 = 3; + lMax3X3 = 3; + } + if (receiver00) { + findFCCells(lMin1X1, lMin1X2, lMin1X3, lMax1X1, lMax1X2, lMax1X3, iNodeSetReceiver00); + } + if (receiver00) { + findFCCells(lMin2X1, lMin2X2, lMin2X3, lMax2X1, lMax2X2, lMax2X3, iNodeSetReceiver00); + } + if (receiver00) { + findFCCells(lMin3X1, lMin3X2, lMin3X3, lMax3X1, lMax3X2, lMax3X3, iNodeSetReceiver00); + } + break; + } } ////////////////////////////////////////////////////////////////////////// -//template< typename VectorTransmitter > +// template< typename VectorTransmitter > void CoarseToFineNodeSetBlock3DConnector::distributeReceiveVectors() { - using namespace D3Q27System; - - SPtr<DistributionArray3D> fTo = block.lock()->getKernel()->getDataSet()->getFdistributions(); - - int index00 = 0; - int index01 = 0; - int index10 = 0; - int index11 = 0; - - vector_type& data00 = this->receiver00->getData(); - vector_type& data01 = this->receiver01->getData(); - vector_type& data10 = this->receiver10->getData(); - vector_type& data11 = this->receiver11->getData(); - - for(INodeVector inode : iNodeSetReceiver00) - { - LBMReal icellC[27]; - this->readICellCfromData(data00, index00, icellC); - iprocessor->writeINodeInv(fTo, icellC, inode[0], inode[1], inode[2]); - } - for(INodeVector inode : iNodeSetReceiver01) - { - LBMReal icellC[27]; - this->readICellCfromData(data01, index01, icellC); - iprocessor->writeINodeInv(fTo, icellC, inode[0], inode[1], inode[2]); - } - for(INodeVector inode : iNodeSetReceiver10) - { - LBMReal icellC[27]; - this->readICellCfromData(data10, index10, icellC); - iprocessor->writeINodeInv(fTo, icellC, inode[0], inode[1], inode[2]); - } - for(INodeVector inode : iNodeSetReceiver11) - { - LBMReal icellC[27]; - this->readICellCfromData(data11, index11, icellC); - iprocessor->writeINodeInv(fTo, icellC, inode[0], inode[1], inode[2]); - } + using namespace D3Q27System; + + SPtr<DistributionArray3D> fTo = block.lock()->getKernel()->getDataSet()->getFdistributions(); + + int index00 = 0; + int index01 = 0; + int index10 = 0; + int index11 = 0; + + vector_type &data00 = this->receiver00->getData(); + vector_type &data01 = this->receiver01->getData(); + vector_type &data10 = this->receiver10->getData(); + vector_type &data11 = this->receiver11->getData(); + + for (INodeVector inode : iNodeSetReceiver00) { + LBMReal icellC[27]; + this->readICellCfromData(data00, index00, icellC); + iprocessor->writeINodeInv(fTo, icellC, inode[0], inode[1], inode[2]); + } + for (INodeVector inode : iNodeSetReceiver01) { + LBMReal icellC[27]; + this->readICellCfromData(data01, index01, icellC); + iprocessor->writeINodeInv(fTo, icellC, inode[0], inode[1], inode[2]); + } + for (INodeVector inode : iNodeSetReceiver10) { + LBMReal icellC[27]; + this->readICellCfromData(data10, index10, icellC); + iprocessor->writeINodeInv(fTo, icellC, inode[0], inode[1], inode[2]); + } + for (INodeVector inode : iNodeSetReceiver11) { + LBMReal icellC[27]; + this->readICellCfromData(data11, index11, icellC); + iprocessor->writeINodeInv(fTo, icellC, inode[0], inode[1], inode[2]); + } } ////////////////////////////////////////////////////////////////////////// -void CoarseToFineNodeSetBlock3DConnector::readICellCfromData(vector_type& data, int& index, LBMReal* icellC) +void CoarseToFineNodeSetBlock3DConnector::readICellCfromData(vector_type &data, int &index, LBMReal *icellC) { - for (int i = D3Q27System::STARTF; i < D3Q27System::ENDF+1; i++) - { - icellC[i] = data[index++]; - } + for (int i = D3Q27System::STARTF; i < D3Q27System::ENDF + 1; i++) { + icellC[i] = data[index++]; + } } ////////////////////////////////////////////////////////////////////////// -void CoarseToFineNodeSetBlock3DConnector::getLocalMinMax(int& minX1, int& minX2, int& minX3, int& maxX1, int& maxX2, int& maxX3) +void CoarseToFineNodeSetBlock3DConnector::getLocalMinMax(int &minX1, int &minX2, int &minX3, int &maxX1, int &maxX2, + int &maxX3) { - using namespace D3Q27System; - int TminX1 = minX1; int TminX2 = minX2; int TminX3 = minX3; int TmaxX1 = maxX1; int TmaxX2 = maxX2; int TmaxX3 = maxX3; - - if (block.lock()->hasInterpolationFlagCF(E)) - { - if (maxX1==TmaxX1) maxX1 -= 2; - } - if (block.lock()->hasInterpolationFlagCF(W)) - { - if (minX1==TminX1) minX1 += 2; - } - if (block.lock()->hasInterpolationFlagCF(N)) - { - if (maxX2==TmaxX2) maxX2 -= 2; - } - if (block.lock()->hasInterpolationFlagCF(S)) - { - if (minX2==TminX2) minX2 += 2; - } - if (block.lock()->hasInterpolationFlagCF(T)) - { - if (maxX3==TmaxX3) maxX3 -= 2; - } - if (block.lock()->hasInterpolationFlagCF(B)) - { - if (minX3==TminX3) minX3 += 2; - } - - //E-W-N-S - if (block.lock()->hasInterpolationFlagCF(NE) && !block.lock()->hasInterpolationFlagCF(N) && !block.lock()->hasInterpolationFlagCF(E)) - { - if (maxX1==TmaxX1) maxX1 -= 2; - if (maxX2==TmaxX2) maxX2 -= 2; - } - if (block.lock()->hasInterpolationFlagCF(SW) && !block.lock()->hasInterpolationFlagCF(W) && !block.lock()->hasInterpolationFlagCF(S)) - { - if (minX1==TminX1) minX1 += 2; - if (minX2==TminX2) minX2 += 2; - } - if (block.lock()->hasInterpolationFlagCF(SE) && !block.lock()->hasInterpolationFlagCF(E) && !block.lock()->hasInterpolationFlagCF(S)) - { - if (maxX1==TmaxX1) maxX1 -= 2; - if (minX2==TminX2) minX2 += 2; - } - if (block.lock()->hasInterpolationFlagCF(NW) && !block.lock()->hasInterpolationFlagCF(N) && !block.lock()->hasInterpolationFlagCF(W)) - { - if (minX1==TminX1) minX1 += 2; - if (maxX2==TmaxX2) maxX2 -= 2; - } - - // ////T-B-E-W - if (block.lock()->hasInterpolationFlagCF(TE) && !block.lock()->hasInterpolationFlagCF(E) && !block.lock()->hasInterpolationFlagCF(T)) - { - if (maxX1==TmaxX1) maxX1 -= 2; - if (maxX3==TmaxX3) maxX3 -= 2; - } - if (block.lock()->hasInterpolationFlagCF(BW) && !block.lock()->hasInterpolationFlagCF(W) && !block.lock()->hasInterpolationFlagCF(B)) - { - if (minX1==TminX1) minX1 += 2; - if (minX3==TminX3) minX3 += 2; - } - if (block.lock()->hasInterpolationFlagCF(BE) && !block.lock()->hasInterpolationFlagCF(E) && !block.lock()->hasInterpolationFlagCF(B)) - { - if (maxX1==TmaxX1) maxX1 -= 2; - if (minX3==TminX3) minX3 += 2; - } - if (block.lock()->hasInterpolationFlagCF(TW) && !block.lock()->hasInterpolationFlagCF(W) && !block.lock()->hasInterpolationFlagCF(T)) - { - if (minX1==TminX1) minX1 += 2; - if (maxX3==TmaxX3) maxX3 -= 2; - } - - - ////T-B-N-S - if (block.lock()->hasInterpolationFlagCF(TN) && !block.lock()->hasInterpolationFlagCF(N) && !block.lock()->hasInterpolationFlagCF(T)) - { - if (maxX2==TmaxX2) maxX2 -= 2; - if (maxX3==TmaxX3) maxX3 -= 2; - } - if (block.lock()->hasInterpolationFlagCF(BS) && !block.lock()->hasInterpolationFlagCF(S) && !block.lock()->hasInterpolationFlagCF(B)) - { - if (minX2==TminX2) minX2 += 2; - if (minX3==TminX3) minX3 += 2; - } - if (block.lock()->hasInterpolationFlagCF(BN) && !block.lock()->hasInterpolationFlagCF(N) && !block.lock()->hasInterpolationFlagCF(B)) - { - if (maxX2==TmaxX2) maxX2 -= 2; - if (minX3==TminX3) minX3 += 2; - } - if (block.lock()->hasInterpolationFlagCF(TS) && !block.lock()->hasInterpolationFlagCF(S) && !block.lock()->hasInterpolationFlagCF(T)) - { - if (minX2==TminX2) minX2 += 2; - if (maxX3==TmaxX3) maxX3 -= 2; - } + using namespace D3Q27System; + int TminX1 = minX1; + int TminX2 = minX2; + int TminX3 = minX3; + int TmaxX1 = maxX1; + int TmaxX2 = maxX2; + int TmaxX3 = maxX3; + + if (block.lock()->hasInterpolationFlagCF(E)) { + if (maxX1 == TmaxX1) + maxX1 -= 2; + } + if (block.lock()->hasInterpolationFlagCF(W)) { + if (minX1 == TminX1) + minX1 += 2; + } + if (block.lock()->hasInterpolationFlagCF(N)) { + if (maxX2 == TmaxX2) + maxX2 -= 2; + } + if (block.lock()->hasInterpolationFlagCF(S)) { + if (minX2 == TminX2) + minX2 += 2; + } + if (block.lock()->hasInterpolationFlagCF(T)) { + if (maxX3 == TmaxX3) + maxX3 -= 2; + } + if (block.lock()->hasInterpolationFlagCF(B)) { + if (minX3 == TminX3) + minX3 += 2; + } + + // E-W-N-S + if (block.lock()->hasInterpolationFlagCF(NE) && !block.lock()->hasInterpolationFlagCF(N) && + !block.lock()->hasInterpolationFlagCF(E)) { + if (maxX1 == TmaxX1) + maxX1 -= 2; + if (maxX2 == TmaxX2) + maxX2 -= 2; + } + if (block.lock()->hasInterpolationFlagCF(SW) && !block.lock()->hasInterpolationFlagCF(W) && + !block.lock()->hasInterpolationFlagCF(S)) { + if (minX1 == TminX1) + minX1 += 2; + if (minX2 == TminX2) + minX2 += 2; + } + if (block.lock()->hasInterpolationFlagCF(SE) && !block.lock()->hasInterpolationFlagCF(E) && + !block.lock()->hasInterpolationFlagCF(S)) { + if (maxX1 == TmaxX1) + maxX1 -= 2; + if (minX2 == TminX2) + minX2 += 2; + } + if (block.lock()->hasInterpolationFlagCF(NW) && !block.lock()->hasInterpolationFlagCF(N) && + !block.lock()->hasInterpolationFlagCF(W)) { + if (minX1 == TminX1) + minX1 += 2; + if (maxX2 == TmaxX2) + maxX2 -= 2; + } + + // ////T-B-E-W + if (block.lock()->hasInterpolationFlagCF(TE) && !block.lock()->hasInterpolationFlagCF(E) && + !block.lock()->hasInterpolationFlagCF(T)) { + if (maxX1 == TmaxX1) + maxX1 -= 2; + if (maxX3 == TmaxX3) + maxX3 -= 2; + } + if (block.lock()->hasInterpolationFlagCF(BW) && !block.lock()->hasInterpolationFlagCF(W) && + !block.lock()->hasInterpolationFlagCF(B)) { + if (minX1 == TminX1) + minX1 += 2; + if (minX3 == TminX3) + minX3 += 2; + } + if (block.lock()->hasInterpolationFlagCF(BE) && !block.lock()->hasInterpolationFlagCF(E) && + !block.lock()->hasInterpolationFlagCF(B)) { + if (maxX1 == TmaxX1) + maxX1 -= 2; + if (minX3 == TminX3) + minX3 += 2; + } + if (block.lock()->hasInterpolationFlagCF(TW) && !block.lock()->hasInterpolationFlagCF(W) && + !block.lock()->hasInterpolationFlagCF(T)) { + if (minX1 == TminX1) + minX1 += 2; + if (maxX3 == TmaxX3) + maxX3 -= 2; + } + + ////T-B-N-S + if (block.lock()->hasInterpolationFlagCF(TN) && !block.lock()->hasInterpolationFlagCF(N) && + !block.lock()->hasInterpolationFlagCF(T)) { + if (maxX2 == TmaxX2) + maxX2 -= 2; + if (maxX3 == TmaxX3) + maxX3 -= 2; + } + if (block.lock()->hasInterpolationFlagCF(BS) && !block.lock()->hasInterpolationFlagCF(S) && + !block.lock()->hasInterpolationFlagCF(B)) { + if (minX2 == TminX2) + minX2 += 2; + if (minX3 == TminX3) + minX3 += 2; + } + if (block.lock()->hasInterpolationFlagCF(BN) && !block.lock()->hasInterpolationFlagCF(N) && + !block.lock()->hasInterpolationFlagCF(B)) { + if (maxX2 == TmaxX2) + maxX2 -= 2; + if (minX3 == TminX3) + minX3 += 2; + } + if (block.lock()->hasInterpolationFlagCF(TS) && !block.lock()->hasInterpolationFlagCF(S) && + !block.lock()->hasInterpolationFlagCF(T)) { + if (minX2 == TminX2) + minX2 += 2; + if (maxX3 == TmaxX3) + maxX3 -= 2; + } } - - diff --git a/src/cpu/VirtualFluidsCore/Connectors/CoarseToFineNodeSetBlock3DConnector.h b/src/cpu/VirtualFluidsCore/Connectors/CoarseToFineNodeSetBlock3DConnector.h index ae8f09b16c4a55034e488b04051260aa3f4c9240..4e71916d4a489a7d834c360c21caafa5bb42526d 100644 --- a/src/cpu/VirtualFluidsCore/Connectors/CoarseToFineNodeSetBlock3DConnector.h +++ b/src/cpu/VirtualFluidsCore/Connectors/CoarseToFineNodeSetBlock3DConnector.h @@ -1,103 +1,98 @@ //! \file CoarseToFineNodeSetBlock3DConnector.h //! \class CoarseToFineNodeSetBlock3DConnector -//! \brief Connector interpolates and sends data from coarse level to fine. +//! \brief Connector interpolates and sends data from coarse level to fine. //! \author Konstantin Kutscher //! \date 18.05.2015 #ifndef CoarseToFineNodeSetBlock3DConnector_H #define CoarseToFineNodeSetBlock3DConnector_H -#include <vector> #include <set> +#include <vector> //#include "basics/transmitter/TbTransmitter.h" //#include "basics/transmitter/TbTransmitterLocal.h" //#include "basics/container/CbVector.h" +#include "BCProcessor.h" +#include "Block3D.h" #include "CoarseToFineBlock3DConnector.h" #include "D3Q27System.h" -#include "Block3D.h" -#include "LBMKernel.h" -#include "BCProcessor.h" +#include "Grid3D.h" #include "InterpolationProcessor.h" +#include "LBMKernel.h" #include "MathUtil.hpp" -#include "Grid3D.h" #include <PointerDefinitions.h> - class Block3D; -//daten werden in einen vector (dieser befindet sich im transmitter) kopiert -//der vector wird via transmitter uebertragen -//transmitter kann ein lokal, MPI, RCG, CTL oder was auch immer fuer ein -//transmitter sein, der von Transmitter abgeleitet ist ;-) - - -// send direction: E<->W N<->S T<->B -// --------- x3 x3 x2 -// | 01 | 11 | ^ ^ ^ -// |----+----| +-> x2 +->x1 +->x1 -// | 00 | 10 | -// --------- +// daten werden in einen vector (dieser befindet sich im transmitter) kopiert +// der vector wird via transmitter uebertragen +// transmitter kann ein lokal, MPI, RCG, CTL oder was auch immer fuer ein +// transmitter sein, der von Transmitter abgeleitet ist ;-) +// send direction: E<->W N<->S T<->B +// --------- x3 x3 x2 +// | 01 | 11 | ^ ^ ^ +// |----+----| +-> x2 +->x1 +->x1 +// | 00 | 10 | +// --------- class CoarseToFineNodeSetBlock3DConnector : public CoarseToFineBlock3DConnector { public: - CoarseToFineNodeSetBlock3DConnector(SPtr<Block3D> block, - VectorTransmitterPtr sender00, VectorTransmitterPtr receiver00, - VectorTransmitterPtr sender01, VectorTransmitterPtr receiver01, - VectorTransmitterPtr sender10, VectorTransmitterPtr receiver10, - VectorTransmitterPtr sender11, VectorTransmitterPtr receiver11, - int sendDir, InterpolationProcessorPtr iprocessor); + CoarseToFineNodeSetBlock3DConnector(SPtr<Block3D> block, VectorTransmitterPtr sender00, + VectorTransmitterPtr receiver00, VectorTransmitterPtr sender01, + VectorTransmitterPtr receiver01, VectorTransmitterPtr sender10, + VectorTransmitterPtr receiver10, VectorTransmitterPtr sender11, + VectorTransmitterPtr receiver11, int sendDir, + InterpolationProcessorPtr iprocessor); - void init() override; + void init() override; - void fillSendVectors() override; - void distributeReceiveVectors() override; + void fillSendVectors() override; + void distributeReceiveVectors() override; protected: - typedef std::vector< int > INodeVector; - using INodeSet = std::vector<INodeVector>; - INodeSet iNodeSetSender00; - INodeSet iNodeSetSender01; - INodeSet iNodeSetSender10; - INodeSet iNodeSetSender11; - INodeSet iNodeSetReceiver00; - INodeSet iNodeSetReceiver01; - INodeSet iNodeSetReceiver10; - INodeSet iNodeSetReceiver11; - - void writeICellFtoData(vector_type& data, int& index, D3Q27ICell& icellF); - void writeNodeToVector(vector_type& data, int& index, LBMReal* inode); - void readICellCfromData(vector_type& data, int& index, LBMReal* icellC); - - void findCFCells(); - void findCFCells(int lMinX1, int lMinX2, int lMinX3, int lMaxX1, int lMaxX2, int lMaxX3, INodeSet &inodes); - - void findFCCells(); - void findFCCells(int lMinX1, int lMinX2, int lMinX3, int lMaxX1, int lMaxX2, int lMaxX3, INodeSet &inodes); - - void getLocalMinMax(int& minX1, int& minX2, int& minX3, int& maxX1, int& maxX2, int& maxX3); - - int bMaxX1, bMaxX2, bMaxX3; - - int minX1; - int minX2; - int minX3; - - int maxX1; - int maxX2; - int maxX3; - - int minHalfX1; - int minHalfX2; - int minHalfX3; - - int maxHalfX1; - int maxHalfX2; - int maxHalfX3; + typedef std::vector<int> INodeVector; + using INodeSet = std::vector<INodeVector>; + INodeSet iNodeSetSender00; + INodeSet iNodeSetSender01; + INodeSet iNodeSetSender10; + INodeSet iNodeSetSender11; + INodeSet iNodeSetReceiver00; + INodeSet iNodeSetReceiver01; + INodeSet iNodeSetReceiver10; + INodeSet iNodeSetReceiver11; + + void writeICellFtoData(vector_type &data, int &index, D3Q27ICell &icellF); + void writeNodeToVector(vector_type &data, int &index, LBMReal *inode); + void readICellCfromData(vector_type &data, int &index, LBMReal *icellC); + + void findCFCells(); + void findCFCells(int lMinX1, int lMinX2, int lMinX3, int lMaxX1, int lMaxX2, int lMaxX3, INodeSet &inodes); + + void findFCCells(); + void findFCCells(int lMinX1, int lMinX2, int lMinX3, int lMaxX1, int lMaxX2, int lMaxX3, INodeSet &inodes); + + void getLocalMinMax(int &minX1, int &minX2, int &minX3, int &maxX1, int &maxX2, int &maxX3); + + int bMaxX1, bMaxX2, bMaxX3; + + int minX1; + int minX2; + int minX3; + + int maxX1; + int maxX2; + int maxX3; + + int minHalfX1; + int minHalfX2; + int minHalfX3; + + int maxHalfX1; + int maxHalfX2; + int maxHalfX3; }; - - -#endif +#endif diff --git a/src/cpu/VirtualFluidsCore/Connectors/ConnectorFactory.h b/src/cpu/VirtualFluidsCore/Connectors/ConnectorFactory.h index 323d0349f26417a9b9ece9cca73289ac5e71caa8..65307fe3a8662375092be6626179399a668388b0 100644 --- a/src/cpu/VirtualFluidsCore/Connectors/ConnectorFactory.h +++ b/src/cpu/VirtualFluidsCore/Connectors/ConnectorFactory.h @@ -2,35 +2,34 @@ #define ConnectorFactory_h__ #include "Block3DConnector.h" -#include "TransmitterType.h" -#include "InterpolationProcessor.h" #include "FineToCoarseBlock3DConnector.h" +#include "InterpolationProcessor.h" +#include "TransmitterType.h" #include <PointerDefinitions.h> class ConnectorFactory { public: - ConnectorFactory() = default;; - virtual ~ConnectorFactory() = default;; + ConnectorFactory() = default; + ; + virtual ~ConnectorFactory() = default; + ; - virtual SPtr<Block3DConnector> createSameLevelDirectConnector(SPtr<Block3D> from, SPtr<Block3D> to, int sendDir) = 0; - virtual SPtr<Block3DConnector> createSameLevelVectorConnector(SPtr<Block3D> block, - VectorTransmitterPtr sender, - VectorTransmitterPtr receiver, - int sendDir) = 0; - virtual SPtr<Block3DConnector> createCoarseToFineConnector(SPtr<Block3D> block, - VectorTransmitterPtr sender00, VectorTransmitterPtr receiver00, - VectorTransmitterPtr sender01, VectorTransmitterPtr receiver01, - VectorTransmitterPtr sender10, VectorTransmitterPtr receiver10, - VectorTransmitterPtr sender11, VectorTransmitterPtr receiver11, - int sendDir, InterpolationProcessorPtr iprocessor) = 0; - virtual SPtr<Block3DConnector> createFineToCoarseConnector(SPtr<Block3D> block, - VectorTransmitterPtr sender, - VectorTransmitterPtr receiver, - int sendDir, - InterpolationProcessorPtr iprocessor, - FineToCoarseBlock3DConnector::CFconnectorType connType) = 0; + virtual SPtr<Block3DConnector> createSameLevelDirectConnector(SPtr<Block3D> from, SPtr<Block3D> to, + int sendDir) = 0; + virtual SPtr<Block3DConnector> createSameLevelVectorConnector(SPtr<Block3D> block, VectorTransmitterPtr sender, + VectorTransmitterPtr receiver, int sendDir) = 0; + virtual SPtr<Block3DConnector> + createCoarseToFineConnector(SPtr<Block3D> block, VectorTransmitterPtr sender00, VectorTransmitterPtr receiver00, + VectorTransmitterPtr sender01, VectorTransmitterPtr receiver01, + VectorTransmitterPtr sender10, VectorTransmitterPtr receiver10, + VectorTransmitterPtr sender11, VectorTransmitterPtr receiver11, int sendDir, + InterpolationProcessorPtr iprocessor) = 0; + virtual SPtr<Block3DConnector> + createFineToCoarseConnector(SPtr<Block3D> block, VectorTransmitterPtr sender, VectorTransmitterPtr receiver, + int sendDir, InterpolationProcessorPtr iprocessor, + FineToCoarseBlock3DConnector::CFconnectorType connType) = 0; protected: private: diff --git a/src/cpu/VirtualFluidsCore/Connectors/D3Q27ETCFOffVectorConnector.h b/src/cpu/VirtualFluidsCore/Connectors/D3Q27ETCFOffVectorConnector.h index 96c8627fe4b113c3e195c041b86975c119f3d285..66a03d63c3915eb6944f9c04a4c4740622aba8f8 100644 --- a/src/cpu/VirtualFluidsCore/Connectors/D3Q27ETCFOffVectorConnector.h +++ b/src/cpu/VirtualFluidsCore/Connectors/D3Q27ETCFOffVectorConnector.h @@ -1,1939 +1,2060 @@ /** -* @file D3Q27ETCFOffVectorConnector.h -* @class D3Q27ETCFOffVectorConnector -* @brief Interpolation from coarse level to fine. -* @author Kostyantyn Kucher and Ehsan Fard -* @date 08.06.2011 -*/ + * @file D3Q27ETCFOffVectorConnector.h + * @class D3Q27ETCFOffVectorConnector + * @brief Interpolation from coarse level to fine. + * @author Kostyantyn Kucher and Ehsan Fard + * @date 08.06.2011 + */ #ifndef D3Q27ETCFOffVectorConnector_H #define D3Q27ETCFOffVectorConnector_H #include <vector> -#include "basics/transmitter/TbTransmitter.h" -#include "basics/transmitter/TbTransmitterLocal.h" -#include "basics/container/CbVector.h" +#include "Block3D.h" #include "Block3DConnector.h" #include "D3Q27System.h" -#include "Block3D.h" -#include "LBMKernel.h" +#include "Grid3D.h" #include "InterpolationProcessor.h" +#include "LBMKernel.h" #include "MathUtil.hpp" -#include "Grid3D.h" +#include "basics/container/CbVector.h" +#include "basics/transmitter/TbTransmitter.h" +#include "basics/transmitter/TbTransmitterLocal.h" #include <PointerDefinitions.h> -#include "D3Q27ETFCOffVectorConnector.h" #include "BCProcessor.h" +#include "D3Q27ETFCOffVectorConnector.h" class Block3D; -//daten werden in einen vector (dieser befindet sich im transmitter) kopiert -//der vector wird via transmitter uebertragen -//transmitter kann ein lokal, MPI, RCG, CTL oder was auch immer fuer ein -//transmitter sein, der von Transmitter abgeleitet ist ;-) +// daten werden in einen vector (dieser befindet sich im transmitter) kopiert +// der vector wird via transmitter uebertragen +// transmitter kann ein lokal, MPI, RCG, CTL oder was auch immer fuer ein +// transmitter sein, der von Transmitter abgeleitet ist ;-) -//sendrichtung: E<->W N<->S T<->B +// sendrichtung: E<->W N<->S T<->B // --------- x3 x3 x2 // | NW | NE | ^ ^ ^ // |----+----| +-> x2 +->x1 +->x1 -// | SW | SE | +// | SW | SE | // --------- // NW==even-odd, SW==even-even, SE==odd-even, NE==odd-odd -template< typename VectorTransmitter > +template <typename VectorTransmitter> class D3Q27ETCFOffVectorConnector : public Block3DConnector { public: - using vector_type = typename VectorTransmitter::value_type; - using VectorTransmitterPtr = SPtr<VectorTransmitter>; + using vector_type = typename VectorTransmitter::value_type; + using VectorTransmitterPtr = SPtr<VectorTransmitter>; + public: - D3Q27ETCFOffVectorConnector(SPtr<Block3D> block, - VectorTransmitterPtr senderEvenEvenSW, VectorTransmitterPtr receiverEvenEvenSW, - VectorTransmitterPtr senderEvenOddNW, VectorTransmitterPtr receiverEvenOddNW, - VectorTransmitterPtr senderOddEvenSE, VectorTransmitterPtr receiverOddEvenSE, - VectorTransmitterPtr senderOddOddNE, VectorTransmitterPtr receiverOddOddNE, - int sendDir, InterpolationProcessorPtr iprocessor); + D3Q27ETCFOffVectorConnector(SPtr<Block3D> block, VectorTransmitterPtr senderEvenEvenSW, + VectorTransmitterPtr receiverEvenEvenSW, VectorTransmitterPtr senderEvenOddNW, + VectorTransmitterPtr receiverEvenOddNW, VectorTransmitterPtr senderOddEvenSE, + VectorTransmitterPtr receiverOddEvenSE, VectorTransmitterPtr senderOddOddNE, + VectorTransmitterPtr receiverOddOddNE, int sendDir, + InterpolationProcessorPtr iprocessor); - bool isLocalConnector() override; - bool isRemoteConnector() override; - void init() override; + bool isLocalConnector() override; + bool isRemoteConnector() override; + void init() override; - void sendTransmitterDataSize() override; - void receiveTransmitterDataSize() override; + void sendTransmitterDataSize() override; + void receiveTransmitterDataSize() override; - void prepareForSend() override; - void sendVectors() override; + void prepareForSend() override; + void sendVectors() override; - void prepareForReceive() override; - void receiveVectors() override; + void prepareForReceive() override; + void receiveVectors() override; - void fillSendVectors() override; - void distributeReceiveVectors() override; + void fillSendVectors() override; + void distributeReceiveVectors() override; - bool isInterpolationConnectorCF() override { return true; } - bool isInterpolationConnectorFC() override { return false; } + bool isInterpolationConnectorCF() override { return true; } + bool isInterpolationConnectorFC() override { return false; } - double getSendRecieveTime(); + double getSendRecieveTime(); - void prepareForSendX1() override {} - void prepareForSendX2() override {} - void prepareForSendX3() override {} + void prepareForSendX1() override {} + void prepareForSendX2() override {} + void prepareForSendX3() override {} - void sendVectorsX1() override {} - void sendVectorsX2() override {} - void sendVectorsX3() override {} + void sendVectorsX1() override {} + void sendVectorsX2() override {} + void sendVectorsX3() override {} - void prepareForReceiveX1() override {} - void prepareForReceiveX2() override {} - void prepareForReceiveX3() override {} + void prepareForReceiveX1() override {} + void prepareForReceiveX2() override {} + void prepareForReceiveX3() override {} - void receiveVectorsX1() override {} - void receiveVectorsX2() override {} - void receiveVectorsX3() override {} + void receiveVectorsX1() override {} + void receiveVectorsX2() override {} + void receiveVectorsX3() override {} protected: - WPtr<Block3D> block; //dieser nvd sendet daten und die empfangenen werden diesem nvd zugeordnet - VectorTransmitterPtr senderEvenEvenSW, receiverEvenEvenSW, - senderEvenOddNW, receiverEvenOddNW, - senderOddEvenSE, receiverOddEvenSE, - senderOddOddNE, receiverOddOddNE; - - InterpolationProcessorPtr iprocessor; - - void writeICellFtoData(vector_type& data, int& index, D3Q27ICell& icellF); - void writeNodeToVector(vector_type& data, int& index, LBMReal* inode); - void getLocalMinMax(const int& gMin, const int& gMax, const bool& even, int& lMin, int& lMax, const bool& dataDistribution); - void getLocalMinMax(int& minX1, int& minX2, int& minX3, int& maxX1, int& maxX2, int& maxX3); - void getLocalMinMax(int& minX1, int& minX2, int& minX3, int& maxX1, int& maxX2, int& maxX3, CFconnectorType connType); - void fillSendVectorExt(SPtr<DistributionArray3D> fFrom, const int& lMinX1, const int& lMinX2, const int& lMinX3, const int& lMaxX1, const int& lMaxX2, const int& lMaxX3, vector_type& data, int& index); - - void distributeReceiveVector(SPtr<DistributionArray3D> fTo, const int& lMinX1, const int& lMinX2, const int& lMinX3, const int& lMaxX1, const int& lMaxX2, const int& lMaxX3, vector_type& data, int& index); - void readICellCfromData(vector_type& data, int& index, LBMReal* icellC); - - void findCFnodes(); - void findCFnodes(SPtr<DistributionArray3D> fFrom, const int& lMinX1, const int& lMinX2, const int& lMinX3, const int& lMaxX1, const int& lMaxX2, const int& lMaxX3, vector_type& data, int& index); - - int bMaxX1, bMaxX2, bMaxX3; + WPtr<Block3D> block; // dieser nvd sendet daten und die empfangenen werden diesem nvd zugeordnet + VectorTransmitterPtr senderEvenEvenSW, receiverEvenEvenSW, senderEvenOddNW, receiverEvenOddNW, senderOddEvenSE, + receiverOddEvenSE, senderOddOddNE, receiverOddOddNE; + + InterpolationProcessorPtr iprocessor; + + void writeICellFtoData(vector_type &data, int &index, D3Q27ICell &icellF); + void writeNodeToVector(vector_type &data, int &index, LBMReal *inode); + void getLocalMinMax(const int &gMin, const int &gMax, const bool &even, int &lMin, int &lMax, + const bool &dataDistribution); + void getLocalMinMax(int &minX1, int &minX2, int &minX3, int &maxX1, int &maxX2, int &maxX3); + void getLocalMinMax(int &minX1, int &minX2, int &minX3, int &maxX1, int &maxX2, int &maxX3, + CFconnectorType connType); + void fillSendVectorExt(SPtr<DistributionArray3D> fFrom, const int &lMinX1, const int &lMinX2, const int &lMinX3, + const int &lMaxX1, const int &lMaxX2, const int &lMaxX3, vector_type &data, int &index); + + void distributeReceiveVector(SPtr<DistributionArray3D> fTo, const int &lMinX1, const int &lMinX2, const int &lMinX3, + const int &lMaxX1, const int &lMaxX2, const int &lMaxX3, vector_type &data, + int &index); + void readICellCfromData(vector_type &data, int &index, LBMReal *icellC); + + void findCFnodes(); + void findCFnodes(SPtr<DistributionArray3D> fFrom, const int &lMinX1, const int &lMinX2, const int &lMinX3, + const int &lMaxX1, const int &lMaxX2, const int &lMaxX3, vector_type &data, int &index); + + int bMaxX1, bMaxX2, bMaxX3; }; //////////////////////////////////////////////////////////////////////////// -template< typename VectorTransmitter > -D3Q27ETCFOffVectorConnector<VectorTransmitter>::D3Q27ETCFOffVectorConnector(SPtr<Block3D> block, - VectorTransmitterPtr senderEvenEvenSW, VectorTransmitterPtr receiverEvenEvenSW, - VectorTransmitterPtr senderEvenOddNW, VectorTransmitterPtr receiverEvenOddNW, - VectorTransmitterPtr senderOddEvenSE, VectorTransmitterPtr receiverOddEvenSE, - VectorTransmitterPtr senderOddOddNE, VectorTransmitterPtr receiverOddOddNE, - int sendDir, InterpolationProcessorPtr iprocessor) : Block3DConnector(sendDir) - , block(block) - , senderEvenEvenSW(senderEvenEvenSW) - , senderEvenOddNW(senderEvenOddNW) - , senderOddEvenSE(senderOddEvenSE) - , senderOddOddNE(senderOddOddNE) - , receiverEvenEvenSW(receiverEvenEvenSW) - , receiverEvenOddNW(receiverEvenOddNW) - , receiverOddEvenSE(receiverOddEvenSE) - , receiverOddOddNE(receiverOddOddNE) - , iprocessor(iprocessor) +template <typename VectorTransmitter> +D3Q27ETCFOffVectorConnector<VectorTransmitter>::D3Q27ETCFOffVectorConnector( + SPtr<Block3D> block, VectorTransmitterPtr senderEvenEvenSW, VectorTransmitterPtr receiverEvenEvenSW, + VectorTransmitterPtr senderEvenOddNW, VectorTransmitterPtr receiverEvenOddNW, VectorTransmitterPtr senderOddEvenSE, + VectorTransmitterPtr receiverOddEvenSE, VectorTransmitterPtr senderOddOddNE, VectorTransmitterPtr receiverOddOddNE, + int sendDir, InterpolationProcessorPtr iprocessor) + : Block3DConnector(sendDir), block(block), senderEvenEvenSW(senderEvenEvenSW), senderEvenOddNW(senderEvenOddNW), + senderOddEvenSE(senderOddEvenSE), senderOddOddNE(senderOddOddNE), receiverEvenEvenSW(receiverEvenEvenSW), + receiverEvenOddNW(receiverEvenOddNW), receiverOddEvenSE(receiverOddEvenSE), receiverOddOddNE(receiverOddOddNE), + iprocessor(iprocessor) { - if (!(sendDir == D3Q27System::E || sendDir == D3Q27System::W || sendDir == D3Q27System::N || sendDir == D3Q27System::S || sendDir == D3Q27System::T || sendDir == D3Q27System::B - || sendDir == D3Q27System::NE || sendDir == D3Q27System::SW || sendDir == D3Q27System::SE || sendDir == D3Q27System::NW - || sendDir == D3Q27System::TE || sendDir == D3Q27System::BW || sendDir == D3Q27System::BE || sendDir == D3Q27System::TW - || sendDir == D3Q27System::TN || sendDir == D3Q27System::BS || sendDir == D3Q27System::BN || sendDir == D3Q27System::TS - || sendDir == D3Q27System::TNE || sendDir == D3Q27System::TNW || sendDir == D3Q27System::TSE || sendDir == D3Q27System::TSW - || sendDir == D3Q27System::BNE || sendDir == D3Q27System::BNW || sendDir == D3Q27System::BSE || sendDir == D3Q27System::BSW - )) - { - throw UbException(UB_EXARGS, "invalid constructor for this direction"); - } + if (!(sendDir == D3Q27System::E || sendDir == D3Q27System::W || sendDir == D3Q27System::N || + sendDir == D3Q27System::S || sendDir == D3Q27System::T || sendDir == D3Q27System::B || + sendDir == D3Q27System::NE || sendDir == D3Q27System::SW || sendDir == D3Q27System::SE || + sendDir == D3Q27System::NW || sendDir == D3Q27System::TE || sendDir == D3Q27System::BW || + sendDir == D3Q27System::BE || sendDir == D3Q27System::TW || sendDir == D3Q27System::TN || + sendDir == D3Q27System::BS || sendDir == D3Q27System::BN || sendDir == D3Q27System::TS || + sendDir == D3Q27System::TNE || sendDir == D3Q27System::TNW || sendDir == D3Q27System::TSE || + sendDir == D3Q27System::TSW || sendDir == D3Q27System::BNE || sendDir == D3Q27System::BNW || + sendDir == D3Q27System::BSE || sendDir == D3Q27System::BSW)) { + throw UbException(UB_EXARGS, "invalid constructor for this direction"); + } } ////////////////////////////////////////////////////////////////////////// -template< typename VectorTransmitter > +template <typename VectorTransmitter> bool D3Q27ETCFOffVectorConnector<VectorTransmitter>::isLocalConnector() { - return !this->isRemoteConnector(); + return !this->isRemoteConnector(); } ////////////////////////////////////////////////////////////////////////// -template< typename VectorTransmitter > +template <typename VectorTransmitter> bool D3Q27ETCFOffVectorConnector<VectorTransmitter>::isRemoteConnector() { - return ((senderOddOddNE && senderOddOddNE->isRemoteTransmitter()) || (receiverOddOddNE && receiverOddOddNE->isRemoteTransmitter()) - || (senderEvenEvenSW && senderEvenEvenSW->isRemoteTransmitter()) || (receiverEvenEvenSW && receiverEvenEvenSW->isRemoteTransmitter()) - || (senderEvenOddNW && senderEvenOddNW->isRemoteTransmitter()) || (receiverEvenOddNW && receiverEvenOddNW->isRemoteTransmitter()) - || (senderOddEvenSE && senderOddEvenSE->isRemoteTransmitter()) || (receiverOddEvenSE && receiverOddEvenSE->isRemoteTransmitter())); + return ((senderOddOddNE && senderOddOddNE->isRemoteTransmitter()) || + (receiverOddOddNE && receiverOddOddNE->isRemoteTransmitter()) || + (senderEvenEvenSW && senderEvenEvenSW->isRemoteTransmitter()) || + (receiverEvenEvenSW && receiverEvenEvenSW->isRemoteTransmitter()) || + (senderEvenOddNW && senderEvenOddNW->isRemoteTransmitter()) || + (receiverEvenOddNW && receiverEvenOddNW->isRemoteTransmitter()) || + (senderOddEvenSE && senderOddEvenSE->isRemoteTransmitter()) || + (receiverOddEvenSE && receiverOddEvenSE->isRemoteTransmitter())); } ////////////////////////////////////////////////////////////////////////// -template< typename VectorTransmitter > +template <typename VectorTransmitter> void D3Q27ETCFOffVectorConnector<VectorTransmitter>::sendTransmitterDataSize() { - if (senderEvenEvenSW) - { - UBLOG(logDEBUG5, "D3Q27ETCFOffVectorConnector<VectorTransmitter>::sendTransmitterDataSize()-senderEvenEvenSW " << block.lock()->toString() << " sendDir=" << sendDir); - senderEvenEvenSW->sendDataSize(); - } - if (senderEvenOddNW) - { - UBLOG(logDEBUG5, "D3Q27ETCFOffVectorConnector<VectorTransmitter>::sendTransmitterDataSize()-senderEvenOddNW " << block.lock()->toString() << "sendDir=" << sendDir); - senderEvenOddNW->sendDataSize(); - } - if (senderOddEvenSE) - { - UBLOG(logDEBUG5, "D3Q27ETCFOffVectorConnector<VectorTransmitter>::sendTransmitterDataSize()-senderOddEvenSE " << block.lock()->toString() + "sendDir=" << sendDir); - senderOddEvenSE->sendDataSize(); - } - if (senderOddOddNE) - { - UBLOG(logDEBUG5, "D3Q27ETCFOffVectorConnector<VectorTransmitter>::sendTransmitterDataSize()-senderOddOddNE " << block.lock()->toString() << "sendDir=" << sendDir); - senderOddOddNE->sendDataSize(); - } + if (senderEvenEvenSW) { + UBLOG(logDEBUG5, "D3Q27ETCFOffVectorConnector<VectorTransmitter>::sendTransmitterDataSize()-senderEvenEvenSW " + << block.lock()->toString() << " sendDir=" << sendDir); + senderEvenEvenSW->sendDataSize(); + } + if (senderEvenOddNW) { + UBLOG(logDEBUG5, "D3Q27ETCFOffVectorConnector<VectorTransmitter>::sendTransmitterDataSize()-senderEvenOddNW " + << block.lock()->toString() << "sendDir=" << sendDir); + senderEvenOddNW->sendDataSize(); + } + if (senderOddEvenSE) { + UBLOG(logDEBUG5, "D3Q27ETCFOffVectorConnector<VectorTransmitter>::sendTransmitterDataSize()-senderOddEvenSE " + << block.lock()->toString() + "sendDir=" << sendDir); + senderOddEvenSE->sendDataSize(); + } + if (senderOddOddNE) { + UBLOG(logDEBUG5, "D3Q27ETCFOffVectorConnector<VectorTransmitter>::sendTransmitterDataSize()-senderOddOddNE " + << block.lock()->toString() << "sendDir=" << sendDir); + senderOddOddNE->sendDataSize(); + } } ////////////////////////////////////////////////////////////////////////// -template< typename VectorTransmitter > +template <typename VectorTransmitter> void D3Q27ETCFOffVectorConnector<VectorTransmitter>::receiveTransmitterDataSize() { - if (receiverEvenEvenSW) - { - UBLOG(logDEBUG5, "D3Q27ETCFOffVectorConnector<VectorTransmitter>::receiveTransmitterDataSize()-receiverEvenEvenSW " << block.lock()->toString() << "sendDir=" << sendDir); - receiverEvenEvenSW->receiveDataSize(); - } - if (receiverEvenOddNW) - { - UBLOG(logDEBUG5, "D3Q27ETCFOffVectorConnector<VectorTransmitter>::receiveTransmitterDataSize()-receiverEvenOddNW " << block.lock()->toString() << "sendDir=" << sendDir); - receiverEvenOddNW->receiveDataSize(); - } - if (receiverOddEvenSE) - { - UBLOG(logDEBUG5, "D3Q27ETCFOffVectorConnector<VectorTransmitter>::receiveTransmitterDataSize()-receiverOddEvenSE " << block.lock()->toString() << "sendDir=" << sendDir); - receiverOddEvenSE->receiveDataSize(); - } - if (receiverOddOddNE) - { - UBLOG(logDEBUG5, "D3Q27ETCFOffVectorConnector<VectorTransmitter>::receiveTransmitterDataSize()-receiverOddOddNE " << block.lock()->toString() << "sendDir=" << sendDir); - receiverOddOddNE->receiveDataSize(); - } + if (receiverEvenEvenSW) { + UBLOG(logDEBUG5, + "D3Q27ETCFOffVectorConnector<VectorTransmitter>::receiveTransmitterDataSize()-receiverEvenEvenSW " + << block.lock()->toString() << "sendDir=" << sendDir); + receiverEvenEvenSW->receiveDataSize(); + } + if (receiverEvenOddNW) { + UBLOG(logDEBUG5, + "D3Q27ETCFOffVectorConnector<VectorTransmitter>::receiveTransmitterDataSize()-receiverEvenOddNW " + << block.lock()->toString() << "sendDir=" << sendDir); + receiverEvenOddNW->receiveDataSize(); + } + if (receiverOddEvenSE) { + UBLOG(logDEBUG5, + "D3Q27ETCFOffVectorConnector<VectorTransmitter>::receiveTransmitterDataSize()-receiverOddEvenSE " + << block.lock()->toString() << "sendDir=" << sendDir); + receiverOddEvenSE->receiveDataSize(); + } + if (receiverOddOddNE) { + UBLOG(logDEBUG5, + "D3Q27ETCFOffVectorConnector<VectorTransmitter>::receiveTransmitterDataSize()-receiverOddOddNE " + << block.lock()->toString() << "sendDir=" << sendDir); + receiverOddOddNE->receiveDataSize(); + } } ////////////////////////////////////////////////////////////////////////// -template< typename VectorTransmitter > +template <typename VectorTransmitter> void D3Q27ETCFOffVectorConnector<VectorTransmitter>::prepareForSend() { - if (senderEvenEvenSW) senderEvenEvenSW->prepareForSend(); - if (senderEvenOddNW) senderEvenOddNW->prepareForSend(); - if (senderOddEvenSE) senderOddEvenSE->prepareForSend(); - if (senderOddOddNE) senderOddOddNE->prepareForSend(); + if (senderEvenEvenSW) + senderEvenEvenSW->prepareForSend(); + if (senderEvenOddNW) + senderEvenOddNW->prepareForSend(); + if (senderOddEvenSE) + senderOddEvenSE->prepareForSend(); + if (senderOddOddNE) + senderOddOddNE->prepareForSend(); } ////////////////////////////////////////////////////////////////////////// -template< typename VectorTransmitter > +template <typename VectorTransmitter> void D3Q27ETCFOffVectorConnector<VectorTransmitter>::sendVectors() { - if (senderEvenEvenSW) senderEvenEvenSW->sendData(); - if (senderEvenOddNW) senderEvenOddNW->sendData(); - if (senderOddEvenSE) senderOddEvenSE->sendData(); - if (senderOddOddNE) senderOddOddNE->sendData(); + if (senderEvenEvenSW) + senderEvenEvenSW->sendData(); + if (senderEvenOddNW) + senderEvenOddNW->sendData(); + if (senderOddEvenSE) + senderOddEvenSE->sendData(); + if (senderOddOddNE) + senderOddOddNE->sendData(); } ////////////////////////////////////////////////////////////////////////// -template< typename VectorTransmitter > +template <typename VectorTransmitter> void D3Q27ETCFOffVectorConnector<VectorTransmitter>::prepareForReceive() { - if (receiverEvenEvenSW) receiverEvenEvenSW->prepareForReceive(); - if (receiverEvenOddNW) receiverEvenOddNW->prepareForReceive(); - if (receiverOddEvenSE) receiverOddEvenSE->prepareForReceive(); - if (receiverOddOddNE) receiverOddOddNE->prepareForReceive(); + if (receiverEvenEvenSW) + receiverEvenEvenSW->prepareForReceive(); + if (receiverEvenOddNW) + receiverEvenOddNW->prepareForReceive(); + if (receiverOddEvenSE) + receiverOddEvenSE->prepareForReceive(); + if (receiverOddOddNE) + receiverOddOddNE->prepareForReceive(); } ////////////////////////////////////////////////////////////////////////// -template< typename VectorTransmitter > +template <typename VectorTransmitter> void D3Q27ETCFOffVectorConnector<VectorTransmitter>::receiveVectors() { - if (receiverEvenEvenSW) receiverEvenEvenSW->receiveData(); - if (receiverEvenOddNW) receiverEvenOddNW->receiveData(); - if (receiverOddEvenSE) receiverOddEvenSE->receiveData(); - if (receiverOddOddNE) receiverOddOddNE->receiveData(); + if (receiverEvenEvenSW) + receiverEvenEvenSW->receiveData(); + if (receiverEvenOddNW) + receiverEvenOddNW->receiveData(); + if (receiverOddEvenSE) + receiverOddEvenSE->receiveData(); + if (receiverOddOddNE) + receiverOddOddNE->receiveData(); } ////////////////////////////////////////////////////////////////////////// -template< typename VectorTransmitter > +template <typename VectorTransmitter> void D3Q27ETCFOffVectorConnector<VectorTransmitter>::init() { - using namespace D3Q27System; - - bMaxX1 = (int)block.lock()->getKernel()->getDataSet()->getFdistributions()->getNX1(); - bMaxX2 = (int)block.lock()->getKernel()->getDataSet()->getFdistributions()->getNX2(); - bMaxX3 = (int)block.lock()->getKernel()->getDataSet()->getFdistributions()->getNX3(); - - int sendSize = 0; - LBMReal initValue = -999.0; - - int sendDataPerNode = 27/*f*/; - int iCellSize = 8; //size of interpolation cell - - switch (this->sendDir) - { - case E: case W: sendSize = bMaxX2*bMaxX3*sendDataPerNode*iCellSize; break; - case N: case S: sendSize = bMaxX1*bMaxX3*sendDataPerNode*iCellSize; break; - case T: case B: sendSize = bMaxX1*bMaxX2*sendDataPerNode*iCellSize; break; - case NE: case SW:case SE: case NW: sendSize = 2 * bMaxX3*sendDataPerNode*iCellSize; break; - case TE: case BW:case BE: case TW: sendSize = 2 * bMaxX2*sendDataPerNode*iCellSize; break; - case TN: case BS:case BN: case TS: sendSize = 2 * bMaxX1*sendDataPerNode*iCellSize; break; - case TNE: case TNW:case TSE: case TSW:case BNE: case BNW:case BSE: case BSW: sendSize = 6 * bMaxX1*sendDataPerNode*iCellSize; break; - default: throw UbException(UB_EXARGS, "direction not allowed in this constructor"); - } - if (senderEvenEvenSW) senderEvenEvenSW->getData().resize(sendSize, initValue); - else senderEvenEvenSW = VectorTransmitterPtr(new TbLocalTransmitter< CbVector< LBMReal > >()); - if (senderEvenOddNW) senderEvenOddNW->getData().resize(sendSize, initValue); - else senderEvenOddNW = VectorTransmitterPtr(new TbLocalTransmitter< CbVector< LBMReal > >()); - if (senderOddEvenSE) senderOddEvenSE->getData().resize(sendSize, initValue); - else senderOddEvenSE = VectorTransmitterPtr(new TbLocalTransmitter< CbVector< LBMReal > >()); - if (senderOddOddNE) senderOddOddNE->getData().resize(sendSize, initValue); - else senderOddOddNE = VectorTransmitterPtr(new TbLocalTransmitter< CbVector< LBMReal > >()); - - if (!receiverEvenEvenSW) receiverEvenEvenSW = VectorTransmitterPtr(new TbLocalTransmitter< CbVector< LBMReal > >()); - if (!receiverEvenOddNW) receiverEvenOddNW = VectorTransmitterPtr(new TbLocalTransmitter< CbVector< LBMReal > >()); - if (!receiverOddEvenSE) receiverOddEvenSE = VectorTransmitterPtr(new TbLocalTransmitter< CbVector< LBMReal > >()); - if (!receiverOddOddNE) receiverOddOddNE = VectorTransmitterPtr(new TbLocalTransmitter< CbVector< LBMReal > >()); - - //findCFnodes(); + using namespace D3Q27System; + + bMaxX1 = (int)block.lock()->getKernel()->getDataSet()->getFdistributions()->getNX1(); + bMaxX2 = (int)block.lock()->getKernel()->getDataSet()->getFdistributions()->getNX2(); + bMaxX3 = (int)block.lock()->getKernel()->getDataSet()->getFdistributions()->getNX3(); + + int sendSize = 0; + LBMReal initValue = -999.0; + + int sendDataPerNode = 27 /*f*/; + int iCellSize = 8; // size of interpolation cell + + switch (this->sendDir) { + case E: + case W: + sendSize = bMaxX2 * bMaxX3 * sendDataPerNode * iCellSize; + break; + case N: + case S: + sendSize = bMaxX1 * bMaxX3 * sendDataPerNode * iCellSize; + break; + case T: + case B: + sendSize = bMaxX1 * bMaxX2 * sendDataPerNode * iCellSize; + break; + case NE: + case SW: + case SE: + case NW: + sendSize = 2 * bMaxX3 * sendDataPerNode * iCellSize; + break; + case TE: + case BW: + case BE: + case TW: + sendSize = 2 * bMaxX2 * sendDataPerNode * iCellSize; + break; + case TN: + case BS: + case BN: + case TS: + sendSize = 2 * bMaxX1 * sendDataPerNode * iCellSize; + break; + case TNE: + case TNW: + case TSE: + case TSW: + case BNE: + case BNW: + case BSE: + case BSW: + sendSize = 6 * bMaxX1 * sendDataPerNode * iCellSize; + break; + default: + throw UbException(UB_EXARGS, "direction not allowed in this constructor"); + } + if (senderEvenEvenSW) + senderEvenEvenSW->getData().resize(sendSize, initValue); + else + senderEvenEvenSW = VectorTransmitterPtr(new TbLocalTransmitter<CbVector<LBMReal>>()); + if (senderEvenOddNW) + senderEvenOddNW->getData().resize(sendSize, initValue); + else + senderEvenOddNW = VectorTransmitterPtr(new TbLocalTransmitter<CbVector<LBMReal>>()); + if (senderOddEvenSE) + senderOddEvenSE->getData().resize(sendSize, initValue); + else + senderOddEvenSE = VectorTransmitterPtr(new TbLocalTransmitter<CbVector<LBMReal>>()); + if (senderOddOddNE) + senderOddOddNE->getData().resize(sendSize, initValue); + else + senderOddOddNE = VectorTransmitterPtr(new TbLocalTransmitter<CbVector<LBMReal>>()); + + if (!receiverEvenEvenSW) + receiverEvenEvenSW = VectorTransmitterPtr(new TbLocalTransmitter<CbVector<LBMReal>>()); + if (!receiverEvenOddNW) + receiverEvenOddNW = VectorTransmitterPtr(new TbLocalTransmitter<CbVector<LBMReal>>()); + if (!receiverOddEvenSE) + receiverOddEvenSE = VectorTransmitterPtr(new TbLocalTransmitter<CbVector<LBMReal>>()); + if (!receiverOddOddNE) + receiverOddOddNE = VectorTransmitterPtr(new TbLocalTransmitter<CbVector<LBMReal>>()); + + // findCFnodes(); } ////////////////////////////////////////////////////////////////////////// -template< typename VectorTransmitter > -void D3Q27ETCFOffVectorConnector< VectorTransmitter>::fillSendVectors() +template <typename VectorTransmitter> +void D3Q27ETCFOffVectorConnector<VectorTransmitter>::fillSendVectors() { - using namespace D3Q27System; - - SPtr<DistributionArray3D> fFrom = block.lock()->getKernel()->getDataSet()->getFdistributions(); - int maxX1 = (int)fFrom->getNX1(); - int maxX2 = (int)fFrom->getNX2(); - int maxX3 = (int)fFrom->getNX3(); - int minX1 = 0; - int minX2 = 0; - int minX3 = 0; - - int indexEvEv = 0; - int indexEvOd = 0; - int indexOdEv = 0; - int indexOdOd = 0; - - vector_type& dataEvEv = this->senderEvenEvenSW->getData(); - vector_type& dataEvOd = this->senderEvenOddNW->getData(); - vector_type& dataOdEv = this->senderOddEvenSE->getData(); - vector_type& dataOdOd = this->senderOddOddNE->getData(); - - int lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3; - //int lMinX1_2, lMinX2_2, lMinX3_2, lMaxX1_2, lMaxX2_2, lMaxX3_2; - - //for coners -// int lMinX1W = 1; -// int lMaxX1W = 2; -// -// int lMinX1E = maxX1 - 3; -// int lMaxX1E = maxX1 - 2; -// -// int lMinX2S = 1; -// int lMaxX2S = 2; -// -// int lMinX2N = maxX2 - 3; -// int lMaxX2N = maxX2 - 2; -// -// int lMinX3B = 1; -// int lMaxX3B = 2; -// -// int lMinX3T = maxX3 - 3; -// int lMaxX3T = maxX3 - 2; - - - switch (sendDir) - { - case E: - lMinX1 = maxX1 - 3; - lMaxX1 = lMinX1 + 1; - - getLocalMinMax(minX2, maxX2, true, lMinX2, lMaxX2, false); - getLocalMinMax(minX3, maxX3, true, lMinX3, lMaxX3, false); - fillSendVectorExt(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); - - getLocalMinMax(minX2, maxX2, true, lMinX2, lMaxX2, false); - getLocalMinMax(minX3, maxX3, false, lMinX3, lMaxX3, false); - fillSendVectorExt(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvOd, indexEvOd); - - getLocalMinMax(minX2, maxX2, false, lMinX2, lMaxX2, false); - getLocalMinMax(minX3, maxX3, true, lMinX3, lMaxX3, false); - fillSendVectorExt(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataOdEv, indexOdEv); - - getLocalMinMax(minX2, maxX2, false, lMinX2, lMaxX2, false); - getLocalMinMax(minX3, maxX3, false, lMinX3, lMaxX3, false); - fillSendVectorExt(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataOdOd, indexOdOd); - break; - case W: - /////////////////////////////////////// - ///DEBUG - //if (block.lock()->getGlobalID() == 5780) - //{ - // int test = 0; - //} - ////////////// - lMinX1 = 1; - lMaxX1 = lMinX1 + 1; - - getLocalMinMax(minX2, maxX2, true, lMinX2, lMaxX2, false); - getLocalMinMax(minX3, maxX3, true, lMinX3, lMaxX3, false); - fillSendVectorExt(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); - - getLocalMinMax(minX2, maxX2, true, lMinX2, lMaxX2, false); - getLocalMinMax(minX3, maxX3, false, lMinX3, lMaxX3, false); - fillSendVectorExt(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvOd, indexEvOd); - - getLocalMinMax(minX2, maxX2, false, lMinX2, lMaxX2, false); - getLocalMinMax(minX3, maxX3, true, lMinX3, lMaxX3, false); - fillSendVectorExt(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataOdEv, indexOdEv); - - getLocalMinMax(minX2, maxX2, false, lMinX2, lMaxX2, false); - getLocalMinMax(minX3, maxX3, false, lMinX3, lMaxX3, false); - fillSendVectorExt(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataOdOd, indexOdOd); - break; - case N: - lMinX2 = maxX2 - 3; - lMaxX2 = lMinX2 + 1; - - getLocalMinMax(minX1, maxX1, true, lMinX1, lMaxX1, false); - getLocalMinMax(minX3, maxX3, true, lMinX3, lMaxX3, false); - fillSendVectorExt(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); - - getLocalMinMax(minX1, maxX1, true, lMinX1, lMaxX1, false); - getLocalMinMax(minX3, maxX3, false, lMinX3, lMaxX3, false); - fillSendVectorExt(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvOd, indexEvOd); - - getLocalMinMax(minX1, maxX1, false, lMinX1, lMaxX1, false); - getLocalMinMax(minX3, maxX3, true, lMinX3, lMaxX3, false); - fillSendVectorExt(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataOdEv, indexOdEv); - - getLocalMinMax(minX1, maxX1, false, lMinX1, lMaxX1, false); - getLocalMinMax(minX3, maxX3, false, lMinX3, lMaxX3, false); - fillSendVectorExt(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataOdOd, indexOdOd); - break; - case S: - lMinX2 = 1; - lMaxX2 = lMinX2 + 1; - - getLocalMinMax(minX1, maxX1, true, lMinX1, lMaxX1, false); - getLocalMinMax(minX3, maxX3, true, lMinX3, lMaxX3, false); - fillSendVectorExt(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); - - getLocalMinMax(minX1, maxX1, true, lMinX1, lMaxX1, false); - getLocalMinMax(minX3, maxX3, false, lMinX3, lMaxX3, false); - fillSendVectorExt(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvOd, indexEvOd); - - getLocalMinMax(minX1, maxX1, false, lMinX1, lMaxX1, false); - getLocalMinMax(minX3, maxX3, true, lMinX3, lMaxX3, false); - fillSendVectorExt(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataOdEv, indexOdEv); - - getLocalMinMax(minX1, maxX1, false, lMinX1, lMaxX1, false); - getLocalMinMax(minX3, maxX3, false, lMinX3, lMaxX3, false); - fillSendVectorExt(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataOdOd, indexOdOd); - break; - case T: - lMinX3 = maxX3 - 3; - lMaxX3 = lMinX3 + 1; - - getLocalMinMax(minX1, maxX1, true, lMinX1, lMaxX1, false); - getLocalMinMax(minX2, maxX2, true, lMinX2, lMaxX2, false); - fillSendVectorExt(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); - - getLocalMinMax(minX1, maxX1, true, lMinX1, lMaxX1, false); - getLocalMinMax(minX2, maxX2, false, lMinX2, lMaxX2, false); - fillSendVectorExt(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvOd, indexEvOd); - - getLocalMinMax(minX1, maxX1, false, lMinX1, lMaxX1, false); - getLocalMinMax(minX2, maxX2, true, lMinX2, lMaxX2, false); - fillSendVectorExt(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataOdEv, indexOdEv); - - getLocalMinMax(minX1, maxX1, false, lMinX1, lMaxX1, false); - getLocalMinMax(minX2, maxX2, false, lMinX2, lMaxX2, false); - fillSendVectorExt(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataOdOd, indexOdOd); - break; - case B: - lMinX3 = 1; - lMaxX3 = lMinX3 + 1; - - getLocalMinMax(minX1, maxX1, true, lMinX1, lMaxX1, false); - getLocalMinMax(minX2, maxX2, true, lMinX2, lMaxX2, false); - fillSendVectorExt(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); - - getLocalMinMax(minX1, maxX1, true, lMinX1, lMaxX1, false); - getLocalMinMax(minX2, maxX2, false, lMinX2, lMaxX2, false); - fillSendVectorExt(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvOd, indexEvOd); - - getLocalMinMax(minX1, maxX1, false, lMinX1, lMaxX1, false); - getLocalMinMax(minX2, maxX2, true, lMinX2, lMaxX2, false); - fillSendVectorExt(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataOdEv, indexOdEv); - - getLocalMinMax(minX1, maxX1, false, lMinX1, lMaxX1, false); - getLocalMinMax(minX2, maxX2, false, lMinX2, lMaxX2, false); - fillSendVectorExt(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataOdOd, indexOdOd); - break; - ///N-S-E-W - case NE: - lMinX1 = maxX1 - 3; - lMaxX1 = lMinX1 + 2; - lMinX2 = maxX2 - 3; - lMaxX2 = lMinX2 + 2; - - getLocalMinMax(minX3, maxX3, true, lMinX3, lMaxX3, false); - fillSendVectorExt(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); - - getLocalMinMax(minX3, maxX3, false, lMinX3, lMaxX3, false); - fillSendVectorExt(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataOdEv, indexOdEv); - - break; - - case SW: - lMinX1 = 0; - lMaxX1 = lMinX1 + 2; - lMinX2 = 0; - lMaxX2 = lMinX2 + 2; - - getLocalMinMax(minX3, maxX3, true, lMinX3, lMaxX3, false); - fillSendVectorExt(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); - - getLocalMinMax(minX3, maxX3, false, lMinX3, lMaxX3, false); - fillSendVectorExt(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataOdEv, indexOdEv); - - break; - - case SE: - lMinX1 = maxX1 - 3; - lMaxX1 = lMinX1 + 2; - lMinX2 = 0; - lMaxX2 = lMinX2 + 2; - - getLocalMinMax(minX3, maxX3, true, lMinX3, lMaxX3, false); - fillSendVectorExt(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); - - getLocalMinMax(minX3, maxX3, false, lMinX3, lMaxX3, false); - fillSendVectorExt(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataOdEv, indexOdEv); - - break; - - case NW: - lMinX1 = 0; - lMaxX1 = lMinX1 + 2; - lMinX2 = maxX2 - 3; - lMaxX2 = lMinX2 + 2; - - getLocalMinMax(minX3, maxX3, true, lMinX3, lMaxX3, false); - fillSendVectorExt(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); - - getLocalMinMax(minX3, maxX3, false, lMinX3, lMaxX3, false); - fillSendVectorExt(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataOdEv, indexOdEv); + using namespace D3Q27System; + + SPtr<DistributionArray3D> fFrom = block.lock()->getKernel()->getDataSet()->getFdistributions(); + int maxX1 = (int)fFrom->getNX1(); + int maxX2 = (int)fFrom->getNX2(); + int maxX3 = (int)fFrom->getNX3(); + int minX1 = 0; + int minX2 = 0; + int minX3 = 0; + + int indexEvEv = 0; + int indexEvOd = 0; + int indexOdEv = 0; + int indexOdOd = 0; + + vector_type &dataEvEv = this->senderEvenEvenSW->getData(); + vector_type &dataEvOd = this->senderEvenOddNW->getData(); + vector_type &dataOdEv = this->senderOddEvenSE->getData(); + vector_type &dataOdOd = this->senderOddOddNE->getData(); + + int lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3; + // int lMinX1_2, lMinX2_2, lMinX3_2, lMaxX1_2, lMaxX2_2, lMaxX3_2; + + // for coners + // int lMinX1W = 1; + // int lMaxX1W = 2; + // + // int lMinX1E = maxX1 - 3; + // int lMaxX1E = maxX1 - 2; + // + // int lMinX2S = 1; + // int lMaxX2S = 2; + // + // int lMinX2N = maxX2 - 3; + // int lMaxX2N = maxX2 - 2; + // + // int lMinX3B = 1; + // int lMaxX3B = 2; + // + // int lMinX3T = maxX3 - 3; + // int lMaxX3T = maxX3 - 2; + + switch (sendDir) { + case E: + lMinX1 = maxX1 - 3; + lMaxX1 = lMinX1 + 1; + + getLocalMinMax(minX2, maxX2, true, lMinX2, lMaxX2, false); + getLocalMinMax(minX3, maxX3, true, lMinX3, lMaxX3, false); + fillSendVectorExt(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); + + getLocalMinMax(minX2, maxX2, true, lMinX2, lMaxX2, false); + getLocalMinMax(minX3, maxX3, false, lMinX3, lMaxX3, false); + fillSendVectorExt(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvOd, indexEvOd); + + getLocalMinMax(minX2, maxX2, false, lMinX2, lMaxX2, false); + getLocalMinMax(minX3, maxX3, true, lMinX3, lMaxX3, false); + fillSendVectorExt(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataOdEv, indexOdEv); + + getLocalMinMax(minX2, maxX2, false, lMinX2, lMaxX2, false); + getLocalMinMax(minX3, maxX3, false, lMinX3, lMaxX3, false); + fillSendVectorExt(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataOdOd, indexOdOd); + break; + case W: + /////////////////////////////////////// + /// DEBUG + // if (block.lock()->getGlobalID() == 5780) + //{ + // int test = 0; + //} + ////////////// + lMinX1 = 1; + lMaxX1 = lMinX1 + 1; + + getLocalMinMax(minX2, maxX2, true, lMinX2, lMaxX2, false); + getLocalMinMax(minX3, maxX3, true, lMinX3, lMaxX3, false); + fillSendVectorExt(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); + + getLocalMinMax(minX2, maxX2, true, lMinX2, lMaxX2, false); + getLocalMinMax(minX3, maxX3, false, lMinX3, lMaxX3, false); + fillSendVectorExt(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvOd, indexEvOd); + + getLocalMinMax(minX2, maxX2, false, lMinX2, lMaxX2, false); + getLocalMinMax(minX3, maxX3, true, lMinX3, lMaxX3, false); + fillSendVectorExt(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataOdEv, indexOdEv); + + getLocalMinMax(minX2, maxX2, false, lMinX2, lMaxX2, false); + getLocalMinMax(minX3, maxX3, false, lMinX3, lMaxX3, false); + fillSendVectorExt(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataOdOd, indexOdOd); + break; + case N: + lMinX2 = maxX2 - 3; + lMaxX2 = lMinX2 + 1; + + getLocalMinMax(minX1, maxX1, true, lMinX1, lMaxX1, false); + getLocalMinMax(minX3, maxX3, true, lMinX3, lMaxX3, false); + fillSendVectorExt(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); + + getLocalMinMax(minX1, maxX1, true, lMinX1, lMaxX1, false); + getLocalMinMax(minX3, maxX3, false, lMinX3, lMaxX3, false); + fillSendVectorExt(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvOd, indexEvOd); + + getLocalMinMax(minX1, maxX1, false, lMinX1, lMaxX1, false); + getLocalMinMax(minX3, maxX3, true, lMinX3, lMaxX3, false); + fillSendVectorExt(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataOdEv, indexOdEv); + + getLocalMinMax(minX1, maxX1, false, lMinX1, lMaxX1, false); + getLocalMinMax(minX3, maxX3, false, lMinX3, lMaxX3, false); + fillSendVectorExt(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataOdOd, indexOdOd); + break; + case S: + lMinX2 = 1; + lMaxX2 = lMinX2 + 1; + + getLocalMinMax(minX1, maxX1, true, lMinX1, lMaxX1, false); + getLocalMinMax(minX3, maxX3, true, lMinX3, lMaxX3, false); + fillSendVectorExt(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); + + getLocalMinMax(minX1, maxX1, true, lMinX1, lMaxX1, false); + getLocalMinMax(minX3, maxX3, false, lMinX3, lMaxX3, false); + fillSendVectorExt(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvOd, indexEvOd); + + getLocalMinMax(minX1, maxX1, false, lMinX1, lMaxX1, false); + getLocalMinMax(minX3, maxX3, true, lMinX3, lMaxX3, false); + fillSendVectorExt(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataOdEv, indexOdEv); + + getLocalMinMax(minX1, maxX1, false, lMinX1, lMaxX1, false); + getLocalMinMax(minX3, maxX3, false, lMinX3, lMaxX3, false); + fillSendVectorExt(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataOdOd, indexOdOd); + break; + case T: + lMinX3 = maxX3 - 3; + lMaxX3 = lMinX3 + 1; + + getLocalMinMax(minX1, maxX1, true, lMinX1, lMaxX1, false); + getLocalMinMax(minX2, maxX2, true, lMinX2, lMaxX2, false); + fillSendVectorExt(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); + + getLocalMinMax(minX1, maxX1, true, lMinX1, lMaxX1, false); + getLocalMinMax(minX2, maxX2, false, lMinX2, lMaxX2, false); + fillSendVectorExt(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvOd, indexEvOd); + + getLocalMinMax(minX1, maxX1, false, lMinX1, lMaxX1, false); + getLocalMinMax(minX2, maxX2, true, lMinX2, lMaxX2, false); + fillSendVectorExt(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataOdEv, indexOdEv); + + getLocalMinMax(minX1, maxX1, false, lMinX1, lMaxX1, false); + getLocalMinMax(minX2, maxX2, false, lMinX2, lMaxX2, false); + fillSendVectorExt(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataOdOd, indexOdOd); + break; + case B: + lMinX3 = 1; + lMaxX3 = lMinX3 + 1; + + getLocalMinMax(minX1, maxX1, true, lMinX1, lMaxX1, false); + getLocalMinMax(minX2, maxX2, true, lMinX2, lMaxX2, false); + fillSendVectorExt(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); + + getLocalMinMax(minX1, maxX1, true, lMinX1, lMaxX1, false); + getLocalMinMax(minX2, maxX2, false, lMinX2, lMaxX2, false); + fillSendVectorExt(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvOd, indexEvOd); + + getLocalMinMax(minX1, maxX1, false, lMinX1, lMaxX1, false); + getLocalMinMax(minX2, maxX2, true, lMinX2, lMaxX2, false); + fillSendVectorExt(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataOdEv, indexOdEv); + + getLocalMinMax(minX1, maxX1, false, lMinX1, lMaxX1, false); + getLocalMinMax(minX2, maxX2, false, lMinX2, lMaxX2, false); + fillSendVectorExt(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataOdOd, indexOdOd); + break; + /// N-S-E-W + case NE: + lMinX1 = maxX1 - 3; + lMaxX1 = lMinX1 + 2; + lMinX2 = maxX2 - 3; + lMaxX2 = lMinX2 + 2; + + getLocalMinMax(minX3, maxX3, true, lMinX3, lMaxX3, false); + fillSendVectorExt(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); + + getLocalMinMax(minX3, maxX3, false, lMinX3, lMaxX3, false); + fillSendVectorExt(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataOdEv, indexOdEv); + + break; + + case SW: + lMinX1 = 0; + lMaxX1 = lMinX1 + 2; + lMinX2 = 0; + lMaxX2 = lMinX2 + 2; + + getLocalMinMax(minX3, maxX3, true, lMinX3, lMaxX3, false); + fillSendVectorExt(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); + + getLocalMinMax(minX3, maxX3, false, lMinX3, lMaxX3, false); + fillSendVectorExt(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataOdEv, indexOdEv); + + break; + + case SE: + lMinX1 = maxX1 - 3; + lMaxX1 = lMinX1 + 2; + lMinX2 = 0; + lMaxX2 = lMinX2 + 2; + + getLocalMinMax(minX3, maxX3, true, lMinX3, lMaxX3, false); + fillSendVectorExt(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); + + getLocalMinMax(minX3, maxX3, false, lMinX3, lMaxX3, false); + fillSendVectorExt(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataOdEv, indexOdEv); + + break; - break; - /////T-B-E-W - case TE: - lMinX1 = maxX1 - 3; - lMaxX1 = lMinX1 + 2; - lMinX3 = maxX3 - 3; - lMaxX3 = lMinX3 + 2; + case NW: + lMinX1 = 0; + lMaxX1 = lMinX1 + 2; + lMinX2 = maxX2 - 3; + lMaxX2 = lMinX2 + 2; + + getLocalMinMax(minX3, maxX3, true, lMinX3, lMaxX3, false); + fillSendVectorExt(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); - getLocalMinMax(minX2, maxX2, true, lMinX2, lMaxX2, false); - fillSendVectorExt(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); + getLocalMinMax(minX3, maxX3, false, lMinX3, lMaxX3, false); + fillSendVectorExt(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataOdEv, indexOdEv); - getLocalMinMax(minX2, maxX2, false, lMinX2, lMaxX2, false); - fillSendVectorExt(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataOdEv, indexOdEv); + break; + /////T-B-E-W + case TE: + lMinX1 = maxX1 - 3; + lMaxX1 = lMinX1 + 2; + lMinX3 = maxX3 - 3; + lMaxX3 = lMinX3 + 2; - break; + getLocalMinMax(minX2, maxX2, true, lMinX2, lMaxX2, false); + fillSendVectorExt(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); - case BW: - lMinX1 = 0; - lMaxX1 = lMinX1 + 2; - lMinX3 = 0; - lMaxX3 = lMinX3 + 2; + getLocalMinMax(minX2, maxX2, false, lMinX2, lMaxX2, false); + fillSendVectorExt(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataOdEv, indexOdEv); - getLocalMinMax(minX2, maxX2, true, lMinX2, lMaxX2, false); - fillSendVectorExt(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); + break; - getLocalMinMax(minX2, maxX2, false, lMinX2, lMaxX2, false); - fillSendVectorExt(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataOdEv, indexOdEv); + case BW: + lMinX1 = 0; + lMaxX1 = lMinX1 + 2; + lMinX3 = 0; + lMaxX3 = lMinX3 + 2; - break; + getLocalMinMax(minX2, maxX2, true, lMinX2, lMaxX2, false); + fillSendVectorExt(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); - case BE: - lMinX1 = maxX1 - 3; - lMaxX1 = lMinX1 + 2; - lMinX3 = 0; - lMaxX3 = lMinX3 + 2; + getLocalMinMax(minX2, maxX2, false, lMinX2, lMaxX2, false); + fillSendVectorExt(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataOdEv, indexOdEv); - getLocalMinMax(minX2, maxX2, true, lMinX2, lMaxX2, false); - fillSendVectorExt(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); + break; - getLocalMinMax(minX2, maxX2, false, lMinX2, lMaxX2, false); - fillSendVectorExt(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataOdEv, indexOdEv); - - break; - - case TW: - lMinX1 = 0; - lMaxX1 = lMinX1 + 2; - lMinX3 = maxX3 - 3; - lMaxX3 = lMinX3 + 2; + case BE: + lMinX1 = maxX1 - 3; + lMaxX1 = lMinX1 + 2; + lMinX3 = 0; + lMaxX3 = lMinX3 + 2; - getLocalMinMax(minX2, maxX2, true, lMinX2, lMaxX2, false); - fillSendVectorExt(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); - - getLocalMinMax(minX2, maxX2, false, lMinX2, lMaxX2, false); - fillSendVectorExt(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataOdEv, indexOdEv); - - break; - //// - /////T-B-N-S - case TN: - lMinX2 = maxX2 - 3; - lMaxX2 = lMinX2 + 2; - lMinX3 = maxX3 - 3; - lMaxX3 = lMinX3 + 2; - - getLocalMinMax(minX1, maxX1, true, lMinX1, lMaxX1, false); - fillSendVectorExt(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); - - getLocalMinMax(minX1, maxX1, false, lMinX1, lMaxX1, false); - fillSendVectorExt(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataOdEv, indexOdEv); - - break; - - case BS: - lMinX2 = 0; - lMaxX2 = lMinX2 + 2; - lMinX3 = 0; - lMaxX3 = lMinX3 + 2; - - getLocalMinMax(minX1, maxX1, true, lMinX1, lMaxX1, false); - fillSendVectorExt(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); - - getLocalMinMax(minX1, maxX1, false, lMinX1, lMaxX1, false); - fillSendVectorExt(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataOdEv, indexOdEv); - - break; - - case BN: - lMinX2 = maxX2 - 3; - lMaxX2 = lMinX2 + 2; - lMinX3 = 0; - lMaxX3 = lMinX3 + 2; - - getLocalMinMax(minX1, maxX1, true, lMinX1, lMaxX1, false); - fillSendVectorExt(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); - - getLocalMinMax(minX1, maxX1, false, lMinX1, lMaxX1, false); - fillSendVectorExt(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataOdEv, indexOdEv); - - break; - - case TS: - lMinX2 = 0; - lMaxX2 = lMinX2 + 2; - lMinX3 = maxX3 - 3; - lMaxX3 = lMinX3 + 2; - - getLocalMinMax(minX1, maxX1, true, lMinX1, lMaxX1, false); - fillSendVectorExt(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); - - getLocalMinMax(minX1, maxX1, false, lMinX1, lMaxX1, false); - fillSendVectorExt(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataOdEv, indexOdEv); - - break; - - - //TNE - case TNE: - lMinX1 = maxX1 - 3; - lMaxX1 = maxX1 - 1; - lMinX2 = maxX2 - 3; - lMaxX2 = maxX2 - 1; - lMinX3 = maxX3 - 3; - lMaxX3 = maxX3 - 1; - - fillSendVectorExt(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); - break; - // TNW - case TNW: - lMinX1 = 0; - lMaxX1 = 2; - lMinX2 = maxX2 - 3; - lMaxX2 = maxX2 - 1; - lMinX3 = maxX3 - 3; - lMaxX3 = maxX3 - 1; - - fillSendVectorExt(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); - break; - // TSE - case TSE: - lMinX1 = maxX1 - 3; - lMaxX1 = maxX1 - 1; - lMinX2 = 0; - lMaxX2 = 2; - lMinX3 = maxX3 - 3; - lMaxX3 = maxX3 - 1; - - fillSendVectorExt(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); - break; - // TSW - case TSW: - lMinX1 = 0; - lMaxX1 = 2; - lMinX2 = 0; - lMaxX2 = 2; - lMinX3 = maxX3 - 3; - lMaxX3 = maxX3 - 1; - - fillSendVectorExt(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); - break; - // BNE - case BNE: - lMinX1 = maxX1 - 3; - lMaxX1 = maxX1 - 1; - lMinX2 = maxX2 - 3; - lMaxX2 = maxX2 - 1; - lMinX3 = 0; - lMaxX3 = 2; - - fillSendVectorExt(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); - break; - // BNW - case BNW: - lMinX1 = 0; - lMaxX1 = 2; - lMinX2 = maxX2 - 3; - lMaxX2 = maxX2 - 1; - lMinX3 = 0; - lMaxX3 = 2; - - fillSendVectorExt(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); - break; - // BSE - case BSE: - lMinX1 = maxX1 - 3; - lMaxX1 = maxX1 - 1; - lMinX2 = 0; - lMaxX2 = 2; - lMinX3 = 0; - lMaxX3 = 2; - - fillSendVectorExt(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); - break; - // BSW - case BSW: - lMinX1 = 0; - lMaxX1 = 2; - lMinX2 = 0; - lMaxX2 = 2; - lMinX3 = 0; - lMaxX3 = 2; - - fillSendVectorExt(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); - break; - } + getLocalMinMax(minX2, maxX2, true, lMinX2, lMaxX2, false); + fillSendVectorExt(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); + + getLocalMinMax(minX2, maxX2, false, lMinX2, lMaxX2, false); + fillSendVectorExt(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataOdEv, indexOdEv); + + break; + + case TW: + lMinX1 = 0; + lMaxX1 = lMinX1 + 2; + lMinX3 = maxX3 - 3; + lMaxX3 = lMinX3 + 2; + + getLocalMinMax(minX2, maxX2, true, lMinX2, lMaxX2, false); + fillSendVectorExt(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); + + getLocalMinMax(minX2, maxX2, false, lMinX2, lMaxX2, false); + fillSendVectorExt(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataOdEv, indexOdEv); + + break; + //// + /////T-B-N-S + case TN: + lMinX2 = maxX2 - 3; + lMaxX2 = lMinX2 + 2; + lMinX3 = maxX3 - 3; + lMaxX3 = lMinX3 + 2; + + getLocalMinMax(minX1, maxX1, true, lMinX1, lMaxX1, false); + fillSendVectorExt(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); + + getLocalMinMax(minX1, maxX1, false, lMinX1, lMaxX1, false); + fillSendVectorExt(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataOdEv, indexOdEv); + + break; + + case BS: + lMinX2 = 0; + lMaxX2 = lMinX2 + 2; + lMinX3 = 0; + lMaxX3 = lMinX3 + 2; + + getLocalMinMax(minX1, maxX1, true, lMinX1, lMaxX1, false); + fillSendVectorExt(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); + + getLocalMinMax(minX1, maxX1, false, lMinX1, lMaxX1, false); + fillSendVectorExt(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataOdEv, indexOdEv); + + break; + + case BN: + lMinX2 = maxX2 - 3; + lMaxX2 = lMinX2 + 2; + lMinX3 = 0; + lMaxX3 = lMinX3 + 2; + + getLocalMinMax(minX1, maxX1, true, lMinX1, lMaxX1, false); + fillSendVectorExt(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); + + getLocalMinMax(minX1, maxX1, false, lMinX1, lMaxX1, false); + fillSendVectorExt(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataOdEv, indexOdEv); + + break; + + case TS: + lMinX2 = 0; + lMaxX2 = lMinX2 + 2; + lMinX3 = maxX3 - 3; + lMaxX3 = lMinX3 + 2; + + getLocalMinMax(minX1, maxX1, true, lMinX1, lMaxX1, false); + fillSendVectorExt(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); + + getLocalMinMax(minX1, maxX1, false, lMinX1, lMaxX1, false); + fillSendVectorExt(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataOdEv, indexOdEv); + + break; + + // TNE + case TNE: + lMinX1 = maxX1 - 3; + lMaxX1 = maxX1 - 1; + lMinX2 = maxX2 - 3; + lMaxX2 = maxX2 - 1; + lMinX3 = maxX3 - 3; + lMaxX3 = maxX3 - 1; + + fillSendVectorExt(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); + break; + // TNW + case TNW: + lMinX1 = 0; + lMaxX1 = 2; + lMinX2 = maxX2 - 3; + lMaxX2 = maxX2 - 1; + lMinX3 = maxX3 - 3; + lMaxX3 = maxX3 - 1; + + fillSendVectorExt(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); + break; + // TSE + case TSE: + lMinX1 = maxX1 - 3; + lMaxX1 = maxX1 - 1; + lMinX2 = 0; + lMaxX2 = 2; + lMinX3 = maxX3 - 3; + lMaxX3 = maxX3 - 1; + + fillSendVectorExt(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); + break; + // TSW + case TSW: + lMinX1 = 0; + lMaxX1 = 2; + lMinX2 = 0; + lMaxX2 = 2; + lMinX3 = maxX3 - 3; + lMaxX3 = maxX3 - 1; + + fillSendVectorExt(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); + break; + // BNE + case BNE: + lMinX1 = maxX1 - 3; + lMaxX1 = maxX1 - 1; + lMinX2 = maxX2 - 3; + lMaxX2 = maxX2 - 1; + lMinX3 = 0; + lMaxX3 = 2; + + fillSendVectorExt(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); + break; + // BNW + case BNW: + lMinX1 = 0; + lMaxX1 = 2; + lMinX2 = maxX2 - 3; + lMaxX2 = maxX2 - 1; + lMinX3 = 0; + lMaxX3 = 2; + + fillSendVectorExt(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); + break; + // BSE + case BSE: + lMinX1 = maxX1 - 3; + lMaxX1 = maxX1 - 1; + lMinX2 = 0; + lMaxX2 = 2; + lMinX3 = 0; + lMaxX3 = 2; + + fillSendVectorExt(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); + break; + // BSW + case BSW: + lMinX1 = 0; + lMaxX1 = 2; + lMinX2 = 0; + lMaxX2 = 2; + lMinX3 = 0; + lMaxX3 = 2; + + fillSendVectorExt(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); + break; + } } ////////////////////////////////////////////////////////////////////////// -template< typename VectorTransmitter > -void D3Q27ETCFOffVectorConnector< VectorTransmitter>::getLocalMinMax(const int& gMin, const int& gMax, const bool& even, int& lMin, int& lMax, const bool& dataDistribution) +template <typename VectorTransmitter> +void D3Q27ETCFOffVectorConnector<VectorTransmitter>::getLocalMinMax(const int &gMin, const int &gMax, const bool &even, + int &lMin, int &lMax, const bool &dataDistribution) { - int halfEven = 0; - int halfOdd = 0; - int dCoef = 0; - - if (dataDistribution) - dCoef = 1; - - if (Utilities::isOdd(gMax)) - { - halfEven = gMax / 2; - halfOdd = gMax / 2; - } - if (Utilities::isEven(gMax)) - { - halfEven = gMax / 2; - halfOdd = gMax / 2 - 1 + dCoef; - } - - if(even) - { - lMin = gMin + dCoef; - lMax = lMin + halfEven - dCoef; - } - else - { - lMin = gMin + halfOdd; - lMax = gMax - 1; - } + int halfEven = 0; + int halfOdd = 0; + int dCoef = 0; + + if (dataDistribution) + dCoef = 1; + + if (Utilities::isOdd(gMax)) { + halfEven = gMax / 2; + halfOdd = gMax / 2; + } + if (Utilities::isEven(gMax)) { + halfEven = gMax / 2; + halfOdd = gMax / 2 - 1 + dCoef; + } + + if (even) { + lMin = gMin + dCoef; + lMax = lMin + halfEven - dCoef; + } else { + lMin = gMin + halfOdd; + lMax = gMax - 1; + } } ////////////////////////////////////////////////////////////////////////// -template< typename VectorTransmitter > -void D3Q27ETCFOffVectorConnector< VectorTransmitter>::fillSendVectorExt(SPtr<DistributionArray3D> fFrom, const int& lMinX1, const int& lMinX2, const int& lMinX3, const int& lMaxX1, const int& lMaxX2, const int& lMaxX3, vector_type& data, int& index) +template <typename VectorTransmitter> +void D3Q27ETCFOffVectorConnector<VectorTransmitter>::fillSendVectorExt(SPtr<DistributionArray3D> fFrom, + const int &lMinX1, const int &lMinX2, + const int &lMinX3, const int &lMaxX1, + const int &lMaxX2, const int &lMaxX3, + vector_type &data, int &index) { - if (data.size() == 0) return; - int ix1, ix2, ix3; - LBMReal xoff, yoff, zoff; - SPtr<BCArray3D> bcArray = block.lock()->getKernel()->getBCProcessor()->getBCArray(); - - for (ix3 = lMinX3; ix3 < lMaxX3; ix3++) - { - for (ix2 = lMinX2; ix2 < lMaxX2; ix2++) - { - for (ix1 = lMinX1; ix1 < lMaxX1; ix1++) - { - D3Q27ICell icellC; - D3Q27ICell icellF; - - int howManySolids = iprocessor->iCellHowManySolids(bcArray, ix1, ix2, ix3); - - if (howManySolids == 0 || howManySolids == 8) - { - iprocessor->readICell(fFrom, icellC, ix1, ix2, ix3); - xoff = 0.0; - yoff = 0.0; - zoff = 0.0; + if (data.size() == 0) + return; + int ix1, ix2, ix3; + LBMReal xoff, yoff, zoff; + SPtr<BCArray3D> bcArray = block.lock()->getKernel()->getBCProcessor()->getBCArray(); + + for (ix3 = lMinX3; ix3 < lMaxX3; ix3++) { + for (ix2 = lMinX2; ix2 < lMaxX2; ix2++) { + for (ix1 = lMinX1; ix1 < lMaxX1; ix1++) { + D3Q27ICell icellC; + D3Q27ICell icellF; + + int howManySolids = iprocessor->iCellHowManySolids(bcArray, ix1, ix2, ix3); + + if (howManySolids == 0 || howManySolids == 8) { + iprocessor->readICell(fFrom, icellC, ix1, ix2, ix3); + xoff = 0.0; + yoff = 0.0; + zoff = 0.0; + } else { + if (!iprocessor->findNeighborICell(bcArray, fFrom, icellC, bMaxX1, bMaxX2, bMaxX3, ix1, ix2, ix3, + xoff, yoff, zoff)) { + std::string err = "For " + block.lock()->toString() + " x1=" + UbSystem::toString(ix1) + + ", x2=" + UbSystem::toString(ix2) + ", x3=" + UbSystem::toString(ix3) + + " interpolation is not implemented for other direction" + + " by using in: " + (std::string) typeid(*this).name() + + " or maybe you have a solid on the block boundary"; + UB_THROW(UbException(UB_EXARGS, err)); + } + } + + iprocessor->interpolateCoarseToFine(icellC, icellF, xoff, yoff, zoff); + this->writeICellFtoData(data, index, icellF); } - else - { - if (!iprocessor->findNeighborICell(bcArray, fFrom, icellC, bMaxX1, bMaxX2, bMaxX3, ix1, ix2, ix3, xoff, yoff, zoff)) - { - std::string err = "For " + block.lock()->toString() + " x1=" + UbSystem::toString(ix1) + ", x2=" + UbSystem::toString(ix2) + ", x3=" + UbSystem::toString(ix3) + - " interpolation is not implemented for other direction" + - " by using in: " + (std::string)typeid(*this).name() + - " or maybe you have a solid on the block boundary"; - UB_THROW(UbException(UB_EXARGS, err)); - } - } - - iprocessor->interpolateCoarseToFine(icellC, icellF, xoff, yoff, zoff); - this->writeICellFtoData(data, index, icellF); - } - } - } + } + } } ////////////////////////////////////////////////////////////////////////// -template< typename VectorTransmitter > -void D3Q27ETCFOffVectorConnector< VectorTransmitter>::writeICellFtoData(vector_type& data, int& index, D3Q27ICell& icellF) +template <typename VectorTransmitter> +void D3Q27ETCFOffVectorConnector<VectorTransmitter>::writeICellFtoData(vector_type &data, int &index, + D3Q27ICell &icellF) { - writeNodeToVector(data, index, icellF.BSW); - writeNodeToVector(data, index, icellF.BSE); - writeNodeToVector(data, index, icellF.BNW); - writeNodeToVector(data, index, icellF.BNE); - writeNodeToVector(data, index, icellF.TSW); - writeNodeToVector(data, index, icellF.TSE); - writeNodeToVector(data, index, icellF.TNW); - writeNodeToVector(data, index, icellF.TNE); + writeNodeToVector(data, index, icellF.BSW); + writeNodeToVector(data, index, icellF.BSE); + writeNodeToVector(data, index, icellF.BNW); + writeNodeToVector(data, index, icellF.BNE); + writeNodeToVector(data, index, icellF.TSW); + writeNodeToVector(data, index, icellF.TSE); + writeNodeToVector(data, index, icellF.TNW); + writeNodeToVector(data, index, icellF.TNE); } ////////////////////////////////////////////////////////////////////////// -template< typename VectorTransmitter > -void D3Q27ETCFOffVectorConnector< VectorTransmitter>::writeNodeToVector(vector_type& data, int& index, LBMReal* inode) +template <typename VectorTransmitter> +void D3Q27ETCFOffVectorConnector<VectorTransmitter>::writeNodeToVector(vector_type &data, int &index, LBMReal *inode) { - for (int i = D3Q27System::STARTF; i < D3Q27System::ENDF + 1; i++) - { - data[index++] = inode[i]; - } + for (int i = D3Q27System::STARTF; i < D3Q27System::ENDF + 1; i++) { + data[index++] = inode[i]; + } } ////////////////////////////////////////////////////////////////////////// -template< typename VectorTransmitter > -void D3Q27ETCFOffVectorConnector< VectorTransmitter>::distributeReceiveVectors() +template <typename VectorTransmitter> +void D3Q27ETCFOffVectorConnector<VectorTransmitter>::distributeReceiveVectors() { - using namespace D3Q27System; - - SPtr<DistributionArray3D> fTo = block.lock()->getKernel()->getDataSet()->getFdistributions(); - int maxX1 = (int)fTo->getNX1(); - int maxX2 = (int)fTo->getNX2(); - int maxX3 = (int)fTo->getNX3(); - int minX1 = 0; - int minX2 = 0; - int minX3 = 0; - - int indexEvEv = 0; - int indexEvOd = 0; - int indexOdEv = 0; - int indexOdOd = 0; - - vector_type& dataEvEv = this->receiverEvenEvenSW->getData(); - vector_type& dataEvOd = this->receiverEvenOddNW->getData(); - vector_type& dataOdEv = this->receiverOddEvenSE->getData(); - vector_type& dataOdOd = this->receiverOddOddNE->getData(); - - int lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3; - int dummy; - - //for coners -// int lMinX1W = 3; -// int lMaxX1W = 3; -// -// int lMinX1E = maxX1 - 3; -// int lMaxX1E = maxX1 - 2; -// -// int lMinX2S = 1; -// int lMaxX2S = 3; -// -// int lMinX2N = maxX2 - 3; -// int lMaxX2N = maxX2 - 2; -// -// int lMinX3B = 1; -// int lMaxX3B = 3; -// -// int lMinX3T = maxX3 - 3; -// int lMaxX3T = maxX3 - 2; - - /////////////////////////////////////// - ///DEBUG - //if (block.lock()->getGlobalID() == 5780) - //{ - // int test = 0; - //} - ////////////// - - switch (sendDir) - { - case E: - lMinX1 = maxX1 - 4; - lMaxX1 = lMinX1 + 1; - getLocalMinMax(minX2, maxX2, true, lMinX2, lMaxX2, true); - getLocalMinMax(minX3, maxX3, true, lMinX3, lMaxX3, true); - getLocalMinMax(dummy, lMinX2, lMinX3, dummy, dummy, dummy); - distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); - - getLocalMinMax(minX2, maxX2, true, lMinX2, lMaxX2, true); - getLocalMinMax(minX3, maxX3, false, lMinX3, lMaxX3, true); - getLocalMinMax(dummy, lMinX2, dummy, dummy, dummy, lMaxX3); - distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvOd, indexEvOd); - - getLocalMinMax(minX2, maxX2, false, lMinX2, lMaxX2, true); - getLocalMinMax(minX3, maxX3, true, lMinX3, lMaxX3, true); - getLocalMinMax(dummy, dummy, lMinX3, dummy, lMaxX2, dummy); - distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataOdEv, indexOdEv); - - getLocalMinMax(minX2, maxX2, false, lMinX2, lMaxX2, true); - getLocalMinMax(minX3, maxX3, false, lMinX3, lMaxX3, true); - getLocalMinMax(dummy, dummy, dummy, dummy, lMaxX2, lMaxX3); - distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataOdOd, indexOdOd); - break; - case W: - /////////////////////////////////////// - ///DEBUG - //if (block.lock()->getGlobalID() == 5780) - //{ - // int test = 0; - //} - ////////////// - lMinX1 = 3; - lMaxX1 = lMinX1 + 1; - getLocalMinMax(minX2, maxX2, true, lMinX2, lMaxX2, true); - getLocalMinMax(minX3, maxX3, true, lMinX3, lMaxX3, true); - getLocalMinMax(dummy, lMinX2, lMinX3, dummy, dummy, dummy); - distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); - - getLocalMinMax(minX2, maxX2, true, lMinX2, lMaxX2, true); - getLocalMinMax(minX3, maxX3, false, lMinX3, lMaxX3, true); - getLocalMinMax(dummy, lMinX2, dummy, dummy, dummy, lMaxX3); - distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvOd, indexEvOd); - - getLocalMinMax(minX2, maxX2, false, lMinX2, lMaxX2, true); - getLocalMinMax(minX3, maxX3, true, lMinX3, lMaxX3, true); - getLocalMinMax(dummy, dummy, lMinX3, dummy, lMaxX2, dummy); - distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataOdEv, indexOdEv); - - getLocalMinMax(minX2, maxX2, false, lMinX2, lMaxX2, true); - getLocalMinMax(minX3, maxX3, false, lMinX3, lMaxX3, true); - getLocalMinMax(dummy, dummy, dummy, dummy, lMaxX2, lMaxX3); - distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataOdOd, indexOdOd); - break; - case N: - lMinX2 = maxX2 - 4; - lMaxX2 = lMinX2 + 1; - getLocalMinMax(minX1, maxX1, true, lMinX1, lMaxX1, true); - getLocalMinMax(minX3, maxX3, true, lMinX3, lMaxX3, true); - getLocalMinMax(lMinX1, dummy, lMinX3, dummy, dummy, dummy); - distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); - - getLocalMinMax(minX1, maxX1, true, lMinX1, lMaxX1, true); - getLocalMinMax(minX3, maxX3, false, lMinX3, lMaxX3, true); - getLocalMinMax(lMinX1, dummy, dummy, dummy, dummy, lMaxX3); - distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvOd, indexEvOd); - - getLocalMinMax(minX1, maxX1, false, lMinX1, lMaxX1, true); - getLocalMinMax(minX3, maxX3, true, lMinX3, lMaxX3, true); - getLocalMinMax(dummy, dummy, lMinX3, lMaxX1, dummy, dummy); - distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataOdEv, indexOdEv); - - getLocalMinMax(minX1, maxX1, false, lMinX1, lMaxX1, true); - getLocalMinMax(minX3, maxX3, false, lMinX3, lMaxX3, true); - getLocalMinMax(dummy, dummy, dummy, lMaxX1, dummy, lMaxX3); - distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataOdOd, indexOdOd); - break; - case S: - lMinX2 = 3; - lMaxX2 = lMinX2 + 1; - getLocalMinMax(minX1, maxX1, true, lMinX1, lMaxX1, true); - getLocalMinMax(minX3, maxX3, true, lMinX3, lMaxX3, true); - getLocalMinMax(lMinX1, dummy, lMinX3, dummy, dummy, dummy); - distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); - - getLocalMinMax(minX1, maxX1, true, lMinX1, lMaxX1, true); - getLocalMinMax(minX3, maxX3, false, lMinX3, lMaxX3, true); - getLocalMinMax(lMinX1, dummy, dummy, dummy, dummy, lMaxX3); - distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvOd, indexEvOd); - - getLocalMinMax(minX1, maxX1, false, lMinX1, lMaxX1, true); - getLocalMinMax(minX3, maxX3, true, lMinX3, lMaxX3, true); - getLocalMinMax(dummy, dummy, lMinX3, lMaxX1, dummy, dummy); - distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataOdEv, indexOdEv); - - getLocalMinMax(minX1, maxX1, false, lMinX1, lMaxX1, true); - getLocalMinMax(minX3, maxX3, false, lMinX3, lMaxX3, true); - getLocalMinMax(dummy, dummy, dummy, lMaxX1, dummy, lMaxX3); - distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataOdOd, indexOdOd); - break; - case T: - lMinX3 = maxX3 - 4; - lMaxX3 = lMinX3 + 1; - getLocalMinMax(minX1, maxX1, true, lMinX1, lMaxX1, true); - getLocalMinMax(minX2, maxX2, true, lMinX2, lMaxX2, true); - getLocalMinMax(lMinX1, lMinX2, dummy, dummy, dummy, dummy); - distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); - - getLocalMinMax(minX1, maxX1, true, lMinX1, lMaxX1, true); - getLocalMinMax(minX2, maxX2, false, lMinX2, lMaxX2, true); - getLocalMinMax(lMinX1, dummy, dummy, dummy, lMaxX2, dummy); - distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvOd, indexEvOd); - - getLocalMinMax(minX1, maxX1, false, lMinX1, lMaxX1, true); - getLocalMinMax(minX2, maxX2, true, lMinX2, lMaxX2, true); - getLocalMinMax(dummy, lMinX2, dummy, lMaxX1, dummy, dummy); - distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataOdEv, indexOdEv); - - getLocalMinMax(minX1, maxX1, false, lMinX1, lMaxX1, true); - getLocalMinMax(minX2, maxX2, false, lMinX2, lMaxX2, true); - getLocalMinMax(dummy, dummy, dummy, lMaxX1, lMaxX2, dummy); - distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataOdOd, indexOdOd); - break; - case B: - lMinX3 = 3; - lMaxX3 = lMinX3 + 1; - getLocalMinMax(minX1, maxX1, true, lMinX1, lMaxX1, true); - getLocalMinMax(minX2, maxX2, true, lMinX2, lMaxX2, true); - getLocalMinMax(lMinX1, lMinX2, dummy, dummy, dummy, dummy); - distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); - - getLocalMinMax(minX1, maxX1, true, lMinX1, lMaxX1, true); - getLocalMinMax(minX2, maxX2, false, lMinX2, lMaxX2, true); - getLocalMinMax(lMinX1, dummy, dummy, dummy, lMaxX2, dummy); - distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvOd, indexEvOd); - - getLocalMinMax(minX1, maxX1, false, lMinX1, lMaxX1, true); - getLocalMinMax(minX2, maxX2, true, lMinX2, lMaxX2, true); - getLocalMinMax(dummy, lMinX2, dummy, lMaxX1, dummy, dummy); - distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataOdEv, indexOdEv); - - getLocalMinMax(minX1, maxX1, false, lMinX1, lMaxX1, true); - getLocalMinMax(minX2, maxX2, false, lMinX2, lMaxX2, true); - getLocalMinMax(dummy, dummy, dummy, lMaxX1, lMaxX2, dummy); - distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataOdOd, indexOdOd); - break; - - // /////E-W-N-S - case NE: - lMinX1 = maxX1 - 4; - lMaxX1 = lMinX1 + 3; - lMinX2 = maxX2 - 4; - lMaxX2 = lMinX2 + 1; - getLocalMinMax(minX3, maxX3, true, lMinX3, lMaxX3, true); - getLocalMinMax(dummy, dummy, lMinX3, dummy, dummy, dummy); - distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); - - getLocalMinMax(minX3, maxX3, false, lMinX3, lMaxX3, true); - getLocalMinMax(dummy, dummy, dummy, dummy, dummy, lMaxX3); - distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataOdEv, indexOdEv); - - lMinX1 = maxX1 - 4; - lMaxX1 = lMinX1 + 1; - lMinX2 = maxX2 - 4; - lMaxX2 = lMinX2 + 3; - getLocalMinMax(minX3, maxX3, true, lMinX3, lMaxX3, true); - getLocalMinMax(dummy, dummy, lMinX3, dummy, dummy, dummy); - distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); - - getLocalMinMax(minX3, maxX3, false, lMinX3, lMaxX3, true); - getLocalMinMax(dummy, dummy, dummy, dummy, dummy, lMaxX3); - distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataOdEv, indexOdEv); - - break; - - case SW: - lMinX1 = 1; - lMaxX1 = lMinX1 + 3; - lMinX2 = 3; - lMaxX2 = lMinX2 + 1; - getLocalMinMax(minX3, maxX3, true, lMinX3, lMaxX3, true); - getLocalMinMax(dummy, dummy, lMinX3, dummy, dummy, dummy); - distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); - - getLocalMinMax(minX3, maxX3, false, lMinX3, lMaxX3, true); - getLocalMinMax(dummy, dummy, dummy, dummy, dummy, lMaxX3); - distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataOdEv, indexOdEv); - - lMinX1 = 3; - lMaxX1 = lMinX1 + 1; - lMinX2 = 1; - lMaxX2 = lMinX2 + 3; - getLocalMinMax(minX3, maxX3, true, lMinX3, lMaxX3, true); - getLocalMinMax(dummy, dummy, lMinX3, dummy, dummy, dummy); - distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); - - getLocalMinMax(minX3, maxX3, false, lMinX3, lMaxX3, true); - getLocalMinMax(dummy, dummy, dummy, dummy, dummy, lMaxX3); - distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataOdEv, indexOdEv); - - break; - - case SE: - lMinX1 = maxX1 - 4; - lMaxX1 = lMinX1 + 3; - lMinX2 = 3; - lMaxX2 = lMinX2 + 1; - getLocalMinMax(minX3, maxX3, true, lMinX3, lMaxX3, true); - getLocalMinMax(dummy, dummy, lMinX3, dummy, dummy, dummy); - distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); - - getLocalMinMax(minX3, maxX3, false, lMinX3, lMaxX3, true); - getLocalMinMax(dummy, dummy, dummy, dummy, dummy, lMaxX3); - distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataOdEv, indexOdEv); - - lMinX1 = maxX1 - 4; - lMaxX1 = lMinX1 + 1; - lMinX2 = 1; - lMaxX2 = lMinX2 + 3; - getLocalMinMax(minX3, maxX3, true, lMinX3, lMaxX3, true); - getLocalMinMax(dummy, dummy, lMinX3, dummy, dummy, dummy); - distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); - - getLocalMinMax(minX3, maxX3, false, lMinX3, lMaxX3, true); - getLocalMinMax(dummy, dummy, dummy, dummy, dummy, lMaxX3); - distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataOdEv, indexOdEv); - - break; - - case NW: - lMinX1 = 1; - lMaxX1 = lMinX1 + 3; - lMinX2 = maxX2 - 4; - lMaxX2 = lMinX2 + 1; - getLocalMinMax(minX3, maxX3, true, lMinX3, lMaxX3, true); - getLocalMinMax(dummy, dummy, lMinX3, dummy, dummy, dummy); - distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); - - getLocalMinMax(minX3, maxX3, false, lMinX3, lMaxX3, true); - getLocalMinMax(dummy, dummy, dummy, dummy, dummy, lMaxX3); - distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataOdEv, indexOdEv); - - lMinX1 = 3; - lMaxX1 = lMinX1 + 1; - lMinX2 = maxX2 - 4; - lMaxX2 = lMinX2 + 3; - getLocalMinMax(minX3, maxX3, true, lMinX3, lMaxX3, true); - getLocalMinMax(dummy, dummy, lMinX3, dummy, dummy, dummy); - distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); - - getLocalMinMax(minX3, maxX3, false, lMinX3, lMaxX3, true); - getLocalMinMax(dummy, dummy, dummy, dummy, dummy, lMaxX3); - distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataOdEv, indexOdEv); - - break; - // /////T-B-E-W - case TE: - lMinX1 = maxX1 - 4; - lMaxX1 = lMinX1 + 3; - lMinX3 = maxX3 - 4; - lMaxX3 = lMinX3 + 1; - getLocalMinMax(minX2, maxX2, true, lMinX2, lMaxX2, true); - getLocalMinMax(dummy, lMinX2, dummy, dummy, dummy, dummy); - distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); - - getLocalMinMax(minX2, maxX2, false, lMinX2, lMaxX2, true); - getLocalMinMax(dummy, dummy, dummy, dummy, lMaxX2, dummy); - distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataOdEv, indexOdEv); - - lMinX1 = maxX1 - 4; - lMaxX1 = lMinX1 + 1; - lMinX3 = maxX3 - 4; - lMaxX3 = lMinX3 + 3; - getLocalMinMax(minX2, maxX2, true, lMinX2, lMaxX2, true); - getLocalMinMax(dummy, lMinX2, dummy, dummy, dummy, dummy); - distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); - - getLocalMinMax(minX2, maxX2, false, lMinX2, lMaxX2, true); - getLocalMinMax(dummy, dummy, dummy, dummy, lMaxX2, dummy); - distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataOdEv, indexOdEv); - - break; - - case BW: - lMinX1 = 1; - lMaxX1 = lMinX1 + 3; - lMinX3 = 3; - lMaxX3 = lMinX3 + 1; - getLocalMinMax(minX2, maxX2, true, lMinX2, lMaxX2, true); - getLocalMinMax(dummy, lMinX2, dummy, dummy, dummy, dummy); - distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); - - getLocalMinMax(minX2, maxX2, false, lMinX2, lMaxX2, true); - getLocalMinMax(dummy, dummy, dummy, dummy, lMaxX2, dummy); - distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataOdEv, indexOdEv); - - lMinX1 = 3; - lMaxX1 = lMinX1 + 1; - lMinX3 = 1; - lMaxX3 = lMinX3 + 3; - getLocalMinMax(minX2, maxX2, true, lMinX2, lMaxX2, true); - getLocalMinMax(dummy, lMinX2, dummy, dummy, dummy, dummy); - distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); - - getLocalMinMax(minX2, maxX2, false, lMinX2, lMaxX2, true); - getLocalMinMax(dummy, dummy, dummy, dummy, lMaxX2, dummy); - distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataOdEv, indexOdEv); - - break; - - case BE: - lMinX1 = maxX1 - 4; - lMaxX1 = lMinX1 + 3; - lMinX3 = 3; - lMaxX3 = lMinX3 + 1; - getLocalMinMax(minX2, maxX2, true, lMinX2, lMaxX2, true); - getLocalMinMax(dummy, lMinX2, dummy, dummy, dummy, dummy); - distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); - - getLocalMinMax(minX2, maxX2, false, lMinX2, lMaxX2, true); - getLocalMinMax(dummy, dummy, dummy, dummy, lMaxX2, dummy); - distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataOdEv, indexOdEv); - - lMinX1 = maxX1 - 4; - lMaxX1 = lMinX1 + 1; - lMinX3 = 1; - lMaxX3 = lMinX3 + 3; - getLocalMinMax(minX2, maxX2, true, lMinX2, lMaxX2, true); - getLocalMinMax(dummy, lMinX2, dummy, dummy, dummy, dummy); - distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); - - getLocalMinMax(minX2, maxX2, false, lMinX2, lMaxX2, true); - getLocalMinMax(dummy, dummy, dummy, dummy, lMaxX2, dummy); - distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataOdEv, indexOdEv); - - break; - - case TW: - lMinX1 = 1; - lMaxX1 = lMinX1 + 3; - lMinX3 = maxX3 - 4; - lMaxX3 = lMinX3 + 1; - getLocalMinMax(minX2, maxX2, true, lMinX2, lMaxX2, true); - getLocalMinMax(dummy, lMinX2, dummy, dummy, dummy, dummy); - distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); - - getLocalMinMax(minX2, maxX2, false, lMinX2, lMaxX2, true); - getLocalMinMax(dummy, dummy, dummy, dummy, lMaxX2, dummy); - distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataOdEv, indexOdEv); - - lMinX1 = 3; - lMaxX1 = lMinX1 + 1; - lMinX3 = maxX3 - 4; - lMaxX3 = lMinX3 + 3; - getLocalMinMax(minX2, maxX2, true, lMinX2, lMaxX2, true); - getLocalMinMax(dummy, lMinX2, dummy, dummy, dummy, dummy); - distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); - - getLocalMinMax(minX2, maxX2, false, lMinX2, lMaxX2, true); - getLocalMinMax(dummy, dummy, dummy, dummy, lMaxX2, dummy); - distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataOdEv, indexOdEv); - - break; - - /////////////////////////T-N-B-S - case TN: - lMinX2 = maxX2 - 4; - lMaxX2 = lMinX2 + 3; - lMinX3 = maxX3 - 4; - lMaxX3 = lMinX3 + 1; - getLocalMinMax(minX1, maxX1, true, lMinX1, lMaxX1, true); - getLocalMinMax(lMinX1, dummy, dummy, dummy, dummy, dummy); - distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); - - getLocalMinMax(minX1, maxX1, false, lMinX1, lMaxX1, true); - getLocalMinMax(dummy, dummy, dummy, lMaxX1, dummy, dummy); - distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataOdEv, indexOdEv); - - lMinX2 = maxX2 - 4; - lMaxX2 = lMinX2 + 1; - lMinX3 = maxX3 - 4; - lMaxX3 = lMinX3 + 3; - getLocalMinMax(minX1, maxX1, true, lMinX1, lMaxX1, true); - getLocalMinMax(lMinX1, dummy, dummy, dummy, dummy, dummy); - distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); - - getLocalMinMax(minX1, maxX1, false, lMinX1, lMaxX1, true); - getLocalMinMax(dummy, dummy, dummy, lMaxX1, dummy, dummy); - distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataOdEv, indexOdEv); - - break; - - case BS: - lMinX2 = 1; - lMaxX2 = lMinX2 + 3; - lMinX3 = 3; - lMaxX3 = lMinX3 + 1; - getLocalMinMax(minX1, maxX1, true, lMinX1, lMaxX1, true); - getLocalMinMax(lMinX1, dummy, dummy, dummy, dummy, dummy); - distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); - - getLocalMinMax(minX1, maxX1, false, lMinX1, lMaxX1, true); - getLocalMinMax(dummy, dummy, dummy, lMaxX1, dummy, dummy); - distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataOdEv, indexOdEv); - - lMinX2 = 3; - lMaxX2 = lMinX2 + 1; - lMinX3 = 1; - lMaxX3 = lMinX3 + 3; - getLocalMinMax(minX1, maxX1, true, lMinX1, lMaxX1, true); - getLocalMinMax(lMinX1, dummy, dummy, dummy, dummy, dummy); - distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); - - getLocalMinMax(minX1, maxX1, false, lMinX1, lMaxX1, true); - getLocalMinMax(dummy, dummy, dummy, lMaxX1, dummy, dummy); - distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataOdEv, indexOdEv); - - break; - - - case BN: - lMinX2 = maxX2 - 4; - lMaxX2 = lMinX2 + 3; - lMinX3 = 3; - lMaxX3 = lMinX3 + 1; - getLocalMinMax(minX1, maxX1, true, lMinX1, lMaxX1, true); - getLocalMinMax(lMinX1, dummy, dummy, dummy, dummy, dummy); - distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); - - getLocalMinMax(minX1, maxX1, false, lMinX1, lMaxX1, true); - getLocalMinMax(dummy, dummy, dummy, lMaxX1, dummy, dummy); - distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataOdEv, indexOdEv); - - lMinX2 = maxX2 - 4; - lMaxX2 = lMinX2 + 1; - lMinX3 = 1; - lMaxX3 = lMinX3 + 3; - getLocalMinMax(minX1, maxX1, true, lMinX1, lMaxX1, true); - getLocalMinMax(lMinX1, dummy, dummy, dummy, dummy, dummy); - distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); - - getLocalMinMax(minX1, maxX1, false, lMinX1, lMaxX1, true); - getLocalMinMax(dummy, dummy, dummy, lMaxX1, dummy, dummy); - distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataOdEv, indexOdEv); - - break; - - case TS: - lMinX2 = 1; - lMaxX2 = lMinX2 + 3; - lMinX3 = maxX3 - 4; - lMaxX3 = lMinX3 + 1; - getLocalMinMax(minX1, maxX1, true, lMinX1, lMaxX1, true); - getLocalMinMax(lMinX1, dummy, dummy, dummy, dummy, dummy); - distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); - - getLocalMinMax(minX1, maxX1, false, lMinX1, lMaxX1, true); - getLocalMinMax(dummy, dummy, dummy, lMaxX1, dummy, dummy); - distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataOdEv, indexOdEv); - - lMinX2 = 3; - lMaxX2 = lMinX2 + 1; - lMinX3 = maxX3 - 4; - lMaxX3 = lMinX3 + 3; - getLocalMinMax(minX1, maxX1, true, lMinX1, lMaxX1, true); - getLocalMinMax(lMinX1, dummy, dummy, dummy, dummy, dummy); - distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); - - getLocalMinMax(minX1, maxX1, false, lMinX1, lMaxX1, true); - getLocalMinMax(dummy, dummy, dummy, lMaxX1, dummy, dummy); - distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataOdEv, indexOdEv); - - break; - - //TNE - case TNE: - lMinX1 = maxX1 - 4; - lMaxX1 = maxX1 - 3; - lMinX2 = maxX2 - 4; - lMaxX2 = maxX2 - 1; - lMinX3 = maxX3 - 4; - lMaxX3 = maxX3 - 1; - distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); - - lMinX1 = maxX1 - 4; - lMaxX1 = maxX1 - 1; - lMinX2 = maxX2 - 4; - lMaxX2 = maxX2 - 3; - lMinX3 = maxX3 - 4; - lMaxX3 = maxX3 - 1; - distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); - - lMinX1 = maxX1 - 4; - lMaxX1 = maxX1 - 1; - lMinX2 = maxX2 - 4; - lMaxX2 = maxX2 - 1; - lMinX3 = maxX3 - 4; - lMaxX3 = maxX3 - 3; - distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); - - break; - // TNW - case TNW: - lMinX1 = 3; - lMaxX1 = 4; - lMinX2 = maxX2 - 4; - lMaxX2 = maxX2 - 1; - lMinX3 = maxX3 - 4; - lMaxX3 = maxX3 - 1; - distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); - - lMinX1 = 1; - lMaxX1 = 4; - lMinX2 = maxX2 - 4; - lMaxX2 = maxX2 - 3; - lMinX3 = maxX3 - 4; - lMaxX3 = maxX3 - 1; - distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); - - lMinX1 = 1; - lMaxX1 = 4; - lMinX2 = maxX2 - 4; - lMaxX2 = maxX2 - 1; - lMinX3 = maxX3 - 4; - lMaxX3 = maxX3 - 3; - distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); - - break; - // TSE - case TSE: - lMinX1 = maxX1 - 4; - lMaxX1 = maxX1 - 3; - lMinX2 = 1; - lMaxX2 = 4; - lMinX3 = maxX3 - 4; - lMaxX3 = maxX3 - 1; - distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); - - lMinX1 = maxX1 - 4; - lMaxX1 = maxX1 - 1; - lMinX2 = 3; - lMaxX2 = 4; - lMinX3 = maxX3 - 4; - lMaxX3 = maxX3 - 1; - distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); - - lMinX1 = maxX1 - 4; - lMaxX1 = maxX1 - 1; - lMinX2 = 1; - lMaxX2 = 4; - lMinX3 = maxX3 - 4; - lMaxX3 = maxX3 - 3; - distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); - break; - // TSW - case TSW: - lMinX1 = 3; - lMaxX1 = 4; - lMinX2 = 1; - lMaxX2 = 4; - lMinX3 = maxX3 - 4; - lMaxX3 = maxX3 - 1; - distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); - - lMinX1 = 1; - lMaxX1 = 4; - lMinX2 = 3; - lMaxX2 = 4; - lMinX3 = maxX3 - 4; - lMaxX3 = maxX3 - 1; - distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); - - lMinX1 = 1; - lMaxX1 = 4; - lMinX2 = 1; - lMaxX2 = 4; - lMinX3 = maxX3 - 4; - lMaxX3 = maxX3 - 3; - distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); - break; - // BNE - case BNE: - lMinX1 = maxX1 - 4; - lMaxX1 = maxX1 - 3; - lMinX2 = maxX2 - 4; - lMaxX2 = maxX2 - 1; - lMinX3 = 1; - lMaxX3 = 4; - distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); - - lMinX1 = maxX1 - 4; - lMaxX1 = maxX1 - 1; - lMinX2 = maxX2 - 4; - lMaxX2 = maxX2 - 3; - lMinX3 = 1; - lMaxX3 = 4; - distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); - - lMinX1 = maxX1 - 4; - lMaxX1 = maxX1 - 1; - lMinX2 = maxX2 - 4; - lMaxX2 = maxX2 - 1; - lMinX3 = 3; - lMaxX3 = 4; - distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); - - break; - // BNW - case BNW: - lMinX1 = 3; - lMaxX1 = 4; - lMinX2 = maxX2 - 4; - lMaxX2 = maxX2 - 1; - lMinX3 = 1; - lMaxX3 = 4; - distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); - - lMinX1 = 1; - lMaxX1 = 4; - lMinX2 = maxX2 - 4; - lMaxX2 = maxX2 - 3; - lMinX3 = 1; - lMaxX3 = 4; - distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); - - lMinX1 = 1; - lMaxX1 = 4; - lMinX2 = maxX2 - 4; - lMaxX2 = maxX2 - 1; - lMinX3 = 3; - lMaxX3 = 4; - distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); - break; - // BSE - case BSE: - lMinX1 = maxX1 - 4; - lMaxX1 = maxX1 - 3; - lMinX2 = 1; - lMaxX2 = 4; - lMinX3 = 1; - lMaxX3 = 4; - distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); - - lMinX1 = maxX1 - 4; - lMaxX1 = maxX1 - 1; - lMinX2 = 3; - lMaxX2 = 4; - lMinX3 = 1; - lMaxX3 = 4; - distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); - - lMinX1 = maxX1 - 4; - lMaxX1 = maxX1 - 1; - lMinX2 = 1; - lMaxX2 = 4; - lMinX3 = 3; - lMaxX3 = 4; - distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); - break; - // BSW - case BSW: - lMinX1 = 3; - lMaxX1 = 4; - lMinX2 = 1; - lMaxX2 = 4; - lMinX3 = 1; - lMaxX3 = 4; - distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); - - lMinX1 = 1; - lMaxX1 = 4; - lMinX2 = 3; - lMaxX2 = 4; - lMinX3 = 1; - lMaxX3 = 4; - distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); - - lMinX1 = 1; - lMaxX1 = 4; - lMinX2 = 1; - lMaxX2 = 4; - lMinX3 = 3; - lMaxX3 = 4; - distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); - - break; - } + using namespace D3Q27System; + + SPtr<DistributionArray3D> fTo = block.lock()->getKernel()->getDataSet()->getFdistributions(); + int maxX1 = (int)fTo->getNX1(); + int maxX2 = (int)fTo->getNX2(); + int maxX3 = (int)fTo->getNX3(); + int minX1 = 0; + int minX2 = 0; + int minX3 = 0; + + int indexEvEv = 0; + int indexEvOd = 0; + int indexOdEv = 0; + int indexOdOd = 0; + + vector_type &dataEvEv = this->receiverEvenEvenSW->getData(); + vector_type &dataEvOd = this->receiverEvenOddNW->getData(); + vector_type &dataOdEv = this->receiverOddEvenSE->getData(); + vector_type &dataOdOd = this->receiverOddOddNE->getData(); + + int lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3; + int dummy; + + // for coners + // int lMinX1W = 3; + // int lMaxX1W = 3; + // + // int lMinX1E = maxX1 - 3; + // int lMaxX1E = maxX1 - 2; + // + // int lMinX2S = 1; + // int lMaxX2S = 3; + // + // int lMinX2N = maxX2 - 3; + // int lMaxX2N = maxX2 - 2; + // + // int lMinX3B = 1; + // int lMaxX3B = 3; + // + // int lMinX3T = maxX3 - 3; + // int lMaxX3T = maxX3 - 2; + + /////////////////////////////////////// + /// DEBUG + // if (block.lock()->getGlobalID() == 5780) + //{ + // int test = 0; + //} + ////////////// + + switch (sendDir) { + case E: + lMinX1 = maxX1 - 4; + lMaxX1 = lMinX1 + 1; + getLocalMinMax(minX2, maxX2, true, lMinX2, lMaxX2, true); + getLocalMinMax(minX3, maxX3, true, lMinX3, lMaxX3, true); + getLocalMinMax(dummy, lMinX2, lMinX3, dummy, dummy, dummy); + distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); + + getLocalMinMax(minX2, maxX2, true, lMinX2, lMaxX2, true); + getLocalMinMax(minX3, maxX3, false, lMinX3, lMaxX3, true); + getLocalMinMax(dummy, lMinX2, dummy, dummy, dummy, lMaxX3); + distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvOd, indexEvOd); + + getLocalMinMax(minX2, maxX2, false, lMinX2, lMaxX2, true); + getLocalMinMax(minX3, maxX3, true, lMinX3, lMaxX3, true); + getLocalMinMax(dummy, dummy, lMinX3, dummy, lMaxX2, dummy); + distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataOdEv, indexOdEv); + + getLocalMinMax(minX2, maxX2, false, lMinX2, lMaxX2, true); + getLocalMinMax(minX3, maxX3, false, lMinX3, lMaxX3, true); + getLocalMinMax(dummy, dummy, dummy, dummy, lMaxX2, lMaxX3); + distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataOdOd, indexOdOd); + break; + case W: + /////////////////////////////////////// + /// DEBUG + // if (block.lock()->getGlobalID() == 5780) + //{ + // int test = 0; + //} + ////////////// + lMinX1 = 3; + lMaxX1 = lMinX1 + 1; + getLocalMinMax(minX2, maxX2, true, lMinX2, lMaxX2, true); + getLocalMinMax(minX3, maxX3, true, lMinX3, lMaxX3, true); + getLocalMinMax(dummy, lMinX2, lMinX3, dummy, dummy, dummy); + distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); + + getLocalMinMax(minX2, maxX2, true, lMinX2, lMaxX2, true); + getLocalMinMax(minX3, maxX3, false, lMinX3, lMaxX3, true); + getLocalMinMax(dummy, lMinX2, dummy, dummy, dummy, lMaxX3); + distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvOd, indexEvOd); + + getLocalMinMax(minX2, maxX2, false, lMinX2, lMaxX2, true); + getLocalMinMax(minX3, maxX3, true, lMinX3, lMaxX3, true); + getLocalMinMax(dummy, dummy, lMinX3, dummy, lMaxX2, dummy); + distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataOdEv, indexOdEv); + + getLocalMinMax(minX2, maxX2, false, lMinX2, lMaxX2, true); + getLocalMinMax(minX3, maxX3, false, lMinX3, lMaxX3, true); + getLocalMinMax(dummy, dummy, dummy, dummy, lMaxX2, lMaxX3); + distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataOdOd, indexOdOd); + break; + case N: + lMinX2 = maxX2 - 4; + lMaxX2 = lMinX2 + 1; + getLocalMinMax(minX1, maxX1, true, lMinX1, lMaxX1, true); + getLocalMinMax(minX3, maxX3, true, lMinX3, lMaxX3, true); + getLocalMinMax(lMinX1, dummy, lMinX3, dummy, dummy, dummy); + distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); + + getLocalMinMax(minX1, maxX1, true, lMinX1, lMaxX1, true); + getLocalMinMax(minX3, maxX3, false, lMinX3, lMaxX3, true); + getLocalMinMax(lMinX1, dummy, dummy, dummy, dummy, lMaxX3); + distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvOd, indexEvOd); + + getLocalMinMax(minX1, maxX1, false, lMinX1, lMaxX1, true); + getLocalMinMax(minX3, maxX3, true, lMinX3, lMaxX3, true); + getLocalMinMax(dummy, dummy, lMinX3, lMaxX1, dummy, dummy); + distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataOdEv, indexOdEv); + + getLocalMinMax(minX1, maxX1, false, lMinX1, lMaxX1, true); + getLocalMinMax(minX3, maxX3, false, lMinX3, lMaxX3, true); + getLocalMinMax(dummy, dummy, dummy, lMaxX1, dummy, lMaxX3); + distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataOdOd, indexOdOd); + break; + case S: + lMinX2 = 3; + lMaxX2 = lMinX2 + 1; + getLocalMinMax(minX1, maxX1, true, lMinX1, lMaxX1, true); + getLocalMinMax(minX3, maxX3, true, lMinX3, lMaxX3, true); + getLocalMinMax(lMinX1, dummy, lMinX3, dummy, dummy, dummy); + distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); + + getLocalMinMax(minX1, maxX1, true, lMinX1, lMaxX1, true); + getLocalMinMax(minX3, maxX3, false, lMinX3, lMaxX3, true); + getLocalMinMax(lMinX1, dummy, dummy, dummy, dummy, lMaxX3); + distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvOd, indexEvOd); + + getLocalMinMax(minX1, maxX1, false, lMinX1, lMaxX1, true); + getLocalMinMax(minX3, maxX3, true, lMinX3, lMaxX3, true); + getLocalMinMax(dummy, dummy, lMinX3, lMaxX1, dummy, dummy); + distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataOdEv, indexOdEv); + + getLocalMinMax(minX1, maxX1, false, lMinX1, lMaxX1, true); + getLocalMinMax(minX3, maxX3, false, lMinX3, lMaxX3, true); + getLocalMinMax(dummy, dummy, dummy, lMaxX1, dummy, lMaxX3); + distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataOdOd, indexOdOd); + break; + case T: + lMinX3 = maxX3 - 4; + lMaxX3 = lMinX3 + 1; + getLocalMinMax(minX1, maxX1, true, lMinX1, lMaxX1, true); + getLocalMinMax(minX2, maxX2, true, lMinX2, lMaxX2, true); + getLocalMinMax(lMinX1, lMinX2, dummy, dummy, dummy, dummy); + distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); + + getLocalMinMax(minX1, maxX1, true, lMinX1, lMaxX1, true); + getLocalMinMax(minX2, maxX2, false, lMinX2, lMaxX2, true); + getLocalMinMax(lMinX1, dummy, dummy, dummy, lMaxX2, dummy); + distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvOd, indexEvOd); + + getLocalMinMax(minX1, maxX1, false, lMinX1, lMaxX1, true); + getLocalMinMax(minX2, maxX2, true, lMinX2, lMaxX2, true); + getLocalMinMax(dummy, lMinX2, dummy, lMaxX1, dummy, dummy); + distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataOdEv, indexOdEv); + + getLocalMinMax(minX1, maxX1, false, lMinX1, lMaxX1, true); + getLocalMinMax(minX2, maxX2, false, lMinX2, lMaxX2, true); + getLocalMinMax(dummy, dummy, dummy, lMaxX1, lMaxX2, dummy); + distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataOdOd, indexOdOd); + break; + case B: + lMinX3 = 3; + lMaxX3 = lMinX3 + 1; + getLocalMinMax(minX1, maxX1, true, lMinX1, lMaxX1, true); + getLocalMinMax(minX2, maxX2, true, lMinX2, lMaxX2, true); + getLocalMinMax(lMinX1, lMinX2, dummy, dummy, dummy, dummy); + distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); + + getLocalMinMax(minX1, maxX1, true, lMinX1, lMaxX1, true); + getLocalMinMax(minX2, maxX2, false, lMinX2, lMaxX2, true); + getLocalMinMax(lMinX1, dummy, dummy, dummy, lMaxX2, dummy); + distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvOd, indexEvOd); + + getLocalMinMax(minX1, maxX1, false, lMinX1, lMaxX1, true); + getLocalMinMax(minX2, maxX2, true, lMinX2, lMaxX2, true); + getLocalMinMax(dummy, lMinX2, dummy, lMaxX1, dummy, dummy); + distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataOdEv, indexOdEv); + + getLocalMinMax(minX1, maxX1, false, lMinX1, lMaxX1, true); + getLocalMinMax(minX2, maxX2, false, lMinX2, lMaxX2, true); + getLocalMinMax(dummy, dummy, dummy, lMaxX1, lMaxX2, dummy); + distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataOdOd, indexOdOd); + break; + + // /////E-W-N-S + case NE: + lMinX1 = maxX1 - 4; + lMaxX1 = lMinX1 + 3; + lMinX2 = maxX2 - 4; + lMaxX2 = lMinX2 + 1; + getLocalMinMax(minX3, maxX3, true, lMinX3, lMaxX3, true); + getLocalMinMax(dummy, dummy, lMinX3, dummy, dummy, dummy); + distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); + + getLocalMinMax(minX3, maxX3, false, lMinX3, lMaxX3, true); + getLocalMinMax(dummy, dummy, dummy, dummy, dummy, lMaxX3); + distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataOdEv, indexOdEv); + + lMinX1 = maxX1 - 4; + lMaxX1 = lMinX1 + 1; + lMinX2 = maxX2 - 4; + lMaxX2 = lMinX2 + 3; + getLocalMinMax(minX3, maxX3, true, lMinX3, lMaxX3, true); + getLocalMinMax(dummy, dummy, lMinX3, dummy, dummy, dummy); + distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); + + getLocalMinMax(minX3, maxX3, false, lMinX3, lMaxX3, true); + getLocalMinMax(dummy, dummy, dummy, dummy, dummy, lMaxX3); + distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataOdEv, indexOdEv); + + break; + + case SW: + lMinX1 = 1; + lMaxX1 = lMinX1 + 3; + lMinX2 = 3; + lMaxX2 = lMinX2 + 1; + getLocalMinMax(minX3, maxX3, true, lMinX3, lMaxX3, true); + getLocalMinMax(dummy, dummy, lMinX3, dummy, dummy, dummy); + distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); + + getLocalMinMax(minX3, maxX3, false, lMinX3, lMaxX3, true); + getLocalMinMax(dummy, dummy, dummy, dummy, dummy, lMaxX3); + distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataOdEv, indexOdEv); + + lMinX1 = 3; + lMaxX1 = lMinX1 + 1; + lMinX2 = 1; + lMaxX2 = lMinX2 + 3; + getLocalMinMax(minX3, maxX3, true, lMinX3, lMaxX3, true); + getLocalMinMax(dummy, dummy, lMinX3, dummy, dummy, dummy); + distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); + + getLocalMinMax(minX3, maxX3, false, lMinX3, lMaxX3, true); + getLocalMinMax(dummy, dummy, dummy, dummy, dummy, lMaxX3); + distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataOdEv, indexOdEv); + + break; + + case SE: + lMinX1 = maxX1 - 4; + lMaxX1 = lMinX1 + 3; + lMinX2 = 3; + lMaxX2 = lMinX2 + 1; + getLocalMinMax(minX3, maxX3, true, lMinX3, lMaxX3, true); + getLocalMinMax(dummy, dummy, lMinX3, dummy, dummy, dummy); + distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); + + getLocalMinMax(minX3, maxX3, false, lMinX3, lMaxX3, true); + getLocalMinMax(dummy, dummy, dummy, dummy, dummy, lMaxX3); + distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataOdEv, indexOdEv); + + lMinX1 = maxX1 - 4; + lMaxX1 = lMinX1 + 1; + lMinX2 = 1; + lMaxX2 = lMinX2 + 3; + getLocalMinMax(minX3, maxX3, true, lMinX3, lMaxX3, true); + getLocalMinMax(dummy, dummy, lMinX3, dummy, dummy, dummy); + distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); + + getLocalMinMax(minX3, maxX3, false, lMinX3, lMaxX3, true); + getLocalMinMax(dummy, dummy, dummy, dummy, dummy, lMaxX3); + distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataOdEv, indexOdEv); + + break; + + case NW: + lMinX1 = 1; + lMaxX1 = lMinX1 + 3; + lMinX2 = maxX2 - 4; + lMaxX2 = lMinX2 + 1; + getLocalMinMax(minX3, maxX3, true, lMinX3, lMaxX3, true); + getLocalMinMax(dummy, dummy, lMinX3, dummy, dummy, dummy); + distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); + + getLocalMinMax(minX3, maxX3, false, lMinX3, lMaxX3, true); + getLocalMinMax(dummy, dummy, dummy, dummy, dummy, lMaxX3); + distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataOdEv, indexOdEv); + + lMinX1 = 3; + lMaxX1 = lMinX1 + 1; + lMinX2 = maxX2 - 4; + lMaxX2 = lMinX2 + 3; + getLocalMinMax(minX3, maxX3, true, lMinX3, lMaxX3, true); + getLocalMinMax(dummy, dummy, lMinX3, dummy, dummy, dummy); + distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); + + getLocalMinMax(minX3, maxX3, false, lMinX3, lMaxX3, true); + getLocalMinMax(dummy, dummy, dummy, dummy, dummy, lMaxX3); + distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataOdEv, indexOdEv); + + break; + // /////T-B-E-W + case TE: + lMinX1 = maxX1 - 4; + lMaxX1 = lMinX1 + 3; + lMinX3 = maxX3 - 4; + lMaxX3 = lMinX3 + 1; + getLocalMinMax(minX2, maxX2, true, lMinX2, lMaxX2, true); + getLocalMinMax(dummy, lMinX2, dummy, dummy, dummy, dummy); + distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); + + getLocalMinMax(minX2, maxX2, false, lMinX2, lMaxX2, true); + getLocalMinMax(dummy, dummy, dummy, dummy, lMaxX2, dummy); + distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataOdEv, indexOdEv); + + lMinX1 = maxX1 - 4; + lMaxX1 = lMinX1 + 1; + lMinX3 = maxX3 - 4; + lMaxX3 = lMinX3 + 3; + getLocalMinMax(minX2, maxX2, true, lMinX2, lMaxX2, true); + getLocalMinMax(dummy, lMinX2, dummy, dummy, dummy, dummy); + distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); + + getLocalMinMax(minX2, maxX2, false, lMinX2, lMaxX2, true); + getLocalMinMax(dummy, dummy, dummy, dummy, lMaxX2, dummy); + distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataOdEv, indexOdEv); + + break; + + case BW: + lMinX1 = 1; + lMaxX1 = lMinX1 + 3; + lMinX3 = 3; + lMaxX3 = lMinX3 + 1; + getLocalMinMax(minX2, maxX2, true, lMinX2, lMaxX2, true); + getLocalMinMax(dummy, lMinX2, dummy, dummy, dummy, dummy); + distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); + + getLocalMinMax(minX2, maxX2, false, lMinX2, lMaxX2, true); + getLocalMinMax(dummy, dummy, dummy, dummy, lMaxX2, dummy); + distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataOdEv, indexOdEv); + + lMinX1 = 3; + lMaxX1 = lMinX1 + 1; + lMinX3 = 1; + lMaxX3 = lMinX3 + 3; + getLocalMinMax(minX2, maxX2, true, lMinX2, lMaxX2, true); + getLocalMinMax(dummy, lMinX2, dummy, dummy, dummy, dummy); + distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); + + getLocalMinMax(minX2, maxX2, false, lMinX2, lMaxX2, true); + getLocalMinMax(dummy, dummy, dummy, dummy, lMaxX2, dummy); + distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataOdEv, indexOdEv); + + break; + + case BE: + lMinX1 = maxX1 - 4; + lMaxX1 = lMinX1 + 3; + lMinX3 = 3; + lMaxX3 = lMinX3 + 1; + getLocalMinMax(minX2, maxX2, true, lMinX2, lMaxX2, true); + getLocalMinMax(dummy, lMinX2, dummy, dummy, dummy, dummy); + distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); + + getLocalMinMax(minX2, maxX2, false, lMinX2, lMaxX2, true); + getLocalMinMax(dummy, dummy, dummy, dummy, lMaxX2, dummy); + distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataOdEv, indexOdEv); + + lMinX1 = maxX1 - 4; + lMaxX1 = lMinX1 + 1; + lMinX3 = 1; + lMaxX3 = lMinX3 + 3; + getLocalMinMax(minX2, maxX2, true, lMinX2, lMaxX2, true); + getLocalMinMax(dummy, lMinX2, dummy, dummy, dummy, dummy); + distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); + + getLocalMinMax(minX2, maxX2, false, lMinX2, lMaxX2, true); + getLocalMinMax(dummy, dummy, dummy, dummy, lMaxX2, dummy); + distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataOdEv, indexOdEv); + + break; + + case TW: + lMinX1 = 1; + lMaxX1 = lMinX1 + 3; + lMinX3 = maxX3 - 4; + lMaxX3 = lMinX3 + 1; + getLocalMinMax(minX2, maxX2, true, lMinX2, lMaxX2, true); + getLocalMinMax(dummy, lMinX2, dummy, dummy, dummy, dummy); + distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); + + getLocalMinMax(minX2, maxX2, false, lMinX2, lMaxX2, true); + getLocalMinMax(dummy, dummy, dummy, dummy, lMaxX2, dummy); + distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataOdEv, indexOdEv); + + lMinX1 = 3; + lMaxX1 = lMinX1 + 1; + lMinX3 = maxX3 - 4; + lMaxX3 = lMinX3 + 3; + getLocalMinMax(minX2, maxX2, true, lMinX2, lMaxX2, true); + getLocalMinMax(dummy, lMinX2, dummy, dummy, dummy, dummy); + distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); + + getLocalMinMax(minX2, maxX2, false, lMinX2, lMaxX2, true); + getLocalMinMax(dummy, dummy, dummy, dummy, lMaxX2, dummy); + distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataOdEv, indexOdEv); + + break; + + /////////////////////////T-N-B-S + case TN: + lMinX2 = maxX2 - 4; + lMaxX2 = lMinX2 + 3; + lMinX3 = maxX3 - 4; + lMaxX3 = lMinX3 + 1; + getLocalMinMax(minX1, maxX1, true, lMinX1, lMaxX1, true); + getLocalMinMax(lMinX1, dummy, dummy, dummy, dummy, dummy); + distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); + + getLocalMinMax(minX1, maxX1, false, lMinX1, lMaxX1, true); + getLocalMinMax(dummy, dummy, dummy, lMaxX1, dummy, dummy); + distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataOdEv, indexOdEv); + + lMinX2 = maxX2 - 4; + lMaxX2 = lMinX2 + 1; + lMinX3 = maxX3 - 4; + lMaxX3 = lMinX3 + 3; + getLocalMinMax(minX1, maxX1, true, lMinX1, lMaxX1, true); + getLocalMinMax(lMinX1, dummy, dummy, dummy, dummy, dummy); + distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); + + getLocalMinMax(minX1, maxX1, false, lMinX1, lMaxX1, true); + getLocalMinMax(dummy, dummy, dummy, lMaxX1, dummy, dummy); + distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataOdEv, indexOdEv); + + break; + + case BS: + lMinX2 = 1; + lMaxX2 = lMinX2 + 3; + lMinX3 = 3; + lMaxX3 = lMinX3 + 1; + getLocalMinMax(minX1, maxX1, true, lMinX1, lMaxX1, true); + getLocalMinMax(lMinX1, dummy, dummy, dummy, dummy, dummy); + distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); + + getLocalMinMax(minX1, maxX1, false, lMinX1, lMaxX1, true); + getLocalMinMax(dummy, dummy, dummy, lMaxX1, dummy, dummy); + distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataOdEv, indexOdEv); + + lMinX2 = 3; + lMaxX2 = lMinX2 + 1; + lMinX3 = 1; + lMaxX3 = lMinX3 + 3; + getLocalMinMax(minX1, maxX1, true, lMinX1, lMaxX1, true); + getLocalMinMax(lMinX1, dummy, dummy, dummy, dummy, dummy); + distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); + + getLocalMinMax(minX1, maxX1, false, lMinX1, lMaxX1, true); + getLocalMinMax(dummy, dummy, dummy, lMaxX1, dummy, dummy); + distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataOdEv, indexOdEv); + + break; + + case BN: + lMinX2 = maxX2 - 4; + lMaxX2 = lMinX2 + 3; + lMinX3 = 3; + lMaxX3 = lMinX3 + 1; + getLocalMinMax(minX1, maxX1, true, lMinX1, lMaxX1, true); + getLocalMinMax(lMinX1, dummy, dummy, dummy, dummy, dummy); + distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); + + getLocalMinMax(minX1, maxX1, false, lMinX1, lMaxX1, true); + getLocalMinMax(dummy, dummy, dummy, lMaxX1, dummy, dummy); + distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataOdEv, indexOdEv); + + lMinX2 = maxX2 - 4; + lMaxX2 = lMinX2 + 1; + lMinX3 = 1; + lMaxX3 = lMinX3 + 3; + getLocalMinMax(minX1, maxX1, true, lMinX1, lMaxX1, true); + getLocalMinMax(lMinX1, dummy, dummy, dummy, dummy, dummy); + distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); + + getLocalMinMax(minX1, maxX1, false, lMinX1, lMaxX1, true); + getLocalMinMax(dummy, dummy, dummy, lMaxX1, dummy, dummy); + distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataOdEv, indexOdEv); + + break; + + case TS: + lMinX2 = 1; + lMaxX2 = lMinX2 + 3; + lMinX3 = maxX3 - 4; + lMaxX3 = lMinX3 + 1; + getLocalMinMax(minX1, maxX1, true, lMinX1, lMaxX1, true); + getLocalMinMax(lMinX1, dummy, dummy, dummy, dummy, dummy); + distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); + + getLocalMinMax(minX1, maxX1, false, lMinX1, lMaxX1, true); + getLocalMinMax(dummy, dummy, dummy, lMaxX1, dummy, dummy); + distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataOdEv, indexOdEv); + + lMinX2 = 3; + lMaxX2 = lMinX2 + 1; + lMinX3 = maxX3 - 4; + lMaxX3 = lMinX3 + 3; + getLocalMinMax(minX1, maxX1, true, lMinX1, lMaxX1, true); + getLocalMinMax(lMinX1, dummy, dummy, dummy, dummy, dummy); + distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); + + getLocalMinMax(minX1, maxX1, false, lMinX1, lMaxX1, true); + getLocalMinMax(dummy, dummy, dummy, lMaxX1, dummy, dummy); + distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataOdEv, indexOdEv); + + break; + + // TNE + case TNE: + lMinX1 = maxX1 - 4; + lMaxX1 = maxX1 - 3; + lMinX2 = maxX2 - 4; + lMaxX2 = maxX2 - 1; + lMinX3 = maxX3 - 4; + lMaxX3 = maxX3 - 1; + distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); + + lMinX1 = maxX1 - 4; + lMaxX1 = maxX1 - 1; + lMinX2 = maxX2 - 4; + lMaxX2 = maxX2 - 3; + lMinX3 = maxX3 - 4; + lMaxX3 = maxX3 - 1; + distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); + + lMinX1 = maxX1 - 4; + lMaxX1 = maxX1 - 1; + lMinX2 = maxX2 - 4; + lMaxX2 = maxX2 - 1; + lMinX3 = maxX3 - 4; + lMaxX3 = maxX3 - 3; + distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); + + break; + // TNW + case TNW: + lMinX1 = 3; + lMaxX1 = 4; + lMinX2 = maxX2 - 4; + lMaxX2 = maxX2 - 1; + lMinX3 = maxX3 - 4; + lMaxX3 = maxX3 - 1; + distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); + + lMinX1 = 1; + lMaxX1 = 4; + lMinX2 = maxX2 - 4; + lMaxX2 = maxX2 - 3; + lMinX3 = maxX3 - 4; + lMaxX3 = maxX3 - 1; + distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); + + lMinX1 = 1; + lMaxX1 = 4; + lMinX2 = maxX2 - 4; + lMaxX2 = maxX2 - 1; + lMinX3 = maxX3 - 4; + lMaxX3 = maxX3 - 3; + distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); + + break; + // TSE + case TSE: + lMinX1 = maxX1 - 4; + lMaxX1 = maxX1 - 3; + lMinX2 = 1; + lMaxX2 = 4; + lMinX3 = maxX3 - 4; + lMaxX3 = maxX3 - 1; + distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); + + lMinX1 = maxX1 - 4; + lMaxX1 = maxX1 - 1; + lMinX2 = 3; + lMaxX2 = 4; + lMinX3 = maxX3 - 4; + lMaxX3 = maxX3 - 1; + distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); + + lMinX1 = maxX1 - 4; + lMaxX1 = maxX1 - 1; + lMinX2 = 1; + lMaxX2 = 4; + lMinX3 = maxX3 - 4; + lMaxX3 = maxX3 - 3; + distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); + break; + // TSW + case TSW: + lMinX1 = 3; + lMaxX1 = 4; + lMinX2 = 1; + lMaxX2 = 4; + lMinX3 = maxX3 - 4; + lMaxX3 = maxX3 - 1; + distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); + + lMinX1 = 1; + lMaxX1 = 4; + lMinX2 = 3; + lMaxX2 = 4; + lMinX3 = maxX3 - 4; + lMaxX3 = maxX3 - 1; + distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); + + lMinX1 = 1; + lMaxX1 = 4; + lMinX2 = 1; + lMaxX2 = 4; + lMinX3 = maxX3 - 4; + lMaxX3 = maxX3 - 3; + distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); + break; + // BNE + case BNE: + lMinX1 = maxX1 - 4; + lMaxX1 = maxX1 - 3; + lMinX2 = maxX2 - 4; + lMaxX2 = maxX2 - 1; + lMinX3 = 1; + lMaxX3 = 4; + distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); + + lMinX1 = maxX1 - 4; + lMaxX1 = maxX1 - 1; + lMinX2 = maxX2 - 4; + lMaxX2 = maxX2 - 3; + lMinX3 = 1; + lMaxX3 = 4; + distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); + + lMinX1 = maxX1 - 4; + lMaxX1 = maxX1 - 1; + lMinX2 = maxX2 - 4; + lMaxX2 = maxX2 - 1; + lMinX3 = 3; + lMaxX3 = 4; + distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); + + break; + // BNW + case BNW: + lMinX1 = 3; + lMaxX1 = 4; + lMinX2 = maxX2 - 4; + lMaxX2 = maxX2 - 1; + lMinX3 = 1; + lMaxX3 = 4; + distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); + + lMinX1 = 1; + lMaxX1 = 4; + lMinX2 = maxX2 - 4; + lMaxX2 = maxX2 - 3; + lMinX3 = 1; + lMaxX3 = 4; + distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); + + lMinX1 = 1; + lMaxX1 = 4; + lMinX2 = maxX2 - 4; + lMaxX2 = maxX2 - 1; + lMinX3 = 3; + lMaxX3 = 4; + distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); + break; + // BSE + case BSE: + lMinX1 = maxX1 - 4; + lMaxX1 = maxX1 - 3; + lMinX2 = 1; + lMaxX2 = 4; + lMinX3 = 1; + lMaxX3 = 4; + distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); + + lMinX1 = maxX1 - 4; + lMaxX1 = maxX1 - 1; + lMinX2 = 3; + lMaxX2 = 4; + lMinX3 = 1; + lMaxX3 = 4; + distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); + + lMinX1 = maxX1 - 4; + lMaxX1 = maxX1 - 1; + lMinX2 = 1; + lMaxX2 = 4; + lMinX3 = 3; + lMaxX3 = 4; + distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); + break; + // BSW + case BSW: + lMinX1 = 3; + lMaxX1 = 4; + lMinX2 = 1; + lMaxX2 = 4; + lMinX3 = 1; + lMaxX3 = 4; + distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); + + lMinX1 = 1; + lMaxX1 = 4; + lMinX2 = 3; + lMaxX2 = 4; + lMinX3 = 1; + lMaxX3 = 4; + distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); + + lMinX1 = 1; + lMaxX1 = 4; + lMinX2 = 1; + lMaxX2 = 4; + lMinX3 = 3; + lMaxX3 = 4; + distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); + + break; + } } ////////////////////////////////////////////////////////////////////////// -template< typename VectorTransmitter > -void D3Q27ETCFOffVectorConnector< VectorTransmitter>::distributeReceiveVector(SPtr<DistributionArray3D> fTo, const int& lMinX1, const int& lMinX2, const int& lMinX3, const int& lMaxX1, const int& lMaxX2, const int& lMaxX3, vector_type& data, int& index) +template <typename VectorTransmitter> +void D3Q27ETCFOffVectorConnector<VectorTransmitter>::distributeReceiveVector(SPtr<DistributionArray3D> fTo, + const int &lMinX1, const int &lMinX2, + const int &lMinX3, const int &lMaxX1, + const int &lMaxX2, const int &lMaxX3, + vector_type &data, int &index) { - if (data.size() == 0) return; - - int ix1, ix2, ix3; - for (ix3 = lMinX3; ix3 < lMaxX3; ix3++) - { - for (ix2 = lMinX2; ix2 < lMaxX2; ix2++) - { - for (ix1 = lMinX1; ix1 < lMaxX1; ix1++) - { - LBMReal icellC[27]; - this->readICellCfromData(data, index, icellC); - iprocessor->writeINodeInv(fTo, icellC, ix1, ix2, ix3); - } - } - } + if (data.size() == 0) + return; + + int ix1, ix2, ix3; + for (ix3 = lMinX3; ix3 < lMaxX3; ix3++) { + for (ix2 = lMinX2; ix2 < lMaxX2; ix2++) { + for (ix1 = lMinX1; ix1 < lMaxX1; ix1++) { + LBMReal icellC[27]; + this->readICellCfromData(data, index, icellC); + iprocessor->writeINodeInv(fTo, icellC, ix1, ix2, ix3); + } + } + } } ////////////////////////////////////////////////////////////////////////// -template< typename VectorTransmitter > -void D3Q27ETCFOffVectorConnector< VectorTransmitter>::readICellCfromData(vector_type& data, int& index, LBMReal* icellC) +template <typename VectorTransmitter> +void D3Q27ETCFOffVectorConnector<VectorTransmitter>::readICellCfromData(vector_type &data, int &index, LBMReal *icellC) { - for (int i = D3Q27System::STARTF; i < D3Q27System::ENDF + 1; i++) - { - icellC[i] = data[index++]; - } + for (int i = D3Q27System::STARTF; i < D3Q27System::ENDF + 1; i++) { + icellC[i] = data[index++]; + } } ////////////////////////////////////////////////////////////////////////// -template< typename VectorTransmitter > -void D3Q27ETCFOffVectorConnector< VectorTransmitter>::getLocalMinMax(int& minX1, int& minX2, int& minX3, int& maxX1, int& maxX2, int& maxX3) +template <typename VectorTransmitter> +void D3Q27ETCFOffVectorConnector<VectorTransmitter>::getLocalMinMax(int &minX1, int &minX2, int &minX3, int &maxX1, + int &maxX2, int &maxX3) { - using namespace D3Q27System; - int TminX1 = minX1; int TminX2 = minX2; int TminX3 = minX3; int TmaxX1 = maxX1; int TmaxX2 = maxX2; int TmaxX3 = maxX3; - - if (block.lock()->hasInterpolationFlagCF(E)) - { - if (maxX1 == TmaxX1) maxX1 -= 2; - } - if (block.lock()->hasInterpolationFlagCF(W)) - { - if (minX1 == TminX1) minX1 += 2; - } - if (block.lock()->hasInterpolationFlagCF(N)) - { - if (maxX2 == TmaxX2) maxX2 -= 2; - } - if (block.lock()->hasInterpolationFlagCF(S)) - { - if (minX2 == TminX2) minX2 += 2; - } - if (block.lock()->hasInterpolationFlagCF(T)) - { - if (maxX3 == TmaxX3) maxX3 -= 2; - } - if (block.lock()->hasInterpolationFlagCF(B)) - { - if (minX3 == TminX3) minX3 += 2; - } - - //E-W-N-S - if (block.lock()->hasInterpolationFlagCF(NE) && !block.lock()->hasInterpolationFlagCF(N) && !block.lock()->hasInterpolationFlagCF(E)) - { - if (maxX1 == TmaxX1) maxX1 -= 2; - if (maxX2 == TmaxX2) maxX2 -= 2; - } - if (block.lock()->hasInterpolationFlagCF(SW) && !block.lock()->hasInterpolationFlagCF(W) && !block.lock()->hasInterpolationFlagCF(S)) - { - if (minX1 == TminX1) minX1 += 2; - if (minX2 == TminX2) minX2 += 2; - } - if (block.lock()->hasInterpolationFlagCF(SE) && !block.lock()->hasInterpolationFlagCF(E) && !block.lock()->hasInterpolationFlagCF(S)) - { - if (maxX1 == TmaxX1) maxX1 -= 2; - if (minX2 == TminX2) minX2 += 2; - } - if (block.lock()->hasInterpolationFlagCF(NW) && !block.lock()->hasInterpolationFlagCF(N) && !block.lock()->hasInterpolationFlagCF(W)) - { - if (minX1 == TminX1) minX1 += 2; - if (maxX2 == TmaxX2) maxX2 -= 2; - } - - // ////T-B-E-W - if (block.lock()->hasInterpolationFlagCF(TE) && !block.lock()->hasInterpolationFlagCF(E) && !block.lock()->hasInterpolationFlagCF(T)) - { - if (maxX1 == TmaxX1) maxX1 -= 2; - if (maxX3 == TmaxX3) maxX3 -= 2; - } - if (block.lock()->hasInterpolationFlagCF(BW) && !block.lock()->hasInterpolationFlagCF(W) && !block.lock()->hasInterpolationFlagCF(B)) - { - if (minX1 == TminX1) minX1 += 2; - if (minX3 == TminX3) minX3 += 2; - } - if (block.lock()->hasInterpolationFlagCF(BE) && !block.lock()->hasInterpolationFlagCF(E) && !block.lock()->hasInterpolationFlagCF(B)) - { - if (maxX1 == TmaxX1) maxX1 -= 2; - if (minX3 == TminX3) minX3 += 2; - } - if (block.lock()->hasInterpolationFlagCF(TW) && !block.lock()->hasInterpolationFlagCF(W) && !block.lock()->hasInterpolationFlagCF(T)) - { - if (minX1 == TminX1) minX1 += 2; - if (maxX3 == TmaxX3) maxX3 -= 2; - } - - - ////T-B-N-S - if (block.lock()->hasInterpolationFlagCF(TN) && !block.lock()->hasInterpolationFlagCF(N) && !block.lock()->hasInterpolationFlagCF(T)) - { - if (maxX2 == TmaxX2) maxX2 -= 2; - if (maxX3 == TmaxX3) maxX3 -= 2; - } - if (block.lock()->hasInterpolationFlagCF(BS) && !block.lock()->hasInterpolationFlagCF(S) && !block.lock()->hasInterpolationFlagCF(B)) - { - if (minX2 == TminX2) minX2 += 2; - if (minX3 == TminX3) minX3 += 2; - } - if (block.lock()->hasInterpolationFlagCF(BN) && !block.lock()->hasInterpolationFlagCF(N) && !block.lock()->hasInterpolationFlagCF(B)) - { - if (maxX2 == TmaxX2) maxX2 -= 2; - if (minX3 == TminX3) minX3 += 2; - } - if (block.lock()->hasInterpolationFlagCF(TS) && !block.lock()->hasInterpolationFlagCF(S) && !block.lock()->hasInterpolationFlagCF(T)) - { - if (minX2 == TminX2) minX2 += 2; - if (maxX3 == TmaxX3) maxX3 -= 2; - } - - //if (block.lock()->hasInterpolationFlagCF(D3Q27System::TNE)&&!block.lock()->hasInterpolationFlagCF(D3Q27System::TE)&&!block.lock()->hasInterpolationFlagCF(D3Q27System::TN)&&!block.lock()->hasInterpolationFlagCF(D3Q27System::NE)&&!block.lock()->hasInterpolationFlagCF(D3Q27System::T)&&!block.lock()->hasInterpolationFlagCF(D3Q27System::N) && !block.lock()->hasInterpolationFlagCF(D3Q27System::E)) - //if (!block.lock()->hasInterpolationFlagCF(D3Q27System::TE)&&!block.lock()->hasInterpolationFlagCF(D3Q27System::T)&& !block.lock()->hasInterpolationFlagCF(D3Q27System::E)) - //{ - // if (maxX1==TmaxX1) maxX1 -= 2; - // if (maxX2==TmaxX2) maxX2 -= 2; - // if (maxX3==TmaxX3) maxX3 -= 2; - //} + using namespace D3Q27System; + int TminX1 = minX1; + int TminX2 = minX2; + int TminX3 = minX3; + int TmaxX1 = maxX1; + int TmaxX2 = maxX2; + int TmaxX3 = maxX3; + + if (block.lock()->hasInterpolationFlagCF(E)) { + if (maxX1 == TmaxX1) + maxX1 -= 2; + } + if (block.lock()->hasInterpolationFlagCF(W)) { + if (minX1 == TminX1) + minX1 += 2; + } + if (block.lock()->hasInterpolationFlagCF(N)) { + if (maxX2 == TmaxX2) + maxX2 -= 2; + } + if (block.lock()->hasInterpolationFlagCF(S)) { + if (minX2 == TminX2) + minX2 += 2; + } + if (block.lock()->hasInterpolationFlagCF(T)) { + if (maxX3 == TmaxX3) + maxX3 -= 2; + } + if (block.lock()->hasInterpolationFlagCF(B)) { + if (minX3 == TminX3) + minX3 += 2; + } + + // E-W-N-S + if (block.lock()->hasInterpolationFlagCF(NE) && !block.lock()->hasInterpolationFlagCF(N) && + !block.lock()->hasInterpolationFlagCF(E)) { + if (maxX1 == TmaxX1) + maxX1 -= 2; + if (maxX2 == TmaxX2) + maxX2 -= 2; + } + if (block.lock()->hasInterpolationFlagCF(SW) && !block.lock()->hasInterpolationFlagCF(W) && + !block.lock()->hasInterpolationFlagCF(S)) { + if (minX1 == TminX1) + minX1 += 2; + if (minX2 == TminX2) + minX2 += 2; + } + if (block.lock()->hasInterpolationFlagCF(SE) && !block.lock()->hasInterpolationFlagCF(E) && + !block.lock()->hasInterpolationFlagCF(S)) { + if (maxX1 == TmaxX1) + maxX1 -= 2; + if (minX2 == TminX2) + minX2 += 2; + } + if (block.lock()->hasInterpolationFlagCF(NW) && !block.lock()->hasInterpolationFlagCF(N) && + !block.lock()->hasInterpolationFlagCF(W)) { + if (minX1 == TminX1) + minX1 += 2; + if (maxX2 == TmaxX2) + maxX2 -= 2; + } + + // ////T-B-E-W + if (block.lock()->hasInterpolationFlagCF(TE) && !block.lock()->hasInterpolationFlagCF(E) && + !block.lock()->hasInterpolationFlagCF(T)) { + if (maxX1 == TmaxX1) + maxX1 -= 2; + if (maxX3 == TmaxX3) + maxX3 -= 2; + } + if (block.lock()->hasInterpolationFlagCF(BW) && !block.lock()->hasInterpolationFlagCF(W) && + !block.lock()->hasInterpolationFlagCF(B)) { + if (minX1 == TminX1) + minX1 += 2; + if (minX3 == TminX3) + minX3 += 2; + } + if (block.lock()->hasInterpolationFlagCF(BE) && !block.lock()->hasInterpolationFlagCF(E) && + !block.lock()->hasInterpolationFlagCF(B)) { + if (maxX1 == TmaxX1) + maxX1 -= 2; + if (minX3 == TminX3) + minX3 += 2; + } + if (block.lock()->hasInterpolationFlagCF(TW) && !block.lock()->hasInterpolationFlagCF(W) && + !block.lock()->hasInterpolationFlagCF(T)) { + if (minX1 == TminX1) + minX1 += 2; + if (maxX3 == TmaxX3) + maxX3 -= 2; + } + + ////T-B-N-S + if (block.lock()->hasInterpolationFlagCF(TN) && !block.lock()->hasInterpolationFlagCF(N) && + !block.lock()->hasInterpolationFlagCF(T)) { + if (maxX2 == TmaxX2) + maxX2 -= 2; + if (maxX3 == TmaxX3) + maxX3 -= 2; + } + if (block.lock()->hasInterpolationFlagCF(BS) && !block.lock()->hasInterpolationFlagCF(S) && + !block.lock()->hasInterpolationFlagCF(B)) { + if (minX2 == TminX2) + minX2 += 2; + if (minX3 == TminX3) + minX3 += 2; + } + if (block.lock()->hasInterpolationFlagCF(BN) && !block.lock()->hasInterpolationFlagCF(N) && + !block.lock()->hasInterpolationFlagCF(B)) { + if (maxX2 == TmaxX2) + maxX2 -= 2; + if (minX3 == TminX3) + minX3 += 2; + } + if (block.lock()->hasInterpolationFlagCF(TS) && !block.lock()->hasInterpolationFlagCF(S) && + !block.lock()->hasInterpolationFlagCF(T)) { + if (minX2 == TminX2) + minX2 += 2; + if (maxX3 == TmaxX3) + maxX3 -= 2; + } + + // if + // (block.lock()->hasInterpolationFlagCF(D3Q27System::TNE)&&!block.lock()->hasInterpolationFlagCF(D3Q27System::TE)&&!block.lock()->hasInterpolationFlagCF(D3Q27System::TN)&&!block.lock()->hasInterpolationFlagCF(D3Q27System::NE)&&!block.lock()->hasInterpolationFlagCF(D3Q27System::T)&&!block.lock()->hasInterpolationFlagCF(D3Q27System::N) + // && !block.lock()->hasInterpolationFlagCF(D3Q27System::E)) if + // (!block.lock()->hasInterpolationFlagCF(D3Q27System::TE)&&!block.lock()->hasInterpolationFlagCF(D3Q27System::T)&& + // !block.lock()->hasInterpolationFlagCF(D3Q27System::E)) + //{ + // if (maxX1==TmaxX1) maxX1 -= 2; + // if (maxX2==TmaxX2) maxX2 -= 2; + // if (maxX3==TmaxX3) maxX3 -= 2; + //} } ////////////////////////////////////////////////////////////////////////// -template< typename VectorTransmitter > -void D3Q27ETCFOffVectorConnector< VectorTransmitter>::getLocalMinMax(int& minX1, int& minX2, int& minX3, int& maxX1, int& maxX2, int& maxX3, CFconnectorType /*connType*/) +template <typename VectorTransmitter> +void D3Q27ETCFOffVectorConnector<VectorTransmitter>::getLocalMinMax(int &minX1, int &minX2, int &minX3, int &maxX1, + int &maxX2, int &maxX3, + CFconnectorType /*connType*/) { - using namespace D3Q27System; - int TminX1 = minX1; int TminX2 = minX2; int TminX3 = minX3; int TmaxX1 = maxX1; int TmaxX2 = maxX2; int TmaxX3 = maxX3; - - if (block.lock()->hasInterpolationFlagCF(E)) - { - if (maxX1 == TmaxX1) maxX1 -= 2; - } - if (block.lock()->hasInterpolationFlagCF(W)) - { - if (minX1 == TminX1) minX1 += 2; - } - if (block.lock()->hasInterpolationFlagCF(N)) - { - if (maxX2 == TmaxX2) maxX2 -= 2; - } - if (block.lock()->hasInterpolationFlagCF(S)) - { - if (minX2 == TminX2) minX2 += 2; - } - if (block.lock()->hasInterpolationFlagCF(T)) - { - if (maxX3 == TmaxX3) maxX3 -= 2; - } - if (block.lock()->hasInterpolationFlagCF(B)) - { - if (minX3 == TminX3) minX3 += 2; - } - - //E-W-N-S - if (block.lock()->hasInterpolationFlagCF(NE) && !block.lock()->hasInterpolationFlagCF(N) && !block.lock()->hasInterpolationFlagCF(E)) - { - if (maxX1 == TmaxX1) maxX1 -= 2; - if (maxX2 == TmaxX2) maxX2 -= 2; - } - if (block.lock()->hasInterpolationFlagCF(SW) && !block.lock()->hasInterpolationFlagCF(W) && !block.lock()->hasInterpolationFlagCF(S)) - { - if (minX1 == TminX1) minX1 += 2; - if (minX2 == TminX2) minX2 += 2; - } - if (block.lock()->hasInterpolationFlagCF(SE) && !block.lock()->hasInterpolationFlagCF(E) && !block.lock()->hasInterpolationFlagCF(S)) - { - if (maxX1 == TmaxX1) maxX1 -= 2; - if (minX2 == TminX2) minX2 += 2; - } - if (block.lock()->hasInterpolationFlagCF(NW) && !block.lock()->hasInterpolationFlagCF(N) && !block.lock()->hasInterpolationFlagCF(W)) - { - if (minX1 == TminX1) minX1 += 2; - if (maxX2 == TmaxX2) maxX2 -= 2; - } - - // ////T-B-E-W - if (block.lock()->hasInterpolationFlagCF(TE) && !block.lock()->hasInterpolationFlagCF(E) && !block.lock()->hasInterpolationFlagCF(T)) - { - if (maxX1 == TmaxX1) maxX1 -= 2; - if (maxX3 == TmaxX3) maxX3 -= 2; - } - if (block.lock()->hasInterpolationFlagCF(BW) && !block.lock()->hasInterpolationFlagCF(W) && !block.lock()->hasInterpolationFlagCF(B)) - { - if (minX1 == TminX1) minX1 += 2; - if (minX3 == TminX3) minX3 += 2; - } - if (block.lock()->hasInterpolationFlagCF(BE) && !block.lock()->hasInterpolationFlagCF(E) && !block.lock()->hasInterpolationFlagCF(B)) - { - if (maxX1 == TmaxX1) maxX1 -= 2; - if (minX3 == TminX3) minX3 += 2; - } - if (block.lock()->hasInterpolationFlagCF(TW) && !block.lock()->hasInterpolationFlagCF(W) && !block.lock()->hasInterpolationFlagCF(T)) - { - if (minX1 == TminX1) minX1 += 2; - if (maxX3 == TmaxX3) maxX3 -= 2; - } - - - ////T-B-N-S - if (block.lock()->hasInterpolationFlagCF(TN) && !block.lock()->hasInterpolationFlagCF(N) && !block.lock()->hasInterpolationFlagCF(T)) - { - if (maxX2 == TmaxX2) maxX2 -= 2; - if (maxX3 == TmaxX3) maxX3 -= 2; - } - if (block.lock()->hasInterpolationFlagCF(BS) && !block.lock()->hasInterpolationFlagCF(S) && !block.lock()->hasInterpolationFlagCF(B)) - { - if (minX2 == TminX2) minX2 += 2; - if (minX3 == TminX3) minX3 += 2; - } - if (block.lock()->hasInterpolationFlagCF(BN) && !block.lock()->hasInterpolationFlagCF(N) && !block.lock()->hasInterpolationFlagCF(B)) - { - if (maxX2 == TmaxX2) maxX2 -= 2; - if (minX3 == TminX3) minX3 += 2; - } - if (block.lock()->hasInterpolationFlagCF(TS) && !block.lock()->hasInterpolationFlagCF(S) && !block.lock()->hasInterpolationFlagCF(T)) - { - if (minX2 == TminX2) minX2 += 2; - if (maxX3 == TmaxX3) maxX3 -= 2; - } - - //if (block.lock()->hasInterpolationFlagCF(D3Q27System::TNE)&&!block.lock()->hasInterpolationFlagCF(D3Q27System::TE)&&!block.lock()->hasInterpolationFlagCF(D3Q27System::TN)&&!block.lock()->hasInterpolationFlagCF(D3Q27System::NE)&&!block.lock()->hasInterpolationFlagCF(D3Q27System::T)&&!block.lock()->hasInterpolationFlagCF(D3Q27System::N) && !block.lock()->hasInterpolationFlagCF(D3Q27System::E)) - //{ - // if (maxX1==TmaxX1) maxX1 -= 2; - // if (maxX2==TmaxX2) maxX2 -= 2; - // if (maxX3==TmaxX3) maxX3 -= 2; - //} + using namespace D3Q27System; + int TminX1 = minX1; + int TminX2 = minX2; + int TminX3 = minX3; + int TmaxX1 = maxX1; + int TmaxX2 = maxX2; + int TmaxX3 = maxX3; + + if (block.lock()->hasInterpolationFlagCF(E)) { + if (maxX1 == TmaxX1) + maxX1 -= 2; + } + if (block.lock()->hasInterpolationFlagCF(W)) { + if (minX1 == TminX1) + minX1 += 2; + } + if (block.lock()->hasInterpolationFlagCF(N)) { + if (maxX2 == TmaxX2) + maxX2 -= 2; + } + if (block.lock()->hasInterpolationFlagCF(S)) { + if (minX2 == TminX2) + minX2 += 2; + } + if (block.lock()->hasInterpolationFlagCF(T)) { + if (maxX3 == TmaxX3) + maxX3 -= 2; + } + if (block.lock()->hasInterpolationFlagCF(B)) { + if (minX3 == TminX3) + minX3 += 2; + } + + // E-W-N-S + if (block.lock()->hasInterpolationFlagCF(NE) && !block.lock()->hasInterpolationFlagCF(N) && + !block.lock()->hasInterpolationFlagCF(E)) { + if (maxX1 == TmaxX1) + maxX1 -= 2; + if (maxX2 == TmaxX2) + maxX2 -= 2; + } + if (block.lock()->hasInterpolationFlagCF(SW) && !block.lock()->hasInterpolationFlagCF(W) && + !block.lock()->hasInterpolationFlagCF(S)) { + if (minX1 == TminX1) + minX1 += 2; + if (minX2 == TminX2) + minX2 += 2; + } + if (block.lock()->hasInterpolationFlagCF(SE) && !block.lock()->hasInterpolationFlagCF(E) && + !block.lock()->hasInterpolationFlagCF(S)) { + if (maxX1 == TmaxX1) + maxX1 -= 2; + if (minX2 == TminX2) + minX2 += 2; + } + if (block.lock()->hasInterpolationFlagCF(NW) && !block.lock()->hasInterpolationFlagCF(N) && + !block.lock()->hasInterpolationFlagCF(W)) { + if (minX1 == TminX1) + minX1 += 2; + if (maxX2 == TmaxX2) + maxX2 -= 2; + } + + // ////T-B-E-W + if (block.lock()->hasInterpolationFlagCF(TE) && !block.lock()->hasInterpolationFlagCF(E) && + !block.lock()->hasInterpolationFlagCF(T)) { + if (maxX1 == TmaxX1) + maxX1 -= 2; + if (maxX3 == TmaxX3) + maxX3 -= 2; + } + if (block.lock()->hasInterpolationFlagCF(BW) && !block.lock()->hasInterpolationFlagCF(W) && + !block.lock()->hasInterpolationFlagCF(B)) { + if (minX1 == TminX1) + minX1 += 2; + if (minX3 == TminX3) + minX3 += 2; + } + if (block.lock()->hasInterpolationFlagCF(BE) && !block.lock()->hasInterpolationFlagCF(E) && + !block.lock()->hasInterpolationFlagCF(B)) { + if (maxX1 == TmaxX1) + maxX1 -= 2; + if (minX3 == TminX3) + minX3 += 2; + } + if (block.lock()->hasInterpolationFlagCF(TW) && !block.lock()->hasInterpolationFlagCF(W) && + !block.lock()->hasInterpolationFlagCF(T)) { + if (minX1 == TminX1) + minX1 += 2; + if (maxX3 == TmaxX3) + maxX3 -= 2; + } + + ////T-B-N-S + if (block.lock()->hasInterpolationFlagCF(TN) && !block.lock()->hasInterpolationFlagCF(N) && + !block.lock()->hasInterpolationFlagCF(T)) { + if (maxX2 == TmaxX2) + maxX2 -= 2; + if (maxX3 == TmaxX3) + maxX3 -= 2; + } + if (block.lock()->hasInterpolationFlagCF(BS) && !block.lock()->hasInterpolationFlagCF(S) && + !block.lock()->hasInterpolationFlagCF(B)) { + if (minX2 == TminX2) + minX2 += 2; + if (minX3 == TminX3) + minX3 += 2; + } + if (block.lock()->hasInterpolationFlagCF(BN) && !block.lock()->hasInterpolationFlagCF(N) && + !block.lock()->hasInterpolationFlagCF(B)) { + if (maxX2 == TmaxX2) + maxX2 -= 2; + if (minX3 == TminX3) + minX3 += 2; + } + if (block.lock()->hasInterpolationFlagCF(TS) && !block.lock()->hasInterpolationFlagCF(S) && + !block.lock()->hasInterpolationFlagCF(T)) { + if (minX2 == TminX2) + minX2 += 2; + if (maxX3 == TmaxX3) + maxX3 -= 2; + } + + // if + // (block.lock()->hasInterpolationFlagCF(D3Q27System::TNE)&&!block.lock()->hasInterpolationFlagCF(D3Q27System::TE)&&!block.lock()->hasInterpolationFlagCF(D3Q27System::TN)&&!block.lock()->hasInterpolationFlagCF(D3Q27System::NE)&&!block.lock()->hasInterpolationFlagCF(D3Q27System::T)&&!block.lock()->hasInterpolationFlagCF(D3Q27System::N) + // && !block.lock()->hasInterpolationFlagCF(D3Q27System::E)) + //{ + // if (maxX1==TmaxX1) maxX1 -= 2; + // if (maxX2==TmaxX2) maxX2 -= 2; + // if (maxX3==TmaxX3) maxX3 -= 2; + //} } ////////////////////////////////////////////////////////////////////////// -template< typename VectorTransmitter > -void D3Q27ETCFOffVectorConnector< VectorTransmitter>::findCFnodes() +template <typename VectorTransmitter> +void D3Q27ETCFOffVectorConnector<VectorTransmitter>::findCFnodes() { - SPtr<DistributionArray3D> fFrom = block.lock()->getKernel()->getDataSet()->getFdistributions(); - int maxX1 = (int)fFrom->getNX1(); - int maxX2 = (int)fFrom->getNX2(); - int maxX3 = (int)fFrom->getNX3(); - int minX1 = 0; - int minX2 = 0; - int minX3 = 0; - - int indexEvEv = 0; - int indexEvOd = 0; - int indexOdEv = 0; - int indexOdOd = 0; - - vector_type& dataEvEv = this->senderEvenEvenSW->getData(); - vector_type& dataEvOd = this->senderEvenOddNW->getData(); - vector_type& dataOdEv = this->senderOddEvenSE->getData(); - vector_type& dataOdOd = this->senderOddOddNE->getData(); - - int lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3; - - using namespace D3Q27System; - if (block.lock()->hasInterpolationFlagCF(W)) - { - lMinX1 = 1; - lMaxX1 = lMinX1 + 1; - - getLocalMinMax(minX2, maxX2, true, lMinX2, lMaxX2, false); - getLocalMinMax(minX3, maxX3, true, lMinX3, lMaxX3, false); - findCFnodes(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); - - getLocalMinMax(minX2, maxX2, true, lMinX2, lMaxX2, false); - getLocalMinMax(minX3, maxX3, false, lMinX3, lMaxX3, false); - findCFnodes(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvOd, indexEvOd); - - getLocalMinMax(minX2, maxX2, false, lMinX2, lMaxX2, false); - getLocalMinMax(minX3, maxX3, true, lMinX3, lMaxX3, false); - findCFnodes(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataOdEv, indexOdEv); - - getLocalMinMax(minX2, maxX2, false, lMinX2, lMaxX2, false); - getLocalMinMax(minX3, maxX3, false, lMinX3, lMaxX3, false); - findCFnodes(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataOdOd, indexOdOd); - } - if (block.lock()->hasInterpolationFlagCF(TN) && !block.lock()->hasInterpolationFlagCF(N) && !block.lock()->hasInterpolationFlagCF(T)) - { - lMinX2 = maxX2 - 3; - lMaxX2 = lMinX2 + 1; - lMinX3 = maxX3 - 3; - lMaxX3 = lMinX3 + 1; - - getLocalMinMax(minX1 + 1, maxX1, true, lMinX1, lMaxX1, false); - findCFnodes(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); - - getLocalMinMax(minX1 + 1, maxX1, false, lMinX1, lMaxX1, false); - findCFnodes(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataOdEv, indexOdEv); - } + SPtr<DistributionArray3D> fFrom = block.lock()->getKernel()->getDataSet()->getFdistributions(); + int maxX1 = (int)fFrom->getNX1(); + int maxX2 = (int)fFrom->getNX2(); + int maxX3 = (int)fFrom->getNX3(); + int minX1 = 0; + int minX2 = 0; + int minX3 = 0; + + int indexEvEv = 0; + int indexEvOd = 0; + int indexOdEv = 0; + int indexOdOd = 0; + + vector_type &dataEvEv = this->senderEvenEvenSW->getData(); + vector_type &dataEvOd = this->senderEvenOddNW->getData(); + vector_type &dataOdEv = this->senderOddEvenSE->getData(); + vector_type &dataOdOd = this->senderOddOddNE->getData(); + + int lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3; + + using namespace D3Q27System; + if (block.lock()->hasInterpolationFlagCF(W)) { + lMinX1 = 1; + lMaxX1 = lMinX1 + 1; + + getLocalMinMax(minX2, maxX2, true, lMinX2, lMaxX2, false); + getLocalMinMax(minX3, maxX3, true, lMinX3, lMaxX3, false); + findCFnodes(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); + + getLocalMinMax(minX2, maxX2, true, lMinX2, lMaxX2, false); + getLocalMinMax(minX3, maxX3, false, lMinX3, lMaxX3, false); + findCFnodes(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvOd, indexEvOd); + + getLocalMinMax(minX2, maxX2, false, lMinX2, lMaxX2, false); + getLocalMinMax(minX3, maxX3, true, lMinX3, lMaxX3, false); + findCFnodes(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataOdEv, indexOdEv); + + getLocalMinMax(minX2, maxX2, false, lMinX2, lMaxX2, false); + getLocalMinMax(minX3, maxX3, false, lMinX3, lMaxX3, false); + findCFnodes(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataOdOd, indexOdOd); + } + if (block.lock()->hasInterpolationFlagCF(TN) && !block.lock()->hasInterpolationFlagCF(N) && + !block.lock()->hasInterpolationFlagCF(T)) { + lMinX2 = maxX2 - 3; + lMaxX2 = lMinX2 + 1; + lMinX3 = maxX3 - 3; + lMaxX3 = lMinX3 + 1; + + getLocalMinMax(minX1 + 1, maxX1, true, lMinX1, lMaxX1, false); + findCFnodes(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataEvEv, indexEvEv); + + getLocalMinMax(minX1 + 1, maxX1, false, lMinX1, lMaxX1, false); + findCFnodes(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, dataOdEv, indexOdEv); + } } ////////////////////////////////////////////////////////////////////////// -template< typename VectorTransmitter > -void D3Q27ETCFOffVectorConnector< VectorTransmitter>::findCFnodes(SPtr<DistributionArray3D> fFrom, const int& lMinX1, const int& lMinX2, const int& lMinX3, const int& lMaxX1, const int& lMaxX2, const int& lMaxX3, vector_type& data, int& index) +template <typename VectorTransmitter> +void D3Q27ETCFOffVectorConnector<VectorTransmitter>::findCFnodes(SPtr<DistributionArray3D> fFrom, const int &lMinX1, + const int &lMinX2, const int &lMinX3, + const int &lMaxX1, const int &lMaxX2, + const int &lMaxX3, vector_type &data, int &index) { - if (data.size() == 0) return; - int ix1, ix2, ix3; - LBMReal xoff, yoff, zoff; - SPtr<BCArray3D> bcArray = block.lock()->getKernel()->getBCProcessor()->getBCArray(); - - for (ix3 = lMinX3; ix3 < lMaxX3; ix3++) - { - for (ix2 = lMinX2; ix2 < lMaxX2; ix2++) - { - for (ix1 = lMinX1; ix1 < lMaxX1; ix1++) - { - D3Q27ICell icellC; - D3Q27ICell icellF; - - int howManySolids = iprocessor->iCellHowManySolids(bcArray, ix1, ix2, ix3); - - if (howManySolids == 0 || howManySolids == 8) - { - iprocessor->readICell(fFrom, icellC, ix1, ix2, ix3); - xoff = 0.0; - yoff = 0.0; - zoff = 0.0; - } - else - { - if (!iprocessor->findNeighborICell(bcArray, fFrom, icellC, bMaxX1, bMaxX2, bMaxX3, ix1, ix2, ix3, xoff, yoff, zoff)) - { - std::string err = "For " + block.lock()->toString() + " x1=" + UbSystem::toString(ix1) + ", x2=" + UbSystem::toString(ix2) + ", x3=" + UbSystem::toString(ix3) + - " interpolation is not implemented for other direction" + - " by using in: " + (std::string)typeid(*this).name() + - " or maybe you have a solid on the block boundary"; - //UBLOG(logINFO, err); - UB_THROW(UbException(UB_EXARGS, err)); - } + if (data.size() == 0) + return; + int ix1, ix2, ix3; + LBMReal xoff, yoff, zoff; + SPtr<BCArray3D> bcArray = block.lock()->getKernel()->getBCProcessor()->getBCArray(); + + for (ix3 = lMinX3; ix3 < lMaxX3; ix3++) { + for (ix2 = lMinX2; ix2 < lMaxX2; ix2++) { + for (ix1 = lMinX1; ix1 < lMaxX1; ix1++) { + D3Q27ICell icellC; + D3Q27ICell icellF; + + int howManySolids = iprocessor->iCellHowManySolids(bcArray, ix1, ix2, ix3); + + if (howManySolids == 0 || howManySolids == 8) { + iprocessor->readICell(fFrom, icellC, ix1, ix2, ix3); + xoff = 0.0; + yoff = 0.0; + zoff = 0.0; + } else { + if (!iprocessor->findNeighborICell(bcArray, fFrom, icellC, bMaxX1, bMaxX2, bMaxX3, ix1, ix2, ix3, + xoff, yoff, zoff)) { + std::string err = "For " + block.lock()->toString() + " x1=" + UbSystem::toString(ix1) + + ", x2=" + UbSystem::toString(ix2) + ", x3=" + UbSystem::toString(ix3) + + " interpolation is not implemented for other direction" + + " by using in: " + (std::string) typeid(*this).name() + + " or maybe you have a solid on the block boundary"; + // UBLOG(logINFO, err); + UB_THROW(UbException(UB_EXARGS, err)); + } + } + + iprocessor->interpolateCoarseToFine(icellC, icellF, xoff, yoff, zoff); + this->writeICellFtoData(data, index, icellF); + // for (int iix3 = ix3; iix3<=ix3+1; iix3++) + //{ + // for (int iix2 = ix2; iix2<=ix2+1; iix2++) + // { + // for (int iix1 = ix1; iix1<=ix1+1; iix1++) + // { + // bcArray->setInterfaceCF(iix1, iix2, iix3); + // } + // } + //} } - - iprocessor->interpolateCoarseToFine(icellC, icellF, xoff, yoff, zoff); - this->writeICellFtoData(data, index, icellF); - //for (int iix3 = ix3; iix3<=ix3+1; iix3++) - //{ - // for (int iix2 = ix2; iix2<=ix2+1; iix2++) - // { - // for (int iix1 = ix1; iix1<=ix1+1; iix1++) - // { - // bcArray->setInterfaceCF(iix1, iix2, iix3); - // } - // } - //} - - } - } - } + } + } } ////////////////////////////////////////////////////////////////////////// -template< typename VectorTransmitter > +template <typename VectorTransmitter> double D3Q27ETCFOffVectorConnector<VectorTransmitter>::getSendRecieveTime() { - return 0; + return 0; } -#endif +#endif diff --git a/src/cpu/VirtualFluidsCore/Connectors/D3Q27ETFCOffVectorConnector.cpp b/src/cpu/VirtualFluidsCore/Connectors/D3Q27ETFCOffVectorConnector.cpp index f745d7597cc79bad851450d1751b0935d535621c..128c7819f5f217d539a977c5bcce115c3c67f736 100644 --- a/src/cpu/VirtualFluidsCore/Connectors/D3Q27ETFCOffVectorConnector.cpp +++ b/src/cpu/VirtualFluidsCore/Connectors/D3Q27ETFCOffVectorConnector.cpp @@ -1,3 +1 @@ #include "D3Q27ETFCOffVectorConnector.h" - - diff --git a/src/cpu/VirtualFluidsCore/Connectors/D3Q27ETFCOffVectorConnector.h b/src/cpu/VirtualFluidsCore/Connectors/D3Q27ETFCOffVectorConnector.h index 14acb11e53250b3510074dc3181b92e2bc76f517..63084e6a38d764623ad131893297a71f19db7a24 100644 --- a/src/cpu/VirtualFluidsCore/Connectors/D3Q27ETFCOffVectorConnector.h +++ b/src/cpu/VirtualFluidsCore/Connectors/D3Q27ETFCOffVectorConnector.h @@ -1,23 +1,23 @@ /** -* @file D3Q27ETFCOffVectorConnector.h -* @class D3Q27ETFCVectorConnector -* @brief Interpolation from fine level to coarse. -* @author Kostyantyn Kucher and Ehsan Fard -* @date 08.06.2011 -*/ + * @file D3Q27ETFCOffVectorConnector.h + * @class D3Q27ETFCVectorConnector + * @brief Interpolation from fine level to coarse. + * @author Kostyantyn Kucher and Ehsan Fard + * @date 08.06.2011 + */ #ifndef D3Q27ETFCOffVectorConnector_H #define D3Q27ETFCOffVectorConnector_H #include <vector> -#include "basics/transmitter/TbTransmitter.h" +#include "Block3D.h" #include "Block3DConnector.h" #include "D3Q27System.h" -#include "Block3D.h" #include "Grid3D.h" -#include "LBMKernel.h" #include "InterpolationProcessor.h" +#include "LBMKernel.h" #include "MathUtil.hpp" +#include "basics/transmitter/TbTransmitter.h" #include <PointerDefinitions.h> #include "BCProcessor.h" @@ -25,1413 +25,1521 @@ class Block3D; -enum CFconnectorType {EvenOddNW, EvenEvenSW, OddEvenSE, OddOddNE}; +enum CFconnectorType { EvenOddNW, EvenEvenSW, OddEvenSE, OddOddNE }; -//daten werden in einen vector (dieser befindet sich im transmitter) kopiert -//der vector wird via transmitter uebertragen -//transmitter kann ein lokal, MPI, RCG, CTL oder was auch immer fuer ein -//transmitter sein, der von Transmitter abgeleitet ist ;-) +// daten werden in einen vector (dieser befindet sich im transmitter) kopiert +// der vector wird via transmitter uebertragen +// transmitter kann ein lokal, MPI, RCG, CTL oder was auch immer fuer ein +// transmitter sein, der von Transmitter abgeleitet ist ;-) -template< typename VectorTransmitter > +template <typename VectorTransmitter> class D3Q27ETFCOffVectorConnector : public Block3DConnector { public: - protected: - using vector_type = typename VectorTransmitter::value_type; - using VectorTransmitterPtr = SPtr<VectorTransmitter>; + using vector_type = typename VectorTransmitter::value_type; + using VectorTransmitterPtr = SPtr<VectorTransmitter>; + public: - D3Q27ETFCOffVectorConnector(SPtr<Block3D> block, VectorTransmitterPtr sender, VectorTransmitterPtr receiver, int sendDir, - InterpolationProcessorPtr iprocessor, CFconnectorType connType); + D3Q27ETFCOffVectorConnector(SPtr<Block3D> block, VectorTransmitterPtr sender, VectorTransmitterPtr receiver, + int sendDir, InterpolationProcessorPtr iprocessor, CFconnectorType connType); - bool isLocalConnector() override; - bool isRemoteConnector() override; - void init() override; + bool isLocalConnector() override; + bool isRemoteConnector() override; + void init() override; - void sendTransmitterDataSize() override; - void receiveTransmitterDataSize() override; + void sendTransmitterDataSize() override; + void receiveTransmitterDataSize() override; - void prepareForSend() override; - void sendVectors() override; + void prepareForSend() override; + void sendVectors() override; - void prepareForReceive() override; - void receiveVectors() override; + void prepareForReceive() override; + void receiveVectors() override; - void fillSendVectors() override; - void distributeReceiveVectors() override; + void fillSendVectors() override; + void distributeReceiveVectors() override; - bool isInterpolationConnectorCF() override { return false; } - bool isInterpolationConnectorFC() override { return true; } + bool isInterpolationConnectorCF() override { return false; } + bool isInterpolationConnectorFC() override { return true; } - double getSendRecieveTime(); + double getSendRecieveTime(); - void prepareForSendX1() override {} - void prepareForSendX2() override {} - void prepareForSendX3() override {} + void prepareForSendX1() override {} + void prepareForSendX2() override {} + void prepareForSendX3() override {} - void sendVectorsX1() override{} - void sendVectorsX2() override{} - void sendVectorsX3() override{} + void sendVectorsX1() override {} + void sendVectorsX2() override {} + void sendVectorsX3() override {} - void prepareForReceiveX1() override {} - void prepareForReceiveX2() override {} - void prepareForReceiveX3() override {} + void prepareForReceiveX1() override {} + void prepareForReceiveX2() override {} + void prepareForReceiveX3() override {} - void receiveVectorsX1() override {} - void receiveVectorsX2() override {} - void receiveVectorsX3() override {} + void receiveVectorsX1() override {} + void receiveVectorsX2() override {} + void receiveVectorsX3() override {} protected: - WPtr<Block3D> block; //dieser nvd sendet daten und die empfangenen werden diesem nvd zugeordnet - //gegenstelle muss "inversen" connector besitzen - VectorTransmitterPtr sender, receiver; - - InterpolationProcessorPtr iprocessor; - - CFconnectorType connType; - - void writeICellCtoData(vector_type& data, int& index, LBMReal* icellC); - void writeNodeToVector(vector_type& data, int& index, LBMReal* inode); - void getLocalMinMax(int& minX1, int& minX2, int& minX3, int& maxX1, int& maxX2, int& maxX3); - void getLocalMinMax(int& minX1, int& minX2, int& minX3, int& maxX1, int& maxX2, int& maxX3, CFconnectorType connType); - void getLocalMinMaxCF(int gMax, int& lMin, int& lMax); - void fillSendVector(SPtr<DistributionArray3D> fFrom, const int& lMinX1, const int& lMinX2, const int& lMinX3, const int& lMaxX1, const int& lMaxX2, const int& lMaxX3, vector_type& data, int& index); - - void distributeReceiveVector(SPtr<DistributionArray3D> fTo, const int& lMinX1, const int& lMinX2, const int& lMinX3, const int& lMaxX1, const int& lMaxX2, const int& lMaxX3, vector_type& data, int& index); - void readICellFfromData(vector_type& data, int& index, D3Q27ICell& icellF); - void readNodeFromVector(vector_type& data, int& index, LBMReal* inode); - void getLocalOffsets(const int& gMax, int& oMin); - void getLocalMins(int& minX1, int& minX2, int& minX3, const int& oMinX1, const int& oMinX2, const int& oMinX3); - - int bMaxX1, bMaxX2, bMaxX3; + WPtr<Block3D> block; // dieser nvd sendet daten und die empfangenen werden diesem nvd zugeordnet + // gegenstelle muss "inversen" connector besitzen + VectorTransmitterPtr sender, receiver; + + InterpolationProcessorPtr iprocessor; + + CFconnectorType connType; + + void writeICellCtoData(vector_type &data, int &index, LBMReal *icellC); + void writeNodeToVector(vector_type &data, int &index, LBMReal *inode); + void getLocalMinMax(int &minX1, int &minX2, int &minX3, int &maxX1, int &maxX2, int &maxX3); + void getLocalMinMax(int &minX1, int &minX2, int &minX3, int &maxX1, int &maxX2, int &maxX3, + CFconnectorType connType); + void getLocalMinMaxCF(int gMax, int &lMin, int &lMax); + void fillSendVector(SPtr<DistributionArray3D> fFrom, const int &lMinX1, const int &lMinX2, const int &lMinX3, + const int &lMaxX1, const int &lMaxX2, const int &lMaxX3, vector_type &data, int &index); + + void distributeReceiveVector(SPtr<DistributionArray3D> fTo, const int &lMinX1, const int &lMinX2, const int &lMinX3, + const int &lMaxX1, const int &lMaxX2, const int &lMaxX3, vector_type &data, + int &index); + void readICellFfromData(vector_type &data, int &index, D3Q27ICell &icellF); + void readNodeFromVector(vector_type &data, int &index, LBMReal *inode); + void getLocalOffsets(const int &gMax, int &oMin); + void getLocalMins(int &minX1, int &minX2, int &minX3, const int &oMinX1, const int &oMinX2, const int &oMinX3); + + int bMaxX1, bMaxX2, bMaxX3; }; //////////////////////////////////////////////////////////////////////////// -template< typename VectorTransmitter > -D3Q27ETFCOffVectorConnector<VectorTransmitter>::D3Q27ETFCOffVectorConnector(SPtr<Block3D> block, VectorTransmitterPtr sender, - VectorTransmitterPtr receiver, int sendDir, - InterpolationProcessorPtr iprocessor, - CFconnectorType connType) - : Block3DConnector(sendDir) - , block(block) - , sender(sender) - , receiver(receiver) - , iprocessor(iprocessor) - , connType(connType) +template <typename VectorTransmitter> +D3Q27ETFCOffVectorConnector<VectorTransmitter>::D3Q27ETFCOffVectorConnector(SPtr<Block3D> block, + VectorTransmitterPtr sender, + VectorTransmitterPtr receiver, int sendDir, + InterpolationProcessorPtr iprocessor, + CFconnectorType connType) + : Block3DConnector(sendDir), block(block), sender(sender), receiver(receiver), iprocessor(iprocessor), + connType(connType) { - if( !( sendDir==D3Q27System::E || sendDir==D3Q27System::W || sendDir==D3Q27System::N || sendDir==D3Q27System::S || sendDir==D3Q27System::T || sendDir==D3Q27System::B - || sendDir==D3Q27System::NE || sendDir==D3Q27System::SW || sendDir==D3Q27System::SE || sendDir==D3Q27System::NW - || sendDir==D3Q27System::TE || sendDir==D3Q27System::BW || sendDir==D3Q27System::BE || sendDir==D3Q27System::TW - || sendDir==D3Q27System::TN || sendDir==D3Q27System::BS || sendDir==D3Q27System::BN || sendDir==D3Q27System::TS - - || sendDir==D3Q27System::TNE || sendDir==D3Q27System::TNW || sendDir==D3Q27System::TSE || sendDir==D3Q27System::TSW - || sendDir==D3Q27System::BNE || sendDir==D3Q27System::BNW || sendDir==D3Q27System::BSE || sendDir==D3Q27System::BSW - - ) ) - { - throw UbException(UB_EXARGS,"invalid constructor for this direction"); - } + if (!(sendDir == D3Q27System::E || sendDir == D3Q27System::W || sendDir == D3Q27System::N || + sendDir == D3Q27System::S || sendDir == D3Q27System::T || sendDir == D3Q27System::B || + sendDir == D3Q27System::NE || sendDir == D3Q27System::SW || sendDir == D3Q27System::SE || + sendDir == D3Q27System::NW || sendDir == D3Q27System::TE || sendDir == D3Q27System::BW || + sendDir == D3Q27System::BE || sendDir == D3Q27System::TW || sendDir == D3Q27System::TN || + sendDir == D3Q27System::BS || sendDir == D3Q27System::BN || sendDir == D3Q27System::TS + + || sendDir == D3Q27System::TNE || sendDir == D3Q27System::TNW || sendDir == D3Q27System::TSE || + sendDir == D3Q27System::TSW || sendDir == D3Q27System::BNE || sendDir == D3Q27System::BNW || + sendDir == D3Q27System::BSE || sendDir == D3Q27System::BSW + + )) { + throw UbException(UB_EXARGS, "invalid constructor for this direction"); + } } ////////////////////////////////////////////////////////////////////////// -template< typename VectorTransmitter > +template <typename VectorTransmitter> bool D3Q27ETFCOffVectorConnector<VectorTransmitter>::isLocalConnector() -{ - return !this->isRemoteConnector(); +{ + return !this->isRemoteConnector(); } ////////////////////////////////////////////////////////////////////////// -template< typename VectorTransmitter > -bool D3Q27ETFCOffVectorConnector<VectorTransmitter>::isRemoteConnector() -{ - return sender->isRemoteTransmitter() || receiver->isRemoteTransmitter(); +template <typename VectorTransmitter> +bool D3Q27ETFCOffVectorConnector<VectorTransmitter>::isRemoteConnector() +{ + return sender->isRemoteTransmitter() || receiver->isRemoteTransmitter(); } ////////////////////////////////////////////////////////////////////////// -template< typename VectorTransmitter > -void D3Q27ETFCOffVectorConnector<VectorTransmitter>::sendTransmitterDataSize() -{ - if(sender) - { - UBLOG(logDEBUG5, "D3Q27ETFCOffVectorConnector<VectorTransmitter>::sendTransmitterDataSize()"<<block.lock()->toString()+"sendDir="<<sendDir); - sender->sendDataSize(); - } +template <typename VectorTransmitter> +void D3Q27ETFCOffVectorConnector<VectorTransmitter>::sendTransmitterDataSize() +{ + if (sender) { + UBLOG(logDEBUG5, "D3Q27ETFCOffVectorConnector<VectorTransmitter>::sendTransmitterDataSize()" + << block.lock()->toString() + "sendDir=" << sendDir); + sender->sendDataSize(); + } } ////////////////////////////////////////////////////////////////////////// -template< typename VectorTransmitter > +template <typename VectorTransmitter> void D3Q27ETFCOffVectorConnector<VectorTransmitter>::receiveTransmitterDataSize() -{ - if(receiver) - { - UBLOG(logDEBUG5, "D3Q27ETFCOffVectorConnector<VectorTransmitter>::receiveTransmitterDataSize()"<<block.lock()->toString()<<"sendDir="<<sendDir); - receiver->receiveDataSize(); - } +{ + if (receiver) { + UBLOG(logDEBUG5, "D3Q27ETFCOffVectorConnector<VectorTransmitter>::receiveTransmitterDataSize()" + << block.lock()->toString() << "sendDir=" << sendDir); + receiver->receiveDataSize(); + } } ////////////////////////////////////////////////////////////////////////// -template< typename VectorTransmitter > +template <typename VectorTransmitter> void D3Q27ETFCOffVectorConnector<VectorTransmitter>::prepareForSend() -{ - if(sender) sender->prepareForSend(); +{ + if (sender) + sender->prepareForSend(); } ////////////////////////////////////////////////////////////////////////// -template< typename VectorTransmitter > -void D3Q27ETFCOffVectorConnector<VectorTransmitter>::sendVectors() -{ - if(sender) sender->sendData(); +template <typename VectorTransmitter> +void D3Q27ETFCOffVectorConnector<VectorTransmitter>::sendVectors() +{ + if (sender) + sender->sendData(); } ////////////////////////////////////////////////////////////////////////// -template< typename VectorTransmitter > -void D3Q27ETFCOffVectorConnector<VectorTransmitter>::prepareForReceive() -{ - if(receiver) receiver->prepareForReceive(); +template <typename VectorTransmitter> +void D3Q27ETFCOffVectorConnector<VectorTransmitter>::prepareForReceive() +{ + if (receiver) + receiver->prepareForReceive(); } ////////////////////////////////////////////////////////////////////////// -template< typename VectorTransmitter > -void D3Q27ETFCOffVectorConnector<VectorTransmitter>::receiveVectors() -{ - if(receiver) receiver->receiveData(); +template <typename VectorTransmitter> +void D3Q27ETFCOffVectorConnector<VectorTransmitter>::receiveVectors() +{ + if (receiver) + receiver->receiveData(); } ////////////////////////////////////////////////////////////////////////// -template< typename VectorTransmitter > +template <typename VectorTransmitter> void D3Q27ETFCOffVectorConnector<VectorTransmitter>::init() { - using namespace D3Q27System; - - bMaxX1 = (int)block.lock()->getKernel()->getDataSet()->getFdistributions()->getNX1(); - bMaxX2 = (int)block.lock()->getKernel()->getDataSet()->getFdistributions()->getNX2(); - bMaxX3 = (int)block.lock()->getKernel()->getDataSet()->getFdistributions()->getNX3(); - - int sendSize = 0; - LBMReal initValue = -999.0; - - int sendDataPerNode = 27/*f*/; - int iCellSize = 1; //size of interpolation cell - - switch(this->sendDir) - { - case E : case W : sendSize = (bMaxX2-1)/2*(bMaxX3-1)/2*sendDataPerNode*iCellSize; break; - case N : case S : sendSize = (bMaxX1-1)/2*(bMaxX3-1)/2*sendDataPerNode*iCellSize; break; - case T : case B : sendSize = (bMaxX1-1)/2*(bMaxX2-1)/2*sendDataPerNode*iCellSize; break; - case NE : case SW :case SE : case NW : sendSize = (3*bMaxX3-3)*sendDataPerNode*iCellSize; break; // buffer overhead, should be (3*bMaxX3-6) for even bMax3 - case TE : case BW :case BE : case TW : sendSize = (3*bMaxX2-3)*sendDataPerNode*iCellSize; break; - case TN : case BS :case BN : case TS : sendSize = (3*bMaxX1-3)*sendDataPerNode*iCellSize; break; - case TNE: case TNW:case TSE: case TSW:case BNE: case BNW:case BSE: case BSW: sendSize = 3*(3*bMaxX1-3)*sendDataPerNode*iCellSize; break; - default: throw UbException(UB_EXARGS,"direction not allowed in this constructor"); - } - sender->getData().resize(sendSize, initValue); + using namespace D3Q27System; + + bMaxX1 = (int)block.lock()->getKernel()->getDataSet()->getFdistributions()->getNX1(); + bMaxX2 = (int)block.lock()->getKernel()->getDataSet()->getFdistributions()->getNX2(); + bMaxX3 = (int)block.lock()->getKernel()->getDataSet()->getFdistributions()->getNX3(); + + int sendSize = 0; + LBMReal initValue = -999.0; + + int sendDataPerNode = 27 /*f*/; + int iCellSize = 1; // size of interpolation cell + + switch (this->sendDir) { + case E: + case W: + sendSize = (bMaxX2 - 1) / 2 * (bMaxX3 - 1) / 2 * sendDataPerNode * iCellSize; + break; + case N: + case S: + sendSize = (bMaxX1 - 1) / 2 * (bMaxX3 - 1) / 2 * sendDataPerNode * iCellSize; + break; + case T: + case B: + sendSize = (bMaxX1 - 1) / 2 * (bMaxX2 - 1) / 2 * sendDataPerNode * iCellSize; + break; + case NE: + case SW: + case SE: + case NW: + sendSize = (3 * bMaxX3 - 3) * sendDataPerNode * iCellSize; + break; // buffer overhead, should be (3*bMaxX3-6) for even bMax3 + case TE: + case BW: + case BE: + case TW: + sendSize = (3 * bMaxX2 - 3) * sendDataPerNode * iCellSize; + break; + case TN: + case BS: + case BN: + case TS: + sendSize = (3 * bMaxX1 - 3) * sendDataPerNode * iCellSize; + break; + case TNE: + case TNW: + case TSE: + case TSW: + case BNE: + case BNW: + case BSE: + case BSW: + sendSize = 3 * (3 * bMaxX1 - 3) * sendDataPerNode * iCellSize; + break; + default: + throw UbException(UB_EXARGS, "direction not allowed in this constructor"); + } + sender->getData().resize(sendSize, initValue); } ////////////////////////////////////////////////////////////////////////// -template< typename VectorTransmitter > -void D3Q27ETFCOffVectorConnector< VectorTransmitter>::fillSendVectors() -{ - using namespace D3Q27System; - - SPtr<DistributionArray3D> fFrom = block.lock()->getKernel()->getDataSet()->getFdistributions(); - int maxX1 = (int)fFrom->getNX1(); - int maxX2 = (int)fFrom->getNX2(); - int maxX3 = (int)fFrom->getNX3(); - int minX1 = 0; - int minX2 = 0; - int minX3 = 0; - - int oMinX1, oMinX2, oMinX3; - getLocalOffsets(maxX1, oMinX1); - getLocalOffsets(maxX2, oMinX2); - getLocalOffsets(maxX3, oMinX3); - - int lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3; - int index = 0; - vector_type& data = sender->getData(); - - lMinX1 = minX1+1; lMinX2 = minX2+1; lMinX3 = minX3+1; - lMaxX1 = maxX1-2; lMaxX2 = maxX2-2; lMaxX3 = maxX3-2; - - /////////////////////////////////////// - ///DEBUG +template <typename VectorTransmitter> +void D3Q27ETFCOffVectorConnector<VectorTransmitter>::fillSendVectors() +{ + using namespace D3Q27System; + + SPtr<DistributionArray3D> fFrom = block.lock()->getKernel()->getDataSet()->getFdistributions(); + int maxX1 = (int)fFrom->getNX1(); + int maxX2 = (int)fFrom->getNX2(); + int maxX3 = (int)fFrom->getNX3(); + int minX1 = 0; + int minX2 = 0; + int minX3 = 0; + + int oMinX1, oMinX2, oMinX3; + getLocalOffsets(maxX1, oMinX1); + getLocalOffsets(maxX2, oMinX2); + getLocalOffsets(maxX3, oMinX3); + + int lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3; + int index = 0; + vector_type &data = sender->getData(); + + lMinX1 = minX1 + 1; + lMinX2 = minX2 + 1; + lMinX3 = minX3 + 1; + lMaxX1 = maxX1 - 2; + lMaxX2 = maxX2 - 2; + lMaxX3 = maxX3 - 2; + + /////////////////////////////////////// + /// DEBUG #ifdef _DEBUG - //if (block.lock()->getGlobalID() == 2558) - //{ - // int test = 0; - //} + // if (block.lock()->getGlobalID() == 2558) + //{ + // int test = 0; + //} #endif - ////////////// - - switch(sendDir) - { - case E: - getLocalMinMax(lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3); - getLocalMins(lMinX1, lMinX2, lMinX3, oMinX1, oMinX2, oMinX3); - lMinX1 = maxX1-7; - lMaxX1 = lMinX1 + 1; - fillSendVector(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); - break; - case W: - /////////////////////////////////////// - ///DEBUG + ////////////// + + switch (sendDir) { + case E: + getLocalMinMax(lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3); + getLocalMins(lMinX1, lMinX2, lMinX3, oMinX1, oMinX2, oMinX3); + lMinX1 = maxX1 - 7; + lMaxX1 = lMinX1 + 1; + fillSendVector(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); + break; + case W: + /////////////////////////////////////// + /// DEBUG #ifdef _DEBUG - //if (block.lock()->getGlobalID() == 2516) - //{ - // int test = 0; - //} + // if (block.lock()->getGlobalID() == 2516) + //{ + // int test = 0; + //} #endif - ////////////// - //getLocalMinMax(lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, none); - getLocalMinMax(lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3); - getLocalMins(lMinX1, lMinX2, lMinX3, oMinX1, oMinX2, oMinX3); - lMinX1 = 5; - lMaxX1 = lMinX1 + 1; - fillSendVector(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); - break; - case N: - getLocalMinMax(lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3); - getLocalMins(lMinX1, lMinX2, lMinX3, oMinX1, oMinX2, oMinX3); - lMinX2 = maxX2-7; - lMaxX2 = lMinX2 + 1; - fillSendVector(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); - break; - case S: - getLocalMinMax(lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3); - getLocalMins(lMinX1, lMinX2, lMinX3, oMinX1, oMinX2, oMinX3); - lMinX2 = 5; - lMaxX2 = lMinX2 + 1; - fillSendVector(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); - break; - case T: - getLocalMinMax(lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3); - getLocalMins(lMinX1, lMinX2, lMinX3, oMinX1, oMinX2, oMinX3); - lMinX3 = maxX3-7; - lMaxX3 = lMinX3 + 1; - fillSendVector(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); - break; - case B: - getLocalMinMax(lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3); - getLocalMins(lMinX1, lMinX2, lMinX3, oMinX1, oMinX2, oMinX3); - lMinX3 = 5; - lMaxX3 = lMinX3 + 1; - fillSendVector(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); - break; - - // ////N-S-E-W - case NE: - getLocalMinMax(lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3); - getLocalMins(lMinX1, lMinX2, lMinX3, oMinX1, oMinX2, oMinX3); - lMinX1 = maxX1-7; - lMaxX1 = lMinX1 +5; - lMinX2 = maxX2-7; - lMaxX2 = lMinX2 + 1; - fillSendVector(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); - - lMinX1 = maxX1-7; - lMaxX1 = lMinX1 + 1; - lMinX2 = maxX2-7; - lMaxX2 = lMinX2 + 5; - fillSendVector(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); - break; - case SW: - - getLocalMinMax(lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3); - getLocalMins(lMinX1, lMinX2, lMinX3, oMinX1, oMinX2, oMinX3); - lMinX1 = 1; - lMaxX1 = lMinX1 + 5; - lMinX2 = 5; - lMaxX2 = lMinX2 + 1; - fillSendVector(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); - - lMinX1 = 5; - lMaxX1 = lMinX1 + 1; - lMinX2 = 1; - lMaxX2 = lMinX2 + 5; - fillSendVector(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); - break; - - case SE: - getLocalMinMax(lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3); - getLocalMins(lMinX1, lMinX2, lMinX3, oMinX1, oMinX2, oMinX3); - lMinX1 = maxX1-7; - lMaxX1 = lMinX1 +5; - lMinX2 = 5; - lMaxX2 = lMinX2 + 1; - fillSendVector(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); - - lMinX1 = maxX1-7; - lMaxX1 = lMinX1 + 1; - lMinX2 = 1; - lMaxX2 = lMinX2 + 5; - fillSendVector(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); - - break; - - case NW: - getLocalMinMax(lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3); - getLocalMins(lMinX1, lMinX2, lMinX3, oMinX1, oMinX2, oMinX3); - lMinX1 = 1; - lMaxX1 = lMinX1 + 5; - lMinX2 = maxX2-7; - lMaxX2 = lMinX2 + 1; - fillSendVector(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); - - lMinX1 = 5; - lMaxX1 = lMinX1 + 1; - lMinX2 = maxX2-7; - lMaxX2 = lMinX2 + 5; - fillSendVector(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); - break; -//////T-B-E-W - case TE: - getLocalMinMax(lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3); - getLocalMins(lMinX1, lMinX2, lMinX3, oMinX1, oMinX2, oMinX3); - lMinX1 = maxX1-7; - lMaxX1 = lMinX1 +5; - lMinX3 = maxX3-7; - lMaxX3 = lMinX3 + 1; - fillSendVector(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); - - lMinX1 = maxX1-7; - lMaxX1 = lMinX1 + 1; - lMinX3 = maxX3-7; - lMaxX3 = lMinX3 + 5; - fillSendVector(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); - break; - - case BW: - getLocalMinMax(lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3); - getLocalMins(lMinX1, lMinX2, lMinX3, oMinX1, oMinX2, oMinX3); - lMinX1 = 1; - lMaxX1 = lMinX1 + 5; - lMinX3 = 5; - lMaxX3 = lMinX3 + 1; - fillSendVector(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); - - lMinX1 = 5; - lMaxX1 = lMinX1 + 1; - lMinX3 = 1; - lMaxX3 = lMinX3 + 5; - fillSendVector(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); - break; - - case BE: - getLocalMinMax(lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3); - getLocalMins(lMinX1, lMinX2, lMinX3, oMinX1, oMinX2, oMinX3); - lMinX1 = maxX1-7; - lMaxX1 = lMinX1 +5; - lMinX3 = 5; - lMaxX3 = lMinX3 + 1; - fillSendVector(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); - - lMinX1 = maxX1-7; - lMaxX1 = lMinX1 + 1; - lMinX3 = 1; - lMaxX3 = lMinX3 + 5; - fillSendVector(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); - break; - - case TW: - getLocalMinMax(lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3); - getLocalMins(lMinX1, lMinX2, lMinX3, oMinX1, oMinX2, oMinX3); - lMinX1 = 1; - lMaxX1 = lMinX1 + 5; - lMinX3 = maxX3-7; - lMaxX3 = lMinX3 + 1; - fillSendVector(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); - - lMinX1 = 5; - lMaxX1 = lMinX1 + 1; - lMinX3 = maxX3-7; - lMaxX3 = lMinX3 + 5; - fillSendVector(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); - break; -///////////////T-B-N-S -// - case TN: - getLocalMinMax(lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3); - getLocalMins(lMinX1, lMinX2, lMinX3, oMinX1, oMinX2, oMinX3); - lMinX2 = maxX2-7; - lMaxX2 = lMinX2 + 5; - lMinX3 = maxX3-7; - lMaxX3 = lMinX3 + 1; - fillSendVector(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); - - lMinX2 = maxX2-7; - lMaxX2 = lMinX2 + 1; - lMinX3 = maxX3-7; - lMaxX3 = lMinX3 + 5; - fillSendVector(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); - break; - - case BS: - getLocalMinMax(lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3); - getLocalMins(lMinX1, lMinX2, lMinX3, oMinX1, oMinX2, oMinX3); - lMinX2 = 1; - lMaxX2 = lMinX2 + 5; - lMinX3 = 5; - lMaxX3 = lMinX3 + 1; - fillSendVector(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); - - lMinX2 = 5; - lMaxX2 = lMinX2 + 1; - lMinX3 = 1; - lMaxX3 = lMinX3 + 5; - fillSendVector(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); - break; - - case BN: - getLocalMinMax(lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3); - getLocalMins(lMinX1, lMinX2, lMinX3, oMinX1, oMinX2, oMinX3); - lMinX2 = maxX2-7; - lMaxX2 = lMinX2 + 5; - lMinX3 = 5; - lMaxX3 = lMinX3 + 1; - fillSendVector(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); - - lMinX2 = maxX2-7; - lMaxX2 = lMinX2 + 1; - lMinX3 = 1; - lMaxX3 = lMinX3 + 5; - fillSendVector(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); - break; - - case TS: - getLocalMinMax(lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3); - getLocalMins(lMinX1, lMinX2, lMinX3, oMinX1, oMinX2, oMinX3); - lMinX2 = 1; - lMaxX2 = lMinX2 + 5; - lMinX3 = maxX3-7; - lMaxX3 = lMinX3 + 1; - fillSendVector(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); - - lMinX2 = 5; - lMaxX2 = lMinX2 + 1; - lMinX3 = maxX3-7; - lMaxX3 = lMinX3 + 5; - fillSendVector(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); - break; - - //TNE - case TNE: - lMinX1 = maxX1-7; - lMaxX1 = maxX1-6; - lMinX2 = maxX2-7; - lMaxX2 = maxX2-2; - lMinX3 = maxX3-7; - lMaxX3 = maxX3-2; - fillSendVector(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); - - lMinX1 = maxX1-7; - lMaxX1 = maxX1-2; - lMinX2 = maxX2-7; - lMaxX2 = maxX2-6; - lMinX3 = maxX3-7; - lMaxX3 = maxX3-2; - fillSendVector(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); - - lMinX1 = maxX1-7; - lMaxX1 = maxX1-2; - lMinX2 = maxX2-7; - lMaxX2 = maxX2-2; - lMinX3 = maxX3-7; - lMaxX3 = maxX3-6; - fillSendVector(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); - break; - - - //TNW - case TNW: - lMinX1 = 5; - lMaxX1 = 6; - lMinX2 = maxX2-7; - lMaxX2 = maxX2-2; - lMinX3 = maxX3-7; - lMaxX3 = maxX3-2; - fillSendVector(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); - - lMinX1 = 1; - lMaxX1 = 6; - lMinX2 = maxX2-7; - lMaxX2 = maxX2-6; - lMinX3 = maxX3-7; - lMaxX3 = maxX3-2; - fillSendVector(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); - - lMinX1 = 1; - lMaxX1 = 6; - lMinX2 = maxX2-7; - lMaxX2 = maxX2-2; - lMinX3 = maxX3-7; - lMaxX3 = maxX3-6; - fillSendVector(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); - break; - - break; - - // TSE - case TSE: - lMinX1 = maxX1-7; - lMaxX1 = maxX1-6; - lMinX2 = 1; - lMaxX2 = 6; - lMinX3 = maxX3-7; - lMaxX3 = maxX3-2; - fillSendVector(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); - - lMinX1 = maxX1-7; - lMaxX1 = maxX1-2; - lMinX2 = 5; - lMaxX2 = 6; - lMinX3 = maxX3-7; - lMaxX3 = maxX3-2; - fillSendVector(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); - - lMinX1 = maxX1-7; - lMaxX1 = maxX1-2; - lMinX2 = 1; - lMaxX2 = 6; - lMinX3 = maxX3-7; - lMaxX3 = maxX3-6; - fillSendVector(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); - - break; - // TSW - case TSW: - lMinX1 = 5; - lMaxX1 = 6; - lMinX2 = 1; - lMaxX2 = 6; - lMinX3 = maxX3-7; - lMaxX3 = maxX3-2; - fillSendVector(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); - - lMinX1 = 1; - lMaxX1 = 6; - lMinX2 = 5; - lMaxX2 = 6; - lMinX3 = maxX3-7; - lMaxX3 = maxX3-2; - fillSendVector(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); - - lMinX1 = 1; - lMaxX1 = 6; - lMinX2 = 1; - lMaxX2 = 6; - lMinX3 = maxX3-7; - lMaxX3 = maxX3-6; - fillSendVector(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); - - break; - // BNE - case BNE: - lMinX1 = maxX1-7; - lMaxX1 = maxX1-6; - lMinX2 = maxX2-7; - lMaxX2 = maxX2-2; - lMinX3 = 1; - lMaxX3 = 6; - fillSendVector(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); - - lMinX1 = maxX1-7; - lMaxX1 = maxX1-2; - lMinX2 = maxX2-7; - lMaxX2 = maxX2-6; - lMinX3 = 1; - lMaxX3 = 6; - fillSendVector(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); - - lMinX1 = maxX1-7; - lMaxX1 = maxX1-2; - lMinX2 = maxX2-7; - lMaxX2 = maxX2-2; - lMinX3 = 5; - lMaxX3 = 6; - fillSendVector(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); - - break; - // BNW - case BNW: - lMinX1 = 5; - lMaxX1 = 6; - lMinX2 = maxX2-7; - lMaxX2 = maxX2-2; - lMinX3 = 1; - lMaxX3 = 6; - fillSendVector(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); - - lMinX1 = 1; - lMaxX1 = 6; - lMinX2 = maxX2-7; - lMaxX2 = maxX2-6; - lMinX3 = 1; - lMaxX3 = 6; - fillSendVector(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); - - lMinX1 = 1; - lMaxX1 = 6; - lMinX2 = maxX2-7; - lMaxX2 = maxX2-2; - lMinX3 = 5; - lMaxX3 = 6; - fillSendVector(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); - - break; - - - // BSE - case BSE: - lMinX1 = maxX1-7; - lMaxX1 = maxX1-6; - lMinX2 = 1; - lMaxX2 = 6; - lMinX3 = 1; - lMaxX3 = 6; - fillSendVector(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); - - lMinX1 = maxX1-7; - lMaxX1 = maxX1-2; - lMinX2 = 5; - lMaxX2 = 6; - lMinX3 = 1; - lMaxX3 = 6; - fillSendVector(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); - - lMinX1 = maxX1-7; - lMaxX1 = maxX1-2; - lMinX2 = 1; - lMaxX2 = 6; - lMinX3 = 5; - lMaxX3 = 6; - fillSendVector(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); - - break; - - //BSW - case BSW: - lMinX1 = 5; - lMaxX1 = 6; - lMinX2 = 1; - lMaxX2 = 6; - lMinX3 = 1; - lMaxX3 = 6; - fillSendVector(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); - - lMinX1 = 1; - lMaxX1 = 6; - lMinX2 = 5; - lMaxX2 = 6; - lMinX3 = 1; - lMaxX3 = 6; - fillSendVector(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); - - lMinX1 = 1; - lMaxX1 = 6; - lMinX2 = 1; - lMaxX2 = 6; - lMinX3 = 5; - lMaxX3 = 6; - fillSendVector(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); - - break; - } + ////////////// + // getLocalMinMax(lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, none); + getLocalMinMax(lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3); + getLocalMins(lMinX1, lMinX2, lMinX3, oMinX1, oMinX2, oMinX3); + lMinX1 = 5; + lMaxX1 = lMinX1 + 1; + fillSendVector(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); + break; + case N: + getLocalMinMax(lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3); + getLocalMins(lMinX1, lMinX2, lMinX3, oMinX1, oMinX2, oMinX3); + lMinX2 = maxX2 - 7; + lMaxX2 = lMinX2 + 1; + fillSendVector(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); + break; + case S: + getLocalMinMax(lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3); + getLocalMins(lMinX1, lMinX2, lMinX3, oMinX1, oMinX2, oMinX3); + lMinX2 = 5; + lMaxX2 = lMinX2 + 1; + fillSendVector(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); + break; + case T: + getLocalMinMax(lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3); + getLocalMins(lMinX1, lMinX2, lMinX3, oMinX1, oMinX2, oMinX3); + lMinX3 = maxX3 - 7; + lMaxX3 = lMinX3 + 1; + fillSendVector(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); + break; + case B: + getLocalMinMax(lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3); + getLocalMins(lMinX1, lMinX2, lMinX3, oMinX1, oMinX2, oMinX3); + lMinX3 = 5; + lMaxX3 = lMinX3 + 1; + fillSendVector(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); + break; + + // ////N-S-E-W + case NE: + getLocalMinMax(lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3); + getLocalMins(lMinX1, lMinX2, lMinX3, oMinX1, oMinX2, oMinX3); + lMinX1 = maxX1 - 7; + lMaxX1 = lMinX1 + 5; + lMinX2 = maxX2 - 7; + lMaxX2 = lMinX2 + 1; + fillSendVector(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); + + lMinX1 = maxX1 - 7; + lMaxX1 = lMinX1 + 1; + lMinX2 = maxX2 - 7; + lMaxX2 = lMinX2 + 5; + fillSendVector(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); + break; + case SW: + + getLocalMinMax(lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3); + getLocalMins(lMinX1, lMinX2, lMinX3, oMinX1, oMinX2, oMinX3); + lMinX1 = 1; + lMaxX1 = lMinX1 + 5; + lMinX2 = 5; + lMaxX2 = lMinX2 + 1; + fillSendVector(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); + + lMinX1 = 5; + lMaxX1 = lMinX1 + 1; + lMinX2 = 1; + lMaxX2 = lMinX2 + 5; + fillSendVector(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); + break; + + case SE: + getLocalMinMax(lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3); + getLocalMins(lMinX1, lMinX2, lMinX3, oMinX1, oMinX2, oMinX3); + lMinX1 = maxX1 - 7; + lMaxX1 = lMinX1 + 5; + lMinX2 = 5; + lMaxX2 = lMinX2 + 1; + fillSendVector(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); + + lMinX1 = maxX1 - 7; + lMaxX1 = lMinX1 + 1; + lMinX2 = 1; + lMaxX2 = lMinX2 + 5; + fillSendVector(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); + + break; + + case NW: + getLocalMinMax(lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3); + getLocalMins(lMinX1, lMinX2, lMinX3, oMinX1, oMinX2, oMinX3); + lMinX1 = 1; + lMaxX1 = lMinX1 + 5; + lMinX2 = maxX2 - 7; + lMaxX2 = lMinX2 + 1; + fillSendVector(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); + + lMinX1 = 5; + lMaxX1 = lMinX1 + 1; + lMinX2 = maxX2 - 7; + lMaxX2 = lMinX2 + 5; + fillSendVector(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); + break; + //////T-B-E-W + case TE: + getLocalMinMax(lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3); + getLocalMins(lMinX1, lMinX2, lMinX3, oMinX1, oMinX2, oMinX3); + lMinX1 = maxX1 - 7; + lMaxX1 = lMinX1 + 5; + lMinX3 = maxX3 - 7; + lMaxX3 = lMinX3 + 1; + fillSendVector(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); + + lMinX1 = maxX1 - 7; + lMaxX1 = lMinX1 + 1; + lMinX3 = maxX3 - 7; + lMaxX3 = lMinX3 + 5; + fillSendVector(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); + break; + + case BW: + getLocalMinMax(lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3); + getLocalMins(lMinX1, lMinX2, lMinX3, oMinX1, oMinX2, oMinX3); + lMinX1 = 1; + lMaxX1 = lMinX1 + 5; + lMinX3 = 5; + lMaxX3 = lMinX3 + 1; + fillSendVector(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); + + lMinX1 = 5; + lMaxX1 = lMinX1 + 1; + lMinX3 = 1; + lMaxX3 = lMinX3 + 5; + fillSendVector(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); + break; + + case BE: + getLocalMinMax(lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3); + getLocalMins(lMinX1, lMinX2, lMinX3, oMinX1, oMinX2, oMinX3); + lMinX1 = maxX1 - 7; + lMaxX1 = lMinX1 + 5; + lMinX3 = 5; + lMaxX3 = lMinX3 + 1; + fillSendVector(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); + + lMinX1 = maxX1 - 7; + lMaxX1 = lMinX1 + 1; + lMinX3 = 1; + lMaxX3 = lMinX3 + 5; + fillSendVector(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); + break; + + case TW: + getLocalMinMax(lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3); + getLocalMins(lMinX1, lMinX2, lMinX3, oMinX1, oMinX2, oMinX3); + lMinX1 = 1; + lMaxX1 = lMinX1 + 5; + lMinX3 = maxX3 - 7; + lMaxX3 = lMinX3 + 1; + fillSendVector(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); + + lMinX1 = 5; + lMaxX1 = lMinX1 + 1; + lMinX3 = maxX3 - 7; + lMaxX3 = lMinX3 + 5; + fillSendVector(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); + break; + ///////////////T-B-N-S + // + case TN: + getLocalMinMax(lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3); + getLocalMins(lMinX1, lMinX2, lMinX3, oMinX1, oMinX2, oMinX3); + lMinX2 = maxX2 - 7; + lMaxX2 = lMinX2 + 5; + lMinX3 = maxX3 - 7; + lMaxX3 = lMinX3 + 1; + fillSendVector(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); + + lMinX2 = maxX2 - 7; + lMaxX2 = lMinX2 + 1; + lMinX3 = maxX3 - 7; + lMaxX3 = lMinX3 + 5; + fillSendVector(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); + break; + + case BS: + getLocalMinMax(lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3); + getLocalMins(lMinX1, lMinX2, lMinX3, oMinX1, oMinX2, oMinX3); + lMinX2 = 1; + lMaxX2 = lMinX2 + 5; + lMinX3 = 5; + lMaxX3 = lMinX3 + 1; + fillSendVector(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); + + lMinX2 = 5; + lMaxX2 = lMinX2 + 1; + lMinX3 = 1; + lMaxX3 = lMinX3 + 5; + fillSendVector(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); + break; + + case BN: + getLocalMinMax(lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3); + getLocalMins(lMinX1, lMinX2, lMinX3, oMinX1, oMinX2, oMinX3); + lMinX2 = maxX2 - 7; + lMaxX2 = lMinX2 + 5; + lMinX3 = 5; + lMaxX3 = lMinX3 + 1; + fillSendVector(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); + + lMinX2 = maxX2 - 7; + lMaxX2 = lMinX2 + 1; + lMinX3 = 1; + lMaxX3 = lMinX3 + 5; + fillSendVector(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); + break; + + case TS: + getLocalMinMax(lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3); + getLocalMins(lMinX1, lMinX2, lMinX3, oMinX1, oMinX2, oMinX3); + lMinX2 = 1; + lMaxX2 = lMinX2 + 5; + lMinX3 = maxX3 - 7; + lMaxX3 = lMinX3 + 1; + fillSendVector(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); + + lMinX2 = 5; + lMaxX2 = lMinX2 + 1; + lMinX3 = maxX3 - 7; + lMaxX3 = lMinX3 + 5; + fillSendVector(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); + break; + + // TNE + case TNE: + lMinX1 = maxX1 - 7; + lMaxX1 = maxX1 - 6; + lMinX2 = maxX2 - 7; + lMaxX2 = maxX2 - 2; + lMinX3 = maxX3 - 7; + lMaxX3 = maxX3 - 2; + fillSendVector(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); + + lMinX1 = maxX1 - 7; + lMaxX1 = maxX1 - 2; + lMinX2 = maxX2 - 7; + lMaxX2 = maxX2 - 6; + lMinX3 = maxX3 - 7; + lMaxX3 = maxX3 - 2; + fillSendVector(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); + + lMinX1 = maxX1 - 7; + lMaxX1 = maxX1 - 2; + lMinX2 = maxX2 - 7; + lMaxX2 = maxX2 - 2; + lMinX3 = maxX3 - 7; + lMaxX3 = maxX3 - 6; + fillSendVector(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); + break; + + // TNW + case TNW: + lMinX1 = 5; + lMaxX1 = 6; + lMinX2 = maxX2 - 7; + lMaxX2 = maxX2 - 2; + lMinX3 = maxX3 - 7; + lMaxX3 = maxX3 - 2; + fillSendVector(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); + + lMinX1 = 1; + lMaxX1 = 6; + lMinX2 = maxX2 - 7; + lMaxX2 = maxX2 - 6; + lMinX3 = maxX3 - 7; + lMaxX3 = maxX3 - 2; + fillSendVector(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); + + lMinX1 = 1; + lMaxX1 = 6; + lMinX2 = maxX2 - 7; + lMaxX2 = maxX2 - 2; + lMinX3 = maxX3 - 7; + lMaxX3 = maxX3 - 6; + fillSendVector(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); + break; + + break; + + // TSE + case TSE: + lMinX1 = maxX1 - 7; + lMaxX1 = maxX1 - 6; + lMinX2 = 1; + lMaxX2 = 6; + lMinX3 = maxX3 - 7; + lMaxX3 = maxX3 - 2; + fillSendVector(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); + + lMinX1 = maxX1 - 7; + lMaxX1 = maxX1 - 2; + lMinX2 = 5; + lMaxX2 = 6; + lMinX3 = maxX3 - 7; + lMaxX3 = maxX3 - 2; + fillSendVector(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); + + lMinX1 = maxX1 - 7; + lMaxX1 = maxX1 - 2; + lMinX2 = 1; + lMaxX2 = 6; + lMinX3 = maxX3 - 7; + lMaxX3 = maxX3 - 6; + fillSendVector(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); + + break; + // TSW + case TSW: + lMinX1 = 5; + lMaxX1 = 6; + lMinX2 = 1; + lMaxX2 = 6; + lMinX3 = maxX3 - 7; + lMaxX3 = maxX3 - 2; + fillSendVector(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); + + lMinX1 = 1; + lMaxX1 = 6; + lMinX2 = 5; + lMaxX2 = 6; + lMinX3 = maxX3 - 7; + lMaxX3 = maxX3 - 2; + fillSendVector(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); + + lMinX1 = 1; + lMaxX1 = 6; + lMinX2 = 1; + lMaxX2 = 6; + lMinX3 = maxX3 - 7; + lMaxX3 = maxX3 - 6; + fillSendVector(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); + + break; + // BNE + case BNE: + lMinX1 = maxX1 - 7; + lMaxX1 = maxX1 - 6; + lMinX2 = maxX2 - 7; + lMaxX2 = maxX2 - 2; + lMinX3 = 1; + lMaxX3 = 6; + fillSendVector(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); + + lMinX1 = maxX1 - 7; + lMaxX1 = maxX1 - 2; + lMinX2 = maxX2 - 7; + lMaxX2 = maxX2 - 6; + lMinX3 = 1; + lMaxX3 = 6; + fillSendVector(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); + + lMinX1 = maxX1 - 7; + lMaxX1 = maxX1 - 2; + lMinX2 = maxX2 - 7; + lMaxX2 = maxX2 - 2; + lMinX3 = 5; + lMaxX3 = 6; + fillSendVector(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); + + break; + // BNW + case BNW: + lMinX1 = 5; + lMaxX1 = 6; + lMinX2 = maxX2 - 7; + lMaxX2 = maxX2 - 2; + lMinX3 = 1; + lMaxX3 = 6; + fillSendVector(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); + + lMinX1 = 1; + lMaxX1 = 6; + lMinX2 = maxX2 - 7; + lMaxX2 = maxX2 - 6; + lMinX3 = 1; + lMaxX3 = 6; + fillSendVector(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); + + lMinX1 = 1; + lMaxX1 = 6; + lMinX2 = maxX2 - 7; + lMaxX2 = maxX2 - 2; + lMinX3 = 5; + lMaxX3 = 6; + fillSendVector(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); + + break; + + // BSE + case BSE: + lMinX1 = maxX1 - 7; + lMaxX1 = maxX1 - 6; + lMinX2 = 1; + lMaxX2 = 6; + lMinX3 = 1; + lMaxX3 = 6; + fillSendVector(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); + + lMinX1 = maxX1 - 7; + lMaxX1 = maxX1 - 2; + lMinX2 = 5; + lMaxX2 = 6; + lMinX3 = 1; + lMaxX3 = 6; + fillSendVector(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); + + lMinX1 = maxX1 - 7; + lMaxX1 = maxX1 - 2; + lMinX2 = 1; + lMaxX2 = 6; + lMinX3 = 5; + lMaxX3 = 6; + fillSendVector(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); + + break; + + // BSW + case BSW: + lMinX1 = 5; + lMaxX1 = 6; + lMinX2 = 1; + lMaxX2 = 6; + lMinX3 = 1; + lMaxX3 = 6; + fillSendVector(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); + + lMinX1 = 1; + lMaxX1 = 6; + lMinX2 = 5; + lMaxX2 = 6; + lMinX3 = 1; + lMaxX3 = 6; + fillSendVector(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); + + lMinX1 = 1; + lMaxX1 = 6; + lMinX2 = 1; + lMaxX2 = 6; + lMinX3 = 5; + lMaxX3 = 6; + fillSendVector(fFrom, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); + + break; + } } ////////////////////////////////////////////////////////////////////////// -template< typename VectorTransmitter > -void D3Q27ETFCOffVectorConnector< VectorTransmitter>::fillSendVector(SPtr<DistributionArray3D> fFrom, const int& lMinX1, const int& lMinX2, const int& lMinX3, const int& lMaxX1, const int& lMaxX2, const int& lMaxX3, vector_type& data, int& index) +template <typename VectorTransmitter> +void D3Q27ETFCOffVectorConnector<VectorTransmitter>::fillSendVector(SPtr<DistributionArray3D> fFrom, const int &lMinX1, + const int &lMinX2, const int &lMinX3, + const int &lMaxX1, const int &lMaxX2, + const int &lMaxX3, vector_type &data, int &index) { - int ix1, ix2, ix3; - LBMReal xoff, yoff, zoff; - SPtr<BCArray3D> bcArray = block.lock()->getKernel()->getBCProcessor()->getBCArray(); - - for (ix3=lMinX3; ix3<lMaxX3; ix3+=2) - { - for (ix2=lMinX2; ix2<lMaxX2; ix2+=2) - { - for (ix1=lMinX1; ix1<lMaxX1; ix1+=2) - { - LBMReal icellC[27]; - D3Q27ICell icellF; - - int howManySolids= iprocessor->iCellHowManySolids(bcArray, ix1, ix2, ix3); - - if(howManySolids == 0 || howManySolids == 8) - { - iprocessor->readICell(fFrom, icellF, ix1, ix2, ix3); - xoff=0.0; - yoff=0.0; - zoff=0.0; - } - else - { - if(!iprocessor->findNeighborICell(bcArray, fFrom, icellF, bMaxX1, bMaxX2, bMaxX3, ix1, ix2, ix3, xoff, yoff, zoff)) - { - std::string err = "For "+block.lock()->toString()+" x1="+UbSystem::toString(ix1)+", x2=" + UbSystem::toString(ix2)+", x3=" + UbSystem::toString(ix3)+ - " interpolation is not implemented for other direction"+ - " by using in: "+(std::string)typeid(*this).name()+ - " or maybe you have a solid on the block boundary"; - //UBLOG(logINFO, err); - UB_THROW(UbException(UB_EXARGS, err)); - } - } - - iprocessor->interpolateFineToCoarse(icellF, icellC, xoff, yoff, zoff); - this->writeICellCtoData(data, index, icellC); - } - } - } + int ix1, ix2, ix3; + LBMReal xoff, yoff, zoff; + SPtr<BCArray3D> bcArray = block.lock()->getKernel()->getBCProcessor()->getBCArray(); + + for (ix3 = lMinX3; ix3 < lMaxX3; ix3 += 2) { + for (ix2 = lMinX2; ix2 < lMaxX2; ix2 += 2) { + for (ix1 = lMinX1; ix1 < lMaxX1; ix1 += 2) { + LBMReal icellC[27]; + D3Q27ICell icellF; + + int howManySolids = iprocessor->iCellHowManySolids(bcArray, ix1, ix2, ix3); + + if (howManySolids == 0 || howManySolids == 8) { + iprocessor->readICell(fFrom, icellF, ix1, ix2, ix3); + xoff = 0.0; + yoff = 0.0; + zoff = 0.0; + } else { + if (!iprocessor->findNeighborICell(bcArray, fFrom, icellF, bMaxX1, bMaxX2, bMaxX3, ix1, ix2, ix3, + xoff, yoff, zoff)) { + std::string err = "For " + block.lock()->toString() + " x1=" + UbSystem::toString(ix1) + + ", x2=" + UbSystem::toString(ix2) + ", x3=" + UbSystem::toString(ix3) + + " interpolation is not implemented for other direction" + + " by using in: " + (std::string) typeid(*this).name() + + " or maybe you have a solid on the block boundary"; + // UBLOG(logINFO, err); + UB_THROW(UbException(UB_EXARGS, err)); + } + } + + iprocessor->interpolateFineToCoarse(icellF, icellC, xoff, yoff, zoff); + this->writeICellCtoData(data, index, icellC); + } + } + } } ////////////////////////////////////////////////////////////////////////// -template< typename VectorTransmitter > -void D3Q27ETFCOffVectorConnector< VectorTransmitter>::writeICellCtoData(vector_type& data, int& index, LBMReal* icellC) +template <typename VectorTransmitter> +void D3Q27ETFCOffVectorConnector<VectorTransmitter>::writeICellCtoData(vector_type &data, int &index, LBMReal *icellC) { - for (int i = D3Q27System::STARTF; i < D3Q27System::ENDF+1; i++) - { - data[index++] = icellC[i]; - } + for (int i = D3Q27System::STARTF; i < D3Q27System::ENDF + 1; i++) { + data[index++] = icellC[i]; + } } ////////////////////////////////////////////////////////////////////////// -template< typename VectorTransmitter > -void D3Q27ETFCOffVectorConnector< VectorTransmitter>::getLocalMinMaxCF(int gMax, int& lMin, int& lMax) +template <typename VectorTransmitter> +void D3Q27ETFCOffVectorConnector<VectorTransmitter>::getLocalMinMaxCF(int gMax, int &lMin, int &lMax) { - if (Utilities::isOdd(gMax)) - { - if(connType == OddEvenSE || connType == OddOddNE) - { - lMin = 1; - lMax = gMax; - } - } + if (Utilities::isOdd(gMax)) { + if (connType == OddEvenSE || connType == OddOddNE) { + lMin = 1; + lMax = gMax; + } + } } ////////////////////////////////////////////////////////////////////////// -template< typename VectorTransmitter > -void D3Q27ETFCOffVectorConnector< VectorTransmitter>::distributeReceiveVectors() +template <typename VectorTransmitter> +void D3Q27ETFCOffVectorConnector<VectorTransmitter>::distributeReceiveVectors() { - using namespace D3Q27System; - - SPtr<DistributionArray3D> fTo = block.lock()->getKernel()->getDataSet()->getFdistributions(); - int maxX1 = (int)fTo->getNX1(); - int maxX2 = (int)fTo->getNX2(); - int maxX3 = (int)fTo->getNX3(); - int minX1 = 0; - int minX2 = 0; - int minX3 = 0; - - int lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3; - int index = 0; - vector_type& data = receiver->getData(); - - lMinX1 = minX1; lMinX2 = minX2; lMinX3 = minX3; - lMaxX1 = maxX1-1; lMaxX2 = maxX2-1; lMaxX3 = maxX3-1; - - switch(sendDir) - { - case E: - lMinX1 = maxX1-4; - lMaxX1 = lMinX1 + 1; - getLocalMinMaxCF(maxX2, lMinX2, lMaxX2); - getLocalMinMaxCF(maxX3, lMinX3, lMaxX3); - distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); - break; - case W: - /////////////////////////////////////// - ///DEBUG - //if (block.lock()->getGlobalID() == 2554) - //{ - // int test = 0; - //} - ////////////// - lMinX1 = 2; - lMaxX1 = lMinX1 + 1; - getLocalMinMaxCF(maxX2, lMinX2, lMaxX2); - getLocalMinMaxCF(maxX3, lMinX3, lMaxX3); - distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); - break; - case N: - lMinX2 = maxX2-4; - lMaxX2 = lMinX2 + 1; - getLocalMinMaxCF(maxX1, lMinX1, lMaxX1); - getLocalMinMaxCF(maxX3, lMinX3, lMaxX3); - distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); - break; - case S: - lMinX2 = 2; - lMaxX2 = lMinX2 + 1; - getLocalMinMaxCF(maxX1, lMinX1, lMaxX1); - getLocalMinMaxCF(maxX3, lMinX3, lMaxX3); - distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); - break; - case T: - lMinX3 = maxX3-4; - lMaxX3 = lMinX3 + 1; - getLocalMinMaxCF(maxX1, lMinX1, lMaxX1); - getLocalMinMaxCF(maxX2, lMinX2, lMaxX2); - distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); - break; - case B: - lMinX3 = 2; - lMaxX3 = lMinX3 + 1; - getLocalMinMaxCF(maxX1, lMinX1, lMaxX1); - getLocalMinMaxCF(maxX2, lMinX2, lMaxX2); - distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); - break; - - /////E-W-N-S - case NE: - lMinX1 = maxX1-4; - lMaxX1 = lMinX1 + 3; - lMinX2 = maxX2-4; - lMaxX2 = lMinX2 + 3; - getLocalMinMaxCF(maxX3, lMinX3, lMaxX3); - distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); - break; - - case SW: - lMinX1 = 0; - lMaxX1 = lMinX1 + 3; - lMinX2 = 0; - lMaxX2 = lMinX2 + 3; - getLocalMinMaxCF(maxX3, lMinX3, lMaxX3); - distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); - break; - - case SE: - lMinX1 = maxX1-4; - lMaxX1 = lMinX1 + 3; - lMinX2 = 0; - lMaxX2 = lMinX2 + 3; - getLocalMinMaxCF(maxX3, lMinX3, lMaxX3); - distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); - break; - - case NW: - lMinX1 = 0; - lMaxX1 = lMinX1 + 3; - lMinX2 = maxX2-4; - lMaxX2 = lMinX2 + 3; - getLocalMinMaxCF(maxX3, lMinX3, lMaxX3); - distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); - break; - // - // /////T-B-E-W - case TE: - lMinX1 = maxX1-4; - lMaxX1 = lMinX1 + 3; - lMinX3 = maxX3-4; - lMaxX3 = lMinX3 + 3; - getLocalMinMaxCF(maxX2, lMinX2, lMaxX2); - distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); - break; - - case BW: - lMinX1 = 0; - lMaxX1 = lMinX1 + 3; - lMinX3 = 0; - lMaxX3 = lMinX3 + 3; - getLocalMinMaxCF(maxX2, lMinX2, lMaxX2); - distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); - break; - - case BE: - lMinX1 = maxX1-4; - lMaxX1 = lMinX1 + 3; - lMinX3 = 0; - lMaxX3 = lMinX3 + 3; - getLocalMinMaxCF(maxX2, lMinX2, lMaxX2); - distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); - break; - - case TW: - lMinX1 = 0; - lMaxX1 = lMinX1 + 3; - lMinX3 = maxX3-4; - lMaxX3 = lMinX3 + 3; - getLocalMinMaxCF(maxX2, lMinX2, lMaxX2); - distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); - break; - - // ////////////////T-B-N-S - // - case TN: - lMinX2 = maxX2-4; - lMaxX2 = lMinX2 + 3; - lMinX3 = maxX3-4; - lMaxX3 = lMinX3 + 3; - getLocalMinMaxCF(maxX1, lMinX1, lMaxX1); - distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); - break; - - case BS: - lMinX2 = 0; - lMaxX2 = lMinX2 + 3; - lMinX3 = 0; - lMaxX3 = lMinX3 + 3; - getLocalMinMaxCF(maxX1, lMinX1, lMaxX1); - distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); - break; - - case BN: - lMinX2 = maxX2-4; - lMaxX2 = lMinX2 + 3; - lMinX3 = 0; - lMaxX3 = lMinX3 + 3; - getLocalMinMaxCF(maxX1, lMinX1, lMaxX1); - distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); - break; - - case TS: - lMinX2 = 0; - lMaxX2 = lMinX2 + 3; - lMinX3 = maxX3-4; - lMaxX3 = lMinX3 + 3; - getLocalMinMaxCF(maxX1, lMinX1, lMaxX1); - distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); - break; - - // //TNE - case TNE: - lMinX1 = maxX1-4; - lMaxX1 = maxX1-1; - lMinX2 = maxX2-4; - lMaxX2 = maxX2-1; - lMinX3 = maxX3-4; - lMaxX3 = maxX3-1; - distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); - break; - // TNW - case TNW: - lMinX1 = 0; - lMaxX1 = 3; - lMinX2 = maxX2-4; - lMaxX2 = maxX2-1; - lMinX3 = maxX3-4; - lMaxX3 = maxX3-1; - distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); - break; - // TSE - case TSE: - lMinX1 = maxX1-4; - lMaxX1 = maxX1-1; - lMinX2 = 0; - lMaxX2 = 3; - lMinX3 = maxX3-4; - lMaxX3 = maxX3-1; - distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); - break; - // TSW - case TSW: - lMinX1 = 0; - lMaxX1 = 3; - lMinX2 = 0; - lMaxX2 = 3; - lMinX3 = maxX3-4; - lMaxX3 = maxX3-1; - distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); - break; - // BNE - case BNE: - lMinX1 = maxX1-4; - lMaxX1 = maxX1-1; - lMinX2 = maxX2-4; - lMaxX2 = maxX2-1; - lMinX3 = 0; - lMaxX3 = 3; - distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); - break; - // BNW - case BNW: - lMinX1 = 0; - lMaxX1 = 3; - lMinX2 = maxX2-4; - lMaxX2 = maxX2-1; - lMinX3 = 0; - lMaxX3 = 3; - distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); - break; - // BSE - case BSE: - lMinX1 = maxX1-4; - lMaxX1 = maxX1-1; - lMinX2 = 0; - lMaxX2 = 3; - lMinX3 = 0; - lMaxX3 = 3; - distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); - break; - //BSW - case BSW: - lMinX1 = 0; - lMaxX1 = 3; - lMinX2 = 0; - lMaxX2 = 3; - lMinX3 = 0; - lMaxX3 = 3; - distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); - break; - } + using namespace D3Q27System; + + SPtr<DistributionArray3D> fTo = block.lock()->getKernel()->getDataSet()->getFdistributions(); + int maxX1 = (int)fTo->getNX1(); + int maxX2 = (int)fTo->getNX2(); + int maxX3 = (int)fTo->getNX3(); + int minX1 = 0; + int minX2 = 0; + int minX3 = 0; + + int lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3; + int index = 0; + vector_type &data = receiver->getData(); + + lMinX1 = minX1; + lMinX2 = minX2; + lMinX3 = minX3; + lMaxX1 = maxX1 - 1; + lMaxX2 = maxX2 - 1; + lMaxX3 = maxX3 - 1; + + switch (sendDir) { + case E: + lMinX1 = maxX1 - 4; + lMaxX1 = lMinX1 + 1; + getLocalMinMaxCF(maxX2, lMinX2, lMaxX2); + getLocalMinMaxCF(maxX3, lMinX3, lMaxX3); + distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); + break; + case W: + /////////////////////////////////////// + /// DEBUG + // if (block.lock()->getGlobalID() == 2554) + //{ + // int test = 0; + //} + ////////////// + lMinX1 = 2; + lMaxX1 = lMinX1 + 1; + getLocalMinMaxCF(maxX2, lMinX2, lMaxX2); + getLocalMinMaxCF(maxX3, lMinX3, lMaxX3); + distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); + break; + case N: + lMinX2 = maxX2 - 4; + lMaxX2 = lMinX2 + 1; + getLocalMinMaxCF(maxX1, lMinX1, lMaxX1); + getLocalMinMaxCF(maxX3, lMinX3, lMaxX3); + distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); + break; + case S: + lMinX2 = 2; + lMaxX2 = lMinX2 + 1; + getLocalMinMaxCF(maxX1, lMinX1, lMaxX1); + getLocalMinMaxCF(maxX3, lMinX3, lMaxX3); + distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); + break; + case T: + lMinX3 = maxX3 - 4; + lMaxX3 = lMinX3 + 1; + getLocalMinMaxCF(maxX1, lMinX1, lMaxX1); + getLocalMinMaxCF(maxX2, lMinX2, lMaxX2); + distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); + break; + case B: + lMinX3 = 2; + lMaxX3 = lMinX3 + 1; + getLocalMinMaxCF(maxX1, lMinX1, lMaxX1); + getLocalMinMaxCF(maxX2, lMinX2, lMaxX2); + distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); + break; + + /////E-W-N-S + case NE: + lMinX1 = maxX1 - 4; + lMaxX1 = lMinX1 + 3; + lMinX2 = maxX2 - 4; + lMaxX2 = lMinX2 + 3; + getLocalMinMaxCF(maxX3, lMinX3, lMaxX3); + distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); + break; + + case SW: + lMinX1 = 0; + lMaxX1 = lMinX1 + 3; + lMinX2 = 0; + lMaxX2 = lMinX2 + 3; + getLocalMinMaxCF(maxX3, lMinX3, lMaxX3); + distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); + break; + + case SE: + lMinX1 = maxX1 - 4; + lMaxX1 = lMinX1 + 3; + lMinX2 = 0; + lMaxX2 = lMinX2 + 3; + getLocalMinMaxCF(maxX3, lMinX3, lMaxX3); + distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); + break; + + case NW: + lMinX1 = 0; + lMaxX1 = lMinX1 + 3; + lMinX2 = maxX2 - 4; + lMaxX2 = lMinX2 + 3; + getLocalMinMaxCF(maxX3, lMinX3, lMaxX3); + distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); + break; + // + // /////T-B-E-W + case TE: + lMinX1 = maxX1 - 4; + lMaxX1 = lMinX1 + 3; + lMinX3 = maxX3 - 4; + lMaxX3 = lMinX3 + 3; + getLocalMinMaxCF(maxX2, lMinX2, lMaxX2); + distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); + break; + + case BW: + lMinX1 = 0; + lMaxX1 = lMinX1 + 3; + lMinX3 = 0; + lMaxX3 = lMinX3 + 3; + getLocalMinMaxCF(maxX2, lMinX2, lMaxX2); + distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); + break; + + case BE: + lMinX1 = maxX1 - 4; + lMaxX1 = lMinX1 + 3; + lMinX3 = 0; + lMaxX3 = lMinX3 + 3; + getLocalMinMaxCF(maxX2, lMinX2, lMaxX2); + distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); + break; + + case TW: + lMinX1 = 0; + lMaxX1 = lMinX1 + 3; + lMinX3 = maxX3 - 4; + lMaxX3 = lMinX3 + 3; + getLocalMinMaxCF(maxX2, lMinX2, lMaxX2); + distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); + break; + + // ////////////////T-B-N-S + // + case TN: + lMinX2 = maxX2 - 4; + lMaxX2 = lMinX2 + 3; + lMinX3 = maxX3 - 4; + lMaxX3 = lMinX3 + 3; + getLocalMinMaxCF(maxX1, lMinX1, lMaxX1); + distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); + break; + + case BS: + lMinX2 = 0; + lMaxX2 = lMinX2 + 3; + lMinX3 = 0; + lMaxX3 = lMinX3 + 3; + getLocalMinMaxCF(maxX1, lMinX1, lMaxX1); + distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); + break; + + case BN: + lMinX2 = maxX2 - 4; + lMaxX2 = lMinX2 + 3; + lMinX3 = 0; + lMaxX3 = lMinX3 + 3; + getLocalMinMaxCF(maxX1, lMinX1, lMaxX1); + distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); + break; + + case TS: + lMinX2 = 0; + lMaxX2 = lMinX2 + 3; + lMinX3 = maxX3 - 4; + lMaxX3 = lMinX3 + 3; + getLocalMinMaxCF(maxX1, lMinX1, lMaxX1); + distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); + break; + + // //TNE + case TNE: + lMinX1 = maxX1 - 4; + lMaxX1 = maxX1 - 1; + lMinX2 = maxX2 - 4; + lMaxX2 = maxX2 - 1; + lMinX3 = maxX3 - 4; + lMaxX3 = maxX3 - 1; + distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); + break; + // TNW + case TNW: + lMinX1 = 0; + lMaxX1 = 3; + lMinX2 = maxX2 - 4; + lMaxX2 = maxX2 - 1; + lMinX3 = maxX3 - 4; + lMaxX3 = maxX3 - 1; + distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); + break; + // TSE + case TSE: + lMinX1 = maxX1 - 4; + lMaxX1 = maxX1 - 1; + lMinX2 = 0; + lMaxX2 = 3; + lMinX3 = maxX3 - 4; + lMaxX3 = maxX3 - 1; + distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); + break; + // TSW + case TSW: + lMinX1 = 0; + lMaxX1 = 3; + lMinX2 = 0; + lMaxX2 = 3; + lMinX3 = maxX3 - 4; + lMaxX3 = maxX3 - 1; + distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); + break; + // BNE + case BNE: + lMinX1 = maxX1 - 4; + lMaxX1 = maxX1 - 1; + lMinX2 = maxX2 - 4; + lMaxX2 = maxX2 - 1; + lMinX3 = 0; + lMaxX3 = 3; + distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); + break; + // BNW + case BNW: + lMinX1 = 0; + lMaxX1 = 3; + lMinX2 = maxX2 - 4; + lMaxX2 = maxX2 - 1; + lMinX3 = 0; + lMaxX3 = 3; + distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); + break; + // BSE + case BSE: + lMinX1 = maxX1 - 4; + lMaxX1 = maxX1 - 1; + lMinX2 = 0; + lMaxX2 = 3; + lMinX3 = 0; + lMaxX3 = 3; + distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); + break; + // BSW + case BSW: + lMinX1 = 0; + lMaxX1 = 3; + lMinX2 = 0; + lMaxX2 = 3; + lMinX3 = 0; + lMaxX3 = 3; + distributeReceiveVector(fTo, lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, data, index); + break; + } } ////////////////////////////////////////////////////////////////////////// -template< typename VectorTransmitter > -void D3Q27ETFCOffVectorConnector< VectorTransmitter>::distributeReceiveVector(SPtr<DistributionArray3D> fTo, const int& lMinX1, const int& lMinX2, const int& lMinX3, const int& lMaxX1, const int& lMaxX2, const int& lMaxX3, vector_type& data, int& index) +template <typename VectorTransmitter> +void D3Q27ETFCOffVectorConnector<VectorTransmitter>::distributeReceiveVector(SPtr<DistributionArray3D> fTo, + const int &lMinX1, const int &lMinX2, + const int &lMinX3, const int &lMaxX1, + const int &lMaxX2, const int &lMaxX3, + vector_type &data, int &index) { - if(data.size() == 0) return; - - int ix1, ix2, ix3; - for (ix3=lMinX3; ix3<lMaxX3; ix3+=2) - { - for (ix2=lMinX2; ix2<lMaxX2; ix2+=2) - { - for (ix1=lMinX1; ix1<lMaxX1; ix1+=2) - { - D3Q27ICell icellF; - this->readICellFfromData(data, index, icellF); - iprocessor->writeICellInv(fTo, icellF, ix1, ix2, ix3); - } - } - } + if (data.size() == 0) + return; + + int ix1, ix2, ix3; + for (ix3 = lMinX3; ix3 < lMaxX3; ix3 += 2) { + for (ix2 = lMinX2; ix2 < lMaxX2; ix2 += 2) { + for (ix1 = lMinX1; ix1 < lMaxX1; ix1 += 2) { + D3Q27ICell icellF; + this->readICellFfromData(data, index, icellF); + iprocessor->writeICellInv(fTo, icellF, ix1, ix2, ix3); + } + } + } } ////////////////////////////////////////////////////////////////////////// -template< typename VectorTransmitter > -void D3Q27ETFCOffVectorConnector< VectorTransmitter>::readICellFfromData(vector_type& data, int& index, D3Q27ICell& icellF) +template <typename VectorTransmitter> +void D3Q27ETFCOffVectorConnector<VectorTransmitter>::readICellFfromData(vector_type &data, int &index, + D3Q27ICell &icellF) { - readNodeFromVector(data, index, icellF.BSW); - readNodeFromVector(data, index, icellF.BSE); - readNodeFromVector(data, index, icellF.BNW); - readNodeFromVector(data, index, icellF.BNE); - readNodeFromVector(data, index, icellF.TSW); - readNodeFromVector(data, index, icellF.TSE); - readNodeFromVector(data, index, icellF.TNW); - readNodeFromVector(data, index, icellF.TNE); + readNodeFromVector(data, index, icellF.BSW); + readNodeFromVector(data, index, icellF.BSE); + readNodeFromVector(data, index, icellF.BNW); + readNodeFromVector(data, index, icellF.BNE); + readNodeFromVector(data, index, icellF.TSW); + readNodeFromVector(data, index, icellF.TSE); + readNodeFromVector(data, index, icellF.TNW); + readNodeFromVector(data, index, icellF.TNE); } ////////////////////////////////////////////////////////////////////////// -template< typename VectorTransmitter > -void D3Q27ETFCOffVectorConnector< VectorTransmitter>::readNodeFromVector(vector_type& data, int& index, LBMReal* inode) +template <typename VectorTransmitter> +void D3Q27ETFCOffVectorConnector<VectorTransmitter>::readNodeFromVector(vector_type &data, int &index, LBMReal *inode) { - for (int i = D3Q27System::STARTF; i < D3Q27System::ENDF+1; i++) - { - inode[i] = data[index++]; - } + for (int i = D3Q27System::STARTF; i < D3Q27System::ENDF + 1; i++) { + inode[i] = data[index++]; + } } ////////////////////////////////////////////////////////////////////////// -template< typename VectorTransmitter > -void D3Q27ETFCOffVectorConnector< VectorTransmitter>::getLocalMinMax(int& minX1, int& minX2, int& minX3, int& maxX1, int& maxX2, int& maxX3) +template <typename VectorTransmitter> +void D3Q27ETFCOffVectorConnector<VectorTransmitter>::getLocalMinMax(int &minX1, int &minX2, int &minX3, int &maxX1, + int &maxX2, int &maxX3) { - using namespace D3Q27System; - int TminX1=minX1; int TminX2=minX2; int TminX3=minX3; int TmaxX1=maxX1; int TmaxX2=maxX2; int TmaxX3=maxX3; - - if(block.lock()->hasInterpolationFlagFC(E)) - { - if (maxX1==TmaxX1) maxX1 -= 3; - } - if(block.lock()->hasInterpolationFlagFC(W)) - { - if (minX1==TminX1) minX1 += 4; - } - if(block.lock()->hasInterpolationFlagFC(N)) - { - if (maxX2==TmaxX2) maxX2 -= 3; - } - if(block.lock()->hasInterpolationFlagFC(S)) - { - if (minX2==TminX2) minX2 += 4; - } - if(block.lock()->hasInterpolationFlagFC(T)) - { - if (maxX3==TmaxX3) maxX3 -= 3; - } - if(block.lock()->hasInterpolationFlagFC(B)) - { - if (minX3==TminX3) minX3 += 4; - } - - //////////// - /////E-W-N-S - if(block.lock()->hasInterpolationFlagFC(NE)&& !block.lock()->hasInterpolationFlagFC(N) && !block.lock()->hasInterpolationFlagFC(E)) - { - if (maxX1==TmaxX1) maxX1 -= 3; - if (maxX2==TmaxX2) maxX2 -= 3; - } - if(block.lock()->hasInterpolationFlagFC(SW)&& !block.lock()->hasInterpolationFlagFC(W) && !block.lock()->hasInterpolationFlagFC(S)) - { - if (minX1==TminX1) minX1 += 4; - if (minX2==TminX2) minX2 += 4; - } - if(block.lock()->hasInterpolationFlagFC(SE)&& !block.lock()->hasInterpolationFlagFC(E) && !block.lock()->hasInterpolationFlagFC(S)) - { - if (maxX1==TmaxX1) maxX1 -= 3; - if (minX2==TminX2) minX2 += 4; - } - if(block.lock()->hasInterpolationFlagFC(NW)&& !block.lock()->hasInterpolationFlagFC(N) && !block.lock()->hasInterpolationFlagFC(W)) - { - if (minX1==TminX1) minX1 += 4; - if (maxX2==TmaxX2) maxX2 -= 3; - } - - //////T-B-E-W - if(block.lock()->hasInterpolationFlagFC(TE) && !block.lock()->hasInterpolationFlagFC(E) && !block.lock()->hasInterpolationFlagFC(T)) - { - if (maxX1==TmaxX1) maxX1 -= 3; - if (maxX3==TmaxX3) maxX3 -= 3; - } - if(block.lock()->hasInterpolationFlagFC(BW)&& !block.lock()->hasInterpolationFlagFC(W) && !block.lock()->hasInterpolationFlagFC(B)) - { - if (minX1==TminX1) minX1 += 4; - if (minX3==TminX3) minX3 += 4; - } - if(block.lock()->hasInterpolationFlagFC(BE)&& !block.lock()->hasInterpolationFlagFC(E) && !block.lock()->hasInterpolationFlagFC(B)) - { - if (maxX1==TmaxX1) maxX1 -= 3; - if (minX3==TminX3) minX3 += 4; - } - if(block.lock()->hasInterpolationFlagFC(TW)&& !block.lock()->hasInterpolationFlagFC(W) && !block.lock()->hasInterpolationFlagFC(T)) - { - if (minX1==TminX1) minX1 += 4; - if (maxX3==TmaxX3) maxX3 -= 3; - } - - - ////T-B-N-S - if(block.lock()->hasInterpolationFlagFC(TN)&& !block.lock()->hasInterpolationFlagFC(N) && !block.lock()->hasInterpolationFlagFC(T)) - { - if (maxX2==TmaxX2) maxX2 -= 3; - if (maxX3==TmaxX3) maxX3 -= 3; - } - if(block.lock()->hasInterpolationFlagFC(BS)&& !block.lock()->hasInterpolationFlagFC(S) && !block.lock()->hasInterpolationFlagFC(B)) - { - if (minX2==TminX2) minX2 += 4; - if (minX3==TminX3) minX3 += 4; - } - if(block.lock()->hasInterpolationFlagFC(BN)&& !block.lock()->hasInterpolationFlagFC(N) && !block.lock()->hasInterpolationFlagFC(B)) - { - if (maxX2==TmaxX2) maxX2 -= 3; - if (minX3==TminX3) minX3 += 4; - } - if(block.lock()->hasInterpolationFlagFC(TS) && !block.lock()->hasInterpolationFlagFC(S) && !block.lock()->hasInterpolationFlagFC(T)) - { - if (minX2==TminX2) minX2 += 4; - if (maxX3==TmaxX3) maxX3 -= 3; - } - - //if (block.lock()->hasInterpolationFlagFC(D3Q27System::TNE)&&!block.lock()->hasInterpolationFlagFC(D3Q27System::TE)&&!block.lock()->hasInterpolationFlagFC(D3Q27System::TN)&&!block.lock()->hasInterpolationFlagFC(D3Q27System::NE)&&!block.lock()->hasInterpolationFlagFC(D3Q27System::T)&&!block.lock()->hasInterpolationFlagFC(D3Q27System::N) && !block.lock()->hasInterpolationFlagFC(D3Q27System::E)) - //if (!block.lock()->hasInterpolationFlagFC(D3Q27System::TE)&&!block.lock()->hasInterpolationFlagFC(D3Q27System::T) && !block.lock()->hasInterpolationFlagFC(D3Q27System::E)) - //{ - // if (maxX1==TmaxX1) maxX1 -= 3; - // if (maxX2==TmaxX2) maxX2 -= 3; - // if (maxX3==TmaxX3) maxX3 -= 3; - //} + using namespace D3Q27System; + int TminX1 = minX1; + int TminX2 = minX2; + int TminX3 = minX3; + int TmaxX1 = maxX1; + int TmaxX2 = maxX2; + int TmaxX3 = maxX3; + + if (block.lock()->hasInterpolationFlagFC(E)) { + if (maxX1 == TmaxX1) + maxX1 -= 3; + } + if (block.lock()->hasInterpolationFlagFC(W)) { + if (minX1 == TminX1) + minX1 += 4; + } + if (block.lock()->hasInterpolationFlagFC(N)) { + if (maxX2 == TmaxX2) + maxX2 -= 3; + } + if (block.lock()->hasInterpolationFlagFC(S)) { + if (minX2 == TminX2) + minX2 += 4; + } + if (block.lock()->hasInterpolationFlagFC(T)) { + if (maxX3 == TmaxX3) + maxX3 -= 3; + } + if (block.lock()->hasInterpolationFlagFC(B)) { + if (minX3 == TminX3) + minX3 += 4; + } + + //////////// + /////E-W-N-S + if (block.lock()->hasInterpolationFlagFC(NE) && !block.lock()->hasInterpolationFlagFC(N) && + !block.lock()->hasInterpolationFlagFC(E)) { + if (maxX1 == TmaxX1) + maxX1 -= 3; + if (maxX2 == TmaxX2) + maxX2 -= 3; + } + if (block.lock()->hasInterpolationFlagFC(SW) && !block.lock()->hasInterpolationFlagFC(W) && + !block.lock()->hasInterpolationFlagFC(S)) { + if (minX1 == TminX1) + minX1 += 4; + if (minX2 == TminX2) + minX2 += 4; + } + if (block.lock()->hasInterpolationFlagFC(SE) && !block.lock()->hasInterpolationFlagFC(E) && + !block.lock()->hasInterpolationFlagFC(S)) { + if (maxX1 == TmaxX1) + maxX1 -= 3; + if (minX2 == TminX2) + minX2 += 4; + } + if (block.lock()->hasInterpolationFlagFC(NW) && !block.lock()->hasInterpolationFlagFC(N) && + !block.lock()->hasInterpolationFlagFC(W)) { + if (minX1 == TminX1) + minX1 += 4; + if (maxX2 == TmaxX2) + maxX2 -= 3; + } + + //////T-B-E-W + if (block.lock()->hasInterpolationFlagFC(TE) && !block.lock()->hasInterpolationFlagFC(E) && + !block.lock()->hasInterpolationFlagFC(T)) { + if (maxX1 == TmaxX1) + maxX1 -= 3; + if (maxX3 == TmaxX3) + maxX3 -= 3; + } + if (block.lock()->hasInterpolationFlagFC(BW) && !block.lock()->hasInterpolationFlagFC(W) && + !block.lock()->hasInterpolationFlagFC(B)) { + if (minX1 == TminX1) + minX1 += 4; + if (minX3 == TminX3) + minX3 += 4; + } + if (block.lock()->hasInterpolationFlagFC(BE) && !block.lock()->hasInterpolationFlagFC(E) && + !block.lock()->hasInterpolationFlagFC(B)) { + if (maxX1 == TmaxX1) + maxX1 -= 3; + if (minX3 == TminX3) + minX3 += 4; + } + if (block.lock()->hasInterpolationFlagFC(TW) && !block.lock()->hasInterpolationFlagFC(W) && + !block.lock()->hasInterpolationFlagFC(T)) { + if (minX1 == TminX1) + minX1 += 4; + if (maxX3 == TmaxX3) + maxX3 -= 3; + } + + ////T-B-N-S + if (block.lock()->hasInterpolationFlagFC(TN) && !block.lock()->hasInterpolationFlagFC(N) && + !block.lock()->hasInterpolationFlagFC(T)) { + if (maxX2 == TmaxX2) + maxX2 -= 3; + if (maxX3 == TmaxX3) + maxX3 -= 3; + } + if (block.lock()->hasInterpolationFlagFC(BS) && !block.lock()->hasInterpolationFlagFC(S) && + !block.lock()->hasInterpolationFlagFC(B)) { + if (minX2 == TminX2) + minX2 += 4; + if (minX3 == TminX3) + minX3 += 4; + } + if (block.lock()->hasInterpolationFlagFC(BN) && !block.lock()->hasInterpolationFlagFC(N) && + !block.lock()->hasInterpolationFlagFC(B)) { + if (maxX2 == TmaxX2) + maxX2 -= 3; + if (minX3 == TminX3) + minX3 += 4; + } + if (block.lock()->hasInterpolationFlagFC(TS) && !block.lock()->hasInterpolationFlagFC(S) && + !block.lock()->hasInterpolationFlagFC(T)) { + if (minX2 == TminX2) + minX2 += 4; + if (maxX3 == TmaxX3) + maxX3 -= 3; + } + + // if + // (block.lock()->hasInterpolationFlagFC(D3Q27System::TNE)&&!block.lock()->hasInterpolationFlagFC(D3Q27System::TE)&&!block.lock()->hasInterpolationFlagFC(D3Q27System::TN)&&!block.lock()->hasInterpolationFlagFC(D3Q27System::NE)&&!block.lock()->hasInterpolationFlagFC(D3Q27System::T)&&!block.lock()->hasInterpolationFlagFC(D3Q27System::N) + // && !block.lock()->hasInterpolationFlagFC(D3Q27System::E)) if + // (!block.lock()->hasInterpolationFlagFC(D3Q27System::TE)&&!block.lock()->hasInterpolationFlagFC(D3Q27System::T) && + // !block.lock()->hasInterpolationFlagFC(D3Q27System::E)) + //{ + // if (maxX1==TmaxX1) maxX1 -= 3; + // if (maxX2==TmaxX2) maxX2 -= 3; + // if (maxX3==TmaxX3) maxX3 -= 3; + //} } ////////////////////////////////////////////////////////////////////////// -template< typename VectorTransmitter > -void D3Q27ETFCOffVectorConnector< VectorTransmitter>::getLocalMinMax(int& minX1, int& minX2, int& minX3, int& maxX1, int& maxX2, int& maxX3, CFconnectorType /*connType*/) +template <typename VectorTransmitter> +void D3Q27ETFCOffVectorConnector<VectorTransmitter>::getLocalMinMax(int &minX1, int &minX2, int &minX3, int &maxX1, + int &maxX2, int &maxX3, + CFconnectorType /*connType*/) { - using namespace D3Q27System; - int TminX1 = minX1; int TminX2 = minX2; int TminX3 = minX3; int TmaxX1 = maxX1; int TmaxX2 = maxX2; int TmaxX3 = maxX3; - - if (block.lock()->hasInterpolationFlagFC(E)) - { - if (maxX1==TmaxX1) maxX1 -= 3; - } - if (block.lock()->hasInterpolationFlagFC(W)) - { - if (minX1==TminX1) minX1 += 4; - } - if (block.lock()->hasInterpolationFlagFC(N)) - { - if (maxX2==TmaxX2) maxX2 -= 3; - } - if (block.lock()->hasInterpolationFlagFC(S)) - { - if (minX2==TminX2) minX2 += 4; - } - if (block.lock()->hasInterpolationFlagFC(T)) - { - if (maxX3==TmaxX3) maxX3 -= 3; - } - if (block.lock()->hasInterpolationFlagFC(B)) - { - if (minX3==TminX3) minX3 += 4; - } - - //////////// - /////E-W-N-S - if (block.lock()->hasInterpolationFlagFC(NE)&& !block.lock()->hasInterpolationFlagFC(N) && !block.lock()->hasInterpolationFlagFC(E)) - { - if (maxX1==TmaxX1) maxX1 -= 3; - if (maxX2==TmaxX2) maxX2 -= 3; - } - if (block.lock()->hasInterpolationFlagFC(SW)&& !block.lock()->hasInterpolationFlagFC(W) && !block.lock()->hasInterpolationFlagFC(S)) - { - if (minX1==TminX1) minX1 += 4; - if (minX2==TminX2) minX2 += 4; - } - if (block.lock()->hasInterpolationFlagFC(SE)&& !block.lock()->hasInterpolationFlagFC(E) && !block.lock()->hasInterpolationFlagFC(S)) - { - if (maxX1==TmaxX1) maxX1 -= 3; - if (minX2==TminX2) minX2 += 4; - } - if (block.lock()->hasInterpolationFlagFC(NW)&& !block.lock()->hasInterpolationFlagFC(N) && !block.lock()->hasInterpolationFlagFC(W)) - { - if (minX1==TminX1) minX1 += 4; - if (maxX2==TmaxX2) maxX2 -= 3; - } - - //////T-B-E-W - if (block.lock()->hasInterpolationFlagFC(TE) && !block.lock()->hasInterpolationFlagFC(E) && !block.lock()->hasInterpolationFlagFC(T)) - { - if (maxX1==TmaxX1) maxX1 -= 3; - if (maxX3==TmaxX3) maxX3 -= 3; - } - if (block.lock()->hasInterpolationFlagFC(BW)&& !block.lock()->hasInterpolationFlagFC(W) && !block.lock()->hasInterpolationFlagFC(B)) - { - if (minX1==TminX1) minX1 += 4; - if (minX3==TminX3) minX3 += 4; - } - if (block.lock()->hasInterpolationFlagFC(BE)&& !block.lock()->hasInterpolationFlagFC(E) && !block.lock()->hasInterpolationFlagFC(B)) - { - if (maxX1==TmaxX1) maxX1 -= 3; - if (minX3==TminX3) minX3 += 4; - } - if (block.lock()->hasInterpolationFlagFC(TW)&& !block.lock()->hasInterpolationFlagFC(W) && !block.lock()->hasInterpolationFlagFC(T)) - { - if (minX1==TminX1) minX1 += 4; - if (maxX3==TmaxX3) maxX3 -= 3; - } - - - ////T-B-N-S - if (block.lock()->hasInterpolationFlagFC(TN)&& !block.lock()->hasInterpolationFlagFC(N) && !block.lock()->hasInterpolationFlagFC(T)) - { - if (maxX2==TmaxX2) maxX2 -= 3; - if (maxX3==TmaxX3) maxX3 -= 3; - } - if (block.lock()->hasInterpolationFlagFC(BS)&& !block.lock()->hasInterpolationFlagFC(S) && !block.lock()->hasInterpolationFlagFC(B)) - { - if (minX2==TminX2) minX2 += 4; - if (minX3==TminX3) minX3 += 4; - } - if (block.lock()->hasInterpolationFlagFC(BN)&& !block.lock()->hasInterpolationFlagFC(N) && !block.lock()->hasInterpolationFlagFC(B)) - { - if (maxX2==TmaxX2) maxX2 -= 3; - if (minX3==TminX3) minX3 += 4; - } - if (block.lock()->hasInterpolationFlagFC(TS) && !block.lock()->hasInterpolationFlagFC(S) && !block.lock()->hasInterpolationFlagFC(T)) - { - if (minX2==TminX2) minX2 += 4; - if (maxX3==TmaxX3) maxX3 -= 3; - } - - //if (block.lock()->hasInterpolationFlagFC(D3Q27System::TNE)&&!block.lock()->hasInterpolationFlagFC(D3Q27System::TE)&&!block.lock()->hasInterpolationFlagFC(D3Q27System::TN)&&!block.lock()->hasInterpolationFlagFC(D3Q27System::NE)&&!block.lock()->hasInterpolationFlagFC(D3Q27System::T)&&!block.lock()->hasInterpolationFlagFC(D3Q27System::N) && !block.lock()->hasInterpolationFlagFC(D3Q27System::E)) - //{ - // if (maxX1==TmaxX1) maxX1 -= 3; - // if (maxX2==TmaxX2) maxX2 -= 3; - // if (maxX3==TmaxX3) maxX3 -= 3; - //} + using namespace D3Q27System; + int TminX1 = minX1; + int TminX2 = minX2; + int TminX3 = minX3; + int TmaxX1 = maxX1; + int TmaxX2 = maxX2; + int TmaxX3 = maxX3; + + if (block.lock()->hasInterpolationFlagFC(E)) { + if (maxX1 == TmaxX1) + maxX1 -= 3; + } + if (block.lock()->hasInterpolationFlagFC(W)) { + if (minX1 == TminX1) + minX1 += 4; + } + if (block.lock()->hasInterpolationFlagFC(N)) { + if (maxX2 == TmaxX2) + maxX2 -= 3; + } + if (block.lock()->hasInterpolationFlagFC(S)) { + if (minX2 == TminX2) + minX2 += 4; + } + if (block.lock()->hasInterpolationFlagFC(T)) { + if (maxX3 == TmaxX3) + maxX3 -= 3; + } + if (block.lock()->hasInterpolationFlagFC(B)) { + if (minX3 == TminX3) + minX3 += 4; + } + + //////////// + /////E-W-N-S + if (block.lock()->hasInterpolationFlagFC(NE) && !block.lock()->hasInterpolationFlagFC(N) && + !block.lock()->hasInterpolationFlagFC(E)) { + if (maxX1 == TmaxX1) + maxX1 -= 3; + if (maxX2 == TmaxX2) + maxX2 -= 3; + } + if (block.lock()->hasInterpolationFlagFC(SW) && !block.lock()->hasInterpolationFlagFC(W) && + !block.lock()->hasInterpolationFlagFC(S)) { + if (minX1 == TminX1) + minX1 += 4; + if (minX2 == TminX2) + minX2 += 4; + } + if (block.lock()->hasInterpolationFlagFC(SE) && !block.lock()->hasInterpolationFlagFC(E) && + !block.lock()->hasInterpolationFlagFC(S)) { + if (maxX1 == TmaxX1) + maxX1 -= 3; + if (minX2 == TminX2) + minX2 += 4; + } + if (block.lock()->hasInterpolationFlagFC(NW) && !block.lock()->hasInterpolationFlagFC(N) && + !block.lock()->hasInterpolationFlagFC(W)) { + if (minX1 == TminX1) + minX1 += 4; + if (maxX2 == TmaxX2) + maxX2 -= 3; + } + + //////T-B-E-W + if (block.lock()->hasInterpolationFlagFC(TE) && !block.lock()->hasInterpolationFlagFC(E) && + !block.lock()->hasInterpolationFlagFC(T)) { + if (maxX1 == TmaxX1) + maxX1 -= 3; + if (maxX3 == TmaxX3) + maxX3 -= 3; + } + if (block.lock()->hasInterpolationFlagFC(BW) && !block.lock()->hasInterpolationFlagFC(W) && + !block.lock()->hasInterpolationFlagFC(B)) { + if (minX1 == TminX1) + minX1 += 4; + if (minX3 == TminX3) + minX3 += 4; + } + if (block.lock()->hasInterpolationFlagFC(BE) && !block.lock()->hasInterpolationFlagFC(E) && + !block.lock()->hasInterpolationFlagFC(B)) { + if (maxX1 == TmaxX1) + maxX1 -= 3; + if (minX3 == TminX3) + minX3 += 4; + } + if (block.lock()->hasInterpolationFlagFC(TW) && !block.lock()->hasInterpolationFlagFC(W) && + !block.lock()->hasInterpolationFlagFC(T)) { + if (minX1 == TminX1) + minX1 += 4; + if (maxX3 == TmaxX3) + maxX3 -= 3; + } + + ////T-B-N-S + if (block.lock()->hasInterpolationFlagFC(TN) && !block.lock()->hasInterpolationFlagFC(N) && + !block.lock()->hasInterpolationFlagFC(T)) { + if (maxX2 == TmaxX2) + maxX2 -= 3; + if (maxX3 == TmaxX3) + maxX3 -= 3; + } + if (block.lock()->hasInterpolationFlagFC(BS) && !block.lock()->hasInterpolationFlagFC(S) && + !block.lock()->hasInterpolationFlagFC(B)) { + if (minX2 == TminX2) + minX2 += 4; + if (minX3 == TminX3) + minX3 += 4; + } + if (block.lock()->hasInterpolationFlagFC(BN) && !block.lock()->hasInterpolationFlagFC(N) && + !block.lock()->hasInterpolationFlagFC(B)) { + if (maxX2 == TmaxX2) + maxX2 -= 3; + if (minX3 == TminX3) + minX3 += 4; + } + if (block.lock()->hasInterpolationFlagFC(TS) && !block.lock()->hasInterpolationFlagFC(S) && + !block.lock()->hasInterpolationFlagFC(T)) { + if (minX2 == TminX2) + minX2 += 4; + if (maxX3 == TmaxX3) + maxX3 -= 3; + } + + // if + // (block.lock()->hasInterpolationFlagFC(D3Q27System::TNE)&&!block.lock()->hasInterpolationFlagFC(D3Q27System::TE)&&!block.lock()->hasInterpolationFlagFC(D3Q27System::TN)&&!block.lock()->hasInterpolationFlagFC(D3Q27System::NE)&&!block.lock()->hasInterpolationFlagFC(D3Q27System::T)&&!block.lock()->hasInterpolationFlagFC(D3Q27System::N) + // && !block.lock()->hasInterpolationFlagFC(D3Q27System::E)) + //{ + // if (maxX1==TmaxX1) maxX1 -= 3; + // if (maxX2==TmaxX2) maxX2 -= 3; + // if (maxX3==TmaxX3) maxX3 -= 3; + //} } ////////////////////////////////////////////////////////////////////////// -template< typename VectorTransmitter > -void D3Q27ETFCOffVectorConnector< VectorTransmitter>::getLocalOffsets(const int& gMax, int& oMin) +template <typename VectorTransmitter> +void D3Q27ETFCOffVectorConnector<VectorTransmitter>::getLocalOffsets(const int &gMax, int &oMin) { - if (Utilities::isEven(gMax)) - { - oMin = 0; - } - if (Utilities::isOdd(gMax)) - { - oMin = -1; - } - + if (Utilities::isEven(gMax)) { + oMin = 0; + } + if (Utilities::isOdd(gMax)) { + oMin = -1; + } } ////////////////////////////////////////////////////////////////////////// -template< typename VectorTransmitter > -void D3Q27ETFCOffVectorConnector< VectorTransmitter>::getLocalMins(int& minX1, int& minX2, int& minX3, const int& oMinX1, const int& oMinX2, const int& oMinX3) +template <typename VectorTransmitter> +void D3Q27ETFCOffVectorConnector<VectorTransmitter>::getLocalMins(int &minX1, int &minX2, int &minX3, const int &oMinX1, + const int &oMinX2, const int &oMinX3) { - using namespace D3Q27System; - - switch(sendDir) - { - case E: case W: - if(connType == OddEvenSE) - minX2 += oMinX2; - if(connType == OddOddNE) - { - minX2 += oMinX2; - minX3 += oMinX3; - } - if(connType == EvenOddNW) - minX3 += oMinX3; - break; - case N: case S: - if(connType == OddEvenSE) - minX1 += oMinX1; - if(connType == OddOddNE) - { - minX1 += oMinX1; - minX3 += oMinX3; - } - if(connType == EvenOddNW) - minX3 += oMinX3; - break; - case T: case B: - if(connType == OddEvenSE) - minX1 += oMinX1; - if(connType == OddOddNE) - { - minX1 += oMinX1; - minX2 += oMinX2; - } - if(connType == EvenOddNW) - minX2 += oMinX2; - break; - - ///// - case NE: case SW: case SE: case NW: - //case SW: - if(connType == OddEvenSE) - //minX2 += oMinX2; - if(connType == OddOddNE) - { - //minX2 += oMinX2; - minX3 += oMinX3; - } - if(connType == EvenOddNW) - minX3 += oMinX3; - break; - - ////// - case TE: case BW: case BE: case TW: - if(connType == OddEvenSE) - // minX1 += oMinX1; - if(connType == OddOddNE) - { - // minX1 += oMinX1; - minX2 += oMinX2; - } - if(connType == EvenOddNW) - minX2 += oMinX2; - break; - - // ////// - case TN: case BS: case BN: case TS: - if(connType == OddEvenSE) - minX1 += oMinX1; - if(connType == OddOddNE) - { - minX1 += oMinX1; - //minX3 += oMinX3; - } - if(connType == EvenOddNW) - //minX3 += oMinX3; - break; - - // ///// - // case TNE: case TNW: case TSE: case TSW: case BNE: case BNW: case BSE: case BSW: - // if(connType == OddEvenSE) - // // minX1 += oMinX1; - // if(connType == OddOddNE) - // { - // //minX1 += oMinX1; - // //minX3 += oMinX3; - // } - // if(connType == EvenOddNW) - // //minX3 += oMinX3; - // break; - } + using namespace D3Q27System; + + switch (sendDir) { + case E: + case W: + if (connType == OddEvenSE) + minX2 += oMinX2; + if (connType == OddOddNE) { + minX2 += oMinX2; + minX3 += oMinX3; + } + if (connType == EvenOddNW) + minX3 += oMinX3; + break; + case N: + case S: + if (connType == OddEvenSE) + minX1 += oMinX1; + if (connType == OddOddNE) { + minX1 += oMinX1; + minX3 += oMinX3; + } + if (connType == EvenOddNW) + minX3 += oMinX3; + break; + case T: + case B: + if (connType == OddEvenSE) + minX1 += oMinX1; + if (connType == OddOddNE) { + minX1 += oMinX1; + minX2 += oMinX2; + } + if (connType == EvenOddNW) + minX2 += oMinX2; + break; + + ///// + case NE: + case SW: + case SE: + case NW: + // case SW: + if (connType == OddEvenSE) + // minX2 += oMinX2; + if (connType == OddOddNE) { + // minX2 += oMinX2; + minX3 += oMinX3; + } + if (connType == EvenOddNW) + minX3 += oMinX3; + break; + + ////// + case TE: + case BW: + case BE: + case TW: + if (connType == OddEvenSE) + // minX1 += oMinX1; + if (connType == OddOddNE) { + // minX1 += oMinX1; + minX2 += oMinX2; + } + if (connType == EvenOddNW) + minX2 += oMinX2; + break; + + // ////// + case TN: + case BS: + case BN: + case TS: + if (connType == OddEvenSE) + minX1 += oMinX1; + if (connType == OddOddNE) { + minX1 += oMinX1; + // minX3 += oMinX3; + } + if (connType == EvenOddNW) + // minX3 += oMinX3; + break; + + // ///// + // case TNE: case TNW: case TSE: case TSW: case BNE: case BNW: case BSE: case BSW: + // if(connType == OddEvenSE) + // // minX1 += oMinX1; + // if(connType == OddOddNE) + // { + // //minX1 += oMinX1; + // //minX3 += oMinX3; + // } + // if(connType == EvenOddNW) + // //minX3 += oMinX3; + // break; + } } ////////////////////////////////////////////////////////////////////////// -template< typename VectorTransmitter > +template <typename VectorTransmitter> double D3Q27ETFCOffVectorConnector<VectorTransmitter>::getSendRecieveTime() { - return 0; + return 0; } #endif diff --git a/src/cpu/VirtualFluidsCore/Connectors/D3Q27ETFullDirectConnector.cpp b/src/cpu/VirtualFluidsCore/Connectors/D3Q27ETFullDirectConnector.cpp index 8519b39d0b2963cd6248d3c3a266d9e84b60e772..1e7e49f63c1e1c541242da02b744b7f462511d20 100644 --- a/src/cpu/VirtualFluidsCore/Connectors/D3Q27ETFullDirectConnector.cpp +++ b/src/cpu/VirtualFluidsCore/Connectors/D3Q27ETFullDirectConnector.cpp @@ -1,28 +1,28 @@ //======================================================================================= -// ____ ____ __ ______ __________ __ __ __ __ -// \ \ | | | | | _ \ |___ ___| | | | | / \ | | -// \ \ | | | | | |_) | | | | | | | / \ | | -// \ \ | | | | | _ / | | | | | | / /\ \ | | -// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ -// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| -// \ \ | | ________________________________________________________________ -// \ \ | | | ______________________________________________________________| -// \ \| | | | __ __ __ __ ______ _______ -// \ | | |_____ | | | | | | | | | _ \ / _____) -// \ | | _____| | | | | | | | | | | \ \ \_______ +// ____ ____ __ ______ __________ __ __ __ __ +// \ \ | | | | | _ \ |___ ___| | | | | / \ | | +// \ \ | | | | | |_) | | | | | | | / \ | | +// \ \ | | | | | _ / | | | | | | / /\ \ | | +// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ +// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| +// \ \ | | ________________________________________________________________ +// \ \ | | | ______________________________________________________________| +// \ \| | | | __ __ __ __ ______ _______ +// \ | | |_____ | | | | | | | | | _ \ / _____) +// \ | | _____| | | | | | | | | | | \ \ \_______ // \ | | | | |_____ | \_/ | | | | |_/ / _____ | -// \ _____| |__| |________| \_______/ |__| |______/ (_______/ +// \ _____| |__| |________| \_______/ |__| |______/ (_______/ // -// This file is part of VirtualFluids. VirtualFluids is free software: you can +// This file is part of VirtualFluids. VirtualFluids is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of +// License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. -// -// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// +// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License along // with VirtualFluids (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>. // @@ -32,212 +32,162 @@ //======================================================================================= #include "D3Q27ETFullDirectConnector.h" -#include "LBMKernel.h" #include "D3Q27EsoTwist3DSplittedVector.h" #include "DataSet3D.h" +#include "LBMKernel.h" using namespace std; D3Q27ETFullDirectConnector::D3Q27ETFullDirectConnector(SPtr<Block3D> from, SPtr<Block3D> to, int sendDir) - : LocalBlock3DConnector(from, to, sendDir) + : LocalBlock3DConnector(from, to, sendDir) { - } ////////////////////////////////////////////////////////////////////////// void D3Q27ETFullDirectConnector::init() { - maxX1 = (int)this->from.lock()->getKernel()->getDataSet()->getFdistributions()->getNX1() - 1; - maxX2 = (int)this->from.lock()->getKernel()->getDataSet()->getFdistributions()->getNX2() - 1; - maxX3 = (int)this->from.lock()->getKernel()->getDataSet()->getFdistributions()->getNX3() - 1; + maxX1 = (int)this->from.lock()->getKernel()->getDataSet()->getFdistributions()->getNX1() - 1; + maxX2 = (int)this->from.lock()->getKernel()->getDataSet()->getFdistributions()->getNX2() - 1; + maxX3 = (int)this->from.lock()->getKernel()->getDataSet()->getFdistributions()->getNX3() - 1; - fFrom = dynamic_pointer_cast<EsoTwist3D>(from.lock()->getKernel()->getDataSet()->getFdistributions()); - fTo = dynamic_pointer_cast<EsoTwist3D>(to.lock()->getKernel()->getDataSet()->getFdistributions()); + fFrom = dynamic_pointer_cast<EsoTwist3D>(from.lock()->getKernel()->getDataSet()->getFdistributions()); + fTo = dynamic_pointer_cast<EsoTwist3D>(to.lock()->getKernel()->getDataSet()->getFdistributions()); } ////////////////////////////////////////////////////////////////////////// void D3Q27ETFullDirectConnector::sendVectors() { - localDistributionsFrom = dynamic_pointer_cast<D3Q27EsoTwist3DSplittedVector>(this->fFrom)->getLocalDistributions(); - nonLocalDistributionsFrom = dynamic_pointer_cast<D3Q27EsoTwist3DSplittedVector>(this->fFrom)->getNonLocalDistributions(); - zeroDistributionsFrom = dynamic_pointer_cast<D3Q27EsoTwist3DSplittedVector>(this->fFrom)->getZeroDistributions(); + localDistributionsFrom = dynamic_pointer_cast<D3Q27EsoTwist3DSplittedVector>(this->fFrom)->getLocalDistributions(); + nonLocalDistributionsFrom = + dynamic_pointer_cast<D3Q27EsoTwist3DSplittedVector>(this->fFrom)->getNonLocalDistributions(); + zeroDistributionsFrom = dynamic_pointer_cast<D3Q27EsoTwist3DSplittedVector>(this->fFrom)->getZeroDistributions(); - localDistributionsTo = dynamic_pointer_cast<D3Q27EsoTwist3DSplittedVector>(this->fTo)->getLocalDistributions(); - nonLocalDistributionsTo = dynamic_pointer_cast<D3Q27EsoTwist3DSplittedVector>(this->fTo)->getNonLocalDistributions(); - zeroDistributionsTo = dynamic_pointer_cast<D3Q27EsoTwist3DSplittedVector>(this->fTo)->getZeroDistributions(); + localDistributionsTo = dynamic_pointer_cast<D3Q27EsoTwist3DSplittedVector>(this->fTo)->getLocalDistributions(); + nonLocalDistributionsTo = + dynamic_pointer_cast<D3Q27EsoTwist3DSplittedVector>(this->fTo)->getNonLocalDistributions(); + zeroDistributionsTo = dynamic_pointer_cast<D3Q27EsoTwist3DSplittedVector>(this->fTo)->getZeroDistributions(); - //EAST - if (sendDir == D3Q27System::E) - { - for (int x3 = 1; x3 < maxX3; x3++) - { - for (int x2 = 1; x2 < maxX2; x2++) - { - exchangeData(maxX1 - 1, x2, x3, 0, x2, x3); - } - } - } - //WEST - else if (sendDir == D3Q27System::W) - { - for (int x3 = 1; x3 < maxX3; x3++) - { - for (int x2 = 1; x2 < maxX2; x2++) - { - exchangeData(1, x2, x3, maxX1, x2, x3); - } - } - } - //NORTH - else if (sendDir == D3Q27System::N) - { - for (int x3 = 1; x3 < maxX3; x3++) - { - for (int x1 = 1; x1 < maxX1; x1++) - { - exchangeData(x1, maxX2 - 1, x3, x1, 0, x3); - } - } - } - //SOUTH - else if (sendDir == D3Q27System::S) - { - for (int x3 = 1; x3 < maxX3; x3++) - { - for (int x1 = 1; x1 < maxX1; x1++) - { - exchangeData(x1, 1, x3, x1, maxX2, x3); - } - } - } + // EAST + if (sendDir == D3Q27System::E) { + for (int x3 = 1; x3 < maxX3; x3++) { + for (int x2 = 1; x2 < maxX2; x2++) { + exchangeData(maxX1 - 1, x2, x3, 0, x2, x3); + } + } + } + // WEST + else if (sendDir == D3Q27System::W) { + for (int x3 = 1; x3 < maxX3; x3++) { + for (int x2 = 1; x2 < maxX2; x2++) { + exchangeData(1, x2, x3, maxX1, x2, x3); + } + } + } + // NORTH + else if (sendDir == D3Q27System::N) { + for (int x3 = 1; x3 < maxX3; x3++) { + for (int x1 = 1; x1 < maxX1; x1++) { + exchangeData(x1, maxX2 - 1, x3, x1, 0, x3); + } + } + } + // SOUTH + else if (sendDir == D3Q27System::S) { + for (int x3 = 1; x3 < maxX3; x3++) { + for (int x1 = 1; x1 < maxX1; x1++) { + exchangeData(x1, 1, x3, x1, maxX2, x3); + } + } + } - //TOP - else if (sendDir == D3Q27System::T) - { - for (int x2 = 1; x2 < maxX2; x2++) - { - for (int x1 = 1; x1 < maxX1; x1++) - { - exchangeData(x1, x2, maxX3 - 1, x1, x2, 0); - } - } - } - //BOTTOM - else if (sendDir == D3Q27System::B) - { - for (int x2 = 1; x2 < maxX2; x2++) - { - for (int x1 = 1; x1 < maxX1; x1++) - { - exchangeData(x1, x2, 1, x1, x2, maxX3); - } - } - } - //NORTHEAST - else if (sendDir == D3Q27System::NE) - { - for (int x3 = 1; x3 < maxX3; x3++) - { - exchangeData(maxX1 - 1, maxX2 - 1, x3, 0, 0, x3); - } - } - //NORTHWEST - else if (sendDir == D3Q27System::NW) - { - for (int x3 = 1; x3 < maxX3; x3++) - { - exchangeData(1, maxX2 - 1, x3, maxX1, 0, x3); - } - } - //SOUTHWEST - else if (sendDir == D3Q27System::SW) - { - for (int x3 = 1; x3 < maxX3; x3++) - { - exchangeData(1, 1, x3, maxX1, maxX2, x3); - } - } - //SOUTHEAST - else if (sendDir == D3Q27System::SE) - { - for (int x3 = 1; x3 < maxX3; x3++) - { - exchangeData(maxX1 - 1, 1, x3, 0, maxX2, x3); - } - } - else if (sendDir == D3Q27System::TE) - for (int x2 = 1; x2 < maxX2; x2++) - { - exchangeData(maxX1 - 1, x2, maxX3 - 1, 0, x2, 0); - } - else if (sendDir == D3Q27System::BW) - for (int x2 = 1; x2 < maxX2; x2++) - { - exchangeData(1, x2, 1, maxX1, x2, maxX3); - } - else if (sendDir == D3Q27System::BE) - for (int x2 = 1; x2 < maxX2; x2++) - { - exchangeData(maxX1 - 1, x2, 1, 0, x2, maxX3); - } - else if (sendDir == D3Q27System::TW) - for (int x2 = 1; x2 < maxX2; x2++) - { - exchangeData(1, x2, maxX3 - 1, maxX1, x2, 0); - } - else if (sendDir == D3Q27System::TN) - for (int x1 = 1; x1 < maxX1; x1++) - { - exchangeData(x1, maxX2 - 1, maxX3 - 1, x1, 0, 0); - } - else if (sendDir == D3Q27System::BS) - for (int x1 = 1; x1 < maxX1; x1++) - { - exchangeData(x1, 1, 1, x1, maxX2, maxX3); - } - else if (sendDir == D3Q27System::BN) - for (int x1 = 1; x1 < maxX1; x1++) - { - exchangeData(x1, maxX2 - 1, 1, x1, 0, maxX3); - } + // TOP + else if (sendDir == D3Q27System::T) { + for (int x2 = 1; x2 < maxX2; x2++) { + for (int x1 = 1; x1 < maxX1; x1++) { + exchangeData(x1, x2, maxX3 - 1, x1, x2, 0); + } + } + } + // BOTTOM + else if (sendDir == D3Q27System::B) { + for (int x2 = 1; x2 < maxX2; x2++) { + for (int x1 = 1; x1 < maxX1; x1++) { + exchangeData(x1, x2, 1, x1, x2, maxX3); + } + } + } + // NORTHEAST + else if (sendDir == D3Q27System::NE) { + for (int x3 = 1; x3 < maxX3; x3++) { + exchangeData(maxX1 - 1, maxX2 - 1, x3, 0, 0, x3); + } + } + // NORTHWEST + else if (sendDir == D3Q27System::NW) { + for (int x3 = 1; x3 < maxX3; x3++) { + exchangeData(1, maxX2 - 1, x3, maxX1, 0, x3); + } + } + // SOUTHWEST + else if (sendDir == D3Q27System::SW) { + for (int x3 = 1; x3 < maxX3; x3++) { + exchangeData(1, 1, x3, maxX1, maxX2, x3); + } + } + // SOUTHEAST + else if (sendDir == D3Q27System::SE) { + for (int x3 = 1; x3 < maxX3; x3++) { + exchangeData(maxX1 - 1, 1, x3, 0, maxX2, x3); + } + } else if (sendDir == D3Q27System::TE) + for (int x2 = 1; x2 < maxX2; x2++) { + exchangeData(maxX1 - 1, x2, maxX3 - 1, 0, x2, 0); + } + else if (sendDir == D3Q27System::BW) + for (int x2 = 1; x2 < maxX2; x2++) { + exchangeData(1, x2, 1, maxX1, x2, maxX3); + } + else if (sendDir == D3Q27System::BE) + for (int x2 = 1; x2 < maxX2; x2++) { + exchangeData(maxX1 - 1, x2, 1, 0, x2, maxX3); + } + else if (sendDir == D3Q27System::TW) + for (int x2 = 1; x2 < maxX2; x2++) { + exchangeData(1, x2, maxX3 - 1, maxX1, x2, 0); + } + else if (sendDir == D3Q27System::TN) + for (int x1 = 1; x1 < maxX1; x1++) { + exchangeData(x1, maxX2 - 1, maxX3 - 1, x1, 0, 0); + } + else if (sendDir == D3Q27System::BS) + for (int x1 = 1; x1 < maxX1; x1++) { + exchangeData(x1, 1, 1, x1, maxX2, maxX3); + } + else if (sendDir == D3Q27System::BN) + for (int x1 = 1; x1 < maxX1; x1++) { + exchangeData(x1, maxX2 - 1, 1, x1, 0, maxX3); + } - else if (sendDir == D3Q27System::TS) - for (int x1 = 1; x1 < maxX1; x1++) - { - exchangeData(x1, 1, maxX3 - 1, x1, maxX2, 0); - } + else if (sendDir == D3Q27System::TS) + for (int x1 = 1; x1 < maxX1; x1++) { + exchangeData(x1, 1, maxX3 - 1, x1, maxX2, 0); + } - else if (sendDir == D3Q27System::TSW) - { - exchangeData(1, 1, maxX3 - 1, maxX1, maxX2, 0); - } - else if (sendDir == D3Q27System::TSE) - { - exchangeData(maxX1 - 1, 1, maxX3 - 1, 0, maxX2, 0); - } - else if (sendDir == D3Q27System::TNW) - { - exchangeData(1, maxX2 - 1, maxX3 - 1, maxX1, 0, 0); - } - else if (sendDir == D3Q27System::TNE) - { - exchangeData(maxX1 - 1, maxX2 - 1, maxX3 - 1, 0, 0, 0); - } - else if (sendDir == D3Q27System::BSW) - { - exchangeData(1, 1, 1, maxX1, maxX2, maxX3); - } - else if (sendDir == D3Q27System::BSE) - { - exchangeData(maxX1 - 1, 1, 1, 0, maxX2, maxX3); - } - else if (sendDir == D3Q27System::BNW) - { - exchangeData(1, maxX2 - 1, 1, maxX1, 0, maxX3); - } - else if (sendDir == D3Q27System::BNE) - { - exchangeData(maxX1 - 1, maxX2 - 1, 1, 0, 0, maxX3); - } - else UB_THROW(UbException(UB_EXARGS, "unknown dir")); + else if (sendDir == D3Q27System::TSW) { + exchangeData(1, 1, maxX3 - 1, maxX1, maxX2, 0); + } else if (sendDir == D3Q27System::TSE) { + exchangeData(maxX1 - 1, 1, maxX3 - 1, 0, maxX2, 0); + } else if (sendDir == D3Q27System::TNW) { + exchangeData(1, maxX2 - 1, maxX3 - 1, maxX1, 0, 0); + } else if (sendDir == D3Q27System::TNE) { + exchangeData(maxX1 - 1, maxX2 - 1, maxX3 - 1, 0, 0, 0); + } else if (sendDir == D3Q27System::BSW) { + exchangeData(1, 1, 1, maxX1, maxX2, maxX3); + } else if (sendDir == D3Q27System::BSE) { + exchangeData(maxX1 - 1, 1, 1, 0, maxX2, maxX3); + } else if (sendDir == D3Q27System::BNW) { + exchangeData(1, maxX2 - 1, 1, maxX1, 0, maxX3); + } else if (sendDir == D3Q27System::BNE) { + exchangeData(maxX1 - 1, maxX2 - 1, 1, 0, 0, maxX3); + } else + UB_THROW(UbException(UB_EXARGS, "unknown dir")); } - diff --git a/src/cpu/VirtualFluidsCore/Connectors/D3Q27ETFullDirectConnector.h b/src/cpu/VirtualFluidsCore/Connectors/D3Q27ETFullDirectConnector.h index ffce993cce0b56cdafde01b875e43be614bdeef3..101bc96af530e75ee442b012766bce11d9f016f4 100644 --- a/src/cpu/VirtualFluidsCore/Connectors/D3Q27ETFullDirectConnector.h +++ b/src/cpu/VirtualFluidsCore/Connectors/D3Q27ETFullDirectConnector.h @@ -1,28 +1,28 @@ //======================================================================================= -// ____ ____ __ ______ __________ __ __ __ __ -// \ \ | | | | | _ \ |___ ___| | | | | / \ | | -// \ \ | | | | | |_) | | | | | | | / \ | | -// \ \ | | | | | _ / | | | | | | / /\ \ | | -// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ -// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| -// \ \ | | ________________________________________________________________ -// \ \ | | | ______________________________________________________________| -// \ \| | | | __ __ __ __ ______ _______ -// \ | | |_____ | | | | | | | | | _ \ / _____) -// \ | | _____| | | | | | | | | | | \ \ \_______ +// ____ ____ __ ______ __________ __ __ __ __ +// \ \ | | | | | _ \ |___ ___| | | | | / \ | | +// \ \ | | | | | |_) | | | | | | | / \ | | +// \ \ | | | | | _ / | | | | | | / /\ \ | | +// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ +// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| +// \ \ | | ________________________________________________________________ +// \ \ | | | ______________________________________________________________| +// \ \| | | | __ __ __ __ ______ _______ +// \ | | |_____ | | | | | | | | | _ \ / _____) +// \ | | _____| | | | | | | | | | | \ \ \_______ // \ | | | | |_____ | \_/ | | | | |_/ / _____ | -// \ _____| |__| |________| \_______/ |__| |______/ (_______/ +// \ _____| |__| |________| \_______/ |__| |______/ (_______/ // -// This file is part of VirtualFluids. VirtualFluids is free software: you can +// This file is part of VirtualFluids. VirtualFluids is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of +// License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. -// -// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// +// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License along // with VirtualFluids (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>. // @@ -34,74 +34,99 @@ #ifndef D3Q27ETFULLDIRECTCONNECTOR_H #define D3Q27ETFULLDIRECTCONNECTOR_H -#include "LocalBlock3DConnector.h" #include "Block3D.h" #include "D3Q27System.h" +#include "EsoTwist3D.h" +#include "LocalBlock3DConnector.h" #include "basics/container/CbArray3D.h" #include "basics/container/CbArray4D.h" -#include "EsoTwist3D.h" -//! \brief Exchange data between blocks. +//! \brief Exchange data between blocks. //! \details Connector send and receive full distributions between two blocks in shared memory. class D3Q27ETFullDirectConnector : public LocalBlock3DConnector { public: - D3Q27ETFullDirectConnector(SPtr<Block3D> from, SPtr<Block3D> to, int sendDir); - void init() override; - void sendVectors() override; + D3Q27ETFullDirectConnector(SPtr<Block3D> from, SPtr<Block3D> to, int sendDir); + void init() override; + void sendVectors() override; protected: - inline void exchangeData(int x1From, int x2From, int x3From, int x1To, int x2To, int x3To); + inline void exchangeData(int x1From, int x2From, int x3From, int x1To, int x2To, int x3To); + private: - int maxX1; - int maxX2; - int maxX3; + int maxX1; + int maxX2; + int maxX3; - CbArray4D <LBMReal, IndexerX4X3X2X1>::CbArray4DPtr localDistributionsFrom; - CbArray4D <LBMReal, IndexerX4X3X2X1>::CbArray4DPtr nonLocalDistributionsFrom; - CbArray3D <LBMReal, IndexerX3X2X1>::CbArray3DPtr zeroDistributionsFrom; + CbArray4D<LBMReal, IndexerX4X3X2X1>::CbArray4DPtr localDistributionsFrom; + CbArray4D<LBMReal, IndexerX4X3X2X1>::CbArray4DPtr nonLocalDistributionsFrom; + CbArray3D<LBMReal, IndexerX3X2X1>::CbArray3DPtr zeroDistributionsFrom; - CbArray4D <LBMReal, IndexerX4X3X2X1>::CbArray4DPtr localDistributionsTo; - CbArray4D <LBMReal, IndexerX4X3X2X1>::CbArray4DPtr nonLocalDistributionsTo; - CbArray3D <LBMReal, IndexerX3X2X1>::CbArray3DPtr zeroDistributionsTo; + CbArray4D<LBMReal, IndexerX4X3X2X1>::CbArray4DPtr localDistributionsTo; + CbArray4D<LBMReal, IndexerX4X3X2X1>::CbArray4DPtr nonLocalDistributionsTo; + CbArray3D<LBMReal, IndexerX3X2X1>::CbArray3DPtr zeroDistributionsTo; - SPtr<EsoTwist3D> fFrom; - SPtr<EsoTwist3D> fTo; + SPtr<EsoTwist3D> fFrom; + SPtr<EsoTwist3D> fTo; }; - ////////////////////////////////////////////////////////////////////////// inline void D3Q27ETFullDirectConnector::exchangeData(int x1From, int x2From, int x3From, int x1To, int x2To, int x3To) { - (*this->localDistributionsTo)(D3Q27System::ET_E, x1To, x2To, x3To) = (*this->localDistributionsFrom)(D3Q27System::ET_E, x1From, x2From, x3From); - (*this->localDistributionsTo)(D3Q27System::ET_N, x1To, x2To, x3To) = (*this->localDistributionsFrom)(D3Q27System::ET_N, x1From, x2From, x3From); - (*this->localDistributionsTo)(D3Q27System::ET_T, x1To, x2To, x3To) = (*this->localDistributionsFrom)(D3Q27System::ET_T, x1From, x2From, x3From); - (*this->localDistributionsTo)(D3Q27System::ET_NE, x1To, x2To, x3To) = (*this->localDistributionsFrom)(D3Q27System::ET_NE, x1From, x2From, x3From); - (*this->localDistributionsTo)(D3Q27System::ET_NW, x1To + 1, x2To, x3To) = (*this->localDistributionsFrom)(D3Q27System::ET_NW, x1From + 1, x2From, x3From); - (*this->localDistributionsTo)(D3Q27System::ET_TE, x1To, x2To, x3To) = (*this->localDistributionsFrom)(D3Q27System::ET_TE, x1From, x2From, x3From); - (*this->localDistributionsTo)(D3Q27System::ET_TW, x1To + 1, x2To, x3To) = (*this->localDistributionsFrom)(D3Q27System::ET_TW, x1From + 1, x2From, x3From); - (*this->localDistributionsTo)(D3Q27System::ET_TN, x1To, x2To, x3To) = (*this->localDistributionsFrom)(D3Q27System::ET_TN, x1From, x2From, x3From); - (*this->localDistributionsTo)(D3Q27System::ET_TS, x1To, x2To + 1, x3To) = (*this->localDistributionsFrom)(D3Q27System::ET_TS, x1From, x2From + 1, x3From); - (*this->localDistributionsTo)(D3Q27System::ET_TNE, x1To, x2To, x3To) = (*this->localDistributionsFrom)(D3Q27System::ET_TNE, x1From, x2From, x3From); - (*this->localDistributionsTo)(D3Q27System::ET_TNW, x1To + 1, x2To, x3To) = (*this->localDistributionsFrom)(D3Q27System::ET_TNW, x1From + 1, x2From, x3From); - (*this->localDistributionsTo)(D3Q27System::ET_TSE, x1To, x2To + 1, x3To) = (*this->localDistributionsFrom)(D3Q27System::ET_TSE, x1From, x2From + 1, x3From); - (*this->localDistributionsTo)(D3Q27System::ET_TSW, x1To + 1, x2To + 1, x3To) = (*this->localDistributionsFrom)(D3Q27System::ET_TSW, x1From + 1, x2From + 1, x3From); + (*this->localDistributionsTo)(D3Q27System::ET_E, x1To, x2To, x3To) = + (*this->localDistributionsFrom)(D3Q27System::ET_E, x1From, x2From, x3From); + (*this->localDistributionsTo)(D3Q27System::ET_N, x1To, x2To, x3To) = + (*this->localDistributionsFrom)(D3Q27System::ET_N, x1From, x2From, x3From); + (*this->localDistributionsTo)(D3Q27System::ET_T, x1To, x2To, x3To) = + (*this->localDistributionsFrom)(D3Q27System::ET_T, x1From, x2From, x3From); + (*this->localDistributionsTo)(D3Q27System::ET_NE, x1To, x2To, x3To) = + (*this->localDistributionsFrom)(D3Q27System::ET_NE, x1From, x2From, x3From); + (*this->localDistributionsTo)(D3Q27System::ET_NW, x1To + 1, x2To, x3To) = + (*this->localDistributionsFrom)(D3Q27System::ET_NW, x1From + 1, x2From, x3From); + (*this->localDistributionsTo)(D3Q27System::ET_TE, x1To, x2To, x3To) = + (*this->localDistributionsFrom)(D3Q27System::ET_TE, x1From, x2From, x3From); + (*this->localDistributionsTo)(D3Q27System::ET_TW, x1To + 1, x2To, x3To) = + (*this->localDistributionsFrom)(D3Q27System::ET_TW, x1From + 1, x2From, x3From); + (*this->localDistributionsTo)(D3Q27System::ET_TN, x1To, x2To, x3To) = + (*this->localDistributionsFrom)(D3Q27System::ET_TN, x1From, x2From, x3From); + (*this->localDistributionsTo)(D3Q27System::ET_TS, x1To, x2To + 1, x3To) = + (*this->localDistributionsFrom)(D3Q27System::ET_TS, x1From, x2From + 1, x3From); + (*this->localDistributionsTo)(D3Q27System::ET_TNE, x1To, x2To, x3To) = + (*this->localDistributionsFrom)(D3Q27System::ET_TNE, x1From, x2From, x3From); + (*this->localDistributionsTo)(D3Q27System::ET_TNW, x1To + 1, x2To, x3To) = + (*this->localDistributionsFrom)(D3Q27System::ET_TNW, x1From + 1, x2From, x3From); + (*this->localDistributionsTo)(D3Q27System::ET_TSE, x1To, x2To + 1, x3To) = + (*this->localDistributionsFrom)(D3Q27System::ET_TSE, x1From, x2From + 1, x3From); + (*this->localDistributionsTo)(D3Q27System::ET_TSW, x1To + 1, x2To + 1, x3To) = + (*this->localDistributionsFrom)(D3Q27System::ET_TSW, x1From + 1, x2From + 1, x3From); - (*this->nonLocalDistributionsTo)(D3Q27System::ET_W, x1To + 1, x2To, x3To) = (*this->nonLocalDistributionsFrom)(D3Q27System::ET_W, x1From + 1, x2From, x3From); - (*this->nonLocalDistributionsTo)(D3Q27System::ET_S, x1To, x2To + 1, x3To) = (*this->nonLocalDistributionsFrom)(D3Q27System::ET_S, x1From, x2From + 1, x3From); - (*this->nonLocalDistributionsTo)(D3Q27System::ET_B, x1To, x2To, x3To + 1) = (*this->nonLocalDistributionsFrom)(D3Q27System::ET_B, x1From, x2From, x3From + 1); - (*this->nonLocalDistributionsTo)(D3Q27System::ET_SW, x1To + 1, x2To + 1, x3To) = (*this->nonLocalDistributionsFrom)(D3Q27System::ET_SW, x1From + 1, x2From + 1, x3From); - (*this->nonLocalDistributionsTo)(D3Q27System::ET_SE, x1To, x2To + 1, x3To) = (*this->nonLocalDistributionsFrom)(D3Q27System::ET_SE, x1From, x2From + 1, x3From); - (*this->nonLocalDistributionsTo)(D3Q27System::ET_BW, x1To + 1, x2To, x3To + 1) = (*this->nonLocalDistributionsFrom)(D3Q27System::ET_BW, x1From + 1, x2From, x3From + 1); - (*this->nonLocalDistributionsTo)(D3Q27System::ET_BE, x1To, x2To, x3To + 1) = (*this->nonLocalDistributionsFrom)(D3Q27System::ET_BE, x1From, x2From, x3From + 1); - (*this->nonLocalDistributionsTo)(D3Q27System::ET_BS, x1To, x2To + 1, x3To + 1) = (*this->nonLocalDistributionsFrom)(D3Q27System::ET_BS, x1From, x2From + 1, x3From + 1); - (*this->nonLocalDistributionsTo)(D3Q27System::ET_BN, x1To, x2To, x3To + 1) = (*this->nonLocalDistributionsFrom)(D3Q27System::ET_BN, x1From, x2From, x3From + 1); - (*this->nonLocalDistributionsTo)(D3Q27System::ET_BSW, x1To + 1, x2To + 1, x3To + 1) = (*this->nonLocalDistributionsFrom)(D3Q27System::ET_BSW, x1From + 1, x2From + 1, x3From + 1); - (*this->nonLocalDistributionsTo)(D3Q27System::ET_BSE, x1To, x2To + 1, x3To + 1) = (*this->nonLocalDistributionsFrom)(D3Q27System::ET_BSE, x1From, x2From + 1, x3From + 1); - (*this->nonLocalDistributionsTo)(D3Q27System::ET_BNW, x1To + 1, x2To, x3To + 1) = (*this->nonLocalDistributionsFrom)(D3Q27System::ET_BNW, x1From + 1, x2From, x3From + 1); - (*this->nonLocalDistributionsTo)(D3Q27System::ET_BNE, x1To, x2To, x3To + 1) = (*this->nonLocalDistributionsFrom)(D3Q27System::ET_BNE, x1From, x2From, x3From + 1); + (*this->nonLocalDistributionsTo)(D3Q27System::ET_W, x1To + 1, x2To, x3To) = + (*this->nonLocalDistributionsFrom)(D3Q27System::ET_W, x1From + 1, x2From, x3From); + (*this->nonLocalDistributionsTo)(D3Q27System::ET_S, x1To, x2To + 1, x3To) = + (*this->nonLocalDistributionsFrom)(D3Q27System::ET_S, x1From, x2From + 1, x3From); + (*this->nonLocalDistributionsTo)(D3Q27System::ET_B, x1To, x2To, x3To + 1) = + (*this->nonLocalDistributionsFrom)(D3Q27System::ET_B, x1From, x2From, x3From + 1); + (*this->nonLocalDistributionsTo)(D3Q27System::ET_SW, x1To + 1, x2To + 1, x3To) = + (*this->nonLocalDistributionsFrom)(D3Q27System::ET_SW, x1From + 1, x2From + 1, x3From); + (*this->nonLocalDistributionsTo)(D3Q27System::ET_SE, x1To, x2To + 1, x3To) = + (*this->nonLocalDistributionsFrom)(D3Q27System::ET_SE, x1From, x2From + 1, x3From); + (*this->nonLocalDistributionsTo)(D3Q27System::ET_BW, x1To + 1, x2To, x3To + 1) = + (*this->nonLocalDistributionsFrom)(D3Q27System::ET_BW, x1From + 1, x2From, x3From + 1); + (*this->nonLocalDistributionsTo)(D3Q27System::ET_BE, x1To, x2To, x3To + 1) = + (*this->nonLocalDistributionsFrom)(D3Q27System::ET_BE, x1From, x2From, x3From + 1); + (*this->nonLocalDistributionsTo)(D3Q27System::ET_BS, x1To, x2To + 1, x3To + 1) = + (*this->nonLocalDistributionsFrom)(D3Q27System::ET_BS, x1From, x2From + 1, x3From + 1); + (*this->nonLocalDistributionsTo)(D3Q27System::ET_BN, x1To, x2To, x3To + 1) = + (*this->nonLocalDistributionsFrom)(D3Q27System::ET_BN, x1From, x2From, x3From + 1); + (*this->nonLocalDistributionsTo)(D3Q27System::ET_BSW, x1To + 1, x2To + 1, x3To + 1) = + (*this->nonLocalDistributionsFrom)(D3Q27System::ET_BSW, x1From + 1, x2From + 1, x3From + 1); + (*this->nonLocalDistributionsTo)(D3Q27System::ET_BSE, x1To, x2To + 1, x3To + 1) = + (*this->nonLocalDistributionsFrom)(D3Q27System::ET_BSE, x1From, x2From + 1, x3From + 1); + (*this->nonLocalDistributionsTo)(D3Q27System::ET_BNW, x1To + 1, x2To, x3To + 1) = + (*this->nonLocalDistributionsFrom)(D3Q27System::ET_BNW, x1From + 1, x2From, x3From + 1); + (*this->nonLocalDistributionsTo)(D3Q27System::ET_BNE, x1To, x2To, x3To + 1) = + (*this->nonLocalDistributionsFrom)(D3Q27System::ET_BNE, x1From, x2From, x3From + 1); - (*this->zeroDistributionsTo)(x1To, x2To, x3To) = (*this->zeroDistributionsFrom)(x1From, x2From, x3From); + (*this->zeroDistributionsTo)(x1To, x2To, x3To) = (*this->zeroDistributionsFrom)(x1From, x2From, x3From); } -#endif - +#endif diff --git a/src/cpu/VirtualFluidsCore/Connectors/D3Q27ETFullVectorConnector.cpp b/src/cpu/VirtualFluidsCore/Connectors/D3Q27ETFullVectorConnector.cpp index e85d1409875df221849375faa9a9ce087c05bf95..70d7c438e0b0a8eb32ffcf7b097ab3148d76e270 100644 --- a/src/cpu/VirtualFluidsCore/Connectors/D3Q27ETFullVectorConnector.cpp +++ b/src/cpu/VirtualFluidsCore/Connectors/D3Q27ETFullVectorConnector.cpp @@ -1,468 +1,458 @@ #include "D3Q27ETFullVectorConnector.h" #include "D3Q27EsoTwist3DSplittedVector.h" -#include "LBMKernel.h" #include "DataSet3D.h" +#include "LBMKernel.h" ////////////////////////////////////////////////////////////////////////// -D3Q27ETFullVectorConnector::D3Q27ETFullVectorConnector(SPtr<Block3D> block - , VectorTransmitterPtr sender - , VectorTransmitterPtr receiver - , int sendDir) - : RemoteBlock3DConnector(block, sender, receiver, sendDir) +D3Q27ETFullVectorConnector::D3Q27ETFullVectorConnector(SPtr<Block3D> block, VectorTransmitterPtr sender, + VectorTransmitterPtr receiver, int sendDir) + : RemoteBlock3DConnector(block, sender, receiver, sendDir) { - if (!block || !sender || !receiver) - UB_THROW(UbException(UB_EXARGS, "sender or receiver == NULL!!")); - + if (!block || !sender || !receiver) + UB_THROW(UbException(UB_EXARGS, "sender or receiver == NULL!!")); } ////////////////////////////////////////////////////////////////////////// void D3Q27ETFullVectorConnector::init() { - maxX1 = (int)block.lock()->getKernel()->getDataSet()->getFdistributions()->getNX1() - 1; - maxX2 = (int)block.lock()->getKernel()->getDataSet()->getFdistributions()->getNX2() - 1; - maxX3 = (int)block.lock()->getKernel()->getDataSet()->getFdistributions()->getNX3() - 1; + maxX1 = (int)block.lock()->getKernel()->getDataSet()->getFdistributions()->getNX1() - 1; + maxX2 = (int)block.lock()->getKernel()->getDataSet()->getFdistributions()->getNX2() - 1; + maxX3 = (int)block.lock()->getKernel()->getDataSet()->getFdistributions()->getNX3() - 1; - fDis = dynamicPointerCast<EsoTwist3D>(block.lock()->getKernel()->getDataSet()->getFdistributions()); + fDis = dynamicPointerCast<EsoTwist3D>(block.lock()->getKernel()->getDataSet()->getFdistributions()); - int anz = 27; - switch (sendDir) - { - case D3Q27System::ZERO: UB_THROW(UbException(UB_EXARGS, "ZERO not allowed")); break; - case D3Q27System::E: - case D3Q27System::W: sender->getData().resize(maxX2*maxX3*anz, 0.0); break; - case D3Q27System::N: - case D3Q27System::S: sender->getData().resize(maxX1*maxX3*anz, 0.0); break; - case D3Q27System::T: - case D3Q27System::B: sender->getData().resize(maxX1*maxX2*anz, 0.0); break; + int anz = 27; + switch (sendDir) { + case D3Q27System::ZERO: + UB_THROW(UbException(UB_EXARGS, "ZERO not allowed")); + break; + case D3Q27System::E: + case D3Q27System::W: + sender->getData().resize(maxX2 * maxX3 * anz, 0.0); + break; + case D3Q27System::N: + case D3Q27System::S: + sender->getData().resize(maxX1 * maxX3 * anz, 0.0); + break; + case D3Q27System::T: + case D3Q27System::B: + sender->getData().resize(maxX1 * maxX2 * anz, 0.0); + break; - case D3Q27System::NE: - case D3Q27System::SW: - case D3Q27System::SE: - case D3Q27System::NW: sender->getData().resize(maxX3*anz, 0.0); break; + case D3Q27System::NE: + case D3Q27System::SW: + case D3Q27System::SE: + case D3Q27System::NW: + sender->getData().resize(maxX3 * anz, 0.0); + break; - case D3Q27System::TE: - case D3Q27System::BW: - case D3Q27System::BE: - case D3Q27System::TW: sender->getData().resize(maxX2*anz, 0.0); break; + case D3Q27System::TE: + case D3Q27System::BW: + case D3Q27System::BE: + case D3Q27System::TW: + sender->getData().resize(maxX2 * anz, 0.0); + break; - case D3Q27System::TN: - case D3Q27System::BS: - case D3Q27System::BN: - case D3Q27System::TS: sender->getData().resize(maxX1*anz, 0.0); break; + case D3Q27System::TN: + case D3Q27System::BS: + case D3Q27System::BN: + case D3Q27System::TS: + sender->getData().resize(maxX1 * anz, 0.0); + break; - case D3Q27System::TNE: - case D3Q27System::BSW: - case D3Q27System::BNE: - case D3Q27System::TSW: - case D3Q27System::TSE: - case D3Q27System::BNW: - case D3Q27System::BSE: - case D3Q27System::TNW: sender->getData().resize(anz, 0.0); break; + case D3Q27System::TNE: + case D3Q27System::BSW: + case D3Q27System::BNE: + case D3Q27System::TSW: + case D3Q27System::TSE: + case D3Q27System::BNW: + case D3Q27System::BSE: + case D3Q27System::TNW: + sender->getData().resize(anz, 0.0); + break; - default: UB_THROW(UbException(UB_EXARGS, "unknown sendDir")); - } + default: + UB_THROW(UbException(UB_EXARGS, "unknown sendDir")); + } } ////////////////////////////////////////////////////////////////////////// void D3Q27ETFullVectorConnector::fillSendVectors() { - localDistributions = dynamicPointerCast<D3Q27EsoTwist3DSplittedVector>(this->fDis)->getLocalDistributions(); - nonLocalDistributions = dynamicPointerCast<D3Q27EsoTwist3DSplittedVector>(this->fDis)->getNonLocalDistributions(); - zeroDistributions = dynamicPointerCast<D3Q27EsoTwist3DSplittedVector>(this->fDis)->getZeroDistributions(); + localDistributions = dynamicPointerCast<D3Q27EsoTwist3DSplittedVector>(this->fDis)->getLocalDistributions(); + nonLocalDistributions = dynamicPointerCast<D3Q27EsoTwist3DSplittedVector>(this->fDis)->getNonLocalDistributions(); + zeroDistributions = dynamicPointerCast<D3Q27EsoTwist3DSplittedVector>(this->fDis)->getZeroDistributions(); - vector_type& sdata = sender->getData(); + vector_type &sdata = sender->getData(); - int index = 0; - //EAST - if (sendDir == D3Q27System::E) - { - for (int x3 = 1; x3 < maxX3; x3++) - { - for (int x2 = 1; x2 < maxX2; x2++) - { - fillData(sdata, index, maxX1 - 1, x2, x3); - } - } - } - //WEST - else if (sendDir == D3Q27System::W) - { - for (int x3 = 1; x3 < maxX3; x3++) - { - for (int x2 = 1; x2 < maxX2; x2++) - { - fillData(sdata, index, 1, x2, x3); - } - } - } - //NORTH - else if (sendDir == D3Q27System::N) - { - for (int x3 = 1; x3 < maxX3; x3++) - { - for (int x1 = 1; x1 < maxX1; x1++) - { - fillData(sdata, index, x1, maxX2 - 1, x3); - } - } - } - //SOUTH - else if (sendDir == D3Q27System::S) - { - for (int x3 = 1; x3 < maxX3; x3++) - { - for (int x1 = 1; x1 < maxX1; x1++) - { - fillData(sdata, index, x1, 1, x3); - } - } - } - //TOP - else if (sendDir == D3Q27System::T) - { - for (int x2 = 1; x2 < maxX2; x2++) - { - for (int x1 = 1; x1 < maxX1; x1++) - { - fillData(sdata, index, x1, x2, maxX3 - 1); - } - } - } - //BOTTOM - else if (sendDir == D3Q27System::B) - { - for (int x2 = 1; x2 < maxX2; x2++) - { - for (int x1 = 1; x1 < maxX1; x1++) - { - fillData(sdata, index, x1, x2, 1); - } - } - } - //NE NW SW SE - else if (sendDir == D3Q27System::NE || sendDir == D3Q27System::NW || sendDir == D3Q27System::SW || sendDir == D3Q27System::SE) - { - int x1 = 0; - int x2 = 0; - switch (sendDir) - { - case D3Q27System::NE: - x1 = maxX1 - 1; - x2 = maxX2 - 1; - break; - case D3Q27System::NW: - x1 = 1; - x2 = maxX2 - 1; - break; - case D3Q27System::SW: - x1 = 1; - x2 = 1; - break; - case D3Q27System::SE: - x1 = maxX1 - 1; - x2 = 1; - break; - } - for (int x3 = 1; x3 < maxX3; x3++) - { - fillData(sdata, index, x1, x2, x3); - } - } - //TE TW BW BE - else if (sendDir == D3Q27System::TE || sendDir == D3Q27System::TW || sendDir == D3Q27System::BW || sendDir == D3Q27System::BE) - { - int x1 = 0; - int x3 = 0; - switch (sendDir) - { - case D3Q27System::TE: - x1 = maxX1 - 1; - x3 = maxX3 - 1; - break; - case D3Q27System::TW: - x1 = 1; - x3 = maxX3 - 1; - break; - case D3Q27System::BW: - x1 = 1; - x3 = 1; - break; - case D3Q27System::BE: - x1 = maxX1 - 1; - x3 = 1; - break; - } - for (int x2 = 1; x2 < maxX2; x2++) - { - fillData(sdata, index, x1, x2, x3); - } - } - //TN BN BS TS - else if (sendDir == D3Q27System::TN || sendDir == D3Q27System::BN || sendDir == D3Q27System::BS || sendDir == D3Q27System::TS) - { - int x2 = 0; - int x3 = 0; - switch (sendDir) - { - case D3Q27System::TN: - x3 = maxX3 - 1; - x2 = maxX2 - 1; - break; - case D3Q27System::BN: - x3 = 1; - x2 = maxX2 - 1; - break; - case D3Q27System::BS: - x3 = 1; - x2 = 1; - break; - case D3Q27System::TS: - x3 = maxX3 - 1; - x2 = 1; - break; - } - for (int x1 = 1; x1 < maxX1; x1++) - { - fillData(sdata, index, x1, x2, x3); - } - } - //TNE TNW TSW TSE BNE BNW BSW BSE - else if (sendDir == D3Q27System::TNE || sendDir == D3Q27System::TNW || sendDir == D3Q27System::TSW || sendDir == D3Q27System::TSE - || sendDir == D3Q27System::BNE || sendDir == D3Q27System::BNW || sendDir == D3Q27System::BSW || sendDir == D3Q27System::BSE) - { - int x1 = 0; - int x2 = 0; - int x3 = 0; - switch (sendDir) - { - case D3Q27System::TNE: x1 = maxX1 - 1; x2 = maxX2 - 1; x3 = maxX3 - 1; break; - case D3Q27System::TNW: x1 = 1; x2 = maxX2 - 1; x3 = maxX3 - 1; break; - case D3Q27System::TSW: x1 = 1; x2 = 1; x3 = maxX3 - 1; break; - case D3Q27System::TSE: x1 = maxX1 - 1; x2 = 1; x3 = maxX3 - 1; break; - case D3Q27System::BNE: x1 = maxX1 - 1; x2 = maxX2 - 1; x3 = 1; break; - case D3Q27System::BNW: x1 = 1; x2 = maxX2 - 1; x3 = 1; break; - case D3Q27System::BSW: x1 = 1; x2 = 1; x3 = 1; break; - case D3Q27System::BSE: x1 = maxX1 - 1; x2 = 1; x3 = 1; break; - } - fillData(sdata, index, x1, x2, x3); - } - else UB_THROW(UbException(UB_EXARGS, "unknown dir")); + int index = 0; + // EAST + if (sendDir == D3Q27System::E) { + for (int x3 = 1; x3 < maxX3; x3++) { + for (int x2 = 1; x2 < maxX2; x2++) { + fillData(sdata, index, maxX1 - 1, x2, x3); + } + } + } + // WEST + else if (sendDir == D3Q27System::W) { + for (int x3 = 1; x3 < maxX3; x3++) { + for (int x2 = 1; x2 < maxX2; x2++) { + fillData(sdata, index, 1, x2, x3); + } + } + } + // NORTH + else if (sendDir == D3Q27System::N) { + for (int x3 = 1; x3 < maxX3; x3++) { + for (int x1 = 1; x1 < maxX1; x1++) { + fillData(sdata, index, x1, maxX2 - 1, x3); + } + } + } + // SOUTH + else if (sendDir == D3Q27System::S) { + for (int x3 = 1; x3 < maxX3; x3++) { + for (int x1 = 1; x1 < maxX1; x1++) { + fillData(sdata, index, x1, 1, x3); + } + } + } + // TOP + else if (sendDir == D3Q27System::T) { + for (int x2 = 1; x2 < maxX2; x2++) { + for (int x1 = 1; x1 < maxX1; x1++) { + fillData(sdata, index, x1, x2, maxX3 - 1); + } + } + } + // BOTTOM + else if (sendDir == D3Q27System::B) { + for (int x2 = 1; x2 < maxX2; x2++) { + for (int x1 = 1; x1 < maxX1; x1++) { + fillData(sdata, index, x1, x2, 1); + } + } + } + // NE NW SW SE + else if (sendDir == D3Q27System::NE || sendDir == D3Q27System::NW || sendDir == D3Q27System::SW || + sendDir == D3Q27System::SE) { + int x1 = 0; + int x2 = 0; + switch (sendDir) { + case D3Q27System::NE: + x1 = maxX1 - 1; + x2 = maxX2 - 1; + break; + case D3Q27System::NW: + x1 = 1; + x2 = maxX2 - 1; + break; + case D3Q27System::SW: + x1 = 1; + x2 = 1; + break; + case D3Q27System::SE: + x1 = maxX1 - 1; + x2 = 1; + break; + } + for (int x3 = 1; x3 < maxX3; x3++) { + fillData(sdata, index, x1, x2, x3); + } + } + // TE TW BW BE + else if (sendDir == D3Q27System::TE || sendDir == D3Q27System::TW || sendDir == D3Q27System::BW || + sendDir == D3Q27System::BE) { + int x1 = 0; + int x3 = 0; + switch (sendDir) { + case D3Q27System::TE: + x1 = maxX1 - 1; + x3 = maxX3 - 1; + break; + case D3Q27System::TW: + x1 = 1; + x3 = maxX3 - 1; + break; + case D3Q27System::BW: + x1 = 1; + x3 = 1; + break; + case D3Q27System::BE: + x1 = maxX1 - 1; + x3 = 1; + break; + } + for (int x2 = 1; x2 < maxX2; x2++) { + fillData(sdata, index, x1, x2, x3); + } + } + // TN BN BS TS + else if (sendDir == D3Q27System::TN || sendDir == D3Q27System::BN || sendDir == D3Q27System::BS || + sendDir == D3Q27System::TS) { + int x2 = 0; + int x3 = 0; + switch (sendDir) { + case D3Q27System::TN: + x3 = maxX3 - 1; + x2 = maxX2 - 1; + break; + case D3Q27System::BN: + x3 = 1; + x2 = maxX2 - 1; + break; + case D3Q27System::BS: + x3 = 1; + x2 = 1; + break; + case D3Q27System::TS: + x3 = maxX3 - 1; + x2 = 1; + break; + } + for (int x1 = 1; x1 < maxX1; x1++) { + fillData(sdata, index, x1, x2, x3); + } + } + // TNE TNW TSW TSE BNE BNW BSW BSE + else if (sendDir == D3Q27System::TNE || sendDir == D3Q27System::TNW || sendDir == D3Q27System::TSW || + sendDir == D3Q27System::TSE || sendDir == D3Q27System::BNE || sendDir == D3Q27System::BNW || + sendDir == D3Q27System::BSW || sendDir == D3Q27System::BSE) { + int x1 = 0; + int x2 = 0; + int x3 = 0; + switch (sendDir) { + case D3Q27System::TNE: + x1 = maxX1 - 1; + x2 = maxX2 - 1; + x3 = maxX3 - 1; + break; + case D3Q27System::TNW: + x1 = 1; + x2 = maxX2 - 1; + x3 = maxX3 - 1; + break; + case D3Q27System::TSW: + x1 = 1; + x2 = 1; + x3 = maxX3 - 1; + break; + case D3Q27System::TSE: + x1 = maxX1 - 1; + x2 = 1; + x3 = maxX3 - 1; + break; + case D3Q27System::BNE: + x1 = maxX1 - 1; + x2 = maxX2 - 1; + x3 = 1; + break; + case D3Q27System::BNW: + x1 = 1; + x2 = maxX2 - 1; + x3 = 1; + break; + case D3Q27System::BSW: + x1 = 1; + x2 = 1; + x3 = 1; + break; + case D3Q27System::BSE: + x1 = maxX1 - 1; + x2 = 1; + x3 = 1; + break; + } + fillData(sdata, index, x1, x2, x3); + } else + UB_THROW(UbException(UB_EXARGS, "unknown dir")); } //////////////////////////////////////////////////////////////////////// void D3Q27ETFullVectorConnector::distributeReceiveVectors() { - /*e.g. connector sendet nach EAST --> empfaengt daten aus WEST ;-)*/ + /*e.g. connector sendet nach EAST --> empfaengt daten aus WEST ;-)*/ - localDistributions = dynamicPointerCast<D3Q27EsoTwist3DSplittedVector>(this->fDis)->getLocalDistributions(); - nonLocalDistributions = dynamicPointerCast<D3Q27EsoTwist3DSplittedVector>(this->fDis)->getNonLocalDistributions(); - zeroDistributions = dynamicPointerCast<D3Q27EsoTwist3DSplittedVector>(this->fDis)->getZeroDistributions(); + localDistributions = dynamicPointerCast<D3Q27EsoTwist3DSplittedVector>(this->fDis)->getLocalDistributions(); + nonLocalDistributions = dynamicPointerCast<D3Q27EsoTwist3DSplittedVector>(this->fDis)->getNonLocalDistributions(); + zeroDistributions = dynamicPointerCast<D3Q27EsoTwist3DSplittedVector>(this->fDis)->getZeroDistributions(); - vector_type& rdata = receiver->getData(); + vector_type &rdata = receiver->getData(); - int index = 0; + int index = 0; - if (sendDir == D3Q27System::W) - { - for (int x3 = 1; x3 < maxX3; x3++) - { - for (int x2 = 1; x2 < maxX2; x2++) - { - distributeData(rdata, index, 0, x2, x3); - } - } - } - else if (sendDir == D3Q27System::E) - { - for (int x3 = 1; x3 < maxX3; x3++) - { - for (int x2 = 1; x2 < maxX2; x2++) - { - distributeData(rdata, index, maxX1, x2, x3); - } - } - } - else if (sendDir == D3Q27System::S) - { - for (int x3 = 1; x3 < maxX3; x3++) - { - for (int x1 = 1; x1 < maxX1; x1++) - { - distributeData(rdata, index, x1, 0, x3); - } - } - } - else if (sendDir == D3Q27System::N) - { - for (int x3 = 1; x3 < maxX3; x3++) - { - for (int x1 = 1; x1 < maxX1; x1++) - { - distributeData(rdata, index, x1, maxX2, x3); - } - } - } - else if (sendDir == D3Q27System::B) - { - for (int x2 = 1; x2 < maxX2; x2++) - { - for (int x1 = 1; x1 < maxX1; x1++) - { - distributeData(rdata, index, x1, x2, 0); - } - } - } - else if (sendDir == D3Q27System::T) - { - for (int x2 = 1; x2 < maxX2; x2++) - { - for (int x1 = 1; x1 < maxX1; x1++) - { - distributeData(rdata, index, x1, x2, maxX3); - } - } - } - //NE NW SW SE - else if (sendDir == D3Q27System::NE || sendDir == D3Q27System::NW || sendDir == D3Q27System::SW || sendDir == D3Q27System::SE) - { - int x1 = 0; - int x2 = 0; - switch (sendDir) //wenn sendir NE dann kommen werte von SW - { - case D3Q27System::NE: - x1 = maxX1; - x2 = maxX2; - break; - case D3Q27System::NW: - x1 = 0; - x2 = maxX2; - break; - case D3Q27System::SW: - x1 = 0; - x2 = 0; - break; - case D3Q27System::SE: - x1 = maxX1; - x2 = 0; - break; - } - for (int x3 = 1; x3 < maxX3; x3++) - { - distributeData(rdata, index, x1, x2, x3); - } + if (sendDir == D3Q27System::W) { + for (int x3 = 1; x3 < maxX3; x3++) { + for (int x2 = 1; x2 < maxX2; x2++) { + distributeData(rdata, index, 0, x2, x3); + } + } + } else if (sendDir == D3Q27System::E) { + for (int x3 = 1; x3 < maxX3; x3++) { + for (int x2 = 1; x2 < maxX2; x2++) { + distributeData(rdata, index, maxX1, x2, x3); + } + } + } else if (sendDir == D3Q27System::S) { + for (int x3 = 1; x3 < maxX3; x3++) { + for (int x1 = 1; x1 < maxX1; x1++) { + distributeData(rdata, index, x1, 0, x3); + } + } + } else if (sendDir == D3Q27System::N) { + for (int x3 = 1; x3 < maxX3; x3++) { + for (int x1 = 1; x1 < maxX1; x1++) { + distributeData(rdata, index, x1, maxX2, x3); + } + } + } else if (sendDir == D3Q27System::B) { + for (int x2 = 1; x2 < maxX2; x2++) { + for (int x1 = 1; x1 < maxX1; x1++) { + distributeData(rdata, index, x1, x2, 0); + } + } + } else if (sendDir == D3Q27System::T) { + for (int x2 = 1; x2 < maxX2; x2++) { + for (int x1 = 1; x1 < maxX1; x1++) { + distributeData(rdata, index, x1, x2, maxX3); + } + } + } + // NE NW SW SE + else if (sendDir == D3Q27System::NE || sendDir == D3Q27System::NW || sendDir == D3Q27System::SW || + sendDir == D3Q27System::SE) { + int x1 = 0; + int x2 = 0; + switch (sendDir) // wenn sendir NE dann kommen werte von SW + { + case D3Q27System::NE: + x1 = maxX1; + x2 = maxX2; + break; + case D3Q27System::NW: + x1 = 0; + x2 = maxX2; + break; + case D3Q27System::SW: + x1 = 0; + x2 = 0; + break; + case D3Q27System::SE: + x1 = maxX1; + x2 = 0; + break; + } + for (int x3 = 1; x3 < maxX3; x3++) { + distributeData(rdata, index, x1, x2, x3); + } - } - //TE TW BW BE - else if (sendDir == D3Q27System::TE || sendDir == D3Q27System::TW || sendDir == D3Q27System::BW || sendDir == D3Q27System::BE) + } + // TE TW BW BE + else if (sendDir == D3Q27System::TE || sendDir == D3Q27System::TW || sendDir == D3Q27System::BW || + sendDir == D3Q27System::BE) - { - int x1 = 0; - int x3 = 0; - switch (sendDir) //wenn sendir NE dann kommen werte von SW - { - case D3Q27System::TE: - x1 = maxX1; - x3 = maxX3; - break; - case D3Q27System::TW: - x1 = 0; - x3 = maxX3; - break; - case D3Q27System::BW: - x1 = 0; - x3 = 0; - break; - case D3Q27System::BE: - x1 = maxX1; - x3 = 0; - break; - } - for (int x2 = 1; x2 < maxX2; x2++) - { - distributeData(rdata, index, x1, x2, x3); - } - } - //TN BN BS TS - else if (sendDir == D3Q27System::TN || sendDir == D3Q27System::BN || sendDir == D3Q27System::BS || sendDir == D3Q27System::TS) - { - int x2 = 0; - int x3 = 0; - switch (sendDir) - { - case D3Q27System::TN: - x3 = maxX3; - x2 = maxX2; - break; - case D3Q27System::BN: - x3 = 0; - x2 = maxX2; - break; - case D3Q27System::BS: - x3 = 0; - x2 = 0; - break; - case D3Q27System::TS: - x3 = maxX3; - x2 = 0; - break; + { + int x1 = 0; + int x3 = 0; + switch (sendDir) // wenn sendir NE dann kommen werte von SW + { + case D3Q27System::TE: + x1 = maxX1; + x3 = maxX3; + break; + case D3Q27System::TW: + x1 = 0; + x3 = maxX3; + break; + case D3Q27System::BW: + x1 = 0; + x3 = 0; + break; + case D3Q27System::BE: + x1 = maxX1; + x3 = 0; + break; + } + for (int x2 = 1; x2 < maxX2; x2++) { + distributeData(rdata, index, x1, x2, x3); + } + } + // TN BN BS TS + else if (sendDir == D3Q27System::TN || sendDir == D3Q27System::BN || sendDir == D3Q27System::BS || + sendDir == D3Q27System::TS) { + int x2 = 0; + int x3 = 0; + switch (sendDir) { + case D3Q27System::TN: + x3 = maxX3; + x2 = maxX2; + break; + case D3Q27System::BN: + x3 = 0; + x2 = maxX2; + break; + case D3Q27System::BS: + x3 = 0; + x2 = 0; + break; + case D3Q27System::TS: + x3 = maxX3; + x2 = 0; + break; + } + for (int x1 = 1; x1 < maxX1; x1++) { + distributeData(rdata, index, x1, x2, x3); + } + } + // TNE TNW TSW TSE BNE BNW BSW BSE + else if (sendDir == D3Q27System::TNE || sendDir == D3Q27System::TNW || sendDir == D3Q27System::TSW || + sendDir == D3Q27System::TSE || sendDir == D3Q27System::BNE || sendDir == D3Q27System::BNW || + sendDir == D3Q27System::BSW || sendDir == D3Q27System::BSE) { + int x1 = 0; + int x2 = 0; + int x3 = 0; - } - for (int x1 = 1; x1 < maxX1; x1++) - { - distributeData(rdata, index, x1, x2, x3); - } - } - //TNE TNW TSW TSE BNE BNW BSW BSE - else if (sendDir == D3Q27System::TNE || sendDir == D3Q27System::TNW || sendDir == D3Q27System::TSW || sendDir == D3Q27System::TSE - || sendDir == D3Q27System::BNE || sendDir == D3Q27System::BNW || sendDir == D3Q27System::BSW || sendDir == D3Q27System::BSE) - { - int x1 = 0; - int x2 = 0; - int x3 = 0; - - switch (sendDir) - { - case D3Q27System::TNE: - x1 = maxX1; - x2 = maxX2; - x3 = maxX3; - break; - case D3Q27System::TNW: - x1 = 0; - x2 = maxX2; - x3 = maxX3; - break; - case D3Q27System::TSW: - x1 = 0; - x2 = 0; - x3 = maxX3; - break; - case D3Q27System::TSE: - x1 = maxX1; - x2 = 0; - x3 = maxX3; - break; - case D3Q27System::BNE: - x1 = maxX1; - x2 = maxX2; - x3 = 0; - break; - case D3Q27System::BNW: - x1 = 0; - x2 = maxX2; - x3 = 0; - break; - case D3Q27System::BSW: - x1 = 0; - x2 = 0; - x3 = 0; - break; - case D3Q27System::BSE: - x1 = maxX1; - x2 = 0; - x3 = 0; - break; - } - distributeData(rdata, index, x1, x2, x3); - } - else UB_THROW(UbException(UB_EXARGS, "unknown dir")); + switch (sendDir) { + case D3Q27System::TNE: + x1 = maxX1; + x2 = maxX2; + x3 = maxX3; + break; + case D3Q27System::TNW: + x1 = 0; + x2 = maxX2; + x3 = maxX3; + break; + case D3Q27System::TSW: + x1 = 0; + x2 = 0; + x3 = maxX3; + break; + case D3Q27System::TSE: + x1 = maxX1; + x2 = 0; + x3 = maxX3; + break; + case D3Q27System::BNE: + x1 = maxX1; + x2 = maxX2; + x3 = 0; + break; + case D3Q27System::BNW: + x1 = 0; + x2 = maxX2; + x3 = 0; + break; + case D3Q27System::BSW: + x1 = 0; + x2 = 0; + x3 = 0; + break; + case D3Q27System::BSE: + x1 = maxX1; + x2 = 0; + x3 = 0; + break; + } + distributeData(rdata, index, x1, x2, x3); + } else + UB_THROW(UbException(UB_EXARGS, "unknown dir")); } ////////////////////////////////////////////////////////////////////////// - - diff --git a/src/cpu/VirtualFluidsCore/Connectors/D3Q27ETFullVectorConnector.h b/src/cpu/VirtualFluidsCore/Connectors/D3Q27ETFullVectorConnector.h index b1c3a8e824385c21463a4e883f8355fbca28eef7..6842293af4f18f2badaa14068de2e0569c5b6a9f 100644 --- a/src/cpu/VirtualFluidsCore/Connectors/D3Q27ETFullVectorConnector.h +++ b/src/cpu/VirtualFluidsCore/Connectors/D3Q27ETFullVectorConnector.h @@ -3,116 +3,111 @@ #include <vector> -#include "RemoteBlock3DConnector.h" -#include "D3Q27System.h" #include "Block3D.h" -#include "LBMKernel.h" +#include "D3Q27System.h" +#include "EsoTwist3D.h" #include "EsoTwistD3Q27System.h" +#include "LBMKernel.h" +#include "RemoteBlock3DConnector.h" #include "basics/container/CbArray3D.h" #include "basics/container/CbArray4D.h" -#include "EsoTwist3D.h" - -//daten werden in einen vector (dieser befindet sich im transmitter) kopiert -//der vector wird via transmitter uebertragen -//transmitter kann ein lokal, MPI, RCG, CTL oder was auch immer fuer ein -//transmitter sein, der von Transmitter abgeleitet ist ;-) +// daten werden in einen vector (dieser befindet sich im transmitter) kopiert +// der vector wird via transmitter uebertragen +// transmitter kann ein lokal, MPI, RCG, CTL oder was auch immer fuer ein +// transmitter sein, der von Transmitter abgeleitet ist ;-) class D3Q27ETFullVectorConnector : public RemoteBlock3DConnector { public: - D3Q27ETFullVectorConnector(SPtr<Block3D> block - , VectorTransmitterPtr sender - , VectorTransmitterPtr receiver - , int sendDir); + D3Q27ETFullVectorConnector(SPtr<Block3D> block, VectorTransmitterPtr sender, VectorTransmitterPtr receiver, + int sendDir); - void init() override; + void init() override; - void fillSendVectors() override; - void distributeReceiveVectors() override; + void fillSendVectors() override; + void distributeReceiveVectors() override; protected: - inline void fillData(vector_type& sdata, int& index, int x1, int x2, int x3); - inline void distributeData(vector_type& rdata, int& index, int x1, int x2, int x3); -private: - int maxX1; - int maxX2; - int maxX3; + inline void fillData(vector_type &sdata, int &index, int x1, int x2, int x3); + inline void distributeData(vector_type &rdata, int &index, int x1, int x2, int x3); - CbArray4D <LBMReal, IndexerX4X3X2X1>::CbArray4DPtr localDistributions; - CbArray4D <LBMReal, IndexerX4X3X2X1>::CbArray4DPtr nonLocalDistributions; - CbArray3D <LBMReal, IndexerX3X2X1>::CbArray3DPtr zeroDistributions; +private: + int maxX1; + int maxX2; + int maxX3; - SPtr<EsoTwist3D> fDis; + CbArray4D<LBMReal, IndexerX4X3X2X1>::CbArray4DPtr localDistributions; + CbArray4D<LBMReal, IndexerX4X3X2X1>::CbArray4DPtr nonLocalDistributions; + CbArray3D<LBMReal, IndexerX3X2X1>::CbArray3DPtr zeroDistributions; + SPtr<EsoTwist3D> fDis; }; ////////////////////////////////////////////////////////////////////////// -inline void D3Q27ETFullVectorConnector::fillData(vector_type& sdata, int& index, int x1, int x2, int x3) +inline void D3Q27ETFullVectorConnector::fillData(vector_type &sdata, int &index, int x1, int x2, int x3) { - sdata[index++] = (*this->localDistributions)(D3Q27System::ET_E, x1, x2, x3); - sdata[index++] = (*this->localDistributions)(D3Q27System::ET_N, x1, x2, x3); - sdata[index++] = (*this->localDistributions)(D3Q27System::ET_T, x1, x2, x3); - sdata[index++] = (*this->localDistributions)(D3Q27System::ET_NE, x1, x2, x3); - sdata[index++] = (*this->localDistributions)(D3Q27System::ET_NW, x1 + 1, x2, x3); - sdata[index++] = (*this->localDistributions)(D3Q27System::ET_TE, x1, x2, x3); - sdata[index++] = (*this->localDistributions)(D3Q27System::ET_TW, x1 + 1, x2, x3); - sdata[index++] = (*this->localDistributions)(D3Q27System::ET_TN, x1, x2, x3); - sdata[index++] = (*this->localDistributions)(D3Q27System::ET_TS, x1, x2 + 1, x3); - sdata[index++] = (*this->localDistributions)(D3Q27System::ET_TNE, x1, x2, x3); - sdata[index++] = (*this->localDistributions)(D3Q27System::ET_TNW, x1 + 1, x2, x3); - sdata[index++] = (*this->localDistributions)(D3Q27System::ET_TSE, x1, x2 + 1, x3); - sdata[index++] = (*this->localDistributions)(D3Q27System::ET_TSW, x1 + 1, x2 + 1, x3); - - sdata[index++] = (*this->nonLocalDistributions)(D3Q27System::ET_W, x1 + 1, x2, x3); - sdata[index++] = (*this->nonLocalDistributions)(D3Q27System::ET_S, x1, x2 + 1, x3); - sdata[index++] = (*this->nonLocalDistributions)(D3Q27System::ET_B, x1, x2, x3 + 1); - sdata[index++] = (*this->nonLocalDistributions)(D3Q27System::ET_SW, x1 + 1, x2 + 1, x3); - sdata[index++] = (*this->nonLocalDistributions)(D3Q27System::ET_SE, x1, x2 + 1, x3); - sdata[index++] = (*this->nonLocalDistributions)(D3Q27System::ET_BW, x1 + 1, x2, x3 + 1); - sdata[index++] = (*this->nonLocalDistributions)(D3Q27System::ET_BE, x1, x2, x3 + 1); - sdata[index++] = (*this->nonLocalDistributions)(D3Q27System::ET_BS, x1, x2 + 1, x3 + 1); - sdata[index++] = (*this->nonLocalDistributions)(D3Q27System::ET_BN, x1, x2, x3 + 1); - sdata[index++] = (*this->nonLocalDistributions)(D3Q27System::ET_BSW, x1 + 1, x2 + 1, x3 + 1); - sdata[index++] = (*this->nonLocalDistributions)(D3Q27System::ET_BSE, x1, x2 + 1, x3 + 1); - sdata[index++] = (*this->nonLocalDistributions)(D3Q27System::ET_BNW, x1 + 1, x2, x3 + 1); - sdata[index++] = (*this->nonLocalDistributions)(D3Q27System::ET_BNE, x1, x2, x3 + 1); - - sdata[index++] = (*this->zeroDistributions)(x1, x2, x3); + sdata[index++] = (*this->localDistributions)(D3Q27System::ET_E, x1, x2, x3); + sdata[index++] = (*this->localDistributions)(D3Q27System::ET_N, x1, x2, x3); + sdata[index++] = (*this->localDistributions)(D3Q27System::ET_T, x1, x2, x3); + sdata[index++] = (*this->localDistributions)(D3Q27System::ET_NE, x1, x2, x3); + sdata[index++] = (*this->localDistributions)(D3Q27System::ET_NW, x1 + 1, x2, x3); + sdata[index++] = (*this->localDistributions)(D3Q27System::ET_TE, x1, x2, x3); + sdata[index++] = (*this->localDistributions)(D3Q27System::ET_TW, x1 + 1, x2, x3); + sdata[index++] = (*this->localDistributions)(D3Q27System::ET_TN, x1, x2, x3); + sdata[index++] = (*this->localDistributions)(D3Q27System::ET_TS, x1, x2 + 1, x3); + sdata[index++] = (*this->localDistributions)(D3Q27System::ET_TNE, x1, x2, x3); + sdata[index++] = (*this->localDistributions)(D3Q27System::ET_TNW, x1 + 1, x2, x3); + sdata[index++] = (*this->localDistributions)(D3Q27System::ET_TSE, x1, x2 + 1, x3); + sdata[index++] = (*this->localDistributions)(D3Q27System::ET_TSW, x1 + 1, x2 + 1, x3); + + sdata[index++] = (*this->nonLocalDistributions)(D3Q27System::ET_W, x1 + 1, x2, x3); + sdata[index++] = (*this->nonLocalDistributions)(D3Q27System::ET_S, x1, x2 + 1, x3); + sdata[index++] = (*this->nonLocalDistributions)(D3Q27System::ET_B, x1, x2, x3 + 1); + sdata[index++] = (*this->nonLocalDistributions)(D3Q27System::ET_SW, x1 + 1, x2 + 1, x3); + sdata[index++] = (*this->nonLocalDistributions)(D3Q27System::ET_SE, x1, x2 + 1, x3); + sdata[index++] = (*this->nonLocalDistributions)(D3Q27System::ET_BW, x1 + 1, x2, x3 + 1); + sdata[index++] = (*this->nonLocalDistributions)(D3Q27System::ET_BE, x1, x2, x3 + 1); + sdata[index++] = (*this->nonLocalDistributions)(D3Q27System::ET_BS, x1, x2 + 1, x3 + 1); + sdata[index++] = (*this->nonLocalDistributions)(D3Q27System::ET_BN, x1, x2, x3 + 1); + sdata[index++] = (*this->nonLocalDistributions)(D3Q27System::ET_BSW, x1 + 1, x2 + 1, x3 + 1); + sdata[index++] = (*this->nonLocalDistributions)(D3Q27System::ET_BSE, x1, x2 + 1, x3 + 1); + sdata[index++] = (*this->nonLocalDistributions)(D3Q27System::ET_BNW, x1 + 1, x2, x3 + 1); + sdata[index++] = (*this->nonLocalDistributions)(D3Q27System::ET_BNE, x1, x2, x3 + 1); + + sdata[index++] = (*this->zeroDistributions)(x1, x2, x3); } ////////////////////////////////////////////////////////////////////////// -inline void D3Q27ETFullVectorConnector::distributeData(vector_type& rdata, int& index, int x1, int x2, int x3) +inline void D3Q27ETFullVectorConnector::distributeData(vector_type &rdata, int &index, int x1, int x2, int x3) { - (*this->localDistributions)(D3Q27System::ET_E, x1, x2, x3) = rdata[index++]; - (*this->localDistributions)(D3Q27System::ET_N, x1, x2, x3) = rdata[index++]; - (*this->localDistributions)(D3Q27System::ET_T, x1, x2, x3) = rdata[index++]; - (*this->localDistributions)(D3Q27System::ET_NE, x1, x2, x3) = rdata[index++]; - (*this->localDistributions)(D3Q27System::ET_NW, x1 + 1, x2, x3) = rdata[index++]; - (*this->localDistributions)(D3Q27System::ET_TE, x1, x2, x3) = rdata[index++]; - (*this->localDistributions)(D3Q27System::ET_TW, x1 + 1, x2, x3) = rdata[index++]; - (*this->localDistributions)(D3Q27System::ET_TN, x1, x2, x3) = rdata[index++]; - (*this->localDistributions)(D3Q27System::ET_TS, x1, x2 + 1, x3) = rdata[index++]; - (*this->localDistributions)(D3Q27System::ET_TNE, x1, x2, x3) = rdata[index++]; - (*this->localDistributions)(D3Q27System::ET_TNW, x1 + 1, x2, x3) = rdata[index++]; - (*this->localDistributions)(D3Q27System::ET_TSE, x1, x2 + 1, x3) = rdata[index++]; - (*this->localDistributions)(D3Q27System::ET_TSW, x1 + 1, x2 + 1, x3) = rdata[index++]; - - (*this->nonLocalDistributions)(D3Q27System::ET_W, x1 + 1, x2, x3) = rdata[index++]; - (*this->nonLocalDistributions)(D3Q27System::ET_S, x1, x2 + 1, x3) = rdata[index++]; - (*this->nonLocalDistributions)(D3Q27System::ET_B, x1, x2, x3 + 1) = rdata[index++]; - (*this->nonLocalDistributions)(D3Q27System::ET_SW, x1 + 1, x2 + 1, x3) = rdata[index++]; - (*this->nonLocalDistributions)(D3Q27System::ET_SE, x1, x2 + 1, x3) = rdata[index++]; - (*this->nonLocalDistributions)(D3Q27System::ET_BW, x1 + 1, x2, x3 + 1) = rdata[index++]; - (*this->nonLocalDistributions)(D3Q27System::ET_BE, x1, x2, x3 + 1) = rdata[index++]; - (*this->nonLocalDistributions)(D3Q27System::ET_BS, x1, x2 + 1, x3 + 1) = rdata[index++]; - (*this->nonLocalDistributions)(D3Q27System::ET_BN, x1, x2, x3 + 1) = rdata[index++]; - (*this->nonLocalDistributions)(D3Q27System::ET_BSW, x1 + 1, x2 + 1, x3 + 1) = rdata[index++]; - (*this->nonLocalDistributions)(D3Q27System::ET_BSE, x1, x2 + 1, x3 + 1) = rdata[index++]; - (*this->nonLocalDistributions)(D3Q27System::ET_BNW, x1 + 1, x2, x3 + 1) = rdata[index++]; - (*this->nonLocalDistributions)(D3Q27System::ET_BNE, x1, x2, x3 + 1) = rdata[index++]; - - (*this->zeroDistributions)(x1, x2, x3) = rdata[index++]; + (*this->localDistributions)(D3Q27System::ET_E, x1, x2, x3) = rdata[index++]; + (*this->localDistributions)(D3Q27System::ET_N, x1, x2, x3) = rdata[index++]; + (*this->localDistributions)(D3Q27System::ET_T, x1, x2, x3) = rdata[index++]; + (*this->localDistributions)(D3Q27System::ET_NE, x1, x2, x3) = rdata[index++]; + (*this->localDistributions)(D3Q27System::ET_NW, x1 + 1, x2, x3) = rdata[index++]; + (*this->localDistributions)(D3Q27System::ET_TE, x1, x2, x3) = rdata[index++]; + (*this->localDistributions)(D3Q27System::ET_TW, x1 + 1, x2, x3) = rdata[index++]; + (*this->localDistributions)(D3Q27System::ET_TN, x1, x2, x3) = rdata[index++]; + (*this->localDistributions)(D3Q27System::ET_TS, x1, x2 + 1, x3) = rdata[index++]; + (*this->localDistributions)(D3Q27System::ET_TNE, x1, x2, x3) = rdata[index++]; + (*this->localDistributions)(D3Q27System::ET_TNW, x1 + 1, x2, x3) = rdata[index++]; + (*this->localDistributions)(D3Q27System::ET_TSE, x1, x2 + 1, x3) = rdata[index++]; + (*this->localDistributions)(D3Q27System::ET_TSW, x1 + 1, x2 + 1, x3) = rdata[index++]; + + (*this->nonLocalDistributions)(D3Q27System::ET_W, x1 + 1, x2, x3) = rdata[index++]; + (*this->nonLocalDistributions)(D3Q27System::ET_S, x1, x2 + 1, x3) = rdata[index++]; + (*this->nonLocalDistributions)(D3Q27System::ET_B, x1, x2, x3 + 1) = rdata[index++]; + (*this->nonLocalDistributions)(D3Q27System::ET_SW, x1 + 1, x2 + 1, x3) = rdata[index++]; + (*this->nonLocalDistributions)(D3Q27System::ET_SE, x1, x2 + 1, x3) = rdata[index++]; + (*this->nonLocalDistributions)(D3Q27System::ET_BW, x1 + 1, x2, x3 + 1) = rdata[index++]; + (*this->nonLocalDistributions)(D3Q27System::ET_BE, x1, x2, x3 + 1) = rdata[index++]; + (*this->nonLocalDistributions)(D3Q27System::ET_BS, x1, x2 + 1, x3 + 1) = rdata[index++]; + (*this->nonLocalDistributions)(D3Q27System::ET_BN, x1, x2, x3 + 1) = rdata[index++]; + (*this->nonLocalDistributions)(D3Q27System::ET_BSW, x1 + 1, x2 + 1, x3 + 1) = rdata[index++]; + (*this->nonLocalDistributions)(D3Q27System::ET_BSE, x1, x2 + 1, x3 + 1) = rdata[index++]; + (*this->nonLocalDistributions)(D3Q27System::ET_BNW, x1 + 1, x2, x3 + 1) = rdata[index++]; + (*this->nonLocalDistributions)(D3Q27System::ET_BNE, x1, x2, x3 + 1) = rdata[index++]; + + (*this->zeroDistributions)(x1, x2, x3) = rdata[index++]; } - -#endif //D3Q27VECTORCONNECTOR_H - +#endif // D3Q27VECTORCONNECTOR_H diff --git a/src/cpu/VirtualFluidsCore/Connectors/D3Q27ETOffConnectorFactory.cpp b/src/cpu/VirtualFluidsCore/Connectors/D3Q27ETOffConnectorFactory.cpp index 4d01e21e5c6c88cd43b3fd7d6a3a66cc1dbb08c7..fdeb0e5569c49e82b4f7c7bbafb07a41ab07aecd 100644 --- a/src/cpu/VirtualFluidsCore/Connectors/D3Q27ETOffConnectorFactory.cpp +++ b/src/cpu/VirtualFluidsCore/Connectors/D3Q27ETOffConnectorFactory.cpp @@ -5,15 +5,15 @@ //#include "D3Q27ETFCVectorConnector.h" //#include "FineToCoarseBlock3DConnector.h" // -//D3Q27ETOffConnectorFactory::D3Q27ETOffConnectorFactory() +// D3Q27ETOffConnectorFactory::D3Q27ETOffConnectorFactory() //{ //} //////////////////////////////////////////////////////////////////////////// -//D3Q27ETOffConnectorFactory::~D3Q27ETOffConnectorFactory() +// D3Q27ETOffConnectorFactory::~D3Q27ETOffConnectorFactory() //{ //} //////////////////////////////////////////////////////////////////////////// -//SPtr<Block3DConnector> D3Q27ETOffConnectorFactory::createCoarseToFineConnector(SPtr<Block3D> block, +// SPtr<Block3DConnector> D3Q27ETOffConnectorFactory::createCoarseToFineConnector(SPtr<Block3D> block, // VectorTransmitterPtr sender00, VectorTransmitterPtr receiver00, // VectorTransmitterPtr sender01, VectorTransmitterPtr receiver01, // VectorTransmitterPtr sender10, VectorTransmitterPtr receiver10, @@ -26,7 +26,7 @@ // sendDir, iprocessor)); //} //////////////////////////////////////////////////////////////////////////// -//SPtr<Block3DConnector> D3Q27ETOffConnectorFactory::createFineToCoarseConnector(SPtr<Block3D> block, +// SPtr<Block3DConnector> D3Q27ETOffConnectorFactory::createFineToCoarseConnector(SPtr<Block3D> block, // VectorTransmitterPtr sender, // VectorTransmitterPtr receiver, // int sendDir, diff --git a/src/cpu/VirtualFluidsCore/Connectors/D3Q27ETOffConnectorFactory.h b/src/cpu/VirtualFluidsCore/Connectors/D3Q27ETOffConnectorFactory.h index 4879a1930c1e4e66be9668eb2ccd938493beb05e..8ed08c80aa56ff71db5c6fff2b9bfeaeca962646 100644 --- a/src/cpu/VirtualFluidsCore/Connectors/D3Q27ETOffConnectorFactory.h +++ b/src/cpu/VirtualFluidsCore/Connectors/D3Q27ETOffConnectorFactory.h @@ -4,12 +4,12 @@ //#include "Block3DConnectorFactory.h" // //#include <PointerDefinitions.h> -//class D3Q27ETOffConnectorFactory; -//typedef SPtr<D3Q27ETOffConnectorFactory> D3Q27ETOffSPtr<ConnectorFactory>; +// class D3Q27ETOffConnectorFactory; +// typedef SPtr<D3Q27ETOffConnectorFactory> D3Q27ETOffSPtr<ConnectorFactory>; // -//class D3Q27ETOffConnectorFactory : public Block3DConnectorFactory +// class D3Q27ETOffConnectorFactory : public Block3DConnectorFactory //{ -//public: +// public: // D3Q27ETOffConnectorFactory(); // virtual ~D3Q27ETOffConnectorFactory(); // @@ -27,8 +27,7 @@ // D3Q27InterpolationProcessorPtr iprocessor, // FineToCoarseBlock3DConnector::CFconnectorType connType); // -//private: +// private: // //}; //#endif // D3Q27ETOffConnectorFactory_h__ - diff --git a/src/cpu/VirtualFluidsCore/Connectors/FineToCoarseBlock3DConnector.cpp b/src/cpu/VirtualFluidsCore/Connectors/FineToCoarseBlock3DConnector.cpp index faaaca492e20f97f75b9faa560753d59ad7a5ae9..ca6d017a59e4c322ab70f42deaa4575cba97a2db 100644 --- a/src/cpu/VirtualFluidsCore/Connectors/FineToCoarseBlock3DConnector.cpp +++ b/src/cpu/VirtualFluidsCore/Connectors/FineToCoarseBlock3DConnector.cpp @@ -2,76 +2,73 @@ //////////////////////////////////////////////////////////////////////////// FineToCoarseBlock3DConnector::FineToCoarseBlock3DConnector(SPtr<Block3D> block, VectorTransmitterPtr sender, - VectorTransmitterPtr receiver, int sendDir, - InterpolationProcessorPtr iprocessor, - CFconnectorType connType) - : Block3DConnector(sendDir) - , block(block) - , sender(sender) - , receiver(receiver) - , iprocessor(iprocessor) - , connType(connType) + VectorTransmitterPtr receiver, int sendDir, + InterpolationProcessorPtr iprocessor, + CFconnectorType connType) + : Block3DConnector(sendDir), block(block), sender(sender), receiver(receiver), iprocessor(iprocessor), + connType(connType) { - if (!(sendDir==D3Q27System::E || sendDir==D3Q27System::W || sendDir==D3Q27System::N || sendDir==D3Q27System::S || sendDir==D3Q27System::T || sendDir==D3Q27System::B - || sendDir==D3Q27System::NE || sendDir==D3Q27System::SW || sendDir==D3Q27System::SE || sendDir==D3Q27System::NW - || sendDir==D3Q27System::TE || sendDir==D3Q27System::BW || sendDir==D3Q27System::BE || sendDir==D3Q27System::TW - || sendDir==D3Q27System::TN || sendDir==D3Q27System::BS || sendDir==D3Q27System::BN || sendDir==D3Q27System::TS + if (!(sendDir == D3Q27System::E || sendDir == D3Q27System::W || sendDir == D3Q27System::N || + sendDir == D3Q27System::S || sendDir == D3Q27System::T || sendDir == D3Q27System::B || + sendDir == D3Q27System::NE || sendDir == D3Q27System::SW || sendDir == D3Q27System::SE || + sendDir == D3Q27System::NW || sendDir == D3Q27System::TE || sendDir == D3Q27System::BW || + sendDir == D3Q27System::BE || sendDir == D3Q27System::TW || sendDir == D3Q27System::TN || + sendDir == D3Q27System::BS || sendDir == D3Q27System::BN || sendDir == D3Q27System::TS - || sendDir==D3Q27System::TNE || sendDir==D3Q27System::TNW || sendDir==D3Q27System::TSE || sendDir==D3Q27System::TSW - || sendDir==D3Q27System::BNE || sendDir==D3Q27System::BNW || sendDir==D3Q27System::BSE || sendDir==D3Q27System::BSW + || sendDir == D3Q27System::TNE || sendDir == D3Q27System::TNW || sendDir == D3Q27System::TSE || + sendDir == D3Q27System::TSW || sendDir == D3Q27System::BNE || sendDir == D3Q27System::BNW || + sendDir == D3Q27System::BSE || sendDir == D3Q27System::BSW - )) - { - throw UbException(UB_EXARGS, "invalid constructor for this direction"); - } + )) { + throw UbException(UB_EXARGS, "invalid constructor for this direction"); + } } ////////////////////////////////////////////////////////////////////////// -bool FineToCoarseBlock3DConnector::isLocalConnector() -{ - return !this->isRemoteConnector(); -} +bool FineToCoarseBlock3DConnector::isLocalConnector() { return !this->isRemoteConnector(); } ////////////////////////////////////////////////////////////////////////// bool FineToCoarseBlock3DConnector::isRemoteConnector() { - return sender->isRemoteTransmitter() || receiver->isRemoteTransmitter(); + return sender->isRemoteTransmitter() || receiver->isRemoteTransmitter(); } ////////////////////////////////////////////////////////////////////////// void FineToCoarseBlock3DConnector::sendTransmitterDataSize() { - if (sender) - { - UBLOG(logDEBUG5, "FineToCoarseBlock3DConnector<VectorTransmitter>::sendTransmitterDataSize()"<<block.lock()->toString()+"sendDir="<<sendDir); - sender->sendDataSize(); - } + if (sender) { + UBLOG(logDEBUG5, "FineToCoarseBlock3DConnector<VectorTransmitter>::sendTransmitterDataSize()" + << block.lock()->toString() + "sendDir=" << sendDir); + sender->sendDataSize(); + } } ////////////////////////////////////////////////////////////////////////// void FineToCoarseBlock3DConnector::receiveTransmitterDataSize() { - if (receiver) - { - UBLOG(logDEBUG5, "FineToCoarseBlock3DConnector<VectorTransmitter>::receiveTransmitterDataSize()"<<block.lock()->toString()<<"sendDir="<<sendDir); - receiver->receiveDataSize(); - } + if (receiver) { + UBLOG(logDEBUG5, "FineToCoarseBlock3DConnector<VectorTransmitter>::receiveTransmitterDataSize()" + << block.lock()->toString() << "sendDir=" << sendDir); + receiver->receiveDataSize(); + } } ////////////////////////////////////////////////////////////////////////// void FineToCoarseBlock3DConnector::prepareForSend() { - if (sender) sender->prepareForSend(); + if (sender) + sender->prepareForSend(); } ////////////////////////////////////////////////////////////////////////// void FineToCoarseBlock3DConnector::sendVectors() { - if (sender) sender->sendData(); + if (sender) + sender->sendData(); } ////////////////////////////////////////////////////////////////////////// void FineToCoarseBlock3DConnector::prepareForReceive() { - if (receiver) receiver->prepareForReceive(); + if (receiver) + receiver->prepareForReceive(); } ////////////////////////////////////////////////////////////////////////// void FineToCoarseBlock3DConnector::receiveVectors() { - if (receiver) receiver->receiveData(); + if (receiver) + receiver->receiveData(); } - - diff --git a/src/cpu/VirtualFluidsCore/Connectors/FineToCoarseBlock3DConnector.h b/src/cpu/VirtualFluidsCore/Connectors/FineToCoarseBlock3DConnector.h index c4bbc182f3c38f27bc1332dc825484da5f6af048..5e988887c427f34ddbae70f1c8fd16b1de75367c 100644 --- a/src/cpu/VirtualFluidsCore/Connectors/FineToCoarseBlock3DConnector.h +++ b/src/cpu/VirtualFluidsCore/Connectors/FineToCoarseBlock3DConnector.h @@ -1,38 +1,37 @@ //! \file FineToCoarseBlock3DConnector.h -//! \brief Base class for connectors that interpolates and sends data from fine level to coarse. +//! \brief Base class for connectors that interpolates and sends data from fine level to coarse. //! \author Konstantin Kutscher //! \date 21.05.2015 #ifndef FineToCoarseBlock3DConnector_H #define FineToCoarseBlock3DConnector_H -#include "TransmitterType.h" +#include "Block3D.h" #include "Block3DConnector.h" #include "D3Q27System.h" -#include "Block3D.h" -#include "LBMKernel.h" #include "InterpolationProcessor.h" +#include "LBMKernel.h" +#include "TransmitterType.h" #include <PointerDefinitions.h> - class Block3D; //! \class FineToCoarseBlock3DConnector -//! \brief Base class for connectors that interpolates and sends data from fine level to coarse. -//! \details The data is copied in a vector (this is located in the transmitter). -//! The vector is transmitted via transmitter. -//! The transmitter can be a local, MPI, RCG, CTL or whatever +//! \brief Base class for connectors that interpolates and sends data from fine level to coarse. +//! \details The data is copied in a vector (this is located in the transmitter). +//! The vector is transmitted via transmitter. +//! The transmitter can be a local, MPI, RCG, CTL or whatever //! which a transmitter that is derived from transmitter base class. //! //! four fine blocks inside a coarse block: //! //! | | | -//! |:--:|:---| -//! | 01 | 11 | -//! | 00 | 10 | +//! |:--:|:---| +//! | 01 | 11 | +//! | 00 | 10 | //! -//! send direction: +//! send direction: //! //! |E<->W | N<->S | T<->B | //! |--------|---------|--------| @@ -43,53 +42,52 @@ class Block3D; class FineToCoarseBlock3DConnector : public Block3DConnector { public: - enum CFconnectorType { Type00, Type10, Type01, Type11 }; + enum CFconnectorType { Type00, Type10, Type01, Type11 }; + public: - FineToCoarseBlock3DConnector(SPtr<Block3D> block, VectorTransmitterPtr sender, VectorTransmitterPtr receiver, int sendDir, InterpolationProcessorPtr iprocessor, CFconnectorType connType); + FineToCoarseBlock3DConnector(SPtr<Block3D> block, VectorTransmitterPtr sender, VectorTransmitterPtr receiver, + int sendDir, InterpolationProcessorPtr iprocessor, CFconnectorType connType); + + bool isLocalConnector() override; + bool isRemoteConnector() override; - bool isLocalConnector() override; - bool isRemoteConnector() override; - - void sendTransmitterDataSize() override; - void receiveTransmitterDataSize() override; + void sendTransmitterDataSize() override; + void receiveTransmitterDataSize() override; - void prepareForSend() override; - void sendVectors() override; + void prepareForSend() override; + void sendVectors() override; - void prepareForReceive() override; - void receiveVectors() override; + void prepareForReceive() override; + void receiveVectors() override; - void init() override =0; - void fillSendVectors() override =0; - void distributeReceiveVectors() override =0; + void init() override = 0; + void fillSendVectors() override = 0; + void distributeReceiveVectors() override = 0; - bool isInterpolationConnectorCF() override { return false; } - bool isInterpolationConnectorFC() override { return true; } + bool isInterpolationConnectorCF() override { return false; } + bool isInterpolationConnectorFC() override { return true; } - void prepareForSendX1() override {} - void prepareForSendX2() override {} - void prepareForSendX3() override {} + void prepareForSendX1() override {} + void prepareForSendX2() override {} + void prepareForSendX3() override {} - void sendVectorsX1() override {} - void sendVectorsX2() override {} - void sendVectorsX3() override {} + void sendVectorsX1() override {} + void sendVectorsX2() override {} + void sendVectorsX3() override {} - void prepareForReceiveX1() override {} - void prepareForReceiveX2() override {} - void prepareForReceiveX3() override {} + void prepareForReceiveX1() override {} + void prepareForReceiveX2() override {} + void prepareForReceiveX3() override {} - void receiveVectorsX1() override {} - void receiveVectorsX2() override {} - void receiveVectorsX3() override {} + void receiveVectorsX1() override {} + void receiveVectorsX2() override {} + void receiveVectorsX3() override {} protected: - WPtr<Block3D> block; - VectorTransmitterPtr sender, receiver; - InterpolationProcessorPtr iprocessor; - CFconnectorType connType; + WPtr<Block3D> block; + VectorTransmitterPtr sender, receiver; + InterpolationProcessorPtr iprocessor; + CFconnectorType connType; }; - - -#endif - +#endif diff --git a/src/cpu/VirtualFluidsCore/Connectors/FineToCoarseNodeSetBlock3DConnector.cpp b/src/cpu/VirtualFluidsCore/Connectors/FineToCoarseNodeSetBlock3DConnector.cpp index 591fc727c07e2072aebda342b6e3b62cba4c1d4c..06bb953285bb191e4f33a383dab54e7347828884 100644 --- a/src/cpu/VirtualFluidsCore/Connectors/FineToCoarseNodeSetBlock3DConnector.cpp +++ b/src/cpu/VirtualFluidsCore/Connectors/FineToCoarseNodeSetBlock3DConnector.cpp @@ -2,1141 +2,1016 @@ #include "BCProcessor.h" #include "DataSet3D.h" - ////////////////////////////////////////////////////////////////////////// -FineToCoarseNodeSetBlock3DConnector::FineToCoarseNodeSetBlock3DConnector(SPtr<Block3D> block, VectorTransmitterPtr sender, VectorTransmitterPtr receiver, - int sendDir, InterpolationProcessorPtr iprocessor, CFconnectorType connType) : FineToCoarseBlock3DConnector(block, sender, receiver, sendDir, iprocessor, connType) +FineToCoarseNodeSetBlock3DConnector::FineToCoarseNodeSetBlock3DConnector(SPtr<Block3D> block, + VectorTransmitterPtr sender, + VectorTransmitterPtr receiver, int sendDir, + InterpolationProcessorPtr iprocessor, + CFconnectorType connType) + : FineToCoarseBlock3DConnector(block, sender, receiver, sendDir, iprocessor, connType) { - } ////////////////////////////////////////////////////////////////////////// void FineToCoarseNodeSetBlock3DConnector::init() { - bMaxX1 = (int)FineToCoarseBlock3DConnector::block.lock()->getKernel()->getDataSet()->getFdistributions()->getNX1(); - bMaxX2 = (int)FineToCoarseBlock3DConnector::block.lock()->getKernel()->getDataSet()->getFdistributions()->getNX2(); - bMaxX3 = (int)FineToCoarseBlock3DConnector::block.lock()->getKernel()->getDataSet()->getFdistributions()->getNX3(); - - minX1 = 0; - minX2 = 0; - minX3 = 0; - maxX1 = bMaxX1 - 1; - maxX2 = bMaxX2 - 1; - maxX3 = bMaxX3 - 1; - - minOffX1 = 0; - minOffX2 = 0; - minOffX3 = 0; - - maxOffX1 = 0; - maxOffX2 = 0; - maxOffX3 = 0; - - if (Utilities::isEven(bMaxX1)) - { - minOffX1 = 0; - maxOffX1 = 0; - } - else if (Utilities::isOdd(bMaxX1)) - { - minOffX1 = 1; - maxOffX1 = -1; - } - - if (Utilities::isEven(bMaxX2)) - { - minOffX2 = 0; - maxOffX2 = 0; - } - else if (Utilities::isOdd(bMaxX2)) - { - minOffX2 = 1; - maxOffX2 = -1; - } - - if (Utilities::isEven(bMaxX3)) - { - minOffX3 = 0; - maxOffX3 = 0; - } - else if (Utilities::isOdd(bMaxX3)) - { - minOffX3 = 1; - maxOffX3 = -1; - } - - //int sendSize = 0; - LBMReal initValue = -999.0; - - int sendDataPerNode = 27/*f*/; - int iCellSize = 1; //size of interpolation cell - - findFCCells(); - findCFCells(); - - ////////////////////////////////////////////////////// - //Debug - ////////////////////////////////////////////////////// -// if (FineToCoarseBlock3DConnector::block.lock()->getGlobalID() == 2183) -// { -// int test = 0; -// } - - - if (FineToCoarseBlock3DConnector::sender) FineToCoarseBlock3DConnector::sender->getData().resize(iNodeSetSender.size()*iCellSize*sendDataPerNode, initValue); - else FineToCoarseBlock3DConnector::sender = VectorTransmitterPtr(new TbLocalTransmitter< CbVector< LBMReal > >()); - - if (!FineToCoarseBlock3DConnector::receiver) FineToCoarseBlock3DConnector::receiver = VectorTransmitterPtr(new TbLocalTransmitter< CbVector< LBMReal > >()); + bMaxX1 = (int)FineToCoarseBlock3DConnector::block.lock()->getKernel()->getDataSet()->getFdistributions()->getNX1(); + bMaxX2 = (int)FineToCoarseBlock3DConnector::block.lock()->getKernel()->getDataSet()->getFdistributions()->getNX2(); + bMaxX3 = (int)FineToCoarseBlock3DConnector::block.lock()->getKernel()->getDataSet()->getFdistributions()->getNX3(); + + minX1 = 0; + minX2 = 0; + minX3 = 0; + maxX1 = bMaxX1 - 1; + maxX2 = bMaxX2 - 1; + maxX3 = bMaxX3 - 1; + + minOffX1 = 0; + minOffX2 = 0; + minOffX3 = 0; + + maxOffX1 = 0; + maxOffX2 = 0; + maxOffX3 = 0; + + if (Utilities::isEven(bMaxX1)) { + minOffX1 = 0; + maxOffX1 = 0; + } else if (Utilities::isOdd(bMaxX1)) { + minOffX1 = 1; + maxOffX1 = -1; + } + + if (Utilities::isEven(bMaxX2)) { + minOffX2 = 0; + maxOffX2 = 0; + } else if (Utilities::isOdd(bMaxX2)) { + minOffX2 = 1; + maxOffX2 = -1; + } + + if (Utilities::isEven(bMaxX3)) { + minOffX3 = 0; + maxOffX3 = 0; + } else if (Utilities::isOdd(bMaxX3)) { + minOffX3 = 1; + maxOffX3 = -1; + } + + // int sendSize = 0; + LBMReal initValue = -999.0; + + int sendDataPerNode = 27 /*f*/; + int iCellSize = 1; // size of interpolation cell + + findFCCells(); + findCFCells(); + + ////////////////////////////////////////////////////// + // Debug + ////////////////////////////////////////////////////// + // if (FineToCoarseBlock3DConnector::block.lock()->getGlobalID() == 2183) + // { + // int test = 0; + // } + + if (FineToCoarseBlock3DConnector::sender) + FineToCoarseBlock3DConnector::sender->getData().resize(iNodeSetSender.size() * iCellSize * sendDataPerNode, + initValue); + else + FineToCoarseBlock3DConnector::sender = VectorTransmitterPtr(new TbLocalTransmitter<CbVector<LBMReal>>()); + + if (!FineToCoarseBlock3DConnector::receiver) + FineToCoarseBlock3DConnector::receiver = VectorTransmitterPtr(new TbLocalTransmitter<CbVector<LBMReal>>()); } ////////////////////////////////////////////////////////////////////////// -void FineToCoarseNodeSetBlock3DConnector::findFCCells(int lMinX1, int lMinX2, int lMinX3, int lMaxX1, int lMaxX2, int lMaxX3, INodeSet &inodes) +void FineToCoarseNodeSetBlock3DConnector::findFCCells(int lMinX1, int lMinX2, int lMinX3, int lMaxX1, int lMaxX2, + int lMaxX3, INodeSet &inodes) { - ////////////////////////////////////////////////////// - //Debug - ////////////////////////////////////////////////////// -// if (FineToCoarseBlock3DConnector::block.lock()->getGlobalID() == 2183) -// { -// int test = 0; -// } + ////////////////////////////////////////////////////// + // Debug + ////////////////////////////////////////////////////// + // if (FineToCoarseBlock3DConnector::block.lock()->getGlobalID() == 2183) + // { + // int test = 0; + // } + + int ix1, ix2, ix3; + LBMReal x1off, x2off, x3off; + + SPtr<DistributionArray3D> fFrom = + FineToCoarseBlock3DConnector::block.lock()->getKernel()->getDataSet()->getFdistributions(); + SPtr<BCArray3D> bcArray = FineToCoarseBlock3DConnector::block.lock()->getKernel()->getBCProcessor()->getBCArray(); + + for (ix3 = lMinX3; ix3 <= lMaxX3; ix3 += 2) { + for (ix2 = lMinX2; ix2 <= lMaxX2; ix2 += 2) { + for (ix1 = lMinX1; ix1 <= lMaxX1; ix1 += 2) { + D3Q27ICell icellC; + + int howManySolids = + FineToCoarseBlock3DConnector::iprocessor->iCellHowManySolids(bcArray, ix1, ix2, ix3); + + if (howManySolids == 0 || howManySolids == 8) { + x1off = 0.0; + x2off = 0.0; + x3off = 0.0; + } else { + if (!iprocessor->findNeighborICell(bcArray, fFrom, icellC, bMaxX1, bMaxX2, bMaxX3, ix1, ix2, ix3, + x1off, x2off, x3off)) { + std::string err = "For " + FineToCoarseBlock3DConnector::block.lock()->toString() + + " x1=" + UbSystem::toString(ix1) + ", x2=" + UbSystem::toString(ix2) + + ", x3=" + UbSystem::toString(ix3) + + " interpolation is not implemented for other direction" + + " by using in: " + (std::string) typeid(*this).name() + + " or maybe you have a solid on the block boundary"; + UB_THROW(UbException(UB_EXARGS, err)); + } + } + + INodeVector inv; + inv.push_back(ix1 + (int)x1off); + inv.push_back(ix2 + (int)x2off); + inv.push_back(ix3 + (int)x3off); + inv.push_back((int)x1off); + inv.push_back((int)x2off); + inv.push_back((int)x3off); + // inodes.insert(inv); + inodes.push_back(inv); + } + } + } +} +////////////////////////////////////////////////////////////////////////// +void FineToCoarseNodeSetBlock3DConnector::findFCCells() +{ + using namespace D3Q27System; + + int lMin1X1, lMin1X2, lMin1X3, lMax1X1, lMax1X2, lMax1X3; + int lMin2X1, lMin2X2, lMin2X3, lMax2X1, lMax2X2, lMax2X3; + int lMin3X1, lMin3X2, lMin3X3, lMax3X1, lMax3X2, lMax3X3; + + // lMin1X1 = minX1+1; lMin1X2 = minX2+1; lMin1X3 = minX3+1; + // lMax1X1 = maxX1-1; lMax1X2 = maxX2-1; lMax1X3 = maxX3-1; + // getLocalMinMax(lMin1X1, lMin1X2, lMin1X3, lMax1X1, lMax1X2, lMax1X3); + + // lMin2X1 = minX1+1; lMin2X2 = minX2+1; lMin2X3 = minX3+1; + // lMax2X1 = maxX1-1; lMax2X2 = maxX2-1; lMax2X3 = maxX3-1; + // getLocalMinMax(lMin2X1, lMin2X2, lMin2X3, lMax2X1, lMax2X2, lMax2X3); + + // lMin3X1 = minX1+1; lMin3X2 = minX2+1; lMin3X3 = minX3+1; + // lMax3X1 = maxX1-1; lMax3X2 = maxX2-1; lMax3X3 = maxX3-1; + // getLocalMinMax(lMin3X1, lMin3X2, lMin3X3, lMax3X1, lMax3X2, lMax3X3); + + switch (sendDir) { + // faces + case E: + case W: + if (sendDir == E) { + lMin1X1 = maxX1 - 6; + lMax1X1 = lMin1X1; + } else if (sendDir == W) { + lMin1X1 = 5; + lMax1X1 = lMin1X1; + } - int ix1, ix2, ix3; - LBMReal x1off, x2off, x3off; + if (FineToCoarseBlock3DConnector::connType == FineToCoarseBlock3DConnector::Type00) { + lMin1X2 = minX2; + lMax1X2 = maxX2 + maxOffX2 - 1; + lMin1X3 = minX3; + lMax1X3 = maxX3 + maxOffX3 - 1; + } else if (FineToCoarseBlock3DConnector::connType == FineToCoarseBlock3DConnector::Type10) { + lMin1X2 = minX2 + minOffX2; + lMax1X2 = maxX2 - 1; + lMin1X3 = minX3; + lMax1X3 = maxX3 + maxOffX3 - 1; + } else if (FineToCoarseBlock3DConnector::connType == FineToCoarseBlock3DConnector::Type01) { + lMin1X2 = minX2; + lMax1X2 = maxX2 + maxOffX2 - 1; + lMin1X3 = minX3 + minOffX3; + lMax1X3 = maxX3 - 1; + } else if (FineToCoarseBlock3DConnector::connType == FineToCoarseBlock3DConnector::Type11) { + lMin1X2 = minX2 + minOffX2; + lMax1X2 = maxX2 - 1; + lMin1X3 = minX3 + minOffX3; + lMax1X3 = maxX3 - 1; + } + findFCCells(lMin1X1, lMin1X2, lMin1X3, lMax1X1, lMax1X2, lMax1X3, iNodeSetSender); + break; + case N: + case S: + if (sendDir == N) { + lMin1X2 = maxX2 - 6; + lMax1X2 = lMin1X2; + } else if (sendDir == S) { + lMin1X2 = 5; + lMax1X2 = lMin1X2; + } - SPtr<DistributionArray3D> fFrom = FineToCoarseBlock3DConnector::block.lock()->getKernel()->getDataSet()->getFdistributions(); - SPtr<BCArray3D> bcArray = FineToCoarseBlock3DConnector::block.lock()->getKernel()->getBCProcessor()->getBCArray(); + if (FineToCoarseBlock3DConnector::connType == FineToCoarseBlock3DConnector::Type00) { + lMin1X1 = minX1; + lMax1X1 = maxX1 + maxOffX1 - 1; + lMin1X3 = minX3; + lMax1X3 = maxX3 + maxOffX3 - 1; + } else if (FineToCoarseBlock3DConnector::connType == FineToCoarseBlock3DConnector::Type10) { + lMin1X1 = minX1 + minOffX1; + lMax1X1 = maxX1 - 1; + lMin1X3 = minX3; + lMax1X3 = maxX3 + maxOffX3 - 1; + } else if (FineToCoarseBlock3DConnector::connType == FineToCoarseBlock3DConnector::Type01) { + lMin1X1 = minX1; + lMax1X1 = maxX1 + maxOffX1 - 1; + lMin1X3 = minX3 + minOffX3; + lMax1X3 = maxX3; + } else if (FineToCoarseBlock3DConnector::connType == FineToCoarseBlock3DConnector::Type11) { + lMin1X1 = minX1 + minOffX1; + lMax1X1 = maxX1 - 1; + lMin1X3 = minX3 + minOffX3; + lMax1X3 = maxX3 - 1; + } + findFCCells(lMin1X1, lMin1X2, lMin1X3, lMax1X1, lMax1X2, lMax1X3, iNodeSetSender); + break; + case T: + case B: + if (sendDir == T) { + lMin1X3 = maxX3 - 6; + lMax1X3 = lMin1X3; + } else if (sendDir == B) { + lMin1X3 = 5; + lMax1X3 = lMin1X3; + } - for (ix3 = lMinX3; ix3<=lMaxX3; ix3 += 2) - { - for (ix2 = lMinX2; ix2<=lMaxX2; ix2 += 2) - { - for (ix1 = lMinX1; ix1<=lMaxX1; ix1 += 2) - { - D3Q27ICell icellC; + if (FineToCoarseBlock3DConnector::connType == FineToCoarseBlock3DConnector::Type00) { + lMin1X1 = minX1; + lMax1X1 = maxX1 + maxOffX1 - 1; + lMin1X2 = minX2; + lMax1X2 = maxX2 + maxOffX2 - 1; + } else if (FineToCoarseBlock3DConnector::connType == FineToCoarseBlock3DConnector::Type10) { + lMin1X1 = minX1 + minOffX1; + lMax1X1 = maxX1 - 1; + lMin1X2 = minX2; + lMax1X2 = maxX2 + maxOffX2 - 1; + } else if (FineToCoarseBlock3DConnector::connType == FineToCoarseBlock3DConnector::Type01) { + lMin1X1 = minX1; + lMax1X1 = maxX1 + maxOffX1 - 1; + lMin1X2 = minX2 + minOffX2; + lMax1X2 = maxX2 - 1; + } else if (FineToCoarseBlock3DConnector::connType == FineToCoarseBlock3DConnector::Type11) { + lMin1X1 = minX1 + minOffX1; + lMax1X1 = maxX1 - 1; + lMin1X2 = minX2 + minOffX2; + lMax1X2 = maxX2 - 1; + } + findFCCells(lMin1X1, lMin1X2, lMin1X3, lMax1X1, lMax1X2, lMax1X3, iNodeSetSender); + break; + // edges + // N-S-E-W + case NE: + case SW: + case SE: + case NW: + if (sendDir == NE) { + lMin1X1 = maxX1 - 6; + lMax1X1 = lMin1X1 + 4; + lMin1X2 = maxX2 - 6; + lMax1X2 = lMin1X2; + + lMin2X1 = maxX1 - 6; + lMax2X1 = lMin2X1; + lMin2X2 = maxX2 - 6; + lMax2X2 = lMin2X2 + 4; + } else if (sendDir == SW) { + lMin1X1 = 1; + lMax1X1 = lMin1X1 + 4; + lMin1X2 = 5; + lMax1X2 = lMin1X2; + + lMin2X1 = 5; + lMax2X1 = lMin2X1; + lMin2X2 = 1; + lMax2X2 = lMin2X2 + 4; + } else if (sendDir == SE) { + lMin1X1 = maxX1 - 6; + lMax1X1 = lMin1X1 + 4; + lMin1X2 = 5; + lMax1X2 = lMin1X2; + + lMin2X1 = maxX1 - 6; + lMax2X1 = lMin2X1; + lMin2X2 = 1; + lMax2X2 = lMin2X2 + 4; + } else if (sendDir == NW) { + lMin1X1 = 1; + lMax1X1 = lMin1X1 + 4; + lMin1X2 = maxX2 - 6; + lMax1X2 = lMin1X2; + + lMin2X1 = 5; + lMax2X1 = lMin2X1; + lMin2X2 = maxX2 - 6; + lMax2X2 = lMin2X2 + 4; + } - int howManySolids = FineToCoarseBlock3DConnector::iprocessor->iCellHowManySolids(bcArray, ix1, ix2, ix3); + if (FineToCoarseBlock3DConnector::connType == FineToCoarseBlock3DConnector::Type00) { + lMin1X3 = minX3; + lMax1X3 = maxX3 + maxOffX3 - 1; + } else if (FineToCoarseBlock3DConnector::connType == FineToCoarseBlock3DConnector::Type10) { + lMin1X3 = minX3 + minOffX3; + lMax1X3 = maxX3 - 1; + } - if (howManySolids == 0 || howManySolids == 8) - { - x1off = 0.0; - x2off = 0.0; - x3off = 0.0; + findFCCells(lMin1X1, lMin1X2, lMin1X3, lMax1X1, lMax1X2, lMax1X3, iNodeSetSender); + findFCCells(lMin2X1, lMin2X2, lMin1X3, lMax2X1, lMax2X2, lMax1X3, iNodeSetSender); + + break; + // T-B-E-W + case TE: + case BW: + case BE: + case TW: + if (sendDir == TE) { + lMin1X1 = maxX1 - 6; + lMax1X1 = lMin1X1 + 4; + lMin1X3 = maxX3 - 6; + lMax1X3 = lMin1X3; + + lMin2X1 = maxX1 - 6; + lMax2X1 = lMin2X1; + lMin2X3 = maxX3 - 6; + lMax2X3 = lMin2X3 + 4; + } else if (sendDir == BW) { + lMin1X1 = 1; + lMax1X1 = lMin1X1 + 4; + lMin1X3 = 5; + lMax1X3 = lMin1X3; + + lMin2X1 = 5; + lMax2X1 = lMin2X1; + lMin2X3 = 1; + lMax2X3 = lMin2X3 + 4; + } else if (sendDir == BE) { + lMin1X1 = maxX1 - 6; + lMax1X1 = lMin1X1 + 4; + lMin1X3 = 5; + lMax1X3 = lMin1X3; + + lMin2X1 = maxX1 - 6; + lMax2X1 = lMin2X1; + lMin2X3 = 1; + lMax2X3 = lMin2X3 + 4; + } else if (sendDir == TW) { + lMin1X1 = 1; + lMax1X1 = lMin1X1 + 5; + lMin1X3 = maxX3 - 6; + lMax1X3 = lMin1X3; + + lMin2X1 = 5; + lMax2X1 = lMin2X1; + lMin2X3 = maxX3 - 6; + lMax2X3 = lMin2X3 + 4; } - else - { - if (!iprocessor->findNeighborICell(bcArray, fFrom, icellC, bMaxX1, bMaxX2, bMaxX3, ix1, ix2, ix3, x1off, x2off, x3off)) - { - std::string err = "For "+FineToCoarseBlock3DConnector::block.lock()->toString()+" x1="+UbSystem::toString(ix1)+", x2=" + UbSystem::toString(ix2)+", x3=" + UbSystem::toString(ix3)+ - " interpolation is not implemented for other direction"+ - " by using in: "+(std::string)typeid(*this).name()+ - " or maybe you have a solid on the block boundary"; - UB_THROW(UbException(UB_EXARGS, err)); - } + + if (FineToCoarseBlock3DConnector::connType == FineToCoarseBlock3DConnector::Type00) { + lMin1X2 = minX2; + lMax1X2 = maxX2 + maxOffX2 - 1; + } else if (FineToCoarseBlock3DConnector::connType == FineToCoarseBlock3DConnector::Type10) { + lMin1X2 = minX2 + minOffX2; + lMax1X2 = maxX2 - 1; } - INodeVector inv; - inv.push_back(ix1 + (int)x1off); - inv.push_back(ix2 + (int)x2off); - inv.push_back(ix3 + (int)x3off); - inv.push_back((int)x1off); - inv.push_back((int)x2off); - inv.push_back((int)x3off); - //inodes.insert(inv); - inodes.push_back(inv); - } - } - } -} -////////////////////////////////////////////////////////////////////////// + findFCCells(lMin1X1, lMin1X2, lMin1X3, lMax1X1, lMax1X2, lMax1X3, iNodeSetSender); + findFCCells(lMin2X1, lMin1X2, lMin2X3, lMax2X1, lMax1X2, lMax2X3, iNodeSetSender); + break; + // T-B-N-S + case TN: + case BS: + case BN: + case TS: + if (sendDir == TN) { + lMin1X2 = maxX2 - 6; + lMax1X2 = lMin1X2 + 4; + lMin1X3 = maxX3 - 6; + lMax1X3 = lMin1X3; + + lMin2X2 = maxX2 - 6; + lMax2X2 = lMin2X2; + lMin2X3 = maxX3 - 6; + lMax2X3 = lMin2X3 + 4; + } else if (sendDir == BS) { + lMin1X2 = 1; + lMax1X2 = lMin1X2 + 4; + lMin1X3 = 5; + lMax1X3 = lMin1X3; + + lMin2X2 = 5; + lMax2X2 = lMin2X2; + lMin2X3 = 1; + lMax2X3 = lMin2X3 + 4; + } else if (sendDir == BN) { + lMin1X2 = maxX2 - 6; + lMax1X2 = lMin1X2 + 4; + lMin1X3 = 5; + lMax1X3 = lMin1X3; + + lMin2X2 = maxX2 - 6; + lMax2X2 = lMin2X2; + lMin2X3 = 1; + lMax2X3 = lMin2X3 + 4; + } else if (sendDir == TS) { + lMin1X2 = 1; + lMax1X2 = lMin1X2 + 4; + lMin1X3 = maxX3 - 6; + lMax1X3 = lMin1X3; + + lMin2X2 = 5; + lMax2X2 = lMin2X2; + lMin2X3 = maxX3 - 6; + lMax2X3 = lMin2X3 + 4; + } -void FineToCoarseNodeSetBlock3DConnector::findFCCells() -{ - using namespace D3Q27System; - - int lMin1X1, lMin1X2, lMin1X3, lMax1X1, lMax1X2, lMax1X3; - int lMin2X1, lMin2X2, lMin2X3, lMax2X1, lMax2X2, lMax2X3; - int lMin3X1, lMin3X2, lMin3X3, lMax3X1, lMax3X2, lMax3X3; - - //lMin1X1 = minX1+1; lMin1X2 = minX2+1; lMin1X3 = minX3+1; - //lMax1X1 = maxX1-1; lMax1X2 = maxX2-1; lMax1X3 = maxX3-1; - //getLocalMinMax(lMin1X1, lMin1X2, lMin1X3, lMax1X1, lMax1X2, lMax1X3); - - //lMin2X1 = minX1+1; lMin2X2 = minX2+1; lMin2X3 = minX3+1; - //lMax2X1 = maxX1-1; lMax2X2 = maxX2-1; lMax2X3 = maxX3-1; - //getLocalMinMax(lMin2X1, lMin2X2, lMin2X3, lMax2X1, lMax2X2, lMax2X3); - - //lMin3X1 = minX1+1; lMin3X2 = minX2+1; lMin3X3 = minX3+1; - //lMax3X1 = maxX1-1; lMax3X2 = maxX2-1; lMax3X3 = maxX3-1; - //getLocalMinMax(lMin3X1, lMin3X2, lMin3X3, lMax3X1, lMax3X2, lMax3X3); - - switch (sendDir) - { - //faces - case E: case W: - if (sendDir == E) - { - lMin1X1 = maxX1 - 6; - lMax1X1 = lMin1X1; - } - else if (sendDir == W) - { - lMin1X1 = 5; - lMax1X1 = lMin1X1; - } - - if (FineToCoarseBlock3DConnector::connType ==FineToCoarseBlock3DConnector::Type00) - { - lMin1X2 = minX2; - lMax1X2 = maxX2 + maxOffX2 - 1; - lMin1X3 = minX3; - lMax1X3 = maxX3 + maxOffX3 - 1; - } - else if (FineToCoarseBlock3DConnector::connType ==FineToCoarseBlock3DConnector::Type10) - { - lMin1X2 = minX2 + minOffX2; - lMax1X2 = maxX2 - 1; - lMin1X3 = minX3; - lMax1X3 = maxX3 + maxOffX3 - 1; - } - else if (FineToCoarseBlock3DConnector::connType ==FineToCoarseBlock3DConnector::Type01) - { - lMin1X2 = minX2; - lMax1X2 = maxX2 + maxOffX2 - 1; - lMin1X3 = minX3 + minOffX3; - lMax1X3 = maxX3 - 1; - } - else if (FineToCoarseBlock3DConnector::connType ==FineToCoarseBlock3DConnector::Type11) - { - lMin1X2 = minX2 + minOffX2; - lMax1X2 = maxX2 - 1; - lMin1X3 = minX3 + minOffX3; - lMax1X3 = maxX3 - 1; - } - findFCCells(lMin1X1, lMin1X2, lMin1X3, lMax1X1, lMax1X2, lMax1X3, iNodeSetSender); - break; - case N: case S: - if (sendDir == N) - { - lMin1X2 = maxX2 - 6; - lMax1X2 = lMin1X2; - } - else if (sendDir == S) - { - lMin1X2 = 5; - lMax1X2 = lMin1X2; - } - - if (FineToCoarseBlock3DConnector::connType ==FineToCoarseBlock3DConnector::Type00) - { - lMin1X1 = minX1; - lMax1X1 = maxX1 + maxOffX1 - 1; - lMin1X3 = minX3; - lMax1X3 = maxX3 + maxOffX3 - 1; - } - else if (FineToCoarseBlock3DConnector::connType ==FineToCoarseBlock3DConnector::Type10) - { - lMin1X1 = minX1 + minOffX1; - lMax1X1 = maxX1 - 1; - lMin1X3 = minX3; - lMax1X3 = maxX3 + maxOffX3 - 1; - } - else if (FineToCoarseBlock3DConnector::connType ==FineToCoarseBlock3DConnector::Type01) - { - lMin1X1 = minX1; - lMax1X1 = maxX1 + maxOffX1 - 1; - lMin1X3 = minX3 + minOffX3; - lMax1X3 = maxX3; - } - else if (FineToCoarseBlock3DConnector::connType ==FineToCoarseBlock3DConnector::Type11) - { - lMin1X1 = minX1 + minOffX1; - lMax1X1 = maxX1 - 1; - lMin1X3 = minX3 + minOffX3; - lMax1X3 = maxX3 - 1; - } - findFCCells(lMin1X1, lMin1X2, lMin1X3, lMax1X1, lMax1X2, lMax1X3, iNodeSetSender); - break; - case T: case B: - if (sendDir == T) - { - lMin1X3 = maxX3 - 6; - lMax1X3 = lMin1X3; - } - else if (sendDir == B) - { - lMin1X3 = 5; - lMax1X3 = lMin1X3; - } - - if (FineToCoarseBlock3DConnector::connType ==FineToCoarseBlock3DConnector::Type00) - { - lMin1X1 = minX1; - lMax1X1 = maxX1 + maxOffX1 - 1; - lMin1X2 = minX2; - lMax1X2 = maxX2 + maxOffX2 - 1; - } - else if (FineToCoarseBlock3DConnector::connType ==FineToCoarseBlock3DConnector::Type10) - { - lMin1X1 = minX1 + minOffX1; - lMax1X1 = maxX1 - 1; - lMin1X2 = minX2; - lMax1X2 = maxX2 + maxOffX2 - 1; - } - else if (FineToCoarseBlock3DConnector::connType ==FineToCoarseBlock3DConnector::Type01) - { - lMin1X1 = minX1; - lMax1X1 = maxX1 + maxOffX1 - 1; - lMin1X2 = minX2 + minOffX2; - lMax1X2 = maxX2 - 1; - } - else if (FineToCoarseBlock3DConnector::connType ==FineToCoarseBlock3DConnector::Type11) - { - lMin1X1 = minX1 + minOffX1; - lMax1X1 = maxX1 - 1; - lMin1X2 = minX2 + minOffX2; - lMax1X2 = maxX2 - 1; - } - findFCCells(lMin1X1, lMin1X2, lMin1X3, lMax1X1, lMax1X2, lMax1X3, iNodeSetSender); - break; - //edges - //N-S-E-W - case NE: case SW: case SE: case NW: - if (sendDir == NE) - { - lMin1X1 = maxX1 - 6; - lMax1X1 = lMin1X1 + 4; - lMin1X2 = maxX2 - 6; - lMax1X2 = lMin1X2; - - lMin2X1 = maxX1 - 6; - lMax2X1 = lMin2X1; - lMin2X2 = maxX2 - 6; - lMax2X2 = lMin2X2 + 4; - } - else if (sendDir == SW) - { - lMin1X1 = 1; - lMax1X1 = lMin1X1 + 4; - lMin1X2 = 5; - lMax1X2 = lMin1X2; - - lMin2X1 = 5; - lMax2X1 = lMin2X1; - lMin2X2 = 1; - lMax2X2 = lMin2X2 + 4; - } - else if (sendDir == SE) - { - lMin1X1 = maxX1 - 6; - lMax1X1 = lMin1X1 + 4; - lMin1X2 = 5; - lMax1X2 = lMin1X2; - - lMin2X1 = maxX1 - 6; - lMax2X1 = lMin2X1; - lMin2X2 = 1; - lMax2X2 = lMin2X2 + 4; - } - else if (sendDir == NW) - { - lMin1X1 = 1; - lMax1X1 = lMin1X1 + 4; - lMin1X2 = maxX2 - 6; - lMax1X2 = lMin1X2; - - lMin2X1 = 5; - lMax2X1 = lMin2X1; - lMin2X2 = maxX2 - 6; - lMax2X2 = lMin2X2 + 4; - } - - if (FineToCoarseBlock3DConnector::connType ==FineToCoarseBlock3DConnector::Type00) - { - lMin1X3 = minX3; - lMax1X3 = maxX3 + maxOffX3 - 1; - } - else if (FineToCoarseBlock3DConnector::connType ==FineToCoarseBlock3DConnector::Type10) - { - lMin1X3 = minX3 + minOffX3; - lMax1X3 = maxX3 - 1; - } - - findFCCells(lMin1X1, lMin1X2, lMin1X3, lMax1X1, lMax1X2, lMax1X3, iNodeSetSender); - findFCCells(lMin2X1, lMin2X2, lMin1X3, lMax2X1, lMax2X2, lMax1X3, iNodeSetSender); - - break; - //T-B-E-W - case TE: case BW: case BE: case TW: - if (sendDir == TE) - { - lMin1X1 = maxX1 - 6; - lMax1X1 = lMin1X1 + 4; - lMin1X3 = maxX3 - 6; - lMax1X3 = lMin1X3; - - lMin2X1 = maxX1 - 6; - lMax2X1 = lMin2X1; - lMin2X3 = maxX3 - 6; - lMax2X3 = lMin2X3 + 4; - } - else if (sendDir == BW) - { - lMin1X1 = 1; - lMax1X1 = lMin1X1 + 4; - lMin1X3 = 5; - lMax1X3 = lMin1X3; - - lMin2X1 = 5; - lMax2X1 = lMin2X1; - lMin2X3 = 1; - lMax2X3 = lMin2X3 + 4; - } - else if (sendDir == BE) - { - lMin1X1 = maxX1 - 6; - lMax1X1 = lMin1X1 + 4; - lMin1X3 = 5; - lMax1X3 = lMin1X3; - - - lMin2X1 = maxX1 - 6; - lMax2X1 = lMin2X1; - lMin2X3 = 1; - lMax2X3 = lMin2X3 + 4; - } - else if (sendDir == TW) - { - lMin1X1 = 1; - lMax1X1 = lMin1X1 + 5; - lMin1X3 = maxX3 - 6; - lMax1X3 = lMin1X3; - - lMin2X1 = 5; - lMax2X1 = lMin2X1; - lMin2X3 = maxX3 - 6; - lMax2X3 = lMin2X3 + 4; - } - - if (FineToCoarseBlock3DConnector::connType ==FineToCoarseBlock3DConnector::Type00) - { - lMin1X2 = minX2; - lMax1X2 = maxX2 + maxOffX2 - 1; - } - else if (FineToCoarseBlock3DConnector::connType ==FineToCoarseBlock3DConnector::Type10) - { - lMin1X2 = minX2 + minOffX2; - lMax1X2 = maxX2 - 1; - } - - findFCCells(lMin1X1, lMin1X2, lMin1X3, lMax1X1, lMax1X2, lMax1X3, iNodeSetSender); - findFCCells(lMin2X1, lMin1X2, lMin2X3, lMax2X1, lMax1X2, lMax2X3, iNodeSetSender); - break; - //T-B-N-S - case TN: case BS: case BN: case TS: - if (sendDir == TN) - { - lMin1X2 = maxX2 - 6; - lMax1X2 = lMin1X2 + 4; - lMin1X3 = maxX3 - 6; - lMax1X3 = lMin1X3; - - lMin2X2 = maxX2 - 6; - lMax2X2 = lMin2X2; - lMin2X3 = maxX3 - 6; - lMax2X3 = lMin2X3 + 4; - } - else if (sendDir == BS) - { - lMin1X2 = 1; - lMax1X2 = lMin1X2 + 4; - lMin1X3 = 5; - lMax1X3 = lMin1X3; - - lMin2X2 = 5; - lMax2X2 = lMin2X2; - lMin2X3 = 1; - lMax2X3 = lMin2X3 + 4; - } - else if (sendDir == BN) - { - lMin1X2 = maxX2 - 6; - lMax1X2 = lMin1X2 + 4; - lMin1X3 = 5; - lMax1X3 = lMin1X3; - - lMin2X2 = maxX2 - 6; - lMax2X2 = lMin2X2; - lMin2X3 = 1; - lMax2X3 = lMin2X3 + 4; - } - else if (sendDir == TS) - { - lMin1X2 = 1; - lMax1X2 = lMin1X2 + 4; - lMin1X3 = maxX3 - 6; - lMax1X3 = lMin1X3; - - lMin2X2 = 5; - lMax2X2 = lMin2X2; - lMin2X3 = maxX3 - 6; - lMax2X3 = lMin2X3 + 4; - } - - if (FineToCoarseBlock3DConnector::connType ==FineToCoarseBlock3DConnector::Type00) - { - lMin1X1 = minX1; - lMax1X1 = maxX1 + maxOffX1 - 1; - } - else if (FineToCoarseBlock3DConnector::connType ==FineToCoarseBlock3DConnector::Type10) - { - lMin1X1 = minX1 + minOffX1; - lMax1X1 = maxX1 - 1; - } - - findFCCells(lMin1X1, lMin1X2, lMin1X3, lMax1X1, lMax1X2, lMax1X3, iNodeSetSender); - findFCCells(lMin1X1, lMin2X2, lMin2X3, lMax1X1, lMax2X2, lMax2X3, iNodeSetSender); - break; - //corners - case TNE: case TNW: case TSE: case TSW: case BNE: case BNW: case BSE: case BSW: - if (sendDir == TNE) - { - lMin1X1 = maxX1-6; - lMax1X1 = maxX1-6; - lMin1X2 = maxX2-6; - lMax1X2 = maxX2-2; - lMin1X3 = maxX3-6; - lMax1X3 = maxX3-2; - - lMin2X1 = maxX1-6; - lMax2X1 = maxX1-2; - lMin2X2 = maxX2-6; - lMax2X2 = maxX2-6; - lMin2X3 = maxX3-6; - lMax2X3 = maxX3-1; - - lMin3X1 = maxX1-6; - lMax3X1 = maxX1-2; - lMin3X2 = maxX2-6; - lMax3X2 = maxX2-2; - lMin3X3 = maxX3-6; - lMax3X3 = maxX3-5; - } - else if (sendDir == TNW) - { - lMin1X1 = 5; - lMax1X1 = 5; - lMin1X2 = maxX2-6; - lMax1X2 = maxX2-2; - lMin1X3 = maxX3-6; - lMax1X3 = maxX3-2; - - lMin2X1 = 1; - lMax2X1 = 5; - lMin2X2 = maxX2-6; - lMax2X2 = maxX2-6; - lMin2X3 = maxX3-6; - lMax2X3 = maxX3-2; - - lMin3X1 = 1; - lMax3X1 = 5; - lMin3X2 = maxX2-6; - lMax3X2 = maxX2-2; - lMin3X3 = maxX3-6; - lMax3X3 = maxX3-6; - } - else if (sendDir == TSE) - { - lMin1X1 = maxX1-6; - lMax1X1 = maxX1-6; - lMin1X2 = 1; - lMax1X2 = 5; - lMin1X3 = maxX3-6; - lMax1X3 = maxX3-2; - - lMin2X1 = maxX1-6; - lMax2X1 = maxX1-2; - lMin2X2 = 5; - lMax2X2 = 5; - lMin2X3 = maxX3-6; - lMax2X3 = maxX3-2; - - lMin3X1 = maxX1-6; - lMax3X1 = maxX1-2; - lMin3X2 = 1; - lMax3X2 = 5; - lMin3X3 = maxX3-6; - lMax3X3 = maxX3-6; - } - else if (sendDir == TSW) - { - lMin1X1 = 5; - lMax1X1 = 5; - lMin1X2 = 1; - lMax1X2 = 5; - lMin1X3 = maxX3-6; - lMax1X3 = maxX3-2; - - lMin2X1 = 1; - lMax2X1 = 5; - lMin2X2 = 5; - lMax2X2 = 5; - lMin2X3 = maxX3-6; - lMax2X3 = maxX3-2; - - lMin3X1 = 1; - lMax3X1 = 5; - lMin3X2 = 1; - lMax3X2 = 5; - lMin3X3 = maxX3-6; - lMax3X3 = maxX3-6; - } - else if (sendDir == BNE) - { - lMin1X1 = maxX1-6; - lMax1X1 = maxX1-6; - lMin1X2 = maxX2-6; - lMax1X2 = maxX2-2; - lMin1X3 = 1; - lMax1X3 = 5; - - lMin2X1 = maxX1-6; - lMax2X1 = maxX1-2; - lMin2X2 = maxX2-6; - lMax2X2 = maxX2-6; - lMin2X3 = 1; - lMax2X3 = 5; - - lMin3X1 = maxX1-6; - lMax3X1 = maxX1-2; - lMin3X2 = maxX2-6; - lMax3X2 = maxX2-2; - lMin3X3 = 5; - lMax3X3 = 5; - } - else if (sendDir == BNW) - { - lMin1X1 = 5; - lMax1X1 = 5; - lMin1X2 = maxX2-6; - lMax1X2 = maxX2-2; - lMin1X3 = 1; - lMax1X3 = 5; - - lMin2X1 = 1; - lMax2X1 = 5; - lMin2X2 = maxX2-6; - lMax2X2 = maxX2-6; - lMin2X3 = 1; - lMax2X3 = 5; - - lMin3X1 = 1; - lMax3X1 = 5; - lMin3X2 = maxX2-6; - lMax3X2 = maxX2-2; - lMin3X3 = 5; - lMax3X3 = 5; - } - else if (sendDir == BSE) - { - lMin1X1 = maxX1-6; - lMax1X1 = maxX1-6; - lMin1X2 = 1; - lMax1X2 = 5; - lMin1X3 = 1; - lMax1X3 = 5; - - lMin2X1 = maxX1-6; - lMax2X1 = maxX1-2; - lMin2X2 = 5; - lMax2X2 = 5; - lMin2X3 = 1; - lMax2X3 = 5; - - lMin3X1 = maxX1-5; - lMax3X1 = maxX1-2; - lMin3X2 = 1; - lMax3X2 = 5; - lMin3X3 = 5; - lMax3X3 = 5; - } - else if (sendDir == BSW) - { - lMin1X1 = 5; - lMax1X1 = 5; - lMin1X2 = 1; - lMax1X2 = 5; - lMin1X3 = 1; - lMax1X3 = 5; - - lMin2X1 = 1; - lMax2X1 = 5; - lMin2X2 = 5; - lMax2X2 = 5; - lMin2X3 = 1; - lMax2X3 = 5; - - lMin3X1 = 1; - lMax3X1 = 5; - lMin3X2 = 1; - lMax3X2 = 5; - lMin3X3 = 5; - lMax3X3 = 5; - } - findFCCells(lMin1X1, lMin1X2, lMin1X3, lMax1X1, lMax1X2, lMax1X3, iNodeSetSender); - findFCCells(lMin2X1, lMin2X2, lMin2X3, lMax2X1, lMax2X2, lMax2X3, iNodeSetSender); - findFCCells(lMin3X1, lMin3X2, lMin3X3, lMax3X1, lMax3X2, lMax3X3, iNodeSetSender); - break; - } + if (FineToCoarseBlock3DConnector::connType == FineToCoarseBlock3DConnector::Type00) { + lMin1X1 = minX1; + lMax1X1 = maxX1 + maxOffX1 - 1; + } else if (FineToCoarseBlock3DConnector::connType == FineToCoarseBlock3DConnector::Type10) { + lMin1X1 = minX1 + minOffX1; + lMax1X1 = maxX1 - 1; + } + + findFCCells(lMin1X1, lMin1X2, lMin1X3, lMax1X1, lMax1X2, lMax1X3, iNodeSetSender); + findFCCells(lMin1X1, lMin2X2, lMin2X3, lMax1X1, lMax2X2, lMax2X3, iNodeSetSender); + break; + // corners + case TNE: + case TNW: + case TSE: + case TSW: + case BNE: + case BNW: + case BSE: + case BSW: + if (sendDir == TNE) { + lMin1X1 = maxX1 - 6; + lMax1X1 = maxX1 - 6; + lMin1X2 = maxX2 - 6; + lMax1X2 = maxX2 - 2; + lMin1X3 = maxX3 - 6; + lMax1X3 = maxX3 - 2; + + lMin2X1 = maxX1 - 6; + lMax2X1 = maxX1 - 2; + lMin2X2 = maxX2 - 6; + lMax2X2 = maxX2 - 6; + lMin2X3 = maxX3 - 6; + lMax2X3 = maxX3 - 1; + + lMin3X1 = maxX1 - 6; + lMax3X1 = maxX1 - 2; + lMin3X2 = maxX2 - 6; + lMax3X2 = maxX2 - 2; + lMin3X3 = maxX3 - 6; + lMax3X3 = maxX3 - 5; + } else if (sendDir == TNW) { + lMin1X1 = 5; + lMax1X1 = 5; + lMin1X2 = maxX2 - 6; + lMax1X2 = maxX2 - 2; + lMin1X3 = maxX3 - 6; + lMax1X3 = maxX3 - 2; + + lMin2X1 = 1; + lMax2X1 = 5; + lMin2X2 = maxX2 - 6; + lMax2X2 = maxX2 - 6; + lMin2X3 = maxX3 - 6; + lMax2X3 = maxX3 - 2; + + lMin3X1 = 1; + lMax3X1 = 5; + lMin3X2 = maxX2 - 6; + lMax3X2 = maxX2 - 2; + lMin3X3 = maxX3 - 6; + lMax3X3 = maxX3 - 6; + } else if (sendDir == TSE) { + lMin1X1 = maxX1 - 6; + lMax1X1 = maxX1 - 6; + lMin1X2 = 1; + lMax1X2 = 5; + lMin1X3 = maxX3 - 6; + lMax1X3 = maxX3 - 2; + + lMin2X1 = maxX1 - 6; + lMax2X1 = maxX1 - 2; + lMin2X2 = 5; + lMax2X2 = 5; + lMin2X3 = maxX3 - 6; + lMax2X3 = maxX3 - 2; + + lMin3X1 = maxX1 - 6; + lMax3X1 = maxX1 - 2; + lMin3X2 = 1; + lMax3X2 = 5; + lMin3X3 = maxX3 - 6; + lMax3X3 = maxX3 - 6; + } else if (sendDir == TSW) { + lMin1X1 = 5; + lMax1X1 = 5; + lMin1X2 = 1; + lMax1X2 = 5; + lMin1X3 = maxX3 - 6; + lMax1X3 = maxX3 - 2; + + lMin2X1 = 1; + lMax2X1 = 5; + lMin2X2 = 5; + lMax2X2 = 5; + lMin2X3 = maxX3 - 6; + lMax2X3 = maxX3 - 2; + + lMin3X1 = 1; + lMax3X1 = 5; + lMin3X2 = 1; + lMax3X2 = 5; + lMin3X3 = maxX3 - 6; + lMax3X3 = maxX3 - 6; + } else if (sendDir == BNE) { + lMin1X1 = maxX1 - 6; + lMax1X1 = maxX1 - 6; + lMin1X2 = maxX2 - 6; + lMax1X2 = maxX2 - 2; + lMin1X3 = 1; + lMax1X3 = 5; + + lMin2X1 = maxX1 - 6; + lMax2X1 = maxX1 - 2; + lMin2X2 = maxX2 - 6; + lMax2X2 = maxX2 - 6; + lMin2X3 = 1; + lMax2X3 = 5; + + lMin3X1 = maxX1 - 6; + lMax3X1 = maxX1 - 2; + lMin3X2 = maxX2 - 6; + lMax3X2 = maxX2 - 2; + lMin3X3 = 5; + lMax3X3 = 5; + } else if (sendDir == BNW) { + lMin1X1 = 5; + lMax1X1 = 5; + lMin1X2 = maxX2 - 6; + lMax1X2 = maxX2 - 2; + lMin1X3 = 1; + lMax1X3 = 5; + + lMin2X1 = 1; + lMax2X1 = 5; + lMin2X2 = maxX2 - 6; + lMax2X2 = maxX2 - 6; + lMin2X3 = 1; + lMax2X3 = 5; + + lMin3X1 = 1; + lMax3X1 = 5; + lMin3X2 = maxX2 - 6; + lMax3X2 = maxX2 - 2; + lMin3X3 = 5; + lMax3X3 = 5; + } else if (sendDir == BSE) { + lMin1X1 = maxX1 - 6; + lMax1X1 = maxX1 - 6; + lMin1X2 = 1; + lMax1X2 = 5; + lMin1X3 = 1; + lMax1X3 = 5; + + lMin2X1 = maxX1 - 6; + lMax2X1 = maxX1 - 2; + lMin2X2 = 5; + lMax2X2 = 5; + lMin2X3 = 1; + lMax2X3 = 5; + + lMin3X1 = maxX1 - 5; + lMax3X1 = maxX1 - 2; + lMin3X2 = 1; + lMax3X2 = 5; + lMin3X3 = 5; + lMax3X3 = 5; + } else if (sendDir == BSW) { + lMin1X1 = 5; + lMax1X1 = 5; + lMin1X2 = 1; + lMax1X2 = 5; + lMin1X3 = 1; + lMax1X3 = 5; + + lMin2X1 = 1; + lMax2X1 = 5; + lMin2X2 = 5; + lMax2X2 = 5; + lMin2X3 = 1; + lMax2X3 = 5; + + lMin3X1 = 1; + lMax3X1 = 5; + lMin3X2 = 1; + lMax3X2 = 5; + lMin3X3 = 5; + lMax3X3 = 5; + } + findFCCells(lMin1X1, lMin1X2, lMin1X3, lMax1X1, lMax1X2, lMax1X3, iNodeSetSender); + findFCCells(lMin2X1, lMin2X2, lMin2X3, lMax2X1, lMax2X2, lMax2X3, iNodeSetSender); + findFCCells(lMin3X1, lMin3X2, lMin3X3, lMax3X1, lMax3X2, lMax3X3, iNodeSetSender); + break; + } } ////////////////////////////////////////////////////////////////////////// void FineToCoarseNodeSetBlock3DConnector::fillSendVectors() { - using namespace D3Q27System; - - SPtr<DistributionArray3D> fFrom = block.lock()->getKernel()->getDataSet()->getFdistributions(); + using namespace D3Q27System; - int index = 0; + SPtr<DistributionArray3D> fFrom = block.lock()->getKernel()->getDataSet()->getFdistributions(); - vector_type& data = this->sender->getData(); + int index = 0; - for(INodeVector inode : iNodeSetSender) - { - LBMReal icellC[27]; - D3Q27ICell icellF; - iprocessor->readICell(fFrom, icellF, inode[0], inode[1], inode[2]); - iprocessor->interpolateFineToCoarse(icellF, icellC, inode[3], inode[4], inode[5]); - writeICellCtoData(data, index, icellC); - } + vector_type &data = this->sender->getData(); + for (INodeVector inode : iNodeSetSender) { + LBMReal icellC[27]; + D3Q27ICell icellF; + iprocessor->readICell(fFrom, icellF, inode[0], inode[1], inode[2]); + iprocessor->interpolateFineToCoarse(icellF, icellC, inode[3], inode[4], inode[5]); + writeICellCtoData(data, index, icellC); + } } ////////////////////////////////////////////////////////////////////////// -void FineToCoarseNodeSetBlock3DConnector::readICellFfromData(vector_type& data, int& index, D3Q27ICell& icellF) +void FineToCoarseNodeSetBlock3DConnector::readICellFfromData(vector_type &data, int &index, D3Q27ICell &icellF) { - readNodeFromVector(data, index, icellF.BSW); - readNodeFromVector(data, index, icellF.BSE); - readNodeFromVector(data, index, icellF.BNW); - readNodeFromVector(data, index, icellF.BNE); - readNodeFromVector(data, index, icellF.TSW); - readNodeFromVector(data, index, icellF.TSE); - readNodeFromVector(data, index, icellF.TNW); - readNodeFromVector(data, index, icellF.TNE); + readNodeFromVector(data, index, icellF.BSW); + readNodeFromVector(data, index, icellF.BSE); + readNodeFromVector(data, index, icellF.BNW); + readNodeFromVector(data, index, icellF.BNE); + readNodeFromVector(data, index, icellF.TSW); + readNodeFromVector(data, index, icellF.TSE); + readNodeFromVector(data, index, icellF.TNW); + readNodeFromVector(data, index, icellF.TNE); } ////////////////////////////////////////////////////////////////////////// -void FineToCoarseNodeSetBlock3DConnector::readNodeFromVector(vector_type& data, int& index, LBMReal* inode) +void FineToCoarseNodeSetBlock3DConnector::readNodeFromVector(vector_type &data, int &index, LBMReal *inode) { - for (int i = D3Q27System::STARTF; i < D3Q27System::ENDF+1; i++) - { - inode[i] = data[index++]; - } + for (int i = D3Q27System::STARTF; i < D3Q27System::ENDF + 1; i++) { + inode[i] = data[index++]; + } } ////////////////////////////////////////////////////////////////////////// -void FineToCoarseNodeSetBlock3DConnector::writeICellCtoData(vector_type& data, int& index, LBMReal* icellC) +void FineToCoarseNodeSetBlock3DConnector::writeICellCtoData(vector_type &data, int &index, LBMReal *icellC) { - for (int i = D3Q27System::STARTF; i < D3Q27System::ENDF+1; i++) - { - data[index++] = icellC[i]; - } + for (int i = D3Q27System::STARTF; i < D3Q27System::ENDF + 1; i++) { + data[index++] = icellC[i]; + } } ////////////////////////////////////////////////////////////////////////// -void FineToCoarseNodeSetBlock3DConnector::findCFCells(int lMinX1, int lMinX2, int lMinX3, int lMaxX1, int lMaxX2, int lMaxX3, INodeSet &inodes) +void FineToCoarseNodeSetBlock3DConnector::findCFCells(int lMinX1, int lMinX2, int lMinX3, int lMaxX1, int lMaxX2, + int lMaxX3, INodeSet &inodes) { - int ix1, ix2, ix3; - - for (ix3 = lMinX3; ix3<=lMaxX3; ix3 += 2) - { - for (ix2 = lMinX2; ix2<=lMaxX2; ix2 += 2) - { - for (ix1 = lMinX1; ix1<=lMaxX1; ix1 += 2) - { - INodeVector inv; - inv.push_back(ix1); - inv.push_back(ix2); - inv.push_back(ix3); - //inodes.insert(inv); - inodes.push_back(inv); - } - } - } + int ix1, ix2, ix3; + + for (ix3 = lMinX3; ix3 <= lMaxX3; ix3 += 2) { + for (ix2 = lMinX2; ix2 <= lMaxX2; ix2 += 2) { + for (ix1 = lMinX1; ix1 <= lMaxX1; ix1 += 2) { + INodeVector inv; + inv.push_back(ix1); + inv.push_back(ix2); + inv.push_back(ix3); + // inodes.insert(inv); + inodes.push_back(inv); + } + } + } } ////////////////////////////////////////////////////////////////////////// void FineToCoarseNodeSetBlock3DConnector::findCFCells() { - using namespace D3Q27System; + using namespace D3Q27System; + + int lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3; + + ////////////////////////////////////////////////////// + // Debug + ////////////////////////////////////////////////////// + // if (block.lock()->getGlobalID() == 2183) + // { + // int test = 0; + // } + + switch (sendDir) { + // faces + case E: + case W: + if (sendDir == E) { + lMinX1 = maxX1 - 3; + lMaxX1 = lMinX1; + } else if (sendDir == W) { + lMinX1 = 2; + lMaxX1 = lMinX1; + } - int lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3; + if (FineToCoarseBlock3DConnector::connType == FineToCoarseBlock3DConnector::Type00) { + lMinX2 = minX2; + lMaxX2 = maxX2 + maxOffX2 - 1; + lMinX3 = minX3; + lMaxX3 = maxX3 + maxOffX3 - 1; + } else if (FineToCoarseBlock3DConnector::connType == FineToCoarseBlock3DConnector::Type10) { + lMinX2 = minX2 + minOffX2; + lMaxX2 = maxX2 - 1; + lMinX3 = minX3; + lMaxX3 = maxX3 + maxOffX3 - 1; + } else if (FineToCoarseBlock3DConnector::connType == FineToCoarseBlock3DConnector::Type01) { + lMinX2 = minX2; + lMaxX2 = maxX2 + maxOffX2 - 1; + lMinX3 = minX3 + minOffX3; + lMaxX3 = maxX3 - 1; + } else if (FineToCoarseBlock3DConnector::connType == FineToCoarseBlock3DConnector::Type11) { + lMinX2 = minX2 + minOffX2; + lMaxX2 = maxX2 - 1; + lMinX3 = minX3 + minOffX3; + lMaxX3 = maxX3 - 1; + } + findCFCells(lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, iNodeSetReceiver); + break; + case N: + case S: + if (sendDir == N) { + lMinX2 = maxX2 - 3; + lMaxX2 = lMinX2; + } else if (sendDir == S) { + lMinX2 = 2; + lMaxX2 = lMinX2; + } - ////////////////////////////////////////////////////// - //Debug - ////////////////////////////////////////////////////// -// if (block.lock()->getGlobalID() == 2183) -// { -// int test = 0; -// } + if (FineToCoarseBlock3DConnector::connType == FineToCoarseBlock3DConnector::Type00) { + lMinX1 = minX1; + lMaxX1 = maxX1 + maxOffX1 - 1; + lMinX3 = minX3; + lMaxX3 = maxX3 + maxOffX3 - 1; + } else if (FineToCoarseBlock3DConnector::connType == FineToCoarseBlock3DConnector::Type10) { + lMinX1 = minX1 + minOffX1; + lMaxX1 = maxX1; + lMinX3 = minX3; + lMaxX3 = maxX3 + maxOffX3 - 1; + } else if (FineToCoarseBlock3DConnector::connType == FineToCoarseBlock3DConnector::Type01) { + lMinX1 = minX1; + lMaxX1 = maxX1 + maxOffX1 - 1; + lMinX3 = minX3 + minOffX3; + lMaxX3 = maxX3 - 1; + } else if (FineToCoarseBlock3DConnector::connType == FineToCoarseBlock3DConnector::Type11) { + lMinX1 = minX1 + minOffX1; + lMaxX1 = maxX1 - 1; + lMinX3 = minX3 + minOffX3; + lMaxX3 = maxX3 - 1; + } + findCFCells(lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, iNodeSetReceiver); + break; + case T: + case B: + if (sendDir == T) { + lMinX3 = maxX3 - 3; + lMaxX3 = lMinX3; + } else if (sendDir == B) { + lMinX3 = 2; + lMaxX3 = lMinX3; + } - switch (sendDir) - { - //faces - case E: case W: - if (sendDir == E) - { - lMinX1 = maxX1 - 3; - lMaxX1 = lMinX1; - } - else if (sendDir == W) - { - lMinX1 = 2; - lMaxX1 = lMinX1; - } - - if (FineToCoarseBlock3DConnector::connType ==FineToCoarseBlock3DConnector::Type00) - { - lMinX2 = minX2; - lMaxX2 = maxX2 + maxOffX2 - 1; - lMinX3 = minX3; - lMaxX3 = maxX3 + maxOffX3 - 1; - } - else if (FineToCoarseBlock3DConnector::connType ==FineToCoarseBlock3DConnector::Type10) - { - lMinX2 = minX2 + minOffX2; - lMaxX2 = maxX2 - 1; - lMinX3 = minX3; - lMaxX3 = maxX3 + maxOffX3 - 1; - } - else if (FineToCoarseBlock3DConnector::connType ==FineToCoarseBlock3DConnector::Type01) - { - lMinX2 = minX2; - lMaxX2 = maxX2 + maxOffX2 - 1; - lMinX3 = minX3 + minOffX3; - lMaxX3 = maxX3 - 1; - } - else if (FineToCoarseBlock3DConnector::connType ==FineToCoarseBlock3DConnector::Type11) - { - lMinX2 = minX2 + minOffX2; - lMaxX2 = maxX2 - 1; - lMinX3 = minX3 + minOffX3; - lMaxX3 = maxX3 - 1; - } - findCFCells(lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, iNodeSetReceiver); - break; - case N: case S: - if (sendDir == N) - { - lMinX2 = maxX2 - 3; - lMaxX2 = lMinX2; - } - else if (sendDir == S) - { - lMinX2 = 2; - lMaxX2 = lMinX2; - } - - if (FineToCoarseBlock3DConnector::connType ==FineToCoarseBlock3DConnector::Type00) - { - lMinX1 = minX1; - lMaxX1 = maxX1 + maxOffX1 - 1; - lMinX3 = minX3; - lMaxX3 = maxX3 + maxOffX3 - 1; - } - else if (FineToCoarseBlock3DConnector::connType ==FineToCoarseBlock3DConnector::Type10) - { - lMinX1 = minX1 + minOffX1; - lMaxX1 = maxX1; - lMinX3 = minX3; - lMaxX3 = maxX3 + maxOffX3 - 1; - } - else if (FineToCoarseBlock3DConnector::connType ==FineToCoarseBlock3DConnector::Type01) - { - lMinX1 = minX1; - lMaxX1 = maxX1 + maxOffX1 - 1; - lMinX3 = minX3 + minOffX3; - lMaxX3 = maxX3 - 1; - } - else if (FineToCoarseBlock3DConnector::connType ==FineToCoarseBlock3DConnector::Type11) - { - lMinX1 = minX1 + minOffX1; - lMaxX1 = maxX1 - 1; - lMinX3 = minX3 + minOffX3; - lMaxX3 = maxX3 - 1; - } - findCFCells(lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, iNodeSetReceiver); - break; - case T: case B: - if (sendDir == T) - { - lMinX3 = maxX3 - 3; - lMaxX3 = lMinX3; - } - else if (sendDir == B) - { - lMinX3 = 2; - lMaxX3 = lMinX3; - } - - if (FineToCoarseBlock3DConnector::connType ==FineToCoarseBlock3DConnector::Type00) - { - lMinX1 = minX1; - lMaxX1 = maxX1 + maxOffX1 - 1; - lMinX2 = minX2; - lMaxX2 = maxX2 + maxOffX2 - 1; - } - else if (FineToCoarseBlock3DConnector::connType ==FineToCoarseBlock3DConnector::Type10) - { - lMinX1 = minX1 + minOffX1; - lMaxX1 = maxX1 - 1; - lMinX2 = minX2; - lMaxX2 = maxX2 + maxOffX2 - 1; - } - else if (FineToCoarseBlock3DConnector::connType ==FineToCoarseBlock3DConnector::Type01) - { - lMinX1 = minX1; - lMaxX1 = maxX1 + maxOffX1 - 1; - lMinX2 = minX2 + minOffX2; - lMaxX2 = maxX2 - 1; - } - else if (FineToCoarseBlock3DConnector::connType ==FineToCoarseBlock3DConnector::Type11) - { - lMinX1 = minX1 + minOffX1; - lMaxX1 = maxX1 - 1; - lMinX2 = minX2 + minOffX2; - lMaxX2 = maxX2 - 1; - } - findCFCells(lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, iNodeSetReceiver); - break; - - //edges - //N-S-E-W - case NE: case SW: case SE: case NW: - if (sendDir == NE) - { - lMinX1 = maxX1 - 3; - lMaxX1 = lMinX1 + 2; - lMinX2 = maxX2 - 3; - lMaxX2 = lMinX2 + 2; - } - else if (sendDir == SW) - { - lMinX1 = 0; - lMaxX1 = lMinX1 + 3; - lMinX2 = 0; - lMaxX2 = lMinX2 + 3; - } - else if (sendDir == SE) - { - lMinX1 = maxX1 - 3; - lMaxX1 = lMinX1 + 2; - lMinX2 = 0; - lMaxX2 = lMinX2 + 2; - } - else if (sendDir == NW) - { - lMinX1 = 0; - lMaxX1 = lMinX1 + 2; - lMinX2 = maxX2 - 3; - lMaxX2 = lMinX2 + 2; - } - - if (FineToCoarseBlock3DConnector::connType ==FineToCoarseBlock3DConnector::Type00) - { - lMinX3 = minX3; - lMaxX3 = maxX3 + maxOffX3 - 1; - } - else if (FineToCoarseBlock3DConnector::connType ==FineToCoarseBlock3DConnector::Type10) - { - lMinX3 = minX3 + minOffX3; - lMaxX3 = maxX3 - 1; - } - - findCFCells(lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, iNodeSetReceiver); - break; - //T-B-E-W - case TE: case BW: case BE: case TW: - if (sendDir == TE) - { - lMinX1 = maxX1 - 3; - lMaxX1 = lMinX1 + 2; - lMinX3 = maxX3 - 3; - lMaxX3 = lMinX3 + 2; - } - else if (sendDir == BW) - { - lMinX1 = 0; - lMaxX1 = lMinX1 + 2; - lMinX3 = 0; - lMaxX3 = lMinX3 + 2; - } - else if (sendDir == BE) - { - lMinX1 = maxX1 - 3; - lMaxX1 = lMinX1 + 2; - lMinX3 = 0; - lMaxX3 = lMinX3 + 2; - } - else if (sendDir == TW) - { - lMinX1 = 0; - lMaxX1 = lMinX1 + 2; - lMinX3 = maxX3 - 3; - lMaxX3 = lMinX3 + 2; - } - - if (FineToCoarseBlock3DConnector::connType ==FineToCoarseBlock3DConnector::Type00) - { - lMinX2 = minX2; - lMaxX2 = maxX2 + maxOffX2 - 1; - } - else if (FineToCoarseBlock3DConnector::connType ==FineToCoarseBlock3DConnector::Type10) - { - lMinX2 = minX2 + minOffX2; - lMaxX2 = maxX2 - 1; - } - - findCFCells(lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, iNodeSetReceiver); - break; - //T-B-N-S - case TN: case BS: case BN: case TS: - if (sendDir == TN) - { - lMinX2 = maxX2 - 3; - lMaxX2 = lMinX2 + 2; - lMinX3 = maxX3 - 3; - lMaxX3 = lMinX3 + 2; - } - else if (sendDir == BS) - { - lMinX2 = 0; - lMaxX2 = lMinX2 + 2; - lMinX3 = 0; - lMaxX3 = lMinX3 + 2; - } - else if (sendDir == BN) - { - lMinX2 = maxX2 - 3; - lMaxX2 = lMinX2 + 2; - lMinX3 = 0; - lMaxX3 = lMinX3 + 2; - } - else if (sendDir == TS) - { - lMinX2 = 0; - lMaxX2 = lMinX2 + 2; - lMinX3 = maxX3 - 3; - lMaxX3 = lMinX3 + 2; - } - - if (FineToCoarseBlock3DConnector::connType ==FineToCoarseBlock3DConnector::Type00) - { - lMinX1 = minX1; - lMaxX1 = maxX1 + maxOffX1 - 1; - } - else if (FineToCoarseBlock3DConnector::connType ==FineToCoarseBlock3DConnector::Type10) - { - lMinX1 = minX1 + minOffX1; - lMaxX1 = maxX1 - 1; - } - - findCFCells(lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, iNodeSetReceiver); - break; - //corners - case TNE: case TNW: case TSE: case TSW: case BNE: case BNW: case BSE: case BSW: - if (sendDir == TNE) - { - lMinX1 = maxX1 - 3; - lMaxX1 = maxX1 - 1; - lMinX2 = maxX2 - 3; - lMaxX2 = maxX2 - 1; - lMinX3 = maxX3 - 3; - lMaxX3 = maxX3 - 1; - } - else if (sendDir == TNW) - { - lMinX1 = 0; - lMaxX1 = 2; - lMinX2 = maxX2 - 3; - lMaxX2 = maxX2 - 1; - lMinX3 = maxX3 - 3; - lMaxX3 = maxX3 - 1; - } - else if (sendDir == TSE) - { - lMinX1 = maxX1 - 3; - lMaxX1 = maxX1 - 1; - lMinX2 = 0; - lMaxX2 = 2; - lMinX3 = maxX3 - 3; - lMaxX3 = maxX3 - 1; - } - else if (sendDir == TSW) - { - lMinX1 = 0; - lMaxX1 = 2; - lMinX2 = 0; - lMaxX2 = 2; - lMinX3 = maxX3 - 3; - lMaxX3 = maxX3 - 1; - } - else if (sendDir == BNE) - { - lMinX1 = maxX1 - 3; - lMaxX1 = maxX1 - 1; - lMinX2 = maxX2 - 3; - lMaxX2 = maxX2 - 1; - lMinX3 = 0; - lMaxX3 = 2; - } - else if (sendDir == BNW) - { - lMinX1 = 0; - lMaxX1 = 2; - lMinX2 = maxX2 - 3; - lMaxX2 = maxX2 - 1; - lMinX3 = 0; - lMaxX3 = 2; - } - else if (sendDir == BSE) - { - lMinX1 = maxX1 - 3; - lMaxX1 = maxX1 - 1; - lMinX2 = 0; - lMaxX2 = 2; - lMinX3 = 0; - lMaxX3 = 2; - } - else if (sendDir == BSW) - { - lMinX1 = 0; - lMaxX1 = 2; - lMinX2 = 0; - lMaxX2 = 2; - lMinX3 = 0; - lMaxX3 = 2; - } - findCFCells(lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, iNodeSetReceiver); - break; - } + if (FineToCoarseBlock3DConnector::connType == FineToCoarseBlock3DConnector::Type00) { + lMinX1 = minX1; + lMaxX1 = maxX1 + maxOffX1 - 1; + lMinX2 = minX2; + lMaxX2 = maxX2 + maxOffX2 - 1; + } else if (FineToCoarseBlock3DConnector::connType == FineToCoarseBlock3DConnector::Type10) { + lMinX1 = minX1 + minOffX1; + lMaxX1 = maxX1 - 1; + lMinX2 = minX2; + lMaxX2 = maxX2 + maxOffX2 - 1; + } else if (FineToCoarseBlock3DConnector::connType == FineToCoarseBlock3DConnector::Type01) { + lMinX1 = minX1; + lMaxX1 = maxX1 + maxOffX1 - 1; + lMinX2 = minX2 + minOffX2; + lMaxX2 = maxX2 - 1; + } else if (FineToCoarseBlock3DConnector::connType == FineToCoarseBlock3DConnector::Type11) { + lMinX1 = minX1 + minOffX1; + lMaxX1 = maxX1 - 1; + lMinX2 = minX2 + minOffX2; + lMaxX2 = maxX2 - 1; + } + findCFCells(lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, iNodeSetReceiver); + break; + + // edges + // N-S-E-W + case NE: + case SW: + case SE: + case NW: + if (sendDir == NE) { + lMinX1 = maxX1 - 3; + lMaxX1 = lMinX1 + 2; + lMinX2 = maxX2 - 3; + lMaxX2 = lMinX2 + 2; + } else if (sendDir == SW) { + lMinX1 = 0; + lMaxX1 = lMinX1 + 3; + lMinX2 = 0; + lMaxX2 = lMinX2 + 3; + } else if (sendDir == SE) { + lMinX1 = maxX1 - 3; + lMaxX1 = lMinX1 + 2; + lMinX2 = 0; + lMaxX2 = lMinX2 + 2; + } else if (sendDir == NW) { + lMinX1 = 0; + lMaxX1 = lMinX1 + 2; + lMinX2 = maxX2 - 3; + lMaxX2 = lMinX2 + 2; + } + + if (FineToCoarseBlock3DConnector::connType == FineToCoarseBlock3DConnector::Type00) { + lMinX3 = minX3; + lMaxX3 = maxX3 + maxOffX3 - 1; + } else if (FineToCoarseBlock3DConnector::connType == FineToCoarseBlock3DConnector::Type10) { + lMinX3 = minX3 + minOffX3; + lMaxX3 = maxX3 - 1; + } + + findCFCells(lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, iNodeSetReceiver); + break; + // T-B-E-W + case TE: + case BW: + case BE: + case TW: + if (sendDir == TE) { + lMinX1 = maxX1 - 3; + lMaxX1 = lMinX1 + 2; + lMinX3 = maxX3 - 3; + lMaxX3 = lMinX3 + 2; + } else if (sendDir == BW) { + lMinX1 = 0; + lMaxX1 = lMinX1 + 2; + lMinX3 = 0; + lMaxX3 = lMinX3 + 2; + } else if (sendDir == BE) { + lMinX1 = maxX1 - 3; + lMaxX1 = lMinX1 + 2; + lMinX3 = 0; + lMaxX3 = lMinX3 + 2; + } else if (sendDir == TW) { + lMinX1 = 0; + lMaxX1 = lMinX1 + 2; + lMinX3 = maxX3 - 3; + lMaxX3 = lMinX3 + 2; + } + + if (FineToCoarseBlock3DConnector::connType == FineToCoarseBlock3DConnector::Type00) { + lMinX2 = minX2; + lMaxX2 = maxX2 + maxOffX2 - 1; + } else if (FineToCoarseBlock3DConnector::connType == FineToCoarseBlock3DConnector::Type10) { + lMinX2 = minX2 + minOffX2; + lMaxX2 = maxX2 - 1; + } + + findCFCells(lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, iNodeSetReceiver); + break; + // T-B-N-S + case TN: + case BS: + case BN: + case TS: + if (sendDir == TN) { + lMinX2 = maxX2 - 3; + lMaxX2 = lMinX2 + 2; + lMinX3 = maxX3 - 3; + lMaxX3 = lMinX3 + 2; + } else if (sendDir == BS) { + lMinX2 = 0; + lMaxX2 = lMinX2 + 2; + lMinX3 = 0; + lMaxX3 = lMinX3 + 2; + } else if (sendDir == BN) { + lMinX2 = maxX2 - 3; + lMaxX2 = lMinX2 + 2; + lMinX3 = 0; + lMaxX3 = lMinX3 + 2; + } else if (sendDir == TS) { + lMinX2 = 0; + lMaxX2 = lMinX2 + 2; + lMinX3 = maxX3 - 3; + lMaxX3 = lMinX3 + 2; + } + + if (FineToCoarseBlock3DConnector::connType == FineToCoarseBlock3DConnector::Type00) { + lMinX1 = minX1; + lMaxX1 = maxX1 + maxOffX1 - 1; + } else if (FineToCoarseBlock3DConnector::connType == FineToCoarseBlock3DConnector::Type10) { + lMinX1 = minX1 + minOffX1; + lMaxX1 = maxX1 - 1; + } + + findCFCells(lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, iNodeSetReceiver); + break; + // corners + case TNE: + case TNW: + case TSE: + case TSW: + case BNE: + case BNW: + case BSE: + case BSW: + if (sendDir == TNE) { + lMinX1 = maxX1 - 3; + lMaxX1 = maxX1 - 1; + lMinX2 = maxX2 - 3; + lMaxX2 = maxX2 - 1; + lMinX3 = maxX3 - 3; + lMaxX3 = maxX3 - 1; + } else if (sendDir == TNW) { + lMinX1 = 0; + lMaxX1 = 2; + lMinX2 = maxX2 - 3; + lMaxX2 = maxX2 - 1; + lMinX3 = maxX3 - 3; + lMaxX3 = maxX3 - 1; + } else if (sendDir == TSE) { + lMinX1 = maxX1 - 3; + lMaxX1 = maxX1 - 1; + lMinX2 = 0; + lMaxX2 = 2; + lMinX3 = maxX3 - 3; + lMaxX3 = maxX3 - 1; + } else if (sendDir == TSW) { + lMinX1 = 0; + lMaxX1 = 2; + lMinX2 = 0; + lMaxX2 = 2; + lMinX3 = maxX3 - 3; + lMaxX3 = maxX3 - 1; + } else if (sendDir == BNE) { + lMinX1 = maxX1 - 3; + lMaxX1 = maxX1 - 1; + lMinX2 = maxX2 - 3; + lMaxX2 = maxX2 - 1; + lMinX3 = 0; + lMaxX3 = 2; + } else if (sendDir == BNW) { + lMinX1 = 0; + lMaxX1 = 2; + lMinX2 = maxX2 - 3; + lMaxX2 = maxX2 - 1; + lMinX3 = 0; + lMaxX3 = 2; + } else if (sendDir == BSE) { + lMinX1 = maxX1 - 3; + lMaxX1 = maxX1 - 1; + lMinX2 = 0; + lMaxX2 = 2; + lMinX3 = 0; + lMaxX3 = 2; + } else if (sendDir == BSW) { + lMinX1 = 0; + lMaxX1 = 2; + lMinX2 = 0; + lMaxX2 = 2; + lMinX3 = 0; + lMaxX3 = 2; + } + findCFCells(lMinX1, lMinX2, lMinX3, lMaxX1, lMaxX2, lMaxX3, iNodeSetReceiver); + break; + } } ////////////////////////////////////////////////////////////////////////// void FineToCoarseNodeSetBlock3DConnector::distributeReceiveVectors() { - using namespace D3Q27System; + using namespace D3Q27System; - SPtr<DistributionArray3D> fTo = FineToCoarseBlock3DConnector::block.lock()->getKernel()->getDataSet()->getFdistributions(); + SPtr<DistributionArray3D> fTo = + FineToCoarseBlock3DConnector::block.lock()->getKernel()->getDataSet()->getFdistributions(); - int index = 0; + int index = 0; - vector_type& data = this->receiver->getData(); + vector_type &data = this->receiver->getData(); - for(INodeVector inode : iNodeSetReceiver) - { - D3Q27ICell icellF; - this->readICellFfromData(data, index, icellF); - iprocessor->writeICellInv(fTo, icellF, inode[0], inode[1], inode[2]); - } + for (INodeVector inode : iNodeSetReceiver) { + D3Q27ICell icellF; + this->readICellFfromData(data, index, icellF); + iprocessor->writeICellInv(fTo, icellF, inode[0], inode[1], inode[2]); + } } ////////////////////////////////////////////////////////////////////////// // -//void FineToCoarseNodeSetBlock3DConnector::getLocalMinMax(int& minX1, int& minX2, int& minX3, int& maxX1, int& maxX2, int& maxX3) +// void FineToCoarseNodeSetBlock3DConnector::getLocalMinMax(int& minX1, int& minX2, int& minX3, int& maxX1, int& maxX2, +// int& maxX3) //{ // using namespace D3Q27System; -// int TminX1 = minX1; int TminX2 = minX2; int TminX3 = minX3; int TmaxX1 = maxX1; int TmaxX2 = maxX2; int TmaxX3 = maxX3; +// int TminX1 = minX1; int TminX2 = minX2; int TminX3 = minX3; int TmaxX1 = maxX1; int TmaxX2 = maxX2; int TmaxX3 = +// maxX3; // // if (block.lock()->hasInterpolationFlagFC(E)) // { @@ -1165,44 +1040,52 @@ void FineToCoarseNodeSetBlock3DConnector::distributeReceiveVectors() // // //////////// // /////E-W-N-S -// if (block.lock()->hasInterpolationFlagFC(NE)&& !block.lock()->hasInterpolationFlagFC(N) && !block.lock()->hasInterpolationFlagFC(E)) +// if (block.lock()->hasInterpolationFlagFC(NE)&& !block.lock()->hasInterpolationFlagFC(N) && +// !block.lock()->hasInterpolationFlagFC(E)) // { // if (maxX1==TmaxX1) maxX1 -= 2; // if (maxX2==TmaxX2) maxX2 -= 2; // } -// if (block.lock()->hasInterpolationFlagFC(SW)&& !block.lock()->hasInterpolationFlagFC(W) && !block.lock()->hasInterpolationFlagFC(S)) +// if (block.lock()->hasInterpolationFlagFC(SW)&& !block.lock()->hasInterpolationFlagFC(W) && +// !block.lock()->hasInterpolationFlagFC(S)) // { // if (minX1==TminX1) minX1 += 4; // if (minX2==TminX2) minX2 += 4; // } -// if (block.lock()->hasInterpolationFlagFC(SE)&& !block.lock()->hasInterpolationFlagFC(E) && !block.lock()->hasInterpolationFlagFC(S)) +// if (block.lock()->hasInterpolationFlagFC(SE)&& !block.lock()->hasInterpolationFlagFC(E) && +// !block.lock()->hasInterpolationFlagFC(S)) // { // if (maxX1==TmaxX1) maxX1 -= 2; // if (minX2==TminX2) minX2 += 4; // } -// if (block.lock()->hasInterpolationFlagFC(NW)&& !block.lock()->hasInterpolationFlagFC(N) && !block.lock()->hasInterpolationFlagFC(W)) +// if (block.lock()->hasInterpolationFlagFC(NW)&& !block.lock()->hasInterpolationFlagFC(N) && +// !block.lock()->hasInterpolationFlagFC(W)) // { // if (minX1==TminX1) minX1 += 4; // if (maxX2==TmaxX2) maxX2 -= 2; // } // // //////T-B-E-W -// if (block.lock()->hasInterpolationFlagFC(TE) && !block.lock()->hasInterpolationFlagFC(E) && !block.lock()->hasInterpolationFlagFC(T)) +// if (block.lock()->hasInterpolationFlagFC(TE) && !block.lock()->hasInterpolationFlagFC(E) && +// !block.lock()->hasInterpolationFlagFC(T)) // { // if (maxX1==TmaxX1) maxX1 -= 2; // if (maxX3==TmaxX3) maxX3 -= 2; // } -// if (block.lock()->hasInterpolationFlagFC(BW)&& !block.lock()->hasInterpolationFlagFC(W) && !block.lock()->hasInterpolationFlagFC(B)) +// if (block.lock()->hasInterpolationFlagFC(BW)&& !block.lock()->hasInterpolationFlagFC(W) && +// !block.lock()->hasInterpolationFlagFC(B)) // { // if (minX1==TminX1) minX1 += 4; // if (minX3==TminX3) minX3 += 4; // } -// if (block.lock()->hasInterpolationFlagFC(BE)&& !block.lock()->hasInterpolationFlagFC(E) && !block.lock()->hasInterpolationFlagFC(B)) +// if (block.lock()->hasInterpolationFlagFC(BE)&& !block.lock()->hasInterpolationFlagFC(E) && +// !block.lock()->hasInterpolationFlagFC(B)) // { // if (maxX1==TmaxX1) maxX1 -= 2; // if (minX3==TminX3) minX3 += 4; // } -// if (block.lock()->hasInterpolationFlagFC(TW)&& !block.lock()->hasInterpolationFlagFC(W) && !block.lock()->hasInterpolationFlagFC(T)) +// if (block.lock()->hasInterpolationFlagFC(TW)&& !block.lock()->hasInterpolationFlagFC(W) && +// !block.lock()->hasInterpolationFlagFC(T)) // { // if (minX1==TminX1) minX1 += 4; // if (maxX3==TmaxX3) maxX3 -= 2; @@ -1210,26 +1093,29 @@ void FineToCoarseNodeSetBlock3DConnector::distributeReceiveVectors() // // // ////T-B-N-S -// if (block.lock()->hasInterpolationFlagFC(TN)&& !block.lock()->hasInterpolationFlagFC(N) && !block.lock()->hasInterpolationFlagFC(T)) +// if (block.lock()->hasInterpolationFlagFC(TN)&& !block.lock()->hasInterpolationFlagFC(N) && +// !block.lock()->hasInterpolationFlagFC(T)) // { // if (maxX2==TmaxX2) maxX2 -= 2; // if (maxX3==TmaxX3) maxX3 -= 2; // } -// if (block.lock()->hasInterpolationFlagFC(BS)&& !block.lock()->hasInterpolationFlagFC(S) && !block.lock()->hasInterpolationFlagFC(B)) +// if (block.lock()->hasInterpolationFlagFC(BS)&& !block.lock()->hasInterpolationFlagFC(S) && +// !block.lock()->hasInterpolationFlagFC(B)) // { // if (minX2==TminX2) minX2 += 4; // if (minX3==TminX3) minX3 += 4; // } -// if (block.lock()->hasInterpolationFlagFC(BN)&& !block.lock()->hasInterpolationFlagFC(N) && !block.lock()->hasInterpolationFlagFC(B)) +// if (block.lock()->hasInterpolationFlagFC(BN)&& !block.lock()->hasInterpolationFlagFC(N) && +// !block.lock()->hasInterpolationFlagFC(B)) // { // if (maxX2==TmaxX2) maxX2 -= 2; // if (minX3==TminX3) minX3 += 4; // } -// if (block.lock()->hasInterpolationFlagFC(TS) && !block.lock()->hasInterpolationFlagFC(S) && !block.lock()->hasInterpolationFlagFC(T)) +// if (block.lock()->hasInterpolationFlagFC(TS) && !block.lock()->hasInterpolationFlagFC(S) && +// !block.lock()->hasInterpolationFlagFC(T)) // { // if (minX2==TminX2) minX2 += 4; // if (maxX3==TmaxX3) maxX3 -= 2; // } //} ////////////////////////////////////////////////////////////////////////// - diff --git a/src/cpu/VirtualFluidsCore/Connectors/FineToCoarseNodeSetBlock3DConnector.h b/src/cpu/VirtualFluidsCore/Connectors/FineToCoarseNodeSetBlock3DConnector.h index 0c10e7778392513f379b07236d280407880cc6ce..bcf29041e06c85611fd478704c09491c0c0a67da 100644 --- a/src/cpu/VirtualFluidsCore/Connectors/FineToCoarseNodeSetBlock3DConnector.h +++ b/src/cpu/VirtualFluidsCore/Connectors/FineToCoarseNodeSetBlock3DConnector.h @@ -1,78 +1,74 @@ /// \file CoarseToFineNodeSetBlock3DConnector.h /// \class CoarseToFineNodeSetBlock3DConnector -/// \brief Connector interpolates and sends data from coarse level to fine. +/// \brief Connector interpolates and sends data from coarse level to fine. /// \author Konstantin Kutscher /// \date 21.05.2015 #ifndef FineToCoarseNodeSetBlock3DConnector_H #define FineToCoarseNodeSetBlock3DConnector_H -#include <vector> -#include "FineToCoarseBlock3DConnector.h" -#include "D3Q27System.h" #include "Block3D.h" +#include "D3Q27System.h" +#include "FineToCoarseBlock3DConnector.h" #include "Grid3D.h" -#include "LBMKernel.h" #include "InterpolationProcessor.h" +#include "LBMKernel.h" #include "MathUtil.hpp" #include <PointerDefinitions.h> - +#include <vector> class Block3D; -//daten werden in einen vector (dieser befindet sich im transmitter) kopiert -//der vector wird via transmitter uebertragen -//transmitter kann ein lokal, MPI, RCG, CTL oder was auch immer fuer ein -//transmitter sein, der von Transmitter abgeleitet ist ;-) +// daten werden in einen vector (dieser befindet sich im transmitter) kopiert +// der vector wird via transmitter uebertragen +// transmitter kann ein lokal, MPI, RCG, CTL oder was auch immer fuer ein +// transmitter sein, der von Transmitter abgeleitet ist ;-) class FineToCoarseNodeSetBlock3DConnector : public FineToCoarseBlock3DConnector { public: - FineToCoarseNodeSetBlock3DConnector(SPtr<Block3D> block, VectorTransmitterPtr sender, VectorTransmitterPtr receiver, int sendDir, InterpolationProcessorPtr iprocessor, CFconnectorType connType); - void init() override; - void fillSendVectors() override; - void distributeReceiveVectors() override; + FineToCoarseNodeSetBlock3DConnector(SPtr<Block3D> block, VectorTransmitterPtr sender, VectorTransmitterPtr receiver, + int sendDir, InterpolationProcessorPtr iprocessor, CFconnectorType connType); + void init() override; + void fillSendVectors() override; + void distributeReceiveVectors() override; + protected: - using INodeVector = std::vector<int>; - using INodeSet = std::vector<INodeVector>; - INodeSet iNodeSetSender; - INodeSet iNodeSetReceiver; + using INodeVector = std::vector<int>; + using INodeSet = std::vector<INodeVector>; + INodeSet iNodeSetSender; + INodeSet iNodeSetReceiver; - void readICellFfromData(vector_type& data, int& index, D3Q27ICell& icellF); - void readNodeFromVector(vector_type& data, int& index, LBMReal* inode); + void readICellFfromData(vector_type &data, int &index, D3Q27ICell &icellF); + void readNodeFromVector(vector_type &data, int &index, LBMReal *inode); - void writeICellCtoData(vector_type& data, int& index, LBMReal* icellC); + void writeICellCtoData(vector_type &data, int &index, LBMReal *icellC); - void findFCCells(); - void findFCCells(int lMinX1, int lMinX2, int lMinX3, int lMaxX1, int lMaxX2, int lMaxX3, INodeSet &inodes); + void findFCCells(); + void findFCCells(int lMinX1, int lMinX2, int lMinX3, int lMaxX1, int lMaxX2, int lMaxX3, INodeSet &inodes); - void findCFCells(); - void findCFCells(int lMinX1, int lMinX2, int lMinX3, int lMaxX1, int lMaxX2, int lMaxX3, INodeSet &inodes); + void findCFCells(); + void findCFCells(int lMinX1, int lMinX2, int lMinX3, int lMaxX1, int lMaxX2, int lMaxX3, INodeSet &inodes); - //void getLocalMinMax(int& minX1, int& minX2, int& minX3, int& maxX1, int& maxX2, int& maxX3); + // void getLocalMinMax(int& minX1, int& minX2, int& minX3, int& maxX1, int& maxX2, int& maxX3); + int bMaxX1, bMaxX2, bMaxX3; - int bMaxX1, bMaxX2, bMaxX3; - - int minX1; - int minX2; - int minX3; + int minX1; + int minX2; + int minX3; - int maxX1; - int maxX2; - int maxX3; + int maxX1; + int maxX2; + int maxX3; - int minOffX1; - int minOffX2; - int minOffX3; + int minOffX1; + int minOffX2; + int minOffX3; - int maxOffX1; - int maxOffX2; - int maxOffX3; + int maxOffX1; + int maxOffX2; + int maxOffX3; }; - - - - #endif diff --git a/src/cpu/VirtualFluidsCore/Connectors/LocalBlock3DConnector.h b/src/cpu/VirtualFluidsCore/Connectors/LocalBlock3DConnector.h index 90790ce7d2e1545bbabb3dcd263fb98c4e05e77c..9e8819ebd645ade3b17b2cb1e3a3f2d2c7c67d0c 100644 --- a/src/cpu/VirtualFluidsCore/Connectors/LocalBlock3DConnector.h +++ b/src/cpu/VirtualFluidsCore/Connectors/LocalBlock3DConnector.h @@ -1,28 +1,28 @@ //======================================================================================= -// ____ ____ __ ______ __________ __ __ __ __ -// \ \ | | | | | _ \ |___ ___| | | | | / \ | | -// \ \ | | | | | |_) | | | | | | | / \ | | -// \ \ | | | | | _ / | | | | | | / /\ \ | | -// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ -// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| -// \ \ | | ________________________________________________________________ -// \ \ | | | ______________________________________________________________| -// \ \| | | | __ __ __ __ ______ _______ -// \ | | |_____ | | | | | | | | | _ \ / _____) -// \ | | _____| | | | | | | | | | | \ \ \_______ +// ____ ____ __ ______ __________ __ __ __ __ +// \ \ | | | | | _ \ |___ ___| | | | | / \ | | +// \ \ | | | | | |_) | | | | | | | / \ | | +// \ \ | | | | | _ / | | | | | | / /\ \ | | +// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ +// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| +// \ \ | | ________________________________________________________________ +// \ \ | | | ______________________________________________________________| +// \ \| | | | __ __ __ __ ______ _______ +// \ | | |_____ | | | | | | | | | _ \ / _____) +// \ | | _____| | | | | | | | | | | \ \ \_______ // \ | | | | |_____ | \_/ | | | | |_/ / _____ | -// \ _____| |__| |________| \_______/ |__| |______/ (_______/ +// \ _____| |__| |________| \_______/ |__| |______/ (_______/ // -// This file is part of VirtualFluids. VirtualFluids is free software: you can +// This file is part of VirtualFluids. VirtualFluids is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of +// License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. -// -// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// +// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License along // with VirtualFluids (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>. // @@ -34,59 +34,56 @@ #ifndef LocalBlock3DConnector_H #define LocalBlock3DConnector_H -#include "Block3DConnector.h" #include "Block3D.h" +#include "Block3DConnector.h" #include "PointerDefinitions.h" //! A class provides an interface for connectors in shared memory class LocalBlock3DConnector : public Block3DConnector { public: - LocalBlock3DConnector(SPtr<Block3D> from, SPtr<Block3D> to, int sendDir) - : Block3DConnector(sendDir) - , from(from) - , to(to) - { - - } - ~LocalBlock3DConnector() override = default; - void sendTransmitterDataSize() override {} - void receiveTransmitterDataSize() override {} - void init() override = 0; - void prepareForReceive() override {} - void prepareForSend() override {} - void fillSendVectors() override {} - void sendVectors() override =0; - void receiveVectors() override {} + LocalBlock3DConnector(SPtr<Block3D> from, SPtr<Block3D> to, int sendDir) + : Block3DConnector(sendDir), from(from), to(to) + { + } + ~LocalBlock3DConnector() override = default; + void sendTransmitterDataSize() override {} + void receiveTransmitterDataSize() override {} + void init() override = 0; + void prepareForReceive() override {} + void prepareForSend() override {} + void fillSendVectors() override {} + void sendVectors() override = 0; + void receiveVectors() override {} - void distributeReceiveVectors() override {} + void distributeReceiveVectors() override {} - bool isLocalConnector() override { return true; } - bool isRemoteConnector() override { return false; } - bool isInterpolationConnectorCF() override { return false; } - bool isInterpolationConnectorFC() override { return false; } + bool isLocalConnector() override { return true; } + bool isRemoteConnector() override { return false; } + bool isInterpolationConnectorCF() override { return false; } + bool isInterpolationConnectorFC() override { return false; } - double getSendRecieveTime(); + double getSendRecieveTime(); - void prepareForSendX1() override {} - void prepareForSendX2() override {} - void prepareForSendX3() override {} + void prepareForSendX1() override {} + void prepareForSendX2() override {} + void prepareForSendX3() override {} - void sendVectorsX1() override {} - void sendVectorsX2() override {} - void sendVectorsX3() override {} + void sendVectorsX1() override {} + void sendVectorsX2() override {} + void sendVectorsX3() override {} - void prepareForReceiveX1() override {} - void prepareForReceiveX2() override {} - void prepareForReceiveX3() override {} + void prepareForReceiveX1() override {} + void prepareForReceiveX2() override {} + void prepareForReceiveX3() override {} - void receiveVectorsX1() override {} - void receiveVectorsX2() override {} - void receiveVectorsX3() override {} + void receiveVectorsX1() override {} + void receiveVectorsX2() override {} + void receiveVectorsX3() override {} protected: - WPtr<Block3D> from; - WPtr<Block3D> to; + WPtr<Block3D> from; + WPtr<Block3D> to; }; -#endif //LocalBlock3DConnector_H +#endif // LocalBlock3DConnector_H diff --git a/src/cpu/VirtualFluidsCore/Connectors/RemoteBlock3DConnector.cpp b/src/cpu/VirtualFluidsCore/Connectors/RemoteBlock3DConnector.cpp index e7adf6a63f95407ebf7f7617920131c2f3d63fa3..cc59274656a27cb9c79c2faf6ec3750081fefa22 100644 --- a/src/cpu/VirtualFluidsCore/Connectors/RemoteBlock3DConnector.cpp +++ b/src/cpu/VirtualFluidsCore/Connectors/RemoteBlock3DConnector.cpp @@ -1,64 +1,61 @@ #include "RemoteBlock3DConnector.h" ////////////////////////////////////////////////////////////////////////// -RemoteBlock3DConnector::RemoteBlock3DConnector(SPtr<Block3D> block - , VectorTransmitterPtr sender - , VectorTransmitterPtr receiver - , int sendDir) - : Block3DConnector(sendDir) - , block(block) - , sender(sender) - , receiver(receiver) +RemoteBlock3DConnector::RemoteBlock3DConnector(SPtr<Block3D> block, VectorTransmitterPtr sender, + VectorTransmitterPtr receiver, int sendDir) + : Block3DConnector(sendDir), block(block), sender(sender), receiver(receiver) { - if (!block || !sender || !receiver) - UB_THROW(UbException(UB_EXARGS, "sender or receiver == NULL!!")); + if (!block || !sender || !receiver) + UB_THROW(UbException(UB_EXARGS, "sender or receiver == NULL!!")); } ////////////////////////////////////////////////////////////////////////// -bool RemoteBlock3DConnector::isLocalConnector() -{ - return !this->isRemoteConnector(); -} +bool RemoteBlock3DConnector::isLocalConnector() { return !this->isRemoteConnector(); } ////////////////////////////////////////////////////////////////////////// bool RemoteBlock3DConnector::isRemoteConnector() { - return ((sender && sender->isRemoteTransmitter()) - || (receiver && receiver->isRemoteTransmitter())); + return ((sender && sender->isRemoteTransmitter()) || (receiver && receiver->isRemoteTransmitter())); } ////////////////////////////////////////////////////////////////////////// void RemoteBlock3DConnector::sendTransmitterDataSize() { - assert(sender !=NULL); sender->sendDataSize(); + assert(sender != NULL); + sender->sendDataSize(); } ////////////////////////////////////////////////////////////////////////// void RemoteBlock3DConnector::receiveTransmitterDataSize() { - assert(receiver!=NULL); receiver->receiveDataSize(); + assert(receiver != NULL); + receiver->receiveDataSize(); } ////////////////////////////////////////////////////////////////////////// void RemoteBlock3DConnector::prepareForSend() { - assert(sender !=NULL); sender->prepareForSend(); + assert(sender != NULL); + sender->prepareForSend(); } ////////////////////////////////////////////////////////////////////////// void RemoteBlock3DConnector::sendVectors() { - assert(sender !=NULL); sender->sendData(); + assert(sender != NULL); + sender->sendData(); } ////////////////////////////////////////////////////////////////////////// void RemoteBlock3DConnector::prepareForReceive() { - assert(receiver!=NULL); receiver->prepareForReceive(); + assert(receiver != NULL); + receiver->prepareForReceive(); } ////////////////////////////////////////////////////////////////////////// void RemoteBlock3DConnector::receiveVectors() { - assert(receiver!=NULL); receiver->receiveData(); + assert(receiver != NULL); + receiver->receiveData(); } diff --git a/src/cpu/VirtualFluidsCore/Connectors/RemoteBlock3DConnector.h b/src/cpu/VirtualFluidsCore/Connectors/RemoteBlock3DConnector.h index 95d34f91fa2520d2b477a1f892826f8165616830..00276a5b2656e8362e59bf29f6166ab8e8263531 100644 --- a/src/cpu/VirtualFluidsCore/Connectors/RemoteBlock3DConnector.h +++ b/src/cpu/VirtualFluidsCore/Connectors/RemoteBlock3DConnector.h @@ -3,70 +3,65 @@ #include <vector> -#include "TransmitterType.h" +#include "Block3D.h" #include "Block3DConnector.h" #include "D3Q27System.h" -#include "Block3D.h" -#include "LBMKernel.h" #include "EsoTwistD3Q27System.h" +#include "LBMKernel.h" +#include "TransmitterType.h" - -//daten werden in einen vector (dieser befindet sich im transmitter) kopiert -//der vector wird via transmitter uebertragen -//transmitter kann ein lokal, MPI, RCG, CTL oder was auch immer fuer ein -//transmitter sein, der von Transmitter abgeleitet ist ;-) +// daten werden in einen vector (dieser befindet sich im transmitter) kopiert +// der vector wird via transmitter uebertragen +// transmitter kann ein lokal, MPI, RCG, CTL oder was auch immer fuer ein +// transmitter sein, der von Transmitter abgeleitet ist ;-) class RemoteBlock3DConnector : public Block3DConnector { public: - RemoteBlock3DConnector(SPtr<Block3D> block - , VectorTransmitterPtr sender - , VectorTransmitterPtr receiver - , int sendDir); + RemoteBlock3DConnector(SPtr<Block3D> block, VectorTransmitterPtr sender, VectorTransmitterPtr receiver, + int sendDir); - bool isLocalConnector() override; - bool isRemoteConnector() override; + bool isLocalConnector() override; + bool isRemoteConnector() override; - void init() override = 0; + void init() override = 0; - void sendTransmitterDataSize() override; - void receiveTransmitterDataSize() override; + void sendTransmitterDataSize() override; + void receiveTransmitterDataSize() override; - void prepareForSend() override; - void sendVectors() override; + void prepareForSend() override; + void sendVectors() override; - void prepareForReceive() override; - void receiveVectors() override; + void prepareForReceive() override; + void receiveVectors() override; - void fillSendVectors() override = 0; - void distributeReceiveVectors() override = 0; + void fillSendVectors() override = 0; + void distributeReceiveVectors() override = 0; - bool isInterpolationConnectorCF() override { return false; } - bool isInterpolationConnectorFC() override { return false; } + bool isInterpolationConnectorCF() override { return false; } + bool isInterpolationConnectorFC() override { return false; } - double getSendRecieveTime() { return 0; } + double getSendRecieveTime() { return 0; } - void prepareForSendX1() override {} - void prepareForSendX2() override {} - void prepareForSendX3() override {} + void prepareForSendX1() override {} + void prepareForSendX2() override {} + void prepareForSendX3() override {} - void sendVectorsX1() override {} - void sendVectorsX2() override {} - void sendVectorsX3() override {} + void sendVectorsX1() override {} + void sendVectorsX2() override {} + void sendVectorsX3() override {} - void prepareForReceiveX1() override {} - void prepareForReceiveX2() override {} - void prepareForReceiveX3() override {} + void prepareForReceiveX1() override {} + void prepareForReceiveX2() override {} + void prepareForReceiveX3() override {} - void receiveVectorsX1() override {} - void receiveVectorsX2() override {} - void receiveVectorsX3() override {} + void receiveVectorsX1() override {} + void receiveVectorsX2() override {} + void receiveVectorsX3() override {} protected: - WPtr<Block3D> block; - VectorTransmitterPtr sender; - VectorTransmitterPtr receiver; + WPtr<Block3D> block; + VectorTransmitterPtr sender; + VectorTransmitterPtr receiver; }; - -#endif //RemoteBlock3DConnector_H - +#endif // RemoteBlock3DConnector_H diff --git a/src/cpu/VirtualFluidsCore/Connectors/TransmitterType.h b/src/cpu/VirtualFluidsCore/Connectors/TransmitterType.h index 27300328c3be08a9a2e9f038f07bf68de916dc20..3690bb917ffe0d2e37c04d5250015253c6e596a2 100644 --- a/src/cpu/VirtualFluidsCore/Connectors/TransmitterType.h +++ b/src/cpu/VirtualFluidsCore/Connectors/TransmitterType.h @@ -1,16 +1,14 @@ #ifndef TransmitterType_h__ #define TransmitterType_h__ +#include "D3Q27System.h" +#include "basics/container/CbVector.h" #include "basics/transmitter/TbTransmitter.h" #include "basics/transmitter/TbTransmitterLocal.h" -#include "basics/container/CbVector.h" -#include "D3Q27System.h" #include <PointerDefinitions.h> - -using VectorTransmitter = TbTransmitter<CbVector<LBMReal> >; -using vector_type = VectorTransmitter::value_type; -using VectorTransmitterPtr = SPtr<TbTransmitter<CbVector<LBMReal> > >; +using VectorTransmitter = TbTransmitter<CbVector<LBMReal>>; +using vector_type = VectorTransmitter::value_type; +using VectorTransmitterPtr = SPtr<TbTransmitter<CbVector<LBMReal>>>; #endif // TransmitterType_h__ - diff --git a/src/cpu/VirtualFluidsCore/Data/D3Q27EsoTwist3DSoA.cpp b/src/cpu/VirtualFluidsCore/Data/D3Q27EsoTwist3DSoA.cpp index 77da3c462c156e080d763d98ccd36b7d056d03d7..d75c90c9dc74a19296950d58f08d05d8a982c791 100644 --- a/src/cpu/VirtualFluidsCore/Data/D3Q27EsoTwist3DSoA.cpp +++ b/src/cpu/VirtualFluidsCore/Data/D3Q27EsoTwist3DSoA.cpp @@ -1,591 +1,610 @@ #include "D3Q27EsoTwist3DSoA.h" -#include <D3Q27System.h> #include "EsoTwistD3Q27System.h" +#include <D3Q27System.h> -D3Q27EsoTwist3DSoA::D3Q27EsoTwist3DSoA() -= default; +D3Q27EsoTwist3DSoA::D3Q27EsoTwist3DSoA() = default; ////////////////////////////////////////////////////////////////////////// -D3Q27EsoTwist3DSoA::D3Q27EsoTwist3DSoA( const size_t& nx1, const size_t& nx2, const size_t& nx3, LBMReal value ) +D3Q27EsoTwist3DSoA::D3Q27EsoTwist3DSoA(const size_t &nx1, const size_t &nx2, const size_t &nx3, LBMReal value) { - this->NX1 = nx1; - this->NX2 = nx2; - this->NX3 = nx3; + this->NX1 = nx1; + this->NX2 = nx2; + this->NX3 = nx3; - d.E = CbArray3D<LBMReal,IndexerX3X2X1>::CbArray3DPtr(new CbArray3D<LBMReal,IndexerX3X2X1>(nx1+1, nx2+1, nx3+1, value)); - d.W = CbArray3D<LBMReal,IndexerX3X2X1>::CbArray3DPtr(new CbArray3D<LBMReal,IndexerX3X2X1>(nx1+1, nx2+1, nx3+1, value)); - d.N = CbArray3D<LBMReal,IndexerX3X2X1>::CbArray3DPtr(new CbArray3D<LBMReal,IndexerX3X2X1>(nx1+1, nx2+1, nx3+1, value)); - d.S = CbArray3D<LBMReal,IndexerX3X2X1>::CbArray3DPtr(new CbArray3D<LBMReal,IndexerX3X2X1>(nx1+1, nx2+1, nx3+1, value)); - d.T = CbArray3D<LBMReal,IndexerX3X2X1>::CbArray3DPtr(new CbArray3D<LBMReal,IndexerX3X2X1>(nx1+1, nx2+1, nx3+1, value)); - d.B = CbArray3D<LBMReal,IndexerX3X2X1>::CbArray3DPtr(new CbArray3D<LBMReal,IndexerX3X2X1>(nx1+1, nx2+1, nx3+1, value)); - d.NE = CbArray3D<LBMReal,IndexerX3X2X1>::CbArray3DPtr(new CbArray3D<LBMReal,IndexerX3X2X1>(nx1+1, nx2+1, nx3+1, value)); - d.SW = CbArray3D<LBMReal,IndexerX3X2X1>::CbArray3DPtr(new CbArray3D<LBMReal,IndexerX3X2X1>(nx1+1, nx2+1, nx3+1, value)); - d.SE = CbArray3D<LBMReal,IndexerX3X2X1>::CbArray3DPtr(new CbArray3D<LBMReal,IndexerX3X2X1>(nx1+1, nx2+1, nx3+1, value)); - d.NW = CbArray3D<LBMReal,IndexerX3X2X1>::CbArray3DPtr(new CbArray3D<LBMReal,IndexerX3X2X1>(nx1+1, nx2+1, nx3+1, value)); - d.TE = CbArray3D<LBMReal,IndexerX3X2X1>::CbArray3DPtr(new CbArray3D<LBMReal,IndexerX3X2X1>(nx1+1, nx2+1, nx3+1, value)); - d.BW = CbArray3D<LBMReal,IndexerX3X2X1>::CbArray3DPtr(new CbArray3D<LBMReal,IndexerX3X2X1>(nx1+1, nx2+1, nx3+1, value)); - d.BE = CbArray3D<LBMReal,IndexerX3X2X1>::CbArray3DPtr(new CbArray3D<LBMReal,IndexerX3X2X1>(nx1+1, nx2+1, nx3+1, value)); - d.TW = CbArray3D<LBMReal,IndexerX3X2X1>::CbArray3DPtr(new CbArray3D<LBMReal,IndexerX3X2X1>(nx1+1, nx2+1, nx3+1, value)); - d.TN = CbArray3D<LBMReal,IndexerX3X2X1>::CbArray3DPtr(new CbArray3D<LBMReal,IndexerX3X2X1>(nx1+1, nx2+1, nx3+1, value)); - d.BS = CbArray3D<LBMReal,IndexerX3X2X1>::CbArray3DPtr(new CbArray3D<LBMReal,IndexerX3X2X1>(nx1+1, nx2+1, nx3+1, value)); - d.BN = CbArray3D<LBMReal,IndexerX3X2X1>::CbArray3DPtr(new CbArray3D<LBMReal,IndexerX3X2X1>(nx1+1, nx2+1, nx3+1, value)); - d.TS = CbArray3D<LBMReal,IndexerX3X2X1>::CbArray3DPtr(new CbArray3D<LBMReal,IndexerX3X2X1>(nx1+1, nx2+1, nx3+1, value)); - d.TNE = CbArray3D<LBMReal,IndexerX3X2X1>::CbArray3DPtr(new CbArray3D<LBMReal,IndexerX3X2X1>(nx1+1, nx2+1, nx3+1, value)); - d.TNW = CbArray3D<LBMReal,IndexerX3X2X1>::CbArray3DPtr(new CbArray3D<LBMReal,IndexerX3X2X1>(nx1+1, nx2+1, nx3+1, value)); - d.TSE = CbArray3D<LBMReal,IndexerX3X2X1>::CbArray3DPtr(new CbArray3D<LBMReal,IndexerX3X2X1>(nx1+1, nx2+1, nx3+1, value)); - d.TSW = CbArray3D<LBMReal,IndexerX3X2X1>::CbArray3DPtr(new CbArray3D<LBMReal,IndexerX3X2X1>(nx1+1, nx2+1, nx3+1, value)); - d.BNE = CbArray3D<LBMReal,IndexerX3X2X1>::CbArray3DPtr(new CbArray3D<LBMReal,IndexerX3X2X1>(nx1+1, nx2+1, nx3+1, value)); - d.BNW = CbArray3D<LBMReal,IndexerX3X2X1>::CbArray3DPtr(new CbArray3D<LBMReal,IndexerX3X2X1>(nx1+1, nx2+1, nx3+1, value)); - d.BSE = CbArray3D<LBMReal,IndexerX3X2X1>::CbArray3DPtr(new CbArray3D<LBMReal,IndexerX3X2X1>(nx1+1, nx2+1, nx3+1, value)); - d.BSW = CbArray3D<LBMReal,IndexerX3X2X1>::CbArray3DPtr(new CbArray3D<LBMReal,IndexerX3X2X1>(nx1+1, nx2+1, nx3+1, value)); - d.ZERO= CbArray3D<LBMReal,IndexerX3X2X1>::CbArray3DPtr(new CbArray3D<LBMReal,IndexerX3X2X1>(nx1, nx2, nx3, value)); + d.E = CbArray3D<LBMReal, IndexerX3X2X1>::CbArray3DPtr( + new CbArray3D<LBMReal, IndexerX3X2X1>(nx1 + 1, nx2 + 1, nx3 + 1, value)); + d.W = CbArray3D<LBMReal, IndexerX3X2X1>::CbArray3DPtr( + new CbArray3D<LBMReal, IndexerX3X2X1>(nx1 + 1, nx2 + 1, nx3 + 1, value)); + d.N = CbArray3D<LBMReal, IndexerX3X2X1>::CbArray3DPtr( + new CbArray3D<LBMReal, IndexerX3X2X1>(nx1 + 1, nx2 + 1, nx3 + 1, value)); + d.S = CbArray3D<LBMReal, IndexerX3X2X1>::CbArray3DPtr( + new CbArray3D<LBMReal, IndexerX3X2X1>(nx1 + 1, nx2 + 1, nx3 + 1, value)); + d.T = CbArray3D<LBMReal, IndexerX3X2X1>::CbArray3DPtr( + new CbArray3D<LBMReal, IndexerX3X2X1>(nx1 + 1, nx2 + 1, nx3 + 1, value)); + d.B = CbArray3D<LBMReal, IndexerX3X2X1>::CbArray3DPtr( + new CbArray3D<LBMReal, IndexerX3X2X1>(nx1 + 1, nx2 + 1, nx3 + 1, value)); + d.NE = CbArray3D<LBMReal, IndexerX3X2X1>::CbArray3DPtr( + new CbArray3D<LBMReal, IndexerX3X2X1>(nx1 + 1, nx2 + 1, nx3 + 1, value)); + d.SW = CbArray3D<LBMReal, IndexerX3X2X1>::CbArray3DPtr( + new CbArray3D<LBMReal, IndexerX3X2X1>(nx1 + 1, nx2 + 1, nx3 + 1, value)); + d.SE = CbArray3D<LBMReal, IndexerX3X2X1>::CbArray3DPtr( + new CbArray3D<LBMReal, IndexerX3X2X1>(nx1 + 1, nx2 + 1, nx3 + 1, value)); + d.NW = CbArray3D<LBMReal, IndexerX3X2X1>::CbArray3DPtr( + new CbArray3D<LBMReal, IndexerX3X2X1>(nx1 + 1, nx2 + 1, nx3 + 1, value)); + d.TE = CbArray3D<LBMReal, IndexerX3X2X1>::CbArray3DPtr( + new CbArray3D<LBMReal, IndexerX3X2X1>(nx1 + 1, nx2 + 1, nx3 + 1, value)); + d.BW = CbArray3D<LBMReal, IndexerX3X2X1>::CbArray3DPtr( + new CbArray3D<LBMReal, IndexerX3X2X1>(nx1 + 1, nx2 + 1, nx3 + 1, value)); + d.BE = CbArray3D<LBMReal, IndexerX3X2X1>::CbArray3DPtr( + new CbArray3D<LBMReal, IndexerX3X2X1>(nx1 + 1, nx2 + 1, nx3 + 1, value)); + d.TW = CbArray3D<LBMReal, IndexerX3X2X1>::CbArray3DPtr( + new CbArray3D<LBMReal, IndexerX3X2X1>(nx1 + 1, nx2 + 1, nx3 + 1, value)); + d.TN = CbArray3D<LBMReal, IndexerX3X2X1>::CbArray3DPtr( + new CbArray3D<LBMReal, IndexerX3X2X1>(nx1 + 1, nx2 + 1, nx3 + 1, value)); + d.BS = CbArray3D<LBMReal, IndexerX3X2X1>::CbArray3DPtr( + new CbArray3D<LBMReal, IndexerX3X2X1>(nx1 + 1, nx2 + 1, nx3 + 1, value)); + d.BN = CbArray3D<LBMReal, IndexerX3X2X1>::CbArray3DPtr( + new CbArray3D<LBMReal, IndexerX3X2X1>(nx1 + 1, nx2 + 1, nx3 + 1, value)); + d.TS = CbArray3D<LBMReal, IndexerX3X2X1>::CbArray3DPtr( + new CbArray3D<LBMReal, IndexerX3X2X1>(nx1 + 1, nx2 + 1, nx3 + 1, value)); + d.TNE = CbArray3D<LBMReal, IndexerX3X2X1>::CbArray3DPtr( + new CbArray3D<LBMReal, IndexerX3X2X1>(nx1 + 1, nx2 + 1, nx3 + 1, value)); + d.TNW = CbArray3D<LBMReal, IndexerX3X2X1>::CbArray3DPtr( + new CbArray3D<LBMReal, IndexerX3X2X1>(nx1 + 1, nx2 + 1, nx3 + 1, value)); + d.TSE = CbArray3D<LBMReal, IndexerX3X2X1>::CbArray3DPtr( + new CbArray3D<LBMReal, IndexerX3X2X1>(nx1 + 1, nx2 + 1, nx3 + 1, value)); + d.TSW = CbArray3D<LBMReal, IndexerX3X2X1>::CbArray3DPtr( + new CbArray3D<LBMReal, IndexerX3X2X1>(nx1 + 1, nx2 + 1, nx3 + 1, value)); + d.BNE = CbArray3D<LBMReal, IndexerX3X2X1>::CbArray3DPtr( + new CbArray3D<LBMReal, IndexerX3X2X1>(nx1 + 1, nx2 + 1, nx3 + 1, value)); + d.BNW = CbArray3D<LBMReal, IndexerX3X2X1>::CbArray3DPtr( + new CbArray3D<LBMReal, IndexerX3X2X1>(nx1 + 1, nx2 + 1, nx3 + 1, value)); + d.BSE = CbArray3D<LBMReal, IndexerX3X2X1>::CbArray3DPtr( + new CbArray3D<LBMReal, IndexerX3X2X1>(nx1 + 1, nx2 + 1, nx3 + 1, value)); + d.BSW = CbArray3D<LBMReal, IndexerX3X2X1>::CbArray3DPtr( + new CbArray3D<LBMReal, IndexerX3X2X1>(nx1 + 1, nx2 + 1, nx3 + 1, value)); + d.ZERO = + CbArray3D<LBMReal, IndexerX3X2X1>::CbArray3DPtr(new CbArray3D<LBMReal, IndexerX3X2X1>(nx1, nx2, nx3, value)); } ////////////////////////////////////////////////////////////////////////// -D3Q27EsoTwist3DSoA::~D3Q27EsoTwist3DSoA() -= default; +D3Q27EsoTwist3DSoA::~D3Q27EsoTwist3DSoA() = default; ////////////////////////////////////////////////////////////////////////// void D3Q27EsoTwist3DSoA::swap() { - std::swap(d.E , d.W ); - std::swap(d.N , d.S ); - std::swap(d.T , d.B ); - std::swap(d.NE , d.SW ); - std::swap(d.NW , d.SE ); - std::swap(d.TE , d.BW ); - std::swap(d.TW , d.BE ); - std::swap(d.TN , d.BS ); - std::swap(d.TS , d.BN ); - std::swap(d.TNE, d.BSW); - std::swap(d.TNW, d.BSE); - std::swap(d.TSE, d.BNW); - std::swap(d.TSW, d.BNE); + std::swap(d.E, d.W); + std::swap(d.N, d.S); + std::swap(d.T, d.B); + std::swap(d.NE, d.SW); + std::swap(d.NW, d.SE); + std::swap(d.TE, d.BW); + std::swap(d.TW, d.BE); + std::swap(d.TN, d.BS); + std::swap(d.TS, d.BN); + std::swap(d.TNE, d.BSW); + std::swap(d.TNW, d.BSE); + std::swap(d.TSE, d.BNW); + std::swap(d.TSW, d.BNE); } ////////////////////////////////////////////////////////////////////////// -void D3Q27EsoTwist3DSoA::getDistribution(LBMReal* const f, size_t x1, size_t x2, size_t x3) +void D3Q27EsoTwist3DSoA::getDistribution(LBMReal *const f, size_t x1, size_t x2, size_t x3) { - size_t x1p = x1 + 1; - size_t x2p = x2 + 1; - size_t x3p = x3 + 1; + size_t x1p = x1 + 1; + size_t x2p = x2 + 1; + size_t x3p = x3 + 1; - f[D3Q27System::E] = (*d.E)(x1,x2,x3); - f[D3Q27System::N] = (*d.N)(x1,x2,x3); - f[D3Q27System::T] = (*d.T)(x1,x2,x3); - f[D3Q27System::NE] = (*d.NE)(x1,x2,x3); - f[D3Q27System::NW] = (*d.NW)(x1p,x2,x3); - f[D3Q27System::TE] = (*d.TE)(x1,x2,x3); - f[D3Q27System::TW] = (*d.TW)(x1p,x2,x3); - f[D3Q27System::TN] = (*d.TN)(x1,x2,x3); - f[D3Q27System::TS] = (*d.TS)(x1,x2p,x3); - f[D3Q27System::TNE] = (*d.TNE)(x1,x2,x3); - f[D3Q27System::TNW] = (*d.TNW)(x1p,x2,x3); - f[D3Q27System::TSE] = (*d.TSE)(x1,x2p,x3); - f[D3Q27System::TSW] = (*d.TSW)(x1p,x2p,x3); + f[D3Q27System::E] = (*d.E)(x1, x2, x3); + f[D3Q27System::N] = (*d.N)(x1, x2, x3); + f[D3Q27System::T] = (*d.T)(x1, x2, x3); + f[D3Q27System::NE] = (*d.NE)(x1, x2, x3); + f[D3Q27System::NW] = (*d.NW)(x1p, x2, x3); + f[D3Q27System::TE] = (*d.TE)(x1, x2, x3); + f[D3Q27System::TW] = (*d.TW)(x1p, x2, x3); + f[D3Q27System::TN] = (*d.TN)(x1, x2, x3); + f[D3Q27System::TS] = (*d.TS)(x1, x2p, x3); + f[D3Q27System::TNE] = (*d.TNE)(x1, x2, x3); + f[D3Q27System::TNW] = (*d.TNW)(x1p, x2, x3); + f[D3Q27System::TSE] = (*d.TSE)(x1, x2p, x3); + f[D3Q27System::TSW] = (*d.TSW)(x1p, x2p, x3); - f[D3Q27System::W ] = (*d.W)(x1p,x2,x3); - f[D3Q27System::S ] = (*d.S)(x1,x2p,x3); - f[D3Q27System::B ] = (*d.B)(x1,x2,x3p); - f[D3Q27System::SW] = (*d.SW)(x1p,x2p,x3); - f[D3Q27System::SE] = (*d.SE)(x1,x2p,x3); - f[D3Q27System::BW] = (*d.BW)(x1p,x2,x3p); - f[D3Q27System::BE] = (*d.BE)(x1,x2,x3p); - f[D3Q27System::BS] = (*d.BS)(x1,x2p,x3p); - f[D3Q27System::BN] = (*d.BN)(x1,x2,x3p); - f[D3Q27System::BSW] = (*d.BSW)(x1p,x2p,x3p); - f[D3Q27System::BSE] = (*d.BSE)(x1,x2p,x3p); - f[D3Q27System::BNW] = (*d.BNW)(x1p,x2,x3p); - f[D3Q27System::BNE] = (*d.BNE)(x1,x2,x3p); + f[D3Q27System::W] = (*d.W)(x1p, x2, x3); + f[D3Q27System::S] = (*d.S)(x1, x2p, x3); + f[D3Q27System::B] = (*d.B)(x1, x2, x3p); + f[D3Q27System::SW] = (*d.SW)(x1p, x2p, x3); + f[D3Q27System::SE] = (*d.SE)(x1, x2p, x3); + f[D3Q27System::BW] = (*d.BW)(x1p, x2, x3p); + f[D3Q27System::BE] = (*d.BE)(x1, x2, x3p); + f[D3Q27System::BS] = (*d.BS)(x1, x2p, x3p); + f[D3Q27System::BN] = (*d.BN)(x1, x2, x3p); + f[D3Q27System::BSW] = (*d.BSW)(x1p, x2p, x3p); + f[D3Q27System::BSE] = (*d.BSE)(x1, x2p, x3p); + f[D3Q27System::BNW] = (*d.BNW)(x1p, x2, x3p); + f[D3Q27System::BNE] = (*d.BNE)(x1, x2, x3p); - f[D3Q27System::ZERO] = (*d.ZERO)(x1,x2,x3); + f[D3Q27System::ZERO] = (*d.ZERO)(x1, x2, x3); } ////////////////////////////////////////////////////////////////////////// -void D3Q27EsoTwist3DSoA::setDistribution(const LBMReal* const f, size_t x1, size_t x2, size_t x3) +void D3Q27EsoTwist3DSoA::setDistribution(const LBMReal *const f, size_t x1, size_t x2, size_t x3) { - size_t x1p = x1 + 1; - size_t x2p = x2 + 1; - size_t x3p = x3 + 1; + size_t x1p = x1 + 1; + size_t x2p = x2 + 1; + size_t x3p = x3 + 1; - (*d.E)(x1,x2,x3) = f[D3Q27System::INV_E]; - (*d.N)(x1,x2,x3) = f[D3Q27System::INV_N]; - (*d.T)(x1,x2,x3) = f[D3Q27System::INV_T]; - (*d.NE)(x1,x2,x3) = f[D3Q27System::INV_NE]; - (*d.NW)(x1p,x2,x3) = f[D3Q27System::INV_NW]; - (*d.TE)(x1,x2,x3) = f[D3Q27System::INV_TE]; - (*d.TW)(x1p,x2,x3) = f[D3Q27System::INV_TW]; - (*d.TN)(x1,x2,x3) = f[D3Q27System::INV_TN]; - (*d.TS)(x1,x2p,x3) = f[D3Q27System::INV_TS]; - (*d.TNE)(x1,x2,x3) = f[D3Q27System::INV_TNE]; - (*d.TNW)(x1p,x2,x3) = f[D3Q27System::INV_TNW]; - (*d.TSE)(x1,x2p,x3) = f[D3Q27System::INV_TSE]; - (*d.TSW)(x1p,x2p,x3) = f[D3Q27System::INV_TSW]; + (*d.E)(x1, x2, x3) = f[D3Q27System::INV_E]; + (*d.N)(x1, x2, x3) = f[D3Q27System::INV_N]; + (*d.T)(x1, x2, x3) = f[D3Q27System::INV_T]; + (*d.NE)(x1, x2, x3) = f[D3Q27System::INV_NE]; + (*d.NW)(x1p, x2, x3) = f[D3Q27System::INV_NW]; + (*d.TE)(x1, x2, x3) = f[D3Q27System::INV_TE]; + (*d.TW)(x1p, x2, x3) = f[D3Q27System::INV_TW]; + (*d.TN)(x1, x2, x3) = f[D3Q27System::INV_TN]; + (*d.TS)(x1, x2p, x3) = f[D3Q27System::INV_TS]; + (*d.TNE)(x1, x2, x3) = f[D3Q27System::INV_TNE]; + (*d.TNW)(x1p, x2, x3) = f[D3Q27System::INV_TNW]; + (*d.TSE)(x1, x2p, x3) = f[D3Q27System::INV_TSE]; + (*d.TSW)(x1p, x2p, x3) = f[D3Q27System::INV_TSW]; - (*d.W)(x1p,x2,x3) = f[D3Q27System::INV_W ]; - (*d.S)(x1,x2p,x3) = f[D3Q27System::INV_S ]; - (*d.B)(x1,x2,x3p) = f[D3Q27System::INV_B ]; - (*d.SW)(x1p,x2p,x3) = f[D3Q27System::INV_SW]; - (*d.SE)(x1,x2p,x3) = f[D3Q27System::INV_SE]; - (*d.BW)(x1p,x2,x3p) = f[D3Q27System::INV_BW]; - (*d.BE)(x1,x2,x3p) = f[D3Q27System::INV_BE]; - (*d.BS)(x1,x2p,x3p) = f[D3Q27System::INV_BS]; - (*d.BN)(x1,x2,x3p) = f[D3Q27System::INV_BN]; - (*d.BSW)(x1p,x2p,x3p) = f[D3Q27System::INV_BSW]; - (*d.BSE)(x1,x2p,x3p) = f[D3Q27System::INV_BSE]; - (*d.BNW)(x1p,x2,x3p) = f[D3Q27System::INV_BNW]; - (*d.BNE)(x1,x2,x3p) = f[D3Q27System::INV_BNE]; + (*d.W)(x1p, x2, x3) = f[D3Q27System::INV_W]; + (*d.S)(x1, x2p, x3) = f[D3Q27System::INV_S]; + (*d.B)(x1, x2, x3p) = f[D3Q27System::INV_B]; + (*d.SW)(x1p, x2p, x3) = f[D3Q27System::INV_SW]; + (*d.SE)(x1, x2p, x3) = f[D3Q27System::INV_SE]; + (*d.BW)(x1p, x2, x3p) = f[D3Q27System::INV_BW]; + (*d.BE)(x1, x2, x3p) = f[D3Q27System::INV_BE]; + (*d.BS)(x1, x2p, x3p) = f[D3Q27System::INV_BS]; + (*d.BN)(x1, x2, x3p) = f[D3Q27System::INV_BN]; + (*d.BSW)(x1p, x2p, x3p) = f[D3Q27System::INV_BSW]; + (*d.BSE)(x1, x2p, x3p) = f[D3Q27System::INV_BSE]; + (*d.BNW)(x1p, x2, x3p) = f[D3Q27System::INV_BNW]; + (*d.BNE)(x1, x2, x3p) = f[D3Q27System::INV_BNE]; - (*d.ZERO)(x1,x2,x3) = f[D3Q27System::ZERO]; + (*d.ZERO)(x1, x2, x3) = f[D3Q27System::ZERO]; } ////////////////////////////////////////////////////////////////////////// -void D3Q27EsoTwist3DSoA::getDistributionInv(LBMReal* const f, size_t x1, size_t x2, size_t x3) +void D3Q27EsoTwist3DSoA::getDistributionInv(LBMReal *const f, size_t x1, size_t x2, size_t x3) { - f[D3Q27System::INV_E] = (*d.E)(x1,x2,x3); - f[D3Q27System::INV_N] = (*d.N)(x1,x2,x3); - f[D3Q27System::INV_T] = (*d.T)(x1,x2,x3); - f[D3Q27System::INV_NE] = (*d.NE)(x1,x2,x3); - f[D3Q27System::INV_NW] = (*d.NW)(x1+1,x2,x3); - f[D3Q27System::INV_TE] = (*d.TE)(x1,x2,x3); - f[D3Q27System::INV_TW] = (*d.TW)(x1+1,x2,x3); - f[D3Q27System::INV_TN] = (*d.TN)(x1,x2,x3); - f[D3Q27System::INV_TS] = (*d.TS)(x1,x2+1,x3); - f[D3Q27System::INV_TNE] = (*d.TNE)(x1,x2,x3); - f[D3Q27System::INV_TNW] = (*d.TNW)(x1+1,x2,x3); - f[D3Q27System::INV_TSE] = (*d.TSE)(x1,x2+1,x3); - f[D3Q27System::INV_TSW] = (*d.TSW)(x1+1,x2+1,x3); + f[D3Q27System::INV_E] = (*d.E)(x1, x2, x3); + f[D3Q27System::INV_N] = (*d.N)(x1, x2, x3); + f[D3Q27System::INV_T] = (*d.T)(x1, x2, x3); + f[D3Q27System::INV_NE] = (*d.NE)(x1, x2, x3); + f[D3Q27System::INV_NW] = (*d.NW)(x1 + 1, x2, x3); + f[D3Q27System::INV_TE] = (*d.TE)(x1, x2, x3); + f[D3Q27System::INV_TW] = (*d.TW)(x1 + 1, x2, x3); + f[D3Q27System::INV_TN] = (*d.TN)(x1, x2, x3); + f[D3Q27System::INV_TS] = (*d.TS)(x1, x2 + 1, x3); + f[D3Q27System::INV_TNE] = (*d.TNE)(x1, x2, x3); + f[D3Q27System::INV_TNW] = (*d.TNW)(x1 + 1, x2, x3); + f[D3Q27System::INV_TSE] = (*d.TSE)(x1, x2 + 1, x3); + f[D3Q27System::INV_TSW] = (*d.TSW)(x1 + 1, x2 + 1, x3); - f[D3Q27System::INV_W ] = (*d.W)(x1+1,x2,x3 ); - f[D3Q27System::INV_S ] = (*d.S)(x1,x2+1,x3 ); - f[D3Q27System::INV_B ] = (*d.B)(x1,x2,x3+1 ); - f[D3Q27System::INV_SW] = (*d.SW)(x1+1,x2+1,x3 ); - f[D3Q27System::INV_SE] = (*d.SE)(x1,x2+1,x3 ); - f[D3Q27System::INV_BW] = (*d.BW)(x1+1,x2,x3+1 ); - f[D3Q27System::INV_BE] = (*d.BE)(x1,x2,x3+1 ); - f[D3Q27System::INV_BS] = (*d.BS)(x1,x2+1,x3+1 ); - f[D3Q27System::INV_BN] = (*d.BN)(x1,x2,x3+1 ); - f[D3Q27System::INV_BSW] = (*d.BSW)(x1+1,x2+1,x3+1); - f[D3Q27System::INV_BSE] = (*d.BSE)(x1,x2+1,x3+1); - f[D3Q27System::INV_BNW] = (*d.BNW)(x1+1,x2,x3+1); - f[D3Q27System::INV_BNE] = (*d.BNE)(x1,x2,x3+1); + f[D3Q27System::INV_W] = (*d.W)(x1 + 1, x2, x3); + f[D3Q27System::INV_S] = (*d.S)(x1, x2 + 1, x3); + f[D3Q27System::INV_B] = (*d.B)(x1, x2, x3 + 1); + f[D3Q27System::INV_SW] = (*d.SW)(x1 + 1, x2 + 1, x3); + f[D3Q27System::INV_SE] = (*d.SE)(x1, x2 + 1, x3); + f[D3Q27System::INV_BW] = (*d.BW)(x1 + 1, x2, x3 + 1); + f[D3Q27System::INV_BE] = (*d.BE)(x1, x2, x3 + 1); + f[D3Q27System::INV_BS] = (*d.BS)(x1, x2 + 1, x3 + 1); + f[D3Q27System::INV_BN] = (*d.BN)(x1, x2, x3 + 1); + f[D3Q27System::INV_BSW] = (*d.BSW)(x1 + 1, x2 + 1, x3 + 1); + f[D3Q27System::INV_BSE] = (*d.BSE)(x1, x2 + 1, x3 + 1); + f[D3Q27System::INV_BNW] = (*d.BNW)(x1 + 1, x2, x3 + 1); + f[D3Q27System::INV_BNE] = (*d.BNE)(x1, x2, x3 + 1); - f[D3Q27System::ZERO] = (*d.ZERO)(x1,x2,x3); + f[D3Q27System::ZERO] = (*d.ZERO)(x1, x2, x3); } ////////////////////////////////////////////////////////////////////////// -void D3Q27EsoTwist3DSoA::setDistributionInv(const LBMReal* const f, size_t x1, size_t x2, size_t x3) +void D3Q27EsoTwist3DSoA::setDistributionInv(const LBMReal *const f, size_t x1, size_t x2, size_t x3) { - //(*this->localDistributions)(D3Q27System::ET_E,x1, x2, x3) = f[D3Q27System::E]; - //(*this->localDistributions)(D3Q27System::ET_N,x1, x2, x3) = f[D3Q27System::N]; - //(*this->localDistributions)(D3Q27System::ET_T,x1, x2, x3) = f[D3Q27System::T]; - //(*this->localDistributions)(D3Q27System::ET_NE,x1, x2, x3) = f[D3Q27System::NE]; - //(*this->localDistributions)(D3Q27System::ET_NW,x1+1,x2, x3) = f[D3Q27System::NW]; - //(*this->localDistributions)(D3Q27System::ET_TE,x1, x2, x3) = f[D3Q27System::TE]; - //(*this->localDistributions)(D3Q27System::ET_TW,x1+1,x2, x3) = f[D3Q27System::TW]; - //(*this->localDistributions)(D3Q27System::ET_TN,x1, x2, x3) = f[D3Q27System::TN]; - //(*this->localDistributions)(D3Q27System::ET_TS,x1, x2+1,x3) = f[D3Q27System::TS]; - //(*this->localDistributions)(D3Q27System::ET_TNE,x1, x2, x3) = f[D3Q27System::TNE]; - //(*this->localDistributions)(D3Q27System::ET_TNW,x1+1,x2, x3) = f[D3Q27System::TNW]; - //(*this->localDistributions)(D3Q27System::ET_TSE,x1, x2+1,x3) = f[D3Q27System::TSE]; - //(*this->localDistributions)(D3Q27System::ET_TSW,x1+1,x2+1,x3) = f[D3Q27System::TSW]; + //(*this->localDistributions)(D3Q27System::ET_E,x1, x2, x3) = f[D3Q27System::E]; + //(*this->localDistributions)(D3Q27System::ET_N,x1, x2, x3) = f[D3Q27System::N]; + //(*this->localDistributions)(D3Q27System::ET_T,x1, x2, x3) = f[D3Q27System::T]; + //(*this->localDistributions)(D3Q27System::ET_NE,x1, x2, x3) = f[D3Q27System::NE]; + //(*this->localDistributions)(D3Q27System::ET_NW,x1+1,x2, x3) = f[D3Q27System::NW]; + //(*this->localDistributions)(D3Q27System::ET_TE,x1, x2, x3) = f[D3Q27System::TE]; + //(*this->localDistributions)(D3Q27System::ET_TW,x1+1,x2, x3) = f[D3Q27System::TW]; + //(*this->localDistributions)(D3Q27System::ET_TN,x1, x2, x3) = f[D3Q27System::TN]; + //(*this->localDistributions)(D3Q27System::ET_TS,x1, x2+1,x3) = f[D3Q27System::TS]; + //(*this->localDistributions)(D3Q27System::ET_TNE,x1, x2, x3) = f[D3Q27System::TNE]; + //(*this->localDistributions)(D3Q27System::ET_TNW,x1+1,x2, x3) = f[D3Q27System::TNW]; + //(*this->localDistributions)(D3Q27System::ET_TSE,x1, x2+1,x3) = f[D3Q27System::TSE]; + //(*this->localDistributions)(D3Q27System::ET_TSW,x1+1,x2+1,x3) = f[D3Q27System::TSW]; - //(*this->nonLocalDistributions)(D3Q27System::ET_W,x1+1,x2, x3 ) = f[D3Q27System::W ]; - //(*this->nonLocalDistributions)(D3Q27System::ET_S,x1, x2+1,x3 ) = f[D3Q27System::S ]; - //(*this->nonLocalDistributions)(D3Q27System::ET_B,x1, x2, x3+1 ) = f[D3Q27System::B ]; - //(*this->nonLocalDistributions)(D3Q27System::ET_SW,x1+1,x2+1,x3 ) = f[D3Q27System::SW]; - //(*this->nonLocalDistributions)(D3Q27System::ET_SE,x1, x2+1,x3 ) = f[D3Q27System::SE]; - //(*this->nonLocalDistributions)(D3Q27System::ET_BW,x1+1,x2, x3+1 ) = f[D3Q27System::BW]; - //(*this->nonLocalDistributions)(D3Q27System::ET_BE,x1, x2, x3+1 ) = f[D3Q27System::BE]; - //(*this->nonLocalDistributions)(D3Q27System::ET_BS,x1, x2+1,x3+1 ) = f[D3Q27System::BS]; - //(*this->nonLocalDistributions)(D3Q27System::ET_BN,x1, x2, x3+1 ) = f[D3Q27System::BN]; - //(*this->nonLocalDistributions)(D3Q27System::ET_BSW,x1+1,x2+1,x3+1) = f[D3Q27System::BSW]; - //(*this->nonLocalDistributions)(D3Q27System::ET_BSE,x1, x2+1,x3+1) = f[D3Q27System::BSE]; - //(*this->nonLocalDistributions)(D3Q27System::ET_BNW,x1+1,x2, x3+1) = f[D3Q27System::BNW]; - //(*this->nonLocalDistributions)(D3Q27System::ET_BNE,x1, x2, x3+1) = f[D3Q27System::BNE]; + //(*this->nonLocalDistributions)(D3Q27System::ET_W,x1+1,x2, x3 ) = f[D3Q27System::W ]; + //(*this->nonLocalDistributions)(D3Q27System::ET_S,x1, x2+1,x3 ) = f[D3Q27System::S ]; + //(*this->nonLocalDistributions)(D3Q27System::ET_B,x1, x2, x3+1 ) = f[D3Q27System::B ]; + //(*this->nonLocalDistributions)(D3Q27System::ET_SW,x1+1,x2+1,x3 ) = f[D3Q27System::SW]; + //(*this->nonLocalDistributions)(D3Q27System::ET_SE,x1, x2+1,x3 ) = f[D3Q27System::SE]; + //(*this->nonLocalDistributions)(D3Q27System::ET_BW,x1+1,x2, x3+1 ) = f[D3Q27System::BW]; + //(*this->nonLocalDistributions)(D3Q27System::ET_BE,x1, x2, x3+1 ) = f[D3Q27System::BE]; + //(*this->nonLocalDistributions)(D3Q27System::ET_BS,x1, x2+1,x3+1 ) = f[D3Q27System::BS]; + //(*this->nonLocalDistributions)(D3Q27System::ET_BN,x1, x2, x3+1 ) = f[D3Q27System::BN]; + //(*this->nonLocalDistributions)(D3Q27System::ET_BSW,x1+1,x2+1,x3+1) = f[D3Q27System::BSW]; + //(*this->nonLocalDistributions)(D3Q27System::ET_BSE,x1, x2+1,x3+1) = f[D3Q27System::BSE]; + //(*this->nonLocalDistributions)(D3Q27System::ET_BNW,x1+1,x2, x3+1) = f[D3Q27System::BNW]; + //(*this->nonLocalDistributions)(D3Q27System::ET_BNE,x1, x2, x3+1) = f[D3Q27System::BNE]; - //(*this->zeroDistributions)(x1,x2,x3) = f[D3Q27System::ZERO]; + //(*this->zeroDistributions)(x1,x2,x3) = f[D3Q27System::ZERO]; } ////////////////////////////////////////////////////////////////////////// -void D3Q27EsoTwist3DSoA::setDistributionForDirection(const LBMReal* const f, size_t x1, size_t x2, size_t x3, unsigned long int direction) +void D3Q27EsoTwist3DSoA::setDistributionForDirection(const LBMReal *const f, size_t x1, size_t x2, size_t x3, + unsigned long int direction) { - //bool directionFlag = false; - //if ((direction & EsoTwistD3Q27System::etE) == EsoTwistD3Q27System::etE) - // (*this->nonLocalDistributions)(D3Q27System::ET_W,x1+1,x2, x3 ) = f[D3Q27System::E]; directionFlag=true; - //if ((direction & EsoTwistD3Q27System::etW) == EsoTwistD3Q27System::etW) - // (*this->localDistributions)(D3Q27System::ET_E,x1, x2, x3) = f[D3Q27System::W]; directionFlag=true; - //if ((direction & EsoTwistD3Q27System::etS) == EsoTwistD3Q27System::etS) - // (*this->localDistributions)(D3Q27System::ET_N,x1, x2, x3) = f[D3Q27System::S]; directionFlag=true; - //if ((direction & EsoTwistD3Q27System::etN) == EsoTwistD3Q27System::etN) - // (*this->nonLocalDistributions)(D3Q27System::ET_S,x1, x2+1,x3 ) = f[D3Q27System::N]; directionFlag=true; - //if ((direction & EsoTwistD3Q27System::etB) == EsoTwistD3Q27System::etB) - // (*this->localDistributions)(D3Q27System::ET_T,x1, x2, x3) = f[D3Q27System::B]; directionFlag=true; - //if ((direction & EsoTwistD3Q27System::etT) == EsoTwistD3Q27System::etT) - // (*this->nonLocalDistributions)(D3Q27System::ET_B,x1, x2, x3+1 ) = f[D3Q27System::T]; directionFlag=true; - //if ((direction & EsoTwistD3Q27System::etSW) == EsoTwistD3Q27System::etSW) - // (*this->localDistributions)(D3Q27System::ET_NE,x1, x2, x3) = f[D3Q27System::SW]; directionFlag=true; - //if ((direction & EsoTwistD3Q27System::etNE) == EsoTwistD3Q27System::etNE) - // (*this->nonLocalDistributions)(D3Q27System::ET_SW,x1+1,x2+1,x3 ) = f[D3Q27System::NE]; directionFlag=true; - //if ((direction & EsoTwistD3Q27System::etNW) == EsoTwistD3Q27System::etNW) - // (*this->nonLocalDistributions)(D3Q27System::ET_SE,x1, x2+1,x3 ) = f[D3Q27System::NW]; directionFlag=true; - //if ((direction & EsoTwistD3Q27System::etSE) == EsoTwistD3Q27System::etSE) - // (*this->localDistributions)(D3Q27System::ET_NW,x1+1,x2, x3) = f[D3Q27System::SE]; directionFlag=true; - //if ((direction & EsoTwistD3Q27System::etBW) == EsoTwistD3Q27System::etBW) - // (*this->localDistributions)(D3Q27System::ET_TE,x1, x2, x3) = f[D3Q27System::BW]; directionFlag=true; - //if ((direction & EsoTwistD3Q27System::etTE) == EsoTwistD3Q27System::etTE) - // (*this->nonLocalDistributions)(D3Q27System::ET_BW,x1+1,x2, x3+1 ) = f[D3Q27System::TE]; directionFlag=true; - //if ((direction & EsoTwistD3Q27System::etTW) == EsoTwistD3Q27System::etTW) - // (*this->nonLocalDistributions)(D3Q27System::ET_BE,x1, x2, x3+1 ) = f[D3Q27System::TW]; directionFlag=true; - //if ((direction & EsoTwistD3Q27System::etBE) == EsoTwistD3Q27System::etBE) - // (*this->localDistributions)(D3Q27System::ET_TW,x1+1,x2, x3) = f[D3Q27System::BE]; directionFlag=true; - //if ((direction & EsoTwistD3Q27System::etBS) == EsoTwistD3Q27System::etBS) - // (*this->localDistributions)(D3Q27System::ET_TN,x1, x2, x3) = f[D3Q27System::BS]; directionFlag=true; - //if ((direction & EsoTwistD3Q27System::etTN) == EsoTwistD3Q27System::etTN) - // (*this->nonLocalDistributions)(D3Q27System::ET_BS,x1, x2+1,x3+1 ) = f[D3Q27System::TN]; directionFlag=true; - //if ((direction & EsoTwistD3Q27System::etTS) == EsoTwistD3Q27System::etTS) - // (*this->nonLocalDistributions)(D3Q27System::ET_BN,x1, x2, x3+1 ) = f[D3Q27System::TS]; directionFlag=true; - //if ((direction & EsoTwistD3Q27System::etBN) == EsoTwistD3Q27System::etBN) - // (*this->localDistributions)(D3Q27System::ET_TS,x1, x2+1,x3) = f[D3Q27System::BN]; directionFlag=true; - //if ((direction & EsoTwistD3Q27System::etBSW) == EsoTwistD3Q27System::etBSW) - // (*this->localDistributions)(D3Q27System::ET_TNE,x1, x2, x3) = f[D3Q27System::BSW]; directionFlag=true; - //if ((direction & EsoTwistD3Q27System::etTNE) == EsoTwistD3Q27System::etTNE) - // (*this->nonLocalDistributions)(D3Q27System::ET_BSW,x1+1,x2+1,x3+1) = f[D3Q27System::TNE]; directionFlag=true; - //if ((direction & EsoTwistD3Q27System::etBSE) == EsoTwistD3Q27System::etBSE) - // (*this->localDistributions)(D3Q27System::ET_TNW,x1+1,x2, x3) = f[D3Q27System::BSE]; directionFlag=true; - //if ((direction & EsoTwistD3Q27System::etTNW) == EsoTwistD3Q27System::etTNW) - // (*this->nonLocalDistributions)(D3Q27System::ET_BSE,x1, x2+1,x3+1) = f[D3Q27System::TNW]; directionFlag=true; - //if ((direction & EsoTwistD3Q27System::etBNW) == EsoTwistD3Q27System::etBNW) - // (*this->localDistributions)(D3Q27System::ET_TSE,x1, x2+1,x3) = f[D3Q27System::BNW]; directionFlag=true; - //if ((direction & EsoTwistD3Q27System::etTSE) == EsoTwistD3Q27System::etTSE) - // (*this->nonLocalDistributions)(D3Q27System::ET_BNW,x1+1,x2, x3+1) = f[D3Q27System::TSE]; directionFlag=true; - //if ((direction & EsoTwistD3Q27System::etBNE) == EsoTwistD3Q27System::etBNE) - // (*this->localDistributions)(D3Q27System::ET_TSW,x1+1,x2+1,x3) = f[D3Q27System::BNE]; directionFlag=true; - //if ((direction & EsoTwistD3Q27System::etTSW) == EsoTwistD3Q27System::etTSW) - // (*this->nonLocalDistributions)(D3Q27System::ET_BNE,x1, x2, x3+1) = f[D3Q27System::TSW]; directionFlag=true; - //if ((direction & EsoTwistD3Q27System::ZERO) == EsoTwistD3Q27System::ZERO) - // (*this->zeroDistributions)(x1,x2,x3) = f[D3Q27System::ZERO]; directionFlag=true; -//#ifdef _DEBUG -// if(!directionFlag)UB_THROW( UbException(UB_EXARGS, "Direction didn't find") ); -//#endif //DEBUG + // bool directionFlag = false; + // if ((direction & EsoTwistD3Q27System::etE) == EsoTwistD3Q27System::etE) + // (*this->nonLocalDistributions)(D3Q27System::ET_W,x1+1,x2, x3 ) = f[D3Q27System::E]; directionFlag=true; + // if ((direction & EsoTwistD3Q27System::etW) == EsoTwistD3Q27System::etW) + // (*this->localDistributions)(D3Q27System::ET_E,x1, x2, x3) = f[D3Q27System::W]; directionFlag=true; + // if ((direction & EsoTwistD3Q27System::etS) == EsoTwistD3Q27System::etS) + // (*this->localDistributions)(D3Q27System::ET_N,x1, x2, x3) = f[D3Q27System::S]; directionFlag=true; + // if ((direction & EsoTwistD3Q27System::etN) == EsoTwistD3Q27System::etN) + // (*this->nonLocalDistributions)(D3Q27System::ET_S,x1, x2+1,x3 ) = f[D3Q27System::N]; directionFlag=true; + // if ((direction & EsoTwistD3Q27System::etB) == EsoTwistD3Q27System::etB) + // (*this->localDistributions)(D3Q27System::ET_T,x1, x2, x3) = f[D3Q27System::B]; directionFlag=true; + // if ((direction & EsoTwistD3Q27System::etT) == EsoTwistD3Q27System::etT) + // (*this->nonLocalDistributions)(D3Q27System::ET_B,x1, x2, x3+1 ) = f[D3Q27System::T]; directionFlag=true; + // if ((direction & EsoTwistD3Q27System::etSW) == EsoTwistD3Q27System::etSW) + // (*this->localDistributions)(D3Q27System::ET_NE,x1, x2, x3) = f[D3Q27System::SW]; directionFlag=true; + // if ((direction & EsoTwistD3Q27System::etNE) == EsoTwistD3Q27System::etNE) + // (*this->nonLocalDistributions)(D3Q27System::ET_SW,x1+1,x2+1,x3 ) = f[D3Q27System::NE]; directionFlag=true; + // if ((direction & EsoTwistD3Q27System::etNW) == EsoTwistD3Q27System::etNW) + // (*this->nonLocalDistributions)(D3Q27System::ET_SE,x1, x2+1,x3 ) = f[D3Q27System::NW]; directionFlag=true; + // if ((direction & EsoTwistD3Q27System::etSE) == EsoTwistD3Q27System::etSE) + // (*this->localDistributions)(D3Q27System::ET_NW,x1+1,x2, x3) = f[D3Q27System::SE]; directionFlag=true; + // if ((direction & EsoTwistD3Q27System::etBW) == EsoTwistD3Q27System::etBW) + // (*this->localDistributions)(D3Q27System::ET_TE,x1, x2, x3) = f[D3Q27System::BW]; directionFlag=true; + // if ((direction & EsoTwistD3Q27System::etTE) == EsoTwistD3Q27System::etTE) + // (*this->nonLocalDistributions)(D3Q27System::ET_BW,x1+1,x2, x3+1 ) = f[D3Q27System::TE]; directionFlag=true; + // if ((direction & EsoTwistD3Q27System::etTW) == EsoTwistD3Q27System::etTW) + // (*this->nonLocalDistributions)(D3Q27System::ET_BE,x1, x2, x3+1 ) = f[D3Q27System::TW]; directionFlag=true; + // if ((direction & EsoTwistD3Q27System::etBE) == EsoTwistD3Q27System::etBE) + // (*this->localDistributions)(D3Q27System::ET_TW,x1+1,x2, x3) = f[D3Q27System::BE]; directionFlag=true; + // if ((direction & EsoTwistD3Q27System::etBS) == EsoTwistD3Q27System::etBS) + // (*this->localDistributions)(D3Q27System::ET_TN,x1, x2, x3) = f[D3Q27System::BS]; directionFlag=true; + // if ((direction & EsoTwistD3Q27System::etTN) == EsoTwistD3Q27System::etTN) + // (*this->nonLocalDistributions)(D3Q27System::ET_BS,x1, x2+1,x3+1 ) = f[D3Q27System::TN]; directionFlag=true; + // if ((direction & EsoTwistD3Q27System::etTS) == EsoTwistD3Q27System::etTS) + // (*this->nonLocalDistributions)(D3Q27System::ET_BN,x1, x2, x3+1 ) = f[D3Q27System::TS]; directionFlag=true; + // if ((direction & EsoTwistD3Q27System::etBN) == EsoTwistD3Q27System::etBN) + // (*this->localDistributions)(D3Q27System::ET_TS,x1, x2+1,x3) = f[D3Q27System::BN]; directionFlag=true; + // if ((direction & EsoTwistD3Q27System::etBSW) == EsoTwistD3Q27System::etBSW) + // (*this->localDistributions)(D3Q27System::ET_TNE,x1, x2, x3) = f[D3Q27System::BSW]; directionFlag=true; + // if ((direction & EsoTwistD3Q27System::etTNE) == EsoTwistD3Q27System::etTNE) + // (*this->nonLocalDistributions)(D3Q27System::ET_BSW,x1+1,x2+1,x3+1) = f[D3Q27System::TNE]; directionFlag=true; + // if ((direction & EsoTwistD3Q27System::etBSE) == EsoTwistD3Q27System::etBSE) + // (*this->localDistributions)(D3Q27System::ET_TNW,x1+1,x2, x3) = f[D3Q27System::BSE]; directionFlag=true; + // if ((direction & EsoTwistD3Q27System::etTNW) == EsoTwistD3Q27System::etTNW) + // (*this->nonLocalDistributions)(D3Q27System::ET_BSE,x1, x2+1,x3+1) = f[D3Q27System::TNW]; directionFlag=true; + // if ((direction & EsoTwistD3Q27System::etBNW) == EsoTwistD3Q27System::etBNW) + // (*this->localDistributions)(D3Q27System::ET_TSE,x1, x2+1,x3) = f[D3Q27System::BNW]; directionFlag=true; + // if ((direction & EsoTwistD3Q27System::etTSE) == EsoTwistD3Q27System::etTSE) + // (*this->nonLocalDistributions)(D3Q27System::ET_BNW,x1+1,x2, x3+1) = f[D3Q27System::TSE]; directionFlag=true; + // if ((direction & EsoTwistD3Q27System::etBNE) == EsoTwistD3Q27System::etBNE) + // (*this->localDistributions)(D3Q27System::ET_TSW,x1+1,x2+1,x3) = f[D3Q27System::BNE]; directionFlag=true; + // if ((direction & EsoTwistD3Q27System::etTSW) == EsoTwistD3Q27System::etTSW) + // (*this->nonLocalDistributions)(D3Q27System::ET_BNE,x1, x2, x3+1) = f[D3Q27System::TSW]; directionFlag=true; + // if ((direction & EsoTwistD3Q27System::ZERO) == EsoTwistD3Q27System::ZERO) + // (*this->zeroDistributions)(x1,x2,x3) = f[D3Q27System::ZERO]; directionFlag=true; + //#ifdef _DEBUG + // if(!directionFlag)UB_THROW( UbException(UB_EXARGS, "Direction didn't find") ); + //#endif //DEBUG } ////////////////////////////////////////////////////////////////////////// void D3Q27EsoTwist3DSoA::setDistributionForDirection(LBMReal f, size_t x1, size_t x2, size_t x3, int direction) { - //switch (direction) - //{ - //case D3Q27System::E : - // (*this->nonLocalDistributions)(D3Q27System::ET_W,x1+1,x2, x3 ) = f; - // break; - //case D3Q27System::W : - // (*this->localDistributions)(D3Q27System::ET_E,x1, x2, x3) = f; - // break; - //case D3Q27System::S : - // (*this->localDistributions)(D3Q27System::ET_N,x1, x2, x3) = f; - // break; - //case D3Q27System::N : - // (*this->nonLocalDistributions)(D3Q27System::ET_S,x1, x2+1,x3 ) = f; - // break; - //case D3Q27System::B : - // (*this->localDistributions)(D3Q27System::ET_T,x1, x2, x3) = f; - // break; - //case D3Q27System::T : - // (*this->nonLocalDistributions)(D3Q27System::ET_B,x1, x2, x3+1 ) = f; - // break; - //case D3Q27System::SW : - // (*this->localDistributions)(D3Q27System::ET_NE,x1, x2, x3) = f; - // break; - //case D3Q27System::NE : - // (*this->nonLocalDistributions)(D3Q27System::ET_SW,x1+1,x2+1,x3 ) = f; - // break; - //case D3Q27System::NW : - // (*this->nonLocalDistributions)(D3Q27System::ET_SE,x1, x2+1,x3 ) = f; - // break; - //case D3Q27System::SE : - // (*this->localDistributions)(D3Q27System::ET_NW,x1+1,x2, x3) = f; - // break; - //case D3Q27System::BW : - // (*this->localDistributions)(D3Q27System::ET_TE,x1, x2, x3) = f; - // break; - //case D3Q27System::TE : - // (*this->nonLocalDistributions)(D3Q27System::ET_BW,x1+1,x2, x3+1 ) = f; - // break; - //case D3Q27System::TW : - // (*this->nonLocalDistributions)(D3Q27System::ET_BE,x1, x2, x3+1 ) = f; - // break; - //case D3Q27System::BE : - // (*this->localDistributions)(D3Q27System::ET_TW,x1+1,x2, x3) = f; - // break; - //case D3Q27System::BS : - // (*this->localDistributions)(D3Q27System::ET_TN,x1, x2, x3) = f; - // break; - //case D3Q27System::TN : - // (*this->nonLocalDistributions)(D3Q27System::ET_BS,x1, x2+1,x3+1 ) = f; - // break; - //case D3Q27System::TS : - // (*this->nonLocalDistributions)(D3Q27System::ET_BN,x1, x2, x3+1 ) = f; - // break; - //case D3Q27System::BN : - // (*this->localDistributions)(D3Q27System::ET_TS,x1, x2+1,x3) = f; - // break; - //case D3Q27System::BSW : - // (*this->localDistributions)(D3Q27System::ET_TNE,x1, x2, x3) = f; - // break; - //case D3Q27System::TNE : - // (*this->nonLocalDistributions)(D3Q27System::ET_BSW,x1+1,x2+1,x3+1) = f; - // break; - //case D3Q27System::BSE : - // (*this->localDistributions)(D3Q27System::ET_TNW,x1+1,x2, x3) = f; - // break; - //case D3Q27System::TNW : - // (*this->nonLocalDistributions)(D3Q27System::ET_BSE,x1, x2+1,x3+1) = f; - // break; - //case D3Q27System::BNW : - // (*this->localDistributions)(D3Q27System::ET_TSE,x1, x2+1,x3) = f; - // break; - //case D3Q27System::TSE : - // (*this->nonLocalDistributions)(D3Q27System::ET_BNW,x1+1,x2, x3+1) = f; - // break; - //case D3Q27System::BNE : - // (*this->localDistributions)(D3Q27System::ET_TSW,x1+1,x2+1,x3) = f; - // break; - //case D3Q27System::TSW : - // (*this->nonLocalDistributions)(D3Q27System::ET_BNE,x1, x2, x3+1) = f; - // break; - //case D3Q27System::ZERO : - // (*this->zeroDistributions)(x1,x2,x3) = f; - // break; - //default: - // UB_THROW( UbException(UB_EXARGS, "Direction didn't find") ); - //} + // switch (direction) + //{ + // case D3Q27System::E : + // (*this->nonLocalDistributions)(D3Q27System::ET_W,x1+1,x2, x3 ) = f; + // break; + // case D3Q27System::W : + // (*this->localDistributions)(D3Q27System::ET_E,x1, x2, x3) = f; + // break; + // case D3Q27System::S : + // (*this->localDistributions)(D3Q27System::ET_N,x1, x2, x3) = f; + // break; + // case D3Q27System::N : + // (*this->nonLocalDistributions)(D3Q27System::ET_S,x1, x2+1,x3 ) = f; + // break; + // case D3Q27System::B : + // (*this->localDistributions)(D3Q27System::ET_T,x1, x2, x3) = f; + // break; + // case D3Q27System::T : + // (*this->nonLocalDistributions)(D3Q27System::ET_B,x1, x2, x3+1 ) = f; + // break; + // case D3Q27System::SW : + // (*this->localDistributions)(D3Q27System::ET_NE,x1, x2, x3) = f; + // break; + // case D3Q27System::NE : + // (*this->nonLocalDistributions)(D3Q27System::ET_SW,x1+1,x2+1,x3 ) = f; + // break; + // case D3Q27System::NW : + // (*this->nonLocalDistributions)(D3Q27System::ET_SE,x1, x2+1,x3 ) = f; + // break; + // case D3Q27System::SE : + // (*this->localDistributions)(D3Q27System::ET_NW,x1+1,x2, x3) = f; + // break; + // case D3Q27System::BW : + // (*this->localDistributions)(D3Q27System::ET_TE,x1, x2, x3) = f; + // break; + // case D3Q27System::TE : + // (*this->nonLocalDistributions)(D3Q27System::ET_BW,x1+1,x2, x3+1 ) = f; + // break; + // case D3Q27System::TW : + // (*this->nonLocalDistributions)(D3Q27System::ET_BE,x1, x2, x3+1 ) = f; + // break; + // case D3Q27System::BE : + // (*this->localDistributions)(D3Q27System::ET_TW,x1+1,x2, x3) = f; + // break; + // case D3Q27System::BS : + // (*this->localDistributions)(D3Q27System::ET_TN,x1, x2, x3) = f; + // break; + // case D3Q27System::TN : + // (*this->nonLocalDistributions)(D3Q27System::ET_BS,x1, x2+1,x3+1 ) = f; + // break; + // case D3Q27System::TS : + // (*this->nonLocalDistributions)(D3Q27System::ET_BN,x1, x2, x3+1 ) = f; + // break; + // case D3Q27System::BN : + // (*this->localDistributions)(D3Q27System::ET_TS,x1, x2+1,x3) = f; + // break; + // case D3Q27System::BSW : + // (*this->localDistributions)(D3Q27System::ET_TNE,x1, x2, x3) = f; + // break; + // case D3Q27System::TNE : + // (*this->nonLocalDistributions)(D3Q27System::ET_BSW,x1+1,x2+1,x3+1) = f; + // break; + // case D3Q27System::BSE : + // (*this->localDistributions)(D3Q27System::ET_TNW,x1+1,x2, x3) = f; + // break; + // case D3Q27System::TNW : + // (*this->nonLocalDistributions)(D3Q27System::ET_BSE,x1, x2+1,x3+1) = f; + // break; + // case D3Q27System::BNW : + // (*this->localDistributions)(D3Q27System::ET_TSE,x1, x2+1,x3) = f; + // break; + // case D3Q27System::TSE : + // (*this->nonLocalDistributions)(D3Q27System::ET_BNW,x1+1,x2, x3+1) = f; + // break; + // case D3Q27System::BNE : + // (*this->localDistributions)(D3Q27System::ET_TSW,x1+1,x2+1,x3) = f; + // break; + // case D3Q27System::TSW : + // (*this->nonLocalDistributions)(D3Q27System::ET_BNE,x1, x2, x3+1) = f; + // break; + // case D3Q27System::ZERO : + // (*this->zeroDistributions)(x1,x2,x3) = f; + // break; + // default: + // UB_THROW( UbException(UB_EXARGS, "Direction didn't find") ); + //} } ////////////////////////////////////////////////////////////////////////// -void D3Q27EsoTwist3DSoA::setDistributionInvForDirection(const LBMReal* const f, size_t x1, size_t x2, size_t x3, unsigned long int direction) +void D3Q27EsoTwist3DSoA::setDistributionInvForDirection(const LBMReal *const f, size_t x1, size_t x2, size_t x3, + unsigned long int direction) { -// bool directionFlag = false; -// if ((direction & EsoTwistD3Q27System::etE) == EsoTwistD3Q27System::etE) -// (*this->localDistributions)(D3Q27System::ET_E,x1, x2, x3) = f[D3Q27System::E]; directionFlag=true; -// if ((direction & EsoTwistD3Q27System::etW) == EsoTwistD3Q27System::etW) -// (*this->nonLocalDistributions)(D3Q27System::ET_W,x1+1,x2, x3 ) = f[D3Q27System::W]; directionFlag=true; -// if ((direction & EsoTwistD3Q27System::etS) == EsoTwistD3Q27System::etS) -// (*this->nonLocalDistributions)(D3Q27System::ET_S,x1, x2+1,x3 ) = f[D3Q27System::S]; directionFlag=true; -// if ((direction & EsoTwistD3Q27System::etN) == EsoTwistD3Q27System::etN) -// (*this->localDistributions)(D3Q27System::ET_N,x1, x2, x3) = f[D3Q27System::N]; directionFlag=true; -// if ((direction & EsoTwistD3Q27System::etB) == EsoTwistD3Q27System::etB) -// (*this->nonLocalDistributions)(D3Q27System::ET_B,x1, x2, x3+1 ) = f[D3Q27System::B]; directionFlag=true; -// if ((direction & EsoTwistD3Q27System::etT) == EsoTwistD3Q27System::etT) -// (*this->localDistributions)(D3Q27System::ET_T,x1, x2, x3) = f[D3Q27System::T]; directionFlag=true; -// if ((direction & EsoTwistD3Q27System::etSW) == EsoTwistD3Q27System::etSW) -// (*this->nonLocalDistributions)(D3Q27System::ET_SW,x1+1,x2+1,x3 ) = f[D3Q27System::SW]; directionFlag=true; -// if ((direction & EsoTwistD3Q27System::etNE) == EsoTwistD3Q27System::etNE) -// (*this->localDistributions)(D3Q27System::ET_NE,x1, x2, x3) = f[D3Q27System::NE]; directionFlag=true; -// if ((direction & EsoTwistD3Q27System::etNW) == EsoTwistD3Q27System::etNW) -// (*this->localDistributions)(D3Q27System::ET_NW,x1+1,x2, x3) = f[D3Q27System::NW]; directionFlag=true; -// if ((direction & EsoTwistD3Q27System::etSE) == EsoTwistD3Q27System::etSE) -// (*this->nonLocalDistributions)(D3Q27System::ET_SE,x1, x2+1,x3 ) = f[D3Q27System::SE]; directionFlag=true; -// if ((direction & EsoTwistD3Q27System::etBW) == EsoTwistD3Q27System::etBW) -// (*this->nonLocalDistributions)(D3Q27System::ET_BW,x1+1,x2, x3+1 ) = f[D3Q27System::BW]; directionFlag=true; -// if ((direction & EsoTwistD3Q27System::etTE) == EsoTwistD3Q27System::etTE) -// (*this->localDistributions)(D3Q27System::ET_TE,x1, x2, x3) = f[D3Q27System::TE]; directionFlag=true; -// if ((direction & EsoTwistD3Q27System::etTW) == EsoTwistD3Q27System::etTW) -// (*this->localDistributions)(D3Q27System::ET_TW,x1+1,x2, x3) = f[D3Q27System::TW]; directionFlag=true; -// if ((direction & EsoTwistD3Q27System::etBE) == EsoTwistD3Q27System::etBE) -// (*this->nonLocalDistributions)(D3Q27System::ET_BE,x1, x2, x3+1 ) = f[D3Q27System::BE]; directionFlag=true; -// if ((direction & EsoTwistD3Q27System::etBS) == EsoTwistD3Q27System::etBS) -// (*this->nonLocalDistributions)(D3Q27System::ET_BS,x1, x2+1,x3+1 ) = f[D3Q27System::BS]; directionFlag=true; -// if ((direction & EsoTwistD3Q27System::etTN) == EsoTwistD3Q27System::etTN) -// (*this->localDistributions)(D3Q27System::ET_TN,x1, x2, x3) = f[D3Q27System::TN]; directionFlag=true; -// if ((direction & EsoTwistD3Q27System::etTS) == EsoTwistD3Q27System::etTS) -// (*this->localDistributions)(D3Q27System::ET_TS,x1, x2+1,x3) = f[D3Q27System::TS]; directionFlag=true; -// if ((direction & EsoTwistD3Q27System::etBN) == EsoTwistD3Q27System::etBN) -// (*this->nonLocalDistributions)(D3Q27System::ET_BN,x1, x2, x3+1 ) = f[D3Q27System::BN]; directionFlag=true; -// if ((direction & EsoTwistD3Q27System::etBSW) == EsoTwistD3Q27System::etBSW) -// (*this->nonLocalDistributions)(D3Q27System::ET_BSW,x1+1,x2+1,x3+1) = f[D3Q27System::BSW]; directionFlag=true; -// if ((direction & EsoTwistD3Q27System::etTNE) == EsoTwistD3Q27System::etTNE) -// (*this->localDistributions)(D3Q27System::ET_TNE,x1, x2, x3) = f[D3Q27System::TNE]; directionFlag=true; -// if ((direction & EsoTwistD3Q27System::etBSE) == EsoTwistD3Q27System::etBSE) -// (*this->nonLocalDistributions)(D3Q27System::ET_BSE,x1, x2+1,x3+1) = f[D3Q27System::BSE]; directionFlag=true; -// if ((direction & EsoTwistD3Q27System::etTNW) == EsoTwistD3Q27System::etTNW) -// (*this->localDistributions)(D3Q27System::ET_TNW,x1+1,x2, x3) = f[D3Q27System::TNW]; directionFlag=true; -// if ((direction & EsoTwistD3Q27System::etBNW) == EsoTwistD3Q27System::etBNW) -// (*this->nonLocalDistributions)(D3Q27System::ET_BNW,x1+1,x2, x3+1) = f[D3Q27System::BNW]; directionFlag=true; -// if ((direction & EsoTwistD3Q27System::etTSE) == EsoTwistD3Q27System::etTSE) -// (*this->localDistributions)(D3Q27System::ET_TSE,x1, x2+1,x3) = f[D3Q27System::TSE]; directionFlag=true; -// if ((direction & EsoTwistD3Q27System::etBNE) == EsoTwistD3Q27System::etBNE) -// (*this->nonLocalDistributions)(D3Q27System::ET_BNE,x1, x2, x3+1)= f[D3Q27System::BNE]; directionFlag=true; -// if ((direction & EsoTwistD3Q27System::etTSW) == EsoTwistD3Q27System::etTSW) -// (*this->localDistributions)(D3Q27System::ET_TSW,x1+1,x2+1,x3) = f[D3Q27System::TSW]; directionFlag=true; -// if ((direction & EsoTwistD3Q27System::ZERO) == EsoTwistD3Q27System::ZERO) -// (*this->zeroDistributions)(x1,x2,x3) = f[D3Q27System::ZERO]; directionFlag=true; -//#ifdef _DEBUG -// if(!directionFlag)UB_THROW( UbException(UB_EXARGS, "Direction didn't find") ); -//#endif //DEBUG + // bool directionFlag = false; + // if ((direction & EsoTwistD3Q27System::etE) == EsoTwistD3Q27System::etE) + // (*this->localDistributions)(D3Q27System::ET_E,x1, x2, x3) = f[D3Q27System::E]; directionFlag=true; + // if ((direction & EsoTwistD3Q27System::etW) == EsoTwistD3Q27System::etW) + // (*this->nonLocalDistributions)(D3Q27System::ET_W,x1+1,x2, x3 ) = f[D3Q27System::W]; directionFlag=true; + // if ((direction & EsoTwistD3Q27System::etS) == EsoTwistD3Q27System::etS) + // (*this->nonLocalDistributions)(D3Q27System::ET_S,x1, x2+1,x3 ) = f[D3Q27System::S]; directionFlag=true; + // if ((direction & EsoTwistD3Q27System::etN) == EsoTwistD3Q27System::etN) + // (*this->localDistributions)(D3Q27System::ET_N,x1, x2, x3) = f[D3Q27System::N]; directionFlag=true; + // if ((direction & EsoTwistD3Q27System::etB) == EsoTwistD3Q27System::etB) + // (*this->nonLocalDistributions)(D3Q27System::ET_B,x1, x2, x3+1 ) = f[D3Q27System::B]; directionFlag=true; + // if ((direction & EsoTwistD3Q27System::etT) == EsoTwistD3Q27System::etT) + // (*this->localDistributions)(D3Q27System::ET_T,x1, x2, x3) = f[D3Q27System::T]; directionFlag=true; + // if ((direction & EsoTwistD3Q27System::etSW) == EsoTwistD3Q27System::etSW) + // (*this->nonLocalDistributions)(D3Q27System::ET_SW,x1+1,x2+1,x3 ) = f[D3Q27System::SW]; directionFlag=true; + // if ((direction & EsoTwistD3Q27System::etNE) == EsoTwistD3Q27System::etNE) + // (*this->localDistributions)(D3Q27System::ET_NE,x1, x2, x3) = f[D3Q27System::NE]; directionFlag=true; + // if ((direction & EsoTwistD3Q27System::etNW) == EsoTwistD3Q27System::etNW) + // (*this->localDistributions)(D3Q27System::ET_NW,x1+1,x2, x3) = f[D3Q27System::NW]; directionFlag=true; + // if ((direction & EsoTwistD3Q27System::etSE) == EsoTwistD3Q27System::etSE) + // (*this->nonLocalDistributions)(D3Q27System::ET_SE,x1, x2+1,x3 ) = f[D3Q27System::SE]; directionFlag=true; + // if ((direction & EsoTwistD3Q27System::etBW) == EsoTwistD3Q27System::etBW) + // (*this->nonLocalDistributions)(D3Q27System::ET_BW,x1+1,x2, x3+1 ) = f[D3Q27System::BW]; directionFlag=true; + // if ((direction & EsoTwistD3Q27System::etTE) == EsoTwistD3Q27System::etTE) + // (*this->localDistributions)(D3Q27System::ET_TE,x1, x2, x3) = f[D3Q27System::TE]; directionFlag=true; + // if ((direction & EsoTwistD3Q27System::etTW) == EsoTwistD3Q27System::etTW) + // (*this->localDistributions)(D3Q27System::ET_TW,x1+1,x2, x3) = f[D3Q27System::TW]; directionFlag=true; + // if ((direction & EsoTwistD3Q27System::etBE) == EsoTwistD3Q27System::etBE) + // (*this->nonLocalDistributions)(D3Q27System::ET_BE,x1, x2, x3+1 ) = f[D3Q27System::BE]; directionFlag=true; + // if ((direction & EsoTwistD3Q27System::etBS) == EsoTwistD3Q27System::etBS) + // (*this->nonLocalDistributions)(D3Q27System::ET_BS,x1, x2+1,x3+1 ) = f[D3Q27System::BS]; directionFlag=true; + // if ((direction & EsoTwistD3Q27System::etTN) == EsoTwistD3Q27System::etTN) + // (*this->localDistributions)(D3Q27System::ET_TN,x1, x2, x3) = f[D3Q27System::TN]; directionFlag=true; + // if ((direction & EsoTwistD3Q27System::etTS) == EsoTwistD3Q27System::etTS) + // (*this->localDistributions)(D3Q27System::ET_TS,x1, x2+1,x3) = f[D3Q27System::TS]; directionFlag=true; + // if ((direction & EsoTwistD3Q27System::etBN) == EsoTwistD3Q27System::etBN) + // (*this->nonLocalDistributions)(D3Q27System::ET_BN,x1, x2, x3+1 ) = f[D3Q27System::BN]; directionFlag=true; + // if ((direction & EsoTwistD3Q27System::etBSW) == EsoTwistD3Q27System::etBSW) + // (*this->nonLocalDistributions)(D3Q27System::ET_BSW,x1+1,x2+1,x3+1) = f[D3Q27System::BSW]; + // directionFlag=true; + // if ((direction & EsoTwistD3Q27System::etTNE) == EsoTwistD3Q27System::etTNE) + // (*this->localDistributions)(D3Q27System::ET_TNE,x1, x2, x3) = f[D3Q27System::TNE]; directionFlag=true; + // if ((direction & EsoTwistD3Q27System::etBSE) == EsoTwistD3Q27System::etBSE) + // (*this->nonLocalDistributions)(D3Q27System::ET_BSE,x1, x2+1,x3+1) = f[D3Q27System::BSE]; + // directionFlag=true; + // if ((direction & EsoTwistD3Q27System::etTNW) == EsoTwistD3Q27System::etTNW) + // (*this->localDistributions)(D3Q27System::ET_TNW,x1+1,x2, x3) = f[D3Q27System::TNW]; directionFlag=true; + // if ((direction & EsoTwistD3Q27System::etBNW) == EsoTwistD3Q27System::etBNW) + // (*this->nonLocalDistributions)(D3Q27System::ET_BNW,x1+1,x2, x3+1) = f[D3Q27System::BNW]; + // directionFlag=true; + // if ((direction & EsoTwistD3Q27System::etTSE) == EsoTwistD3Q27System::etTSE) + // (*this->localDistributions)(D3Q27System::ET_TSE,x1, x2+1,x3) = f[D3Q27System::TSE]; directionFlag=true; + // if ((direction & EsoTwistD3Q27System::etBNE) == EsoTwistD3Q27System::etBNE) + // (*this->nonLocalDistributions)(D3Q27System::ET_BNE,x1, x2, x3+1)= f[D3Q27System::BNE]; directionFlag=true; + // if ((direction & EsoTwistD3Q27System::etTSW) == EsoTwistD3Q27System::etTSW) + // (*this->localDistributions)(D3Q27System::ET_TSW,x1+1,x2+1,x3) = f[D3Q27System::TSW]; directionFlag=true; + // if ((direction & EsoTwistD3Q27System::ZERO) == EsoTwistD3Q27System::ZERO) + // (*this->zeroDistributions)(x1,x2,x3) = f[D3Q27System::ZERO]; directionFlag=true; + //#ifdef _DEBUG + // if(!directionFlag)UB_THROW( UbException(UB_EXARGS, "Direction didn't find") ); + //#endif //DEBUG } ////////////////////////////////////////////////////////////////////////// -void D3Q27EsoTwist3DSoA::setDistributionInvForDirection(LBMReal f, size_t x1, size_t x2, size_t x3, unsigned long int direction) +void D3Q27EsoTwist3DSoA::setDistributionInvForDirection(LBMReal f, size_t x1, size_t x2, size_t x3, + unsigned long int direction) { - //switch (direction) - //{ - //case D3Q27System::E : - // (*this->localDistributions)(D3Q27System::ET_E,x1, x2, x3) = f; - // break; - //case D3Q27System::W : - // (*this->nonLocalDistributions)(D3Q27System::ET_W,x1+1,x2, x3 ) = f; - // break; - //case D3Q27System::S : - // (*this->nonLocalDistributions)(D3Q27System::ET_S,x1, x2+1,x3 ) = f; - // break; - //case D3Q27System::N : - // (*this->localDistributions)(D3Q27System::ET_N,x1, x2, x3) = f; - // break; - //case D3Q27System::B : - // (*this->nonLocalDistributions)(D3Q27System::ET_B,x1, x2, x3+1 ) = f; - // break; - //case D3Q27System::T : - // (*this->localDistributions)(D3Q27System::ET_T,x1, x2, x3) = f; - // break; - //case D3Q27System::SW : - // (*this->nonLocalDistributions)(D3Q27System::ET_SW,x1+1,x2+1,x3 ) = f; - // break; - //case D3Q27System::NE : - // (*this->localDistributions)(D3Q27System::ET_NE,x1, x2, x3) = f; - // break; - //case D3Q27System::NW : - // (*this->localDistributions)(D3Q27System::ET_NW,x1+1,x2, x3) = f; - // break; - //case D3Q27System::SE : - // (*this->nonLocalDistributions)(D3Q27System::ET_SE,x1, x2+1,x3 ) = f; - // break; - //case D3Q27System::BW : - // (*this->nonLocalDistributions)(D3Q27System::ET_BW,x1+1,x2, x3+1 ) = f; - // break; - //case D3Q27System::TE : - // (*this->localDistributions)(D3Q27System::ET_TE,x1, x2, x3) = f; - // break; - //case D3Q27System::TW : - // (*this->localDistributions)(D3Q27System::ET_TW,x1+1,x2, x3) = f; - // break; - //case D3Q27System::BE : - // (*this->nonLocalDistributions)(D3Q27System::ET_BE,x1, x2, x3+1 ) = f; - // break; - //case D3Q27System::BS : - // (*this->nonLocalDistributions)(D3Q27System::ET_BS,x1, x2+1,x3+1 ) = f; - // break; - //case D3Q27System::TN : - // (*this->localDistributions)(D3Q27System::ET_TN,x1, x2, x3) = f; - // break; - //case D3Q27System::TS : - // (*this->localDistributions)(D3Q27System::ET_TS,x1, x2+1,x3) = f; - // break; - //case D3Q27System::BN : - // (*this->nonLocalDistributions)(D3Q27System::ET_BN,x1, x2, x3+1 ) = f; - // break; - //case D3Q27System::BSW : - // (*this->nonLocalDistributions)(D3Q27System::ET_BSW,x1+1,x2+1,x3+1) = f; - // break; - //case D3Q27System::TNE : - // (*this->localDistributions)(D3Q27System::ET_TNE,x1, x2, x3) = f; - // break; - //case D3Q27System::BSE : - // (*this->nonLocalDistributions)(D3Q27System::ET_BSE,x1, x2+1,x3+1) = f; - // break; - //case D3Q27System::TNW : - // (*this->localDistributions)(D3Q27System::ET_TNW,x1+1,x2, x3) = f; - // break; - //case D3Q27System::BNW : - // (*this->nonLocalDistributions)(D3Q27System::ET_BNW,x1+1,x2, x3+1) = f; - // break; - //case D3Q27System::TSE : - // (*this->localDistributions)(D3Q27System::ET_TSE,x1, x2+1,x3) = f; - // break; - //case D3Q27System::BNE : - // (*this->nonLocalDistributions)(D3Q27System::ET_BNE,x1, x2, x3+1) = f; - // break; - //case D3Q27System::TSW : - // (*this->localDistributions)(D3Q27System::ET_TSW,x1+1,x2+1,x3) = f; - // break; - //case D3Q27System::ZERO : - // (*this->zeroDistributions)(x1,x2,x3) = f; - // break; - //default: - // UB_THROW( UbException(UB_EXARGS, "Direction didn't find") ); - //} + // switch (direction) + //{ + // case D3Q27System::E : + // (*this->localDistributions)(D3Q27System::ET_E,x1, x2, x3) = f; + // break; + // case D3Q27System::W : + // (*this->nonLocalDistributions)(D3Q27System::ET_W,x1+1,x2, x3 ) = f; + // break; + // case D3Q27System::S : + // (*this->nonLocalDistributions)(D3Q27System::ET_S,x1, x2+1,x3 ) = f; + // break; + // case D3Q27System::N : + // (*this->localDistributions)(D3Q27System::ET_N,x1, x2, x3) = f; + // break; + // case D3Q27System::B : + // (*this->nonLocalDistributions)(D3Q27System::ET_B,x1, x2, x3+1 ) = f; + // break; + // case D3Q27System::T : + // (*this->localDistributions)(D3Q27System::ET_T,x1, x2, x3) = f; + // break; + // case D3Q27System::SW : + // (*this->nonLocalDistributions)(D3Q27System::ET_SW,x1+1,x2+1,x3 ) = f; + // break; + // case D3Q27System::NE : + // (*this->localDistributions)(D3Q27System::ET_NE,x1, x2, x3) = f; + // break; + // case D3Q27System::NW : + // (*this->localDistributions)(D3Q27System::ET_NW,x1+1,x2, x3) = f; + // break; + // case D3Q27System::SE : + // (*this->nonLocalDistributions)(D3Q27System::ET_SE,x1, x2+1,x3 ) = f; + // break; + // case D3Q27System::BW : + // (*this->nonLocalDistributions)(D3Q27System::ET_BW,x1+1,x2, x3+1 ) = f; + // break; + // case D3Q27System::TE : + // (*this->localDistributions)(D3Q27System::ET_TE,x1, x2, x3) = f; + // break; + // case D3Q27System::TW : + // (*this->localDistributions)(D3Q27System::ET_TW,x1+1,x2, x3) = f; + // break; + // case D3Q27System::BE : + // (*this->nonLocalDistributions)(D3Q27System::ET_BE,x1, x2, x3+1 ) = f; + // break; + // case D3Q27System::BS : + // (*this->nonLocalDistributions)(D3Q27System::ET_BS,x1, x2+1,x3+1 ) = f; + // break; + // case D3Q27System::TN : + // (*this->localDistributions)(D3Q27System::ET_TN,x1, x2, x3) = f; + // break; + // case D3Q27System::TS : + // (*this->localDistributions)(D3Q27System::ET_TS,x1, x2+1,x3) = f; + // break; + // case D3Q27System::BN : + // (*this->nonLocalDistributions)(D3Q27System::ET_BN,x1, x2, x3+1 ) = f; + // break; + // case D3Q27System::BSW : + // (*this->nonLocalDistributions)(D3Q27System::ET_BSW,x1+1,x2+1,x3+1) = f; + // break; + // case D3Q27System::TNE : + // (*this->localDistributions)(D3Q27System::ET_TNE,x1, x2, x3) = f; + // break; + // case D3Q27System::BSE : + // (*this->nonLocalDistributions)(D3Q27System::ET_BSE,x1, x2+1,x3+1) = f; + // break; + // case D3Q27System::TNW : + // (*this->localDistributions)(D3Q27System::ET_TNW,x1+1,x2, x3) = f; + // break; + // case D3Q27System::BNW : + // (*this->nonLocalDistributions)(D3Q27System::ET_BNW,x1+1,x2, x3+1) = f; + // break; + // case D3Q27System::TSE : + // (*this->localDistributions)(D3Q27System::ET_TSE,x1, x2+1,x3) = f; + // break; + // case D3Q27System::BNE : + // (*this->nonLocalDistributions)(D3Q27System::ET_BNE,x1, x2, x3+1) = f; + // break; + // case D3Q27System::TSW : + // (*this->localDistributions)(D3Q27System::ET_TSW,x1+1,x2+1,x3) = f; + // break; + // case D3Q27System::ZERO : + // (*this->zeroDistributions)(x1,x2,x3) = f; + // break; + // default: + // UB_THROW( UbException(UB_EXARGS, "Direction didn't find") ); + //} } ////////////////////////////////////////////////////////////////////////// -LBMReal D3Q27EsoTwist3DSoA::getDistributionInvForDirection(size_t /*x1*/, size_t /*x2*/, size_t /*x3*/, int /*direction*/) +LBMReal D3Q27EsoTwist3DSoA::getDistributionInvForDirection(size_t /*x1*/, size_t /*x2*/, size_t /*x3*/, + int /*direction*/) { - //switch (direction) - //{ - //case D3Q27System::E : - // return (*this->nonLocalDistributions)(D3Q27System::ET_W,x1+1,x2, x3 ); - //case D3Q27System::W : - // return (*this->localDistributions)(D3Q27System::ET_E,x1, x2, x3); - //case D3Q27System::S : - // return (*this->localDistributions)(D3Q27System::ET_N,x1, x2, x3); - //case D3Q27System::N : - // return (*this->nonLocalDistributions)(D3Q27System::ET_S,x1, x2+1,x3 ); - //case D3Q27System::B : - // return (*this->localDistributions)(D3Q27System::ET_T,x1, x2, x3); - //case D3Q27System::T : - // return (*this->nonLocalDistributions)(D3Q27System::ET_B,x1, x2, x3+1 ); - //case D3Q27System::SW : - // return (*this->localDistributions)(D3Q27System::ET_NE,x1, x2, x3); - //case D3Q27System::NE : - // return (*this->nonLocalDistributions)(D3Q27System::ET_SW,x1+1,x2+1,x3 ); - //case D3Q27System::NW : - // return (*this->nonLocalDistributions)(D3Q27System::ET_SE,x1, x2+1,x3 ); - //case D3Q27System::SE : - // return (*this->localDistributions)(D3Q27System::ET_NW,x1+1,x2, x3); - //case D3Q27System::BW : - // return (*this->localDistributions)(D3Q27System::ET_TE,x1, x2, x3); - //case D3Q27System::TE : - // return (*this->nonLocalDistributions)(D3Q27System::ET_BW,x1+1,x2, x3+1 ); - //case D3Q27System::TW : - // return (*this->nonLocalDistributions)(D3Q27System::ET_BE,x1, x2, x3+1 ); - //case D3Q27System::BE : - // return (*this->localDistributions)(D3Q27System::ET_TW,x1+1,x2, x3); - //case D3Q27System::BS : - // return (*this->localDistributions)(D3Q27System::ET_TN,x1, x2, x3); - //case D3Q27System::TN : - // return (*this->nonLocalDistributions)(D3Q27System::ET_BS,x1, x2+1,x3+1 ); - //case D3Q27System::TS : - // return (*this->nonLocalDistributions)(D3Q27System::ET_BN,x1, x2, x3+1 ); - //case D3Q27System::BN : - // return (*this->localDistributions)(D3Q27System::ET_TS,x1, x2+1,x3); - //case D3Q27System::BSW : - // return (*this->localDistributions)(D3Q27System::ET_TNE,x1, x2, x3); - //case D3Q27System::TNE : - // return (*this->nonLocalDistributions)(D3Q27System::ET_BSW,x1+1,x2+1,x3+1); - //case D3Q27System::BSE : - // return (*this->localDistributions)(D3Q27System::ET_TNW,x1+1,x2, x3); - //case D3Q27System::TNW : - // return (*this->nonLocalDistributions)(D3Q27System::ET_BSE,x1, x2+1,x3+1); - //case D3Q27System::BNW : - // return (*this->localDistributions)(D3Q27System::ET_TSE,x1, x2+1,x3); - //case D3Q27System::TSE : - // return (*this->nonLocalDistributions)(D3Q27System::ET_BNW,x1+1,x2, x3+1); - //case D3Q27System::BNE : - // return (*this->localDistributions)(D3Q27System::ET_TSW,x1+1,x2+1,x3); - //case D3Q27System::TSW : - // return (*this->nonLocalDistributions)(D3Q27System::ET_BNE,x1, x2, x3+1); - //case D3Q27System::ZERO : - // return (*this->zeroDistributions)(x1,x2,x3); - //default: - // UB_THROW( UbException(UB_EXARGS, "Direction didn't find") ); - //} - return 0; + // switch (direction) + //{ + // case D3Q27System::E : + // return (*this->nonLocalDistributions)(D3Q27System::ET_W,x1+1,x2, x3 ); + // case D3Q27System::W : + // return (*this->localDistributions)(D3Q27System::ET_E,x1, x2, x3); + // case D3Q27System::S : + // return (*this->localDistributions)(D3Q27System::ET_N,x1, x2, x3); + // case D3Q27System::N : + // return (*this->nonLocalDistributions)(D3Q27System::ET_S,x1, x2+1,x3 ); + // case D3Q27System::B : + // return (*this->localDistributions)(D3Q27System::ET_T,x1, x2, x3); + // case D3Q27System::T : + // return (*this->nonLocalDistributions)(D3Q27System::ET_B,x1, x2, x3+1 ); + // case D3Q27System::SW : + // return (*this->localDistributions)(D3Q27System::ET_NE,x1, x2, x3); + // case D3Q27System::NE : + // return (*this->nonLocalDistributions)(D3Q27System::ET_SW,x1+1,x2+1,x3 ); + // case D3Q27System::NW : + // return (*this->nonLocalDistributions)(D3Q27System::ET_SE,x1, x2+1,x3 ); + // case D3Q27System::SE : + // return (*this->localDistributions)(D3Q27System::ET_NW,x1+1,x2, x3); + // case D3Q27System::BW : + // return (*this->localDistributions)(D3Q27System::ET_TE,x1, x2, x3); + // case D3Q27System::TE : + // return (*this->nonLocalDistributions)(D3Q27System::ET_BW,x1+1,x2, x3+1 ); + // case D3Q27System::TW : + // return (*this->nonLocalDistributions)(D3Q27System::ET_BE,x1, x2, x3+1 ); + // case D3Q27System::BE : + // return (*this->localDistributions)(D3Q27System::ET_TW,x1+1,x2, x3); + // case D3Q27System::BS : + // return (*this->localDistributions)(D3Q27System::ET_TN,x1, x2, x3); + // case D3Q27System::TN : + // return (*this->nonLocalDistributions)(D3Q27System::ET_BS,x1, x2+1,x3+1 ); + // case D3Q27System::TS : + // return (*this->nonLocalDistributions)(D3Q27System::ET_BN,x1, x2, x3+1 ); + // case D3Q27System::BN : + // return (*this->localDistributions)(D3Q27System::ET_TS,x1, x2+1,x3); + // case D3Q27System::BSW : + // return (*this->localDistributions)(D3Q27System::ET_TNE,x1, x2, x3); + // case D3Q27System::TNE : + // return (*this->nonLocalDistributions)(D3Q27System::ET_BSW,x1+1,x2+1,x3+1); + // case D3Q27System::BSE : + // return (*this->localDistributions)(D3Q27System::ET_TNW,x1+1,x2, x3); + // case D3Q27System::TNW : + // return (*this->nonLocalDistributions)(D3Q27System::ET_BSE,x1, x2+1,x3+1); + // case D3Q27System::BNW : + // return (*this->localDistributions)(D3Q27System::ET_TSE,x1, x2+1,x3); + // case D3Q27System::TSE : + // return (*this->nonLocalDistributions)(D3Q27System::ET_BNW,x1+1,x2, x3+1); + // case D3Q27System::BNE : + // return (*this->localDistributions)(D3Q27System::ET_TSW,x1+1,x2+1,x3); + // case D3Q27System::TSW : + // return (*this->nonLocalDistributions)(D3Q27System::ET_BNE,x1, x2, x3+1); + // case D3Q27System::ZERO : + // return (*this->zeroDistributions)(x1,x2,x3); + // default: + // UB_THROW( UbException(UB_EXARGS, "Direction didn't find") ); + //} + return 0; } ////////////////////////////////////////////////////////////////////////// -size_t D3Q27EsoTwist3DSoA::getNX1() const -{ - return NX1; -} +size_t D3Q27EsoTwist3DSoA::getNX1() const { return NX1; } ////////////////////////////////////////////////////////////////////////// -size_t D3Q27EsoTwist3DSoA::getNX2() const -{ - return NX2; -} +size_t D3Q27EsoTwist3DSoA::getNX2() const { return NX2; } ////////////////////////////////////////////////////////////////////////// -size_t D3Q27EsoTwist3DSoA::getNX3() const -{ - return NX3; -} +size_t D3Q27EsoTwist3DSoA::getNX3() const { return NX3; } ////////////////////////////////////////////////////////////////////////// -Distributions D3Q27EsoTwist3DSoA::getDistributions() -{ - return d; -} +Distributions D3Q27EsoTwist3DSoA::getDistributions() { return d; } ////////////////////////////////////////////////////////////////////////// - diff --git a/src/cpu/VirtualFluidsCore/Data/D3Q27EsoTwist3DSoA.h b/src/cpu/VirtualFluidsCore/Data/D3Q27EsoTwist3DSoA.h index c409b03a6545553e4c2c0bd17bfc2bc0faa9ccc0..72951922a3580c9c4b00379e2eb6f79eefad4ef9 100644 --- a/src/cpu/VirtualFluidsCore/Data/D3Q27EsoTwist3DSoA.h +++ b/src/cpu/VirtualFluidsCore/Data/D3Q27EsoTwist3DSoA.h @@ -8,84 +8,82 @@ //#include <boost/serialization/serialization.hpp> //#include <boost/serialization/base_object.hpp> - -struct Distributions -{ - CbArray3D<LBMReal,IndexerX3X2X1>::CbArray3DPtr E; - CbArray3D<LBMReal,IndexerX3X2X1>::CbArray3DPtr W; - CbArray3D<LBMReal,IndexerX3X2X1>::CbArray3DPtr N; - CbArray3D<LBMReal,IndexerX3X2X1>::CbArray3DPtr S; - CbArray3D<LBMReal,IndexerX3X2X1>::CbArray3DPtr T; - CbArray3D<LBMReal,IndexerX3X2X1>::CbArray3DPtr B; - CbArray3D<LBMReal,IndexerX3X2X1>::CbArray3DPtr NE; - CbArray3D<LBMReal,IndexerX3X2X1>::CbArray3DPtr SW; - CbArray3D<LBMReal,IndexerX3X2X1>::CbArray3DPtr SE; - CbArray3D<LBMReal,IndexerX3X2X1>::CbArray3DPtr NW; - CbArray3D<LBMReal,IndexerX3X2X1>::CbArray3DPtr TE; - CbArray3D<LBMReal,IndexerX3X2X1>::CbArray3DPtr BW; - CbArray3D<LBMReal,IndexerX3X2X1>::CbArray3DPtr BE; - CbArray3D<LBMReal,IndexerX3X2X1>::CbArray3DPtr TW; - CbArray3D<LBMReal,IndexerX3X2X1>::CbArray3DPtr TN; - CbArray3D<LBMReal,IndexerX3X2X1>::CbArray3DPtr BS; - CbArray3D<LBMReal,IndexerX3X2X1>::CbArray3DPtr BN; - CbArray3D<LBMReal,IndexerX3X2X1>::CbArray3DPtr TS; - CbArray3D<LBMReal,IndexerX3X2X1>::CbArray3DPtr TNE; - CbArray3D<LBMReal,IndexerX3X2X1>::CbArray3DPtr TNW; - CbArray3D<LBMReal,IndexerX3X2X1>::CbArray3DPtr TSE; - CbArray3D<LBMReal,IndexerX3X2X1>::CbArray3DPtr TSW; - CbArray3D<LBMReal,IndexerX3X2X1>::CbArray3DPtr BNE; - CbArray3D<LBMReal,IndexerX3X2X1>::CbArray3DPtr BNW; - CbArray3D<LBMReal,IndexerX3X2X1>::CbArray3DPtr BSE; - CbArray3D<LBMReal,IndexerX3X2X1>::CbArray3DPtr BSW; - CbArray3D<LBMReal,IndexerX3X2X1>::CbArray3DPtr ZERO; +struct Distributions { + CbArray3D<LBMReal, IndexerX3X2X1>::CbArray3DPtr E; + CbArray3D<LBMReal, IndexerX3X2X1>::CbArray3DPtr W; + CbArray3D<LBMReal, IndexerX3X2X1>::CbArray3DPtr N; + CbArray3D<LBMReal, IndexerX3X2X1>::CbArray3DPtr S; + CbArray3D<LBMReal, IndexerX3X2X1>::CbArray3DPtr T; + CbArray3D<LBMReal, IndexerX3X2X1>::CbArray3DPtr B; + CbArray3D<LBMReal, IndexerX3X2X1>::CbArray3DPtr NE; + CbArray3D<LBMReal, IndexerX3X2X1>::CbArray3DPtr SW; + CbArray3D<LBMReal, IndexerX3X2X1>::CbArray3DPtr SE; + CbArray3D<LBMReal, IndexerX3X2X1>::CbArray3DPtr NW; + CbArray3D<LBMReal, IndexerX3X2X1>::CbArray3DPtr TE; + CbArray3D<LBMReal, IndexerX3X2X1>::CbArray3DPtr BW; + CbArray3D<LBMReal, IndexerX3X2X1>::CbArray3DPtr BE; + CbArray3D<LBMReal, IndexerX3X2X1>::CbArray3DPtr TW; + CbArray3D<LBMReal, IndexerX3X2X1>::CbArray3DPtr TN; + CbArray3D<LBMReal, IndexerX3X2X1>::CbArray3DPtr BS; + CbArray3D<LBMReal, IndexerX3X2X1>::CbArray3DPtr BN; + CbArray3D<LBMReal, IndexerX3X2X1>::CbArray3DPtr TS; + CbArray3D<LBMReal, IndexerX3X2X1>::CbArray3DPtr TNE; + CbArray3D<LBMReal, IndexerX3X2X1>::CbArray3DPtr TNW; + CbArray3D<LBMReal, IndexerX3X2X1>::CbArray3DPtr TSE; + CbArray3D<LBMReal, IndexerX3X2X1>::CbArray3DPtr TSW; + CbArray3D<LBMReal, IndexerX3X2X1>::CbArray3DPtr BNE; + CbArray3D<LBMReal, IndexerX3X2X1>::CbArray3DPtr BNW; + CbArray3D<LBMReal, IndexerX3X2X1>::CbArray3DPtr BSE; + CbArray3D<LBMReal, IndexerX3X2X1>::CbArray3DPtr BSW; + CbArray3D<LBMReal, IndexerX3X2X1>::CbArray3DPtr ZERO; }; - class D3Q27EsoTwist3DSoA : public EsoTwist3D { public: - D3Q27EsoTwist3DSoA(); - D3Q27EsoTwist3DSoA(const size_t& nx1, const size_t& nx2, const size_t& nx3, LBMReal value); - ////////////////////////////////////////////////////////////////////////// - ~D3Q27EsoTwist3DSoA() override; - ////////////////////////////////////////////////////////////////////////// - void swap() override; - ////////////////////////////////////////////////////////////////////////// - void getDistribution( LBMReal* const f, size_t x1, size_t x2, size_t x3) override; - ////////////////////////////////////////////////////////////////////////// - void setDistribution(const LBMReal* const f, size_t x1, size_t x2, size_t x3) override; - //////////////////////////////////////////////////////////////////////// - void getDistributionInv( LBMReal* const f, size_t x1, size_t x2, size_t x3) override; - ////////////////////////////////////////////////////////////////////////// - void setDistributionInv(const LBMReal* const f, size_t x1, size_t x2, size_t x3) override; - ////////////////////////////////////////////////////////////////////////// - void setDistributionForDirection(const LBMReal* const f, size_t x1, size_t x2, size_t x3, unsigned long int direction) override; - ////////////////////////////////////////////////////////////////////////// - void setDistributionForDirection(LBMReal f, size_t x1, size_t x2, size_t x3, int direction) override; - ////////////////////////////////////////////////////////////////////////// - LBMReal getDistributionInvForDirection(size_t x1, size_t x2, size_t x3, int direction) override; - ////////////////////////////////////////////////////////////////////////// - void setDistributionInvForDirection(const LBMReal* const f, size_t x1, size_t x2, size_t x3, unsigned long int direction) override; - ////////////////////////////////////////////////////////////////////////// - void setDistributionInvForDirection(LBMReal f, size_t x1, size_t x2, size_t x3, unsigned long int direction) override; - ////////////////////////////////////////////////////////////////////////// - LBMReal getDistributionForDirection(size_t x1, size_t x2, size_t x3, int direction) override; - ////////////////////////////////////////////////////////////////////////// - size_t getNX1() const override; - ////////////////////////////////////////////////////////////////////////// - size_t getNX2() const override; - ////////////////////////////////////////////////////////////////////////// - size_t getNX3() const override; - ////////////////////////////////////////////////////////////////////////// - Distributions getDistributions(); - ////////////////////////////////////////////////////////////////////////// - void getDistributionAfterLastStep(LBMReal* const f, size_t x1, size_t x2, size_t x3); + D3Q27EsoTwist3DSoA(); + D3Q27EsoTwist3DSoA(const size_t &nx1, const size_t &nx2, const size_t &nx3, LBMReal value); + ////////////////////////////////////////////////////////////////////////// + ~D3Q27EsoTwist3DSoA() override; + ////////////////////////////////////////////////////////////////////////// + void swap() override; + ////////////////////////////////////////////////////////////////////////// + void getDistribution(LBMReal *const f, size_t x1, size_t x2, size_t x3) override; + ////////////////////////////////////////////////////////////////////////// + void setDistribution(const LBMReal *const f, size_t x1, size_t x2, size_t x3) override; + //////////////////////////////////////////////////////////////////////// + void getDistributionInv(LBMReal *const f, size_t x1, size_t x2, size_t x3) override; + ////////////////////////////////////////////////////////////////////////// + void setDistributionInv(const LBMReal *const f, size_t x1, size_t x2, size_t x3) override; + ////////////////////////////////////////////////////////////////////////// + void setDistributionForDirection(const LBMReal *const f, size_t x1, size_t x2, size_t x3, + unsigned long int direction) override; + ////////////////////////////////////////////////////////////////////////// + void setDistributionForDirection(LBMReal f, size_t x1, size_t x2, size_t x3, int direction) override; + ////////////////////////////////////////////////////////////////////////// + LBMReal getDistributionInvForDirection(size_t x1, size_t x2, size_t x3, int direction) override; + ////////////////////////////////////////////////////////////////////////// + void setDistributionInvForDirection(const LBMReal *const f, size_t x1, size_t x2, size_t x3, + unsigned long int direction) override; + ////////////////////////////////////////////////////////////////////////// + void setDistributionInvForDirection(LBMReal f, size_t x1, size_t x2, size_t x3, + unsigned long int direction) override; + ////////////////////////////////////////////////////////////////////////// + LBMReal getDistributionForDirection(size_t x1, size_t x2, size_t x3, int direction) override; + ////////////////////////////////////////////////////////////////////////// + size_t getNX1() const override; + ////////////////////////////////////////////////////////////////////////// + size_t getNX2() const override; + ////////////////////////////////////////////////////////////////////////// + size_t getNX3() const override; + ////////////////////////////////////////////////////////////////////////// + Distributions getDistributions(); + ////////////////////////////////////////////////////////////////////////// + void getDistributionAfterLastStep(LBMReal *const f, size_t x1, size_t x2, size_t x3); protected: - Distributions d; - size_t NX1, NX2, NX3; - + Distributions d; + size_t NX1, NX2, NX3; }; #endif - diff --git a/src/cpu/VirtualFluidsCore/Data/D3Q27EsoTwist3DSplittedVector.cpp b/src/cpu/VirtualFluidsCore/Data/D3Q27EsoTwist3DSplittedVector.cpp index 113fd04ce73e162db48eca9396038920bc348321..6f8a6e74664cf82a550b9000071d4f6beb9ebac2 100644 --- a/src/cpu/VirtualFluidsCore/Data/D3Q27EsoTwist3DSplittedVector.cpp +++ b/src/cpu/VirtualFluidsCore/Data/D3Q27EsoTwist3DSplittedVector.cpp @@ -1,28 +1,28 @@ //======================================================================================= -// ____ ____ __ ______ __________ __ __ __ __ -// \ \ | | | | | _ \ |___ ___| | | | | / \ | | -// \ \ | | | | | |_) | | | | | | | / \ | | -// \ \ | | | | | _ / | | | | | | / /\ \ | | -// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ -// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| -// \ \ | | ________________________________________________________________ -// \ \ | | | ______________________________________________________________| -// \ \| | | | __ __ __ __ ______ _______ -// \ | | |_____ | | | | | | | | | _ \ / _____) -// \ | | _____| | | | | | | | | | | \ \ \_______ +// ____ ____ __ ______ __________ __ __ __ __ +// \ \ | | | | | _ \ |___ ___| | | | | / \ | | +// \ \ | | | | | |_) | | | | | | | / \ | | +// \ \ | | | | | _ / | | | | | | / /\ \ | | +// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ +// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| +// \ \ | | ________________________________________________________________ +// \ \ | | | ______________________________________________________________| +// \ \| | | | __ __ __ __ ______ _______ +// \ | | |_____ | | | | | | | | | _ \ / _____) +// \ | | _____| | | | | | | | | | | \ \ \_______ // \ | | | | |_____ | \_/ | | | | |_/ / _____ | -// \ _____| |__| |________| \_______/ |__| |______/ (_______/ +// \ _____| |__| |________| \_______/ |__| |______/ (_______/ // -// This file is part of VirtualFluids. VirtualFluids is free software: you can +// This file is part of VirtualFluids. VirtualFluids is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of +// License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. -// -// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// +// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License along // with VirtualFluids (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>. // @@ -34,642 +34,620 @@ #include "D3Q27EsoTwist3DSplittedVector.h" #include "EsoTwistD3Q27System.h" -D3Q27EsoTwist3DSplittedVector::D3Q27EsoTwist3DSplittedVector() -= default; +D3Q27EsoTwist3DSplittedVector::D3Q27EsoTwist3DSplittedVector() = default; ////////////////////////////////////////////////////////////////////////// -D3Q27EsoTwist3DSplittedVector::D3Q27EsoTwist3DSplittedVector( size_t nx1, size_t nx2, size_t nx3, LBMReal value ) +D3Q27EsoTwist3DSplittedVector::D3Q27EsoTwist3DSplittedVector(size_t nx1, size_t nx2, size_t nx3, LBMReal value) { - this->NX1 = nx1; - this->NX2 = nx2; - this->NX3 = nx3; + this->NX1 = nx1; + this->NX2 = nx2; + this->NX3 = nx3; - this->localDistributions = std::make_shared<CbArray4D<LBMReal, IndexerX4X3X2X1> >(13, nx1+1, nx2+1, nx3+1, value); - this->nonLocalDistributions = std::make_shared<CbArray4D<LBMReal, IndexerX4X3X2X1> >(13, nx1+1, nx2+1, nx3+1, value); + this->localDistributions = + std::make_shared<CbArray4D<LBMReal, IndexerX4X3X2X1>>(13, nx1 + 1, nx2 + 1, nx3 + 1, value); + this->nonLocalDistributions = + std::make_shared<CbArray4D<LBMReal, IndexerX4X3X2X1>>(13, nx1 + 1, nx2 + 1, nx3 + 1, value); - this->zeroDistributions = std::make_shared<CbArray3D<LBMReal, IndexerX3X2X1> >(nx1, nx2, nx3, value); + this->zeroDistributions = std::make_shared<CbArray3D<LBMReal, IndexerX3X2X1>>(nx1, nx2, nx3, value); } ////////////////////////////////////////////////////////////////////////// -D3Q27EsoTwist3DSplittedVector::~D3Q27EsoTwist3DSplittedVector() -= default; +D3Q27EsoTwist3DSplittedVector::~D3Q27EsoTwist3DSplittedVector() = default; ////////////////////////////////////////////////////////////////////////// -void D3Q27EsoTwist3DSplittedVector::swap() -{ - std::swap( this->localDistributions, this->nonLocalDistributions ); -} +void D3Q27EsoTwist3DSplittedVector::swap() { std::swap(this->localDistributions, this->nonLocalDistributions); } ////////////////////////////////////////////////////////////////////////// -void D3Q27EsoTwist3DSplittedVector::getDistribution(LBMReal* const f, size_t x1, size_t x2, size_t x3) +void D3Q27EsoTwist3DSplittedVector::getDistribution(LBMReal *const f, size_t x1, size_t x2, size_t x3) { - f[D3Q27System::E] = (*this->localDistributions)(D3Q27System::ET_E, x1,x2,x3); - f[D3Q27System::N] = (*this->localDistributions)(D3Q27System::ET_N,x1,x2,x3); - f[D3Q27System::T] = (*this->localDistributions)(D3Q27System::ET_T,x1,x2,x3); - f[D3Q27System::NE] = (*this->localDistributions)(D3Q27System::ET_NE,x1,x2,x3); - f[D3Q27System::NW] = (*this->localDistributions)(D3Q27System::ET_NW,x1+1,x2,x3); - f[D3Q27System::TE] = (*this->localDistributions)(D3Q27System::ET_TE,x1,x2,x3); - f[D3Q27System::TW] = (*this->localDistributions)(D3Q27System::ET_TW, x1+1,x2,x3); - f[D3Q27System::TN] = (*this->localDistributions)(D3Q27System::ET_TN,x1,x2,x3); - f[D3Q27System::TS] = (*this->localDistributions)(D3Q27System::ET_TS,x1,x2+1,x3); - f[D3Q27System::TNE] = (*this->localDistributions)(D3Q27System::ET_TNE,x1,x2,x3); - f[D3Q27System::TNW] = (*this->localDistributions)(D3Q27System::ET_TNW,x1+1,x2,x3); - f[D3Q27System::TSE] = (*this->localDistributions)(D3Q27System::ET_TSE,x1,x2+1,x3); - f[D3Q27System::TSW] = (*this->localDistributions)(D3Q27System::ET_TSW,x1+1,x2+1,x3); + f[D3Q27System::E] = (*this->localDistributions)(D3Q27System::ET_E, x1, x2, x3); + f[D3Q27System::N] = (*this->localDistributions)(D3Q27System::ET_N, x1, x2, x3); + f[D3Q27System::T] = (*this->localDistributions)(D3Q27System::ET_T, x1, x2, x3); + f[D3Q27System::NE] = (*this->localDistributions)(D3Q27System::ET_NE, x1, x2, x3); + f[D3Q27System::NW] = (*this->localDistributions)(D3Q27System::ET_NW, x1 + 1, x2, x3); + f[D3Q27System::TE] = (*this->localDistributions)(D3Q27System::ET_TE, x1, x2, x3); + f[D3Q27System::TW] = (*this->localDistributions)(D3Q27System::ET_TW, x1 + 1, x2, x3); + f[D3Q27System::TN] = (*this->localDistributions)(D3Q27System::ET_TN, x1, x2, x3); + f[D3Q27System::TS] = (*this->localDistributions)(D3Q27System::ET_TS, x1, x2 + 1, x3); + f[D3Q27System::TNE] = (*this->localDistributions)(D3Q27System::ET_TNE, x1, x2, x3); + f[D3Q27System::TNW] = (*this->localDistributions)(D3Q27System::ET_TNW, x1 + 1, x2, x3); + f[D3Q27System::TSE] = (*this->localDistributions)(D3Q27System::ET_TSE, x1, x2 + 1, x3); + f[D3Q27System::TSW] = (*this->localDistributions)(D3Q27System::ET_TSW, x1 + 1, x2 + 1, x3); - f[D3Q27System::W ] = (*this->nonLocalDistributions)(D3Q27System::ET_W,x1+1,x2,x3 ); - f[D3Q27System::S ] = (*this->nonLocalDistributions)(D3Q27System::ET_S,x1,x2+1,x3 ); - f[D3Q27System::B ] = (*this->nonLocalDistributions)(D3Q27System::ET_B,x1,x2,x3+1 ); - f[D3Q27System::SW] = (*this->nonLocalDistributions)(D3Q27System::ET_SW,x1+1,x2+1,x3 ); - f[D3Q27System::SE] = (*this->nonLocalDistributions)(D3Q27System::ET_SE,x1,x2+1,x3 ); - f[D3Q27System::BW] = (*this->nonLocalDistributions)(D3Q27System::ET_BW,x1+1,x2,x3+1 ); - f[D3Q27System::BE] = (*this->nonLocalDistributions)(D3Q27System::ET_BE,x1,x2,x3+1 ); - f[D3Q27System::BS] = (*this->nonLocalDistributions)(D3Q27System::ET_BS,x1,x2+1,x3+1 ); - f[D3Q27System::BN] = (*this->nonLocalDistributions)(D3Q27System::ET_BN,x1,x2,x3+1 ); - f[D3Q27System::BSW] = (*this->nonLocalDistributions)(D3Q27System::ET_BSW,x1+1,x2+1,x3+1); - f[D3Q27System::BSE] = (*this->nonLocalDistributions)(D3Q27System::ET_BSE,x1,x2+1,x3+1); - f[D3Q27System::BNW] = (*this->nonLocalDistributions)(D3Q27System::ET_BNW,x1+1,x2,x3+1); - f[D3Q27System::BNE] = (*this->nonLocalDistributions)(D3Q27System::ET_BNE,x1,x2,x3+1); + f[D3Q27System::W] = (*this->nonLocalDistributions)(D3Q27System::ET_W, x1 + 1, x2, x3); + f[D3Q27System::S] = (*this->nonLocalDistributions)(D3Q27System::ET_S, x1, x2 + 1, x3); + f[D3Q27System::B] = (*this->nonLocalDistributions)(D3Q27System::ET_B, x1, x2, x3 + 1); + f[D3Q27System::SW] = (*this->nonLocalDistributions)(D3Q27System::ET_SW, x1 + 1, x2 + 1, x3); + f[D3Q27System::SE] = (*this->nonLocalDistributions)(D3Q27System::ET_SE, x1, x2 + 1, x3); + f[D3Q27System::BW] = (*this->nonLocalDistributions)(D3Q27System::ET_BW, x1 + 1, x2, x3 + 1); + f[D3Q27System::BE] = (*this->nonLocalDistributions)(D3Q27System::ET_BE, x1, x2, x3 + 1); + f[D3Q27System::BS] = (*this->nonLocalDistributions)(D3Q27System::ET_BS, x1, x2 + 1, x3 + 1); + f[D3Q27System::BN] = (*this->nonLocalDistributions)(D3Q27System::ET_BN, x1, x2, x3 + 1); + f[D3Q27System::BSW] = (*this->nonLocalDistributions)(D3Q27System::ET_BSW, x1 + 1, x2 + 1, x3 + 1); + f[D3Q27System::BSE] = (*this->nonLocalDistributions)(D3Q27System::ET_BSE, x1, x2 + 1, x3 + 1); + f[D3Q27System::BNW] = (*this->nonLocalDistributions)(D3Q27System::ET_BNW, x1 + 1, x2, x3 + 1); + f[D3Q27System::BNE] = (*this->nonLocalDistributions)(D3Q27System::ET_BNE, x1, x2, x3 + 1); - f[D3Q27System::ZERO] = (*this->zeroDistributions)(x1,x2,x3); + f[D3Q27System::ZERO] = (*this->zeroDistributions)(x1, x2, x3); } ////////////////////////////////////////////////////////////////////////// -void D3Q27EsoTwist3DSplittedVector::setDistribution(const LBMReal* const f, size_t x1, size_t x2, size_t x3) +void D3Q27EsoTwist3DSplittedVector::setDistribution(const LBMReal *const f, size_t x1, size_t x2, size_t x3) { - (*this->localDistributions)(D3Q27System::ET_E,x1, x2, x3) = f[D3Q27System::INV_E]; - (*this->localDistributions)(D3Q27System::ET_N,x1, x2, x3) = f[D3Q27System::INV_N]; - (*this->localDistributions)(D3Q27System::ET_T,x1, x2, x3) = f[D3Q27System::INV_T]; - (*this->localDistributions)(D3Q27System::ET_NE,x1, x2, x3) = f[D3Q27System::INV_NE]; - (*this->localDistributions)(D3Q27System::ET_NW,x1+1,x2, x3) = f[D3Q27System::INV_NW]; - (*this->localDistributions)(D3Q27System::ET_TE,x1, x2, x3) = f[D3Q27System::INV_TE]; - (*this->localDistributions)(D3Q27System::ET_TW,x1+1,x2, x3) = f[D3Q27System::INV_TW]; - (*this->localDistributions)(D3Q27System::ET_TN,x1, x2, x3) = f[D3Q27System::INV_TN]; - (*this->localDistributions)(D3Q27System::ET_TS,x1, x2+1,x3) = f[D3Q27System::INV_TS]; - (*this->localDistributions)(D3Q27System::ET_TNE,x1, x2, x3) = f[D3Q27System::INV_TNE]; - (*this->localDistributions)(D3Q27System::ET_TNW,x1+1,x2, x3) = f[D3Q27System::INV_TNW]; - (*this->localDistributions)(D3Q27System::ET_TSE,x1, x2+1,x3) = f[D3Q27System::INV_TSE]; - (*this->localDistributions)(D3Q27System::ET_TSW,x1+1,x2+1,x3) = f[D3Q27System::INV_TSW]; + (*this->localDistributions)(D3Q27System::ET_E, x1, x2, x3) = f[D3Q27System::INV_E]; + (*this->localDistributions)(D3Q27System::ET_N, x1, x2, x3) = f[D3Q27System::INV_N]; + (*this->localDistributions)(D3Q27System::ET_T, x1, x2, x3) = f[D3Q27System::INV_T]; + (*this->localDistributions)(D3Q27System::ET_NE, x1, x2, x3) = f[D3Q27System::INV_NE]; + (*this->localDistributions)(D3Q27System::ET_NW, x1 + 1, x2, x3) = f[D3Q27System::INV_NW]; + (*this->localDistributions)(D3Q27System::ET_TE, x1, x2, x3) = f[D3Q27System::INV_TE]; + (*this->localDistributions)(D3Q27System::ET_TW, x1 + 1, x2, x3) = f[D3Q27System::INV_TW]; + (*this->localDistributions)(D3Q27System::ET_TN, x1, x2, x3) = f[D3Q27System::INV_TN]; + (*this->localDistributions)(D3Q27System::ET_TS, x1, x2 + 1, x3) = f[D3Q27System::INV_TS]; + (*this->localDistributions)(D3Q27System::ET_TNE, x1, x2, x3) = f[D3Q27System::INV_TNE]; + (*this->localDistributions)(D3Q27System::ET_TNW, x1 + 1, x2, x3) = f[D3Q27System::INV_TNW]; + (*this->localDistributions)(D3Q27System::ET_TSE, x1, x2 + 1, x3) = f[D3Q27System::INV_TSE]; + (*this->localDistributions)(D3Q27System::ET_TSW, x1 + 1, x2 + 1, x3) = f[D3Q27System::INV_TSW]; - (*this->nonLocalDistributions)(D3Q27System::ET_W,x1+1,x2, x3 ) = f[D3Q27System::INV_W ]; - (*this->nonLocalDistributions)(D3Q27System::ET_S,x1, x2+1,x3 ) = f[D3Q27System::INV_S ]; - (*this->nonLocalDistributions)(D3Q27System::ET_B,x1, x2, x3+1 ) = f[D3Q27System::INV_B ]; - (*this->nonLocalDistributions)(D3Q27System::ET_SW,x1+1,x2+1,x3 ) = f[D3Q27System::INV_SW]; - (*this->nonLocalDistributions)(D3Q27System::ET_SE,x1, x2+1,x3 ) = f[D3Q27System::INV_SE]; - (*this->nonLocalDistributions)(D3Q27System::ET_BW,x1+1,x2, x3+1 ) = f[D3Q27System::INV_BW]; - (*this->nonLocalDistributions)(D3Q27System::ET_BE,x1, x2, x3+1 ) = f[D3Q27System::INV_BE]; - (*this->nonLocalDistributions)(D3Q27System::ET_BS,x1, x2+1,x3+1 ) = f[D3Q27System::INV_BS]; - (*this->nonLocalDistributions)(D3Q27System::ET_BN,x1, x2, x3+1 ) = f[D3Q27System::INV_BN]; - (*this->nonLocalDistributions)(D3Q27System::ET_BSW,x1+1,x2+1,x3+1) = f[D3Q27System::INV_BSW]; - (*this->nonLocalDistributions)(D3Q27System::ET_BSE,x1, x2+1,x3+1) = f[D3Q27System::INV_BSE]; - (*this->nonLocalDistributions)(D3Q27System::ET_BNW,x1+1,x2, x3+1) = f[D3Q27System::INV_BNW]; - (*this->nonLocalDistributions)(D3Q27System::ET_BNE,x1, x2, x3+1) = f[D3Q27System::INV_BNE]; + (*this->nonLocalDistributions)(D3Q27System::ET_W, x1 + 1, x2, x3) = f[D3Q27System::INV_W]; + (*this->nonLocalDistributions)(D3Q27System::ET_S, x1, x2 + 1, x3) = f[D3Q27System::INV_S]; + (*this->nonLocalDistributions)(D3Q27System::ET_B, x1, x2, x3 + 1) = f[D3Q27System::INV_B]; + (*this->nonLocalDistributions)(D3Q27System::ET_SW, x1 + 1, x2 + 1, x3) = f[D3Q27System::INV_SW]; + (*this->nonLocalDistributions)(D3Q27System::ET_SE, x1, x2 + 1, x3) = f[D3Q27System::INV_SE]; + (*this->nonLocalDistributions)(D3Q27System::ET_BW, x1 + 1, x2, x3 + 1) = f[D3Q27System::INV_BW]; + (*this->nonLocalDistributions)(D3Q27System::ET_BE, x1, x2, x3 + 1) = f[D3Q27System::INV_BE]; + (*this->nonLocalDistributions)(D3Q27System::ET_BS, x1, x2 + 1, x3 + 1) = f[D3Q27System::INV_BS]; + (*this->nonLocalDistributions)(D3Q27System::ET_BN, x1, x2, x3 + 1) = f[D3Q27System::INV_BN]; + (*this->nonLocalDistributions)(D3Q27System::ET_BSW, x1 + 1, x2 + 1, x3 + 1) = f[D3Q27System::INV_BSW]; + (*this->nonLocalDistributions)(D3Q27System::ET_BSE, x1, x2 + 1, x3 + 1) = f[D3Q27System::INV_BSE]; + (*this->nonLocalDistributions)(D3Q27System::ET_BNW, x1 + 1, x2, x3 + 1) = f[D3Q27System::INV_BNW]; + (*this->nonLocalDistributions)(D3Q27System::ET_BNE, x1, x2, x3 + 1) = f[D3Q27System::INV_BNE]; - (*this->zeroDistributions)(x1,x2,x3) = f[D3Q27System::ZERO]; + (*this->zeroDistributions)(x1, x2, x3) = f[D3Q27System::ZERO]; } ////////////////////////////////////////////////////////////////////////// -void D3Q27EsoTwist3DSplittedVector::getDistributionInv(LBMReal* const f, size_t x1, size_t x2, size_t x3) +void D3Q27EsoTwist3DSplittedVector::getDistributionInv(LBMReal *const f, size_t x1, size_t x2, size_t x3) { - f[D3Q27System::INV_E] = (*this->localDistributions)(D3Q27System::ET_E, x1,x2,x3); - f[D3Q27System::INV_N] = (*this->localDistributions)(D3Q27System::ET_N,x1,x2,x3); - f[D3Q27System::INV_T] = (*this->localDistributions)(D3Q27System::ET_T,x1,x2,x3); - f[D3Q27System::INV_NE] = (*this->localDistributions)(D3Q27System::ET_NE,x1,x2,x3); - f[D3Q27System::INV_NW] = (*this->localDistributions)(D3Q27System::ET_NW,x1+1,x2,x3); - f[D3Q27System::INV_TE] = (*this->localDistributions)(D3Q27System::ET_TE,x1,x2,x3); - f[D3Q27System::INV_TW] = (*this->localDistributions)(D3Q27System::ET_TW, x1+1,x2,x3); - f[D3Q27System::INV_TN] = (*this->localDistributions)(D3Q27System::ET_TN,x1,x2,x3); - f[D3Q27System::INV_TS] = (*this->localDistributions)(D3Q27System::ET_TS,x1,x2+1,x3); - f[D3Q27System::INV_TNE] = (*this->localDistributions)(D3Q27System::ET_TNE,x1,x2,x3); - f[D3Q27System::INV_TNW] = (*this->localDistributions)(D3Q27System::ET_TNW,x1+1,x2,x3); - f[D3Q27System::INV_TSE] = (*this->localDistributions)(D3Q27System::ET_TSE,x1,x2+1,x3); - f[D3Q27System::INV_TSW] = (*this->localDistributions)(D3Q27System::ET_TSW,x1+1,x2+1,x3); + f[D3Q27System::INV_E] = (*this->localDistributions)(D3Q27System::ET_E, x1, x2, x3); + f[D3Q27System::INV_N] = (*this->localDistributions)(D3Q27System::ET_N, x1, x2, x3); + f[D3Q27System::INV_T] = (*this->localDistributions)(D3Q27System::ET_T, x1, x2, x3); + f[D3Q27System::INV_NE] = (*this->localDistributions)(D3Q27System::ET_NE, x1, x2, x3); + f[D3Q27System::INV_NW] = (*this->localDistributions)(D3Q27System::ET_NW, x1 + 1, x2, x3); + f[D3Q27System::INV_TE] = (*this->localDistributions)(D3Q27System::ET_TE, x1, x2, x3); + f[D3Q27System::INV_TW] = (*this->localDistributions)(D3Q27System::ET_TW, x1 + 1, x2, x3); + f[D3Q27System::INV_TN] = (*this->localDistributions)(D3Q27System::ET_TN, x1, x2, x3); + f[D3Q27System::INV_TS] = (*this->localDistributions)(D3Q27System::ET_TS, x1, x2 + 1, x3); + f[D3Q27System::INV_TNE] = (*this->localDistributions)(D3Q27System::ET_TNE, x1, x2, x3); + f[D3Q27System::INV_TNW] = (*this->localDistributions)(D3Q27System::ET_TNW, x1 + 1, x2, x3); + f[D3Q27System::INV_TSE] = (*this->localDistributions)(D3Q27System::ET_TSE, x1, x2 + 1, x3); + f[D3Q27System::INV_TSW] = (*this->localDistributions)(D3Q27System::ET_TSW, x1 + 1, x2 + 1, x3); - f[D3Q27System::INV_W ] = (*this->nonLocalDistributions)(D3Q27System::ET_W,x1+1,x2,x3 ); - f[D3Q27System::INV_S ] = (*this->nonLocalDistributions)(D3Q27System::ET_S,x1,x2+1,x3 ); - f[D3Q27System::INV_B ] = (*this->nonLocalDistributions)(D3Q27System::ET_B,x1,x2,x3+1 ); - f[D3Q27System::INV_SW] = (*this->nonLocalDistributions)(D3Q27System::ET_SW,x1+1,x2+1,x3 ); - f[D3Q27System::INV_SE] = (*this->nonLocalDistributions)(D3Q27System::ET_SE,x1,x2+1,x3 ); - f[D3Q27System::INV_BW] = (*this->nonLocalDistributions)(D3Q27System::ET_BW,x1+1,x2,x3+1 ); - f[D3Q27System::INV_BE] = (*this->nonLocalDistributions)(D3Q27System::ET_BE,x1,x2,x3+1 ); - f[D3Q27System::INV_BS] = (*this->nonLocalDistributions)(D3Q27System::ET_BS,x1,x2+1,x3+1 ); - f[D3Q27System::INV_BN] = (*this->nonLocalDistributions)(D3Q27System::ET_BN,x1,x2,x3+1 ); - f[D3Q27System::INV_BSW] = (*this->nonLocalDistributions)(D3Q27System::ET_BSW,x1+1,x2+1,x3+1); - f[D3Q27System::INV_BSE] = (*this->nonLocalDistributions)(D3Q27System::ET_BSE,x1,x2+1,x3+1); - f[D3Q27System::INV_BNW] = (*this->nonLocalDistributions)(D3Q27System::ET_BNW,x1+1,x2,x3+1); - f[D3Q27System::INV_BNE] = (*this->nonLocalDistributions)(D3Q27System::ET_BNE,x1,x2,x3+1); + f[D3Q27System::INV_W] = (*this->nonLocalDistributions)(D3Q27System::ET_W, x1 + 1, x2, x3); + f[D3Q27System::INV_S] = (*this->nonLocalDistributions)(D3Q27System::ET_S, x1, x2 + 1, x3); + f[D3Q27System::INV_B] = (*this->nonLocalDistributions)(D3Q27System::ET_B, x1, x2, x3 + 1); + f[D3Q27System::INV_SW] = (*this->nonLocalDistributions)(D3Q27System::ET_SW, x1 + 1, x2 + 1, x3); + f[D3Q27System::INV_SE] = (*this->nonLocalDistributions)(D3Q27System::ET_SE, x1, x2 + 1, x3); + f[D3Q27System::INV_BW] = (*this->nonLocalDistributions)(D3Q27System::ET_BW, x1 + 1, x2, x3 + 1); + f[D3Q27System::INV_BE] = (*this->nonLocalDistributions)(D3Q27System::ET_BE, x1, x2, x3 + 1); + f[D3Q27System::INV_BS] = (*this->nonLocalDistributions)(D3Q27System::ET_BS, x1, x2 + 1, x3 + 1); + f[D3Q27System::INV_BN] = (*this->nonLocalDistributions)(D3Q27System::ET_BN, x1, x2, x3 + 1); + f[D3Q27System::INV_BSW] = (*this->nonLocalDistributions)(D3Q27System::ET_BSW, x1 + 1, x2 + 1, x3 + 1); + f[D3Q27System::INV_BSE] = (*this->nonLocalDistributions)(D3Q27System::ET_BSE, x1, x2 + 1, x3 + 1); + f[D3Q27System::INV_BNW] = (*this->nonLocalDistributions)(D3Q27System::ET_BNW, x1 + 1, x2, x3 + 1); + f[D3Q27System::INV_BNE] = (*this->nonLocalDistributions)(D3Q27System::ET_BNE, x1, x2, x3 + 1); - f[D3Q27System::ZERO] = (*this->zeroDistributions)(x1,x2,x3); + f[D3Q27System::ZERO] = (*this->zeroDistributions)(x1, x2, x3); } ////////////////////////////////////////////////////////////////////////// -void D3Q27EsoTwist3DSplittedVector::setDistributionInv(const LBMReal* const f, size_t x1, size_t x2, size_t x3) +void D3Q27EsoTwist3DSplittedVector::setDistributionInv(const LBMReal *const f, size_t x1, size_t x2, size_t x3) { - (*this->localDistributions)(D3Q27System::ET_E,x1, x2, x3) = f[D3Q27System::E]; - (*this->localDistributions)(D3Q27System::ET_N,x1, x2, x3) = f[D3Q27System::N]; - (*this->localDistributions)(D3Q27System::ET_T,x1, x2, x3) = f[D3Q27System::T]; - (*this->localDistributions)(D3Q27System::ET_NE,x1, x2, x3) = f[D3Q27System::NE]; - (*this->localDistributions)(D3Q27System::ET_NW,x1+1,x2, x3) = f[D3Q27System::NW]; - (*this->localDistributions)(D3Q27System::ET_TE,x1, x2, x3) = f[D3Q27System::TE]; - (*this->localDistributions)(D3Q27System::ET_TW,x1+1,x2, x3) = f[D3Q27System::TW]; - (*this->localDistributions)(D3Q27System::ET_TN,x1, x2, x3) = f[D3Q27System::TN]; - (*this->localDistributions)(D3Q27System::ET_TS,x1, x2+1,x3) = f[D3Q27System::TS]; - (*this->localDistributions)(D3Q27System::ET_TNE,x1, x2, x3) = f[D3Q27System::TNE]; - (*this->localDistributions)(D3Q27System::ET_TNW,x1+1,x2, x3) = f[D3Q27System::TNW]; - (*this->localDistributions)(D3Q27System::ET_TSE,x1, x2+1,x3) = f[D3Q27System::TSE]; - (*this->localDistributions)(D3Q27System::ET_TSW,x1+1,x2+1,x3) = f[D3Q27System::TSW]; + (*this->localDistributions)(D3Q27System::ET_E, x1, x2, x3) = f[D3Q27System::E]; + (*this->localDistributions)(D3Q27System::ET_N, x1, x2, x3) = f[D3Q27System::N]; + (*this->localDistributions)(D3Q27System::ET_T, x1, x2, x3) = f[D3Q27System::T]; + (*this->localDistributions)(D3Q27System::ET_NE, x1, x2, x3) = f[D3Q27System::NE]; + (*this->localDistributions)(D3Q27System::ET_NW, x1 + 1, x2, x3) = f[D3Q27System::NW]; + (*this->localDistributions)(D3Q27System::ET_TE, x1, x2, x3) = f[D3Q27System::TE]; + (*this->localDistributions)(D3Q27System::ET_TW, x1 + 1, x2, x3) = f[D3Q27System::TW]; + (*this->localDistributions)(D3Q27System::ET_TN, x1, x2, x3) = f[D3Q27System::TN]; + (*this->localDistributions)(D3Q27System::ET_TS, x1, x2 + 1, x3) = f[D3Q27System::TS]; + (*this->localDistributions)(D3Q27System::ET_TNE, x1, x2, x3) = f[D3Q27System::TNE]; + (*this->localDistributions)(D3Q27System::ET_TNW, x1 + 1, x2, x3) = f[D3Q27System::TNW]; + (*this->localDistributions)(D3Q27System::ET_TSE, x1, x2 + 1, x3) = f[D3Q27System::TSE]; + (*this->localDistributions)(D3Q27System::ET_TSW, x1 + 1, x2 + 1, x3) = f[D3Q27System::TSW]; - (*this->nonLocalDistributions)(D3Q27System::ET_W,x1+1,x2, x3 ) = f[D3Q27System::W ]; - (*this->nonLocalDistributions)(D3Q27System::ET_S,x1, x2+1,x3 ) = f[D3Q27System::S ]; - (*this->nonLocalDistributions)(D3Q27System::ET_B,x1, x2, x3+1 ) = f[D3Q27System::B ]; - (*this->nonLocalDistributions)(D3Q27System::ET_SW,x1+1,x2+1,x3 ) = f[D3Q27System::SW]; - (*this->nonLocalDistributions)(D3Q27System::ET_SE,x1, x2+1,x3 ) = f[D3Q27System::SE]; - (*this->nonLocalDistributions)(D3Q27System::ET_BW,x1+1,x2, x3+1 ) = f[D3Q27System::BW]; - (*this->nonLocalDistributions)(D3Q27System::ET_BE,x1, x2, x3+1 ) = f[D3Q27System::BE]; - (*this->nonLocalDistributions)(D3Q27System::ET_BS,x1, x2+1,x3+1 ) = f[D3Q27System::BS]; - (*this->nonLocalDistributions)(D3Q27System::ET_BN,x1, x2, x3+1 ) = f[D3Q27System::BN]; - (*this->nonLocalDistributions)(D3Q27System::ET_BSW,x1+1,x2+1,x3+1) = f[D3Q27System::BSW]; - (*this->nonLocalDistributions)(D3Q27System::ET_BSE,x1, x2+1,x3+1) = f[D3Q27System::BSE]; - (*this->nonLocalDistributions)(D3Q27System::ET_BNW,x1+1,x2, x3+1) = f[D3Q27System::BNW]; - (*this->nonLocalDistributions)(D3Q27System::ET_BNE,x1, x2, x3+1) = f[D3Q27System::BNE]; + (*this->nonLocalDistributions)(D3Q27System::ET_W, x1 + 1, x2, x3) = f[D3Q27System::W]; + (*this->nonLocalDistributions)(D3Q27System::ET_S, x1, x2 + 1, x3) = f[D3Q27System::S]; + (*this->nonLocalDistributions)(D3Q27System::ET_B, x1, x2, x3 + 1) = f[D3Q27System::B]; + (*this->nonLocalDistributions)(D3Q27System::ET_SW, x1 + 1, x2 + 1, x3) = f[D3Q27System::SW]; + (*this->nonLocalDistributions)(D3Q27System::ET_SE, x1, x2 + 1, x3) = f[D3Q27System::SE]; + (*this->nonLocalDistributions)(D3Q27System::ET_BW, x1 + 1, x2, x3 + 1) = f[D3Q27System::BW]; + (*this->nonLocalDistributions)(D3Q27System::ET_BE, x1, x2, x3 + 1) = f[D3Q27System::BE]; + (*this->nonLocalDistributions)(D3Q27System::ET_BS, x1, x2 + 1, x3 + 1) = f[D3Q27System::BS]; + (*this->nonLocalDistributions)(D3Q27System::ET_BN, x1, x2, x3 + 1) = f[D3Q27System::BN]; + (*this->nonLocalDistributions)(D3Q27System::ET_BSW, x1 + 1, x2 + 1, x3 + 1) = f[D3Q27System::BSW]; + (*this->nonLocalDistributions)(D3Q27System::ET_BSE, x1, x2 + 1, x3 + 1) = f[D3Q27System::BSE]; + (*this->nonLocalDistributions)(D3Q27System::ET_BNW, x1 + 1, x2, x3 + 1) = f[D3Q27System::BNW]; + (*this->nonLocalDistributions)(D3Q27System::ET_BNE, x1, x2, x3 + 1) = f[D3Q27System::BNE]; - (*this->zeroDistributions)(x1,x2,x3) = f[D3Q27System::ZERO]; + (*this->zeroDistributions)(x1, x2, x3) = f[D3Q27System::ZERO]; } ////////////////////////////////////////////////////////////////////////// -void D3Q27EsoTwist3DSplittedVector::setDistributionForDirection(const LBMReal* const f, size_t x1, size_t x2, size_t x3, unsigned long int direction) +void D3Q27EsoTwist3DSplittedVector::setDistributionForDirection(const LBMReal *const f, size_t x1, size_t x2, size_t x3, + unsigned long int direction) { - if ((direction & EsoTwistD3Q27System::etE) == EsoTwistD3Q27System::etE) - (*this->nonLocalDistributions)(D3Q27System::ET_W,x1+1,x2, x3 ) = f[D3Q27System::E]; - if ((direction & EsoTwistD3Q27System::etW) == EsoTwistD3Q27System::etW) - (*this->localDistributions)(D3Q27System::ET_E,x1, x2, x3) = f[D3Q27System::W]; - if ((direction & EsoTwistD3Q27System::etS) == EsoTwistD3Q27System::etS) - (*this->localDistributions)(D3Q27System::ET_N,x1, x2, x3) = f[D3Q27System::S]; - if ((direction & EsoTwistD3Q27System::etN) == EsoTwistD3Q27System::etN) - (*this->nonLocalDistributions)(D3Q27System::ET_S,x1, x2+1,x3 ) = f[D3Q27System::N]; - if ((direction & EsoTwistD3Q27System::etB) == EsoTwistD3Q27System::etB) - (*this->localDistributions)(D3Q27System::ET_T,x1, x2, x3) = f[D3Q27System::B]; - if ((direction & EsoTwistD3Q27System::etT) == EsoTwistD3Q27System::etT) - (*this->nonLocalDistributions)(D3Q27System::ET_B,x1, x2, x3+1 ) = f[D3Q27System::T]; - if ((direction & EsoTwistD3Q27System::etSW) == EsoTwistD3Q27System::etSW) - (*this->localDistributions)(D3Q27System::ET_NE,x1, x2, x3) = f[D3Q27System::SW]; - if ((direction & EsoTwistD3Q27System::etNE) == EsoTwistD3Q27System::etNE) - (*this->nonLocalDistributions)(D3Q27System::ET_SW,x1+1,x2+1,x3 ) = f[D3Q27System::NE]; - if ((direction & EsoTwistD3Q27System::etNW) == EsoTwistD3Q27System::etNW) - (*this->nonLocalDistributions)(D3Q27System::ET_SE,x1, x2+1,x3 ) = f[D3Q27System::NW]; - if ((direction & EsoTwistD3Q27System::etSE) == EsoTwistD3Q27System::etSE) - (*this->localDistributions)(D3Q27System::ET_NW,x1+1,x2, x3) = f[D3Q27System::SE]; - if ((direction & EsoTwistD3Q27System::etBW) == EsoTwistD3Q27System::etBW) - (*this->localDistributions)(D3Q27System::ET_TE,x1, x2, x3) = f[D3Q27System::BW]; - if ((direction & EsoTwistD3Q27System::etTE) == EsoTwistD3Q27System::etTE) - (*this->nonLocalDistributions)(D3Q27System::ET_BW,x1+1,x2, x3+1 ) = f[D3Q27System::TE]; - if ((direction & EsoTwistD3Q27System::etTW) == EsoTwistD3Q27System::etTW) - (*this->nonLocalDistributions)(D3Q27System::ET_BE,x1, x2, x3+1 ) = f[D3Q27System::TW]; - if ((direction & EsoTwistD3Q27System::etBE) == EsoTwistD3Q27System::etBE) - (*this->localDistributions)(D3Q27System::ET_TW,x1+1,x2, x3) = f[D3Q27System::BE]; - if ((direction & EsoTwistD3Q27System::etBS) == EsoTwistD3Q27System::etBS) - (*this->localDistributions)(D3Q27System::ET_TN,x1, x2, x3) = f[D3Q27System::BS]; - if ((direction & EsoTwistD3Q27System::etTN) == EsoTwistD3Q27System::etTN) - (*this->nonLocalDistributions)(D3Q27System::ET_BS,x1, x2+1,x3+1 ) = f[D3Q27System::TN]; - if ((direction & EsoTwistD3Q27System::etTS) == EsoTwistD3Q27System::etTS) - (*this->nonLocalDistributions)(D3Q27System::ET_BN,x1, x2, x3+1 ) = f[D3Q27System::TS]; - if ((direction & EsoTwistD3Q27System::etBN) == EsoTwistD3Q27System::etBN) - (*this->localDistributions)(D3Q27System::ET_TS,x1, x2+1,x3) = f[D3Q27System::BN]; - if ((direction & EsoTwistD3Q27System::etBSW) == EsoTwistD3Q27System::etBSW) - (*this->localDistributions)(D3Q27System::ET_TNE,x1, x2, x3) = f[D3Q27System::BSW]; - if ((direction & EsoTwistD3Q27System::etTNE) == EsoTwistD3Q27System::etTNE) - (*this->nonLocalDistributions)(D3Q27System::ET_BSW,x1+1,x2+1,x3+1) = f[D3Q27System::TNE]; - if ((direction & EsoTwistD3Q27System::etBSE) == EsoTwistD3Q27System::etBSE) - (*this->localDistributions)(D3Q27System::ET_TNW,x1+1,x2, x3) = f[D3Q27System::BSE]; - if ((direction & EsoTwistD3Q27System::etTNW) == EsoTwistD3Q27System::etTNW) - (*this->nonLocalDistributions)(D3Q27System::ET_BSE,x1, x2+1,x3+1) = f[D3Q27System::TNW]; - if ((direction & EsoTwistD3Q27System::etBNW) == EsoTwistD3Q27System::etBNW) - (*this->localDistributions)(D3Q27System::ET_TSE,x1, x2+1,x3) = f[D3Q27System::BNW]; - if ((direction & EsoTwistD3Q27System::etTSE) == EsoTwistD3Q27System::etTSE) - (*this->nonLocalDistributions)(D3Q27System::ET_BNW,x1+1,x2, x3+1) = f[D3Q27System::TSE]; - if ((direction & EsoTwistD3Q27System::etBNE) == EsoTwistD3Q27System::etBNE) - (*this->localDistributions)(D3Q27System::ET_TSW,x1+1,x2+1,x3) = f[D3Q27System::BNE]; - if ((direction & EsoTwistD3Q27System::etTSW) == EsoTwistD3Q27System::etTSW) - (*this->nonLocalDistributions)(D3Q27System::ET_BNE,x1, x2, x3+1) = f[D3Q27System::TSW]; - if ((direction & EsoTwistD3Q27System::ZERO) == EsoTwistD3Q27System::ZERO) - (*this->zeroDistributions)(x1,x2,x3) = f[D3Q27System::ZERO]; + if ((direction & EsoTwistD3Q27System::etE) == EsoTwistD3Q27System::etE) + (*this->nonLocalDistributions)(D3Q27System::ET_W, x1 + 1, x2, x3) = f[D3Q27System::E]; + if ((direction & EsoTwistD3Q27System::etW) == EsoTwistD3Q27System::etW) + (*this->localDistributions)(D3Q27System::ET_E, x1, x2, x3) = f[D3Q27System::W]; + if ((direction & EsoTwistD3Q27System::etS) == EsoTwistD3Q27System::etS) + (*this->localDistributions)(D3Q27System::ET_N, x1, x2, x3) = f[D3Q27System::S]; + if ((direction & EsoTwistD3Q27System::etN) == EsoTwistD3Q27System::etN) + (*this->nonLocalDistributions)(D3Q27System::ET_S, x1, x2 + 1, x3) = f[D3Q27System::N]; + if ((direction & EsoTwistD3Q27System::etB) == EsoTwistD3Q27System::etB) + (*this->localDistributions)(D3Q27System::ET_T, x1, x2, x3) = f[D3Q27System::B]; + if ((direction & EsoTwistD3Q27System::etT) == EsoTwistD3Q27System::etT) + (*this->nonLocalDistributions)(D3Q27System::ET_B, x1, x2, x3 + 1) = f[D3Q27System::T]; + if ((direction & EsoTwistD3Q27System::etSW) == EsoTwistD3Q27System::etSW) + (*this->localDistributions)(D3Q27System::ET_NE, x1, x2, x3) = f[D3Q27System::SW]; + if ((direction & EsoTwistD3Q27System::etNE) == EsoTwistD3Q27System::etNE) + (*this->nonLocalDistributions)(D3Q27System::ET_SW, x1 + 1, x2 + 1, x3) = f[D3Q27System::NE]; + if ((direction & EsoTwistD3Q27System::etNW) == EsoTwistD3Q27System::etNW) + (*this->nonLocalDistributions)(D3Q27System::ET_SE, x1, x2 + 1, x3) = f[D3Q27System::NW]; + if ((direction & EsoTwistD3Q27System::etSE) == EsoTwistD3Q27System::etSE) + (*this->localDistributions)(D3Q27System::ET_NW, x1 + 1, x2, x3) = f[D3Q27System::SE]; + if ((direction & EsoTwistD3Q27System::etBW) == EsoTwistD3Q27System::etBW) + (*this->localDistributions)(D3Q27System::ET_TE, x1, x2, x3) = f[D3Q27System::BW]; + if ((direction & EsoTwistD3Q27System::etTE) == EsoTwistD3Q27System::etTE) + (*this->nonLocalDistributions)(D3Q27System::ET_BW, x1 + 1, x2, x3 + 1) = f[D3Q27System::TE]; + if ((direction & EsoTwistD3Q27System::etTW) == EsoTwistD3Q27System::etTW) + (*this->nonLocalDistributions)(D3Q27System::ET_BE, x1, x2, x3 + 1) = f[D3Q27System::TW]; + if ((direction & EsoTwistD3Q27System::etBE) == EsoTwistD3Q27System::etBE) + (*this->localDistributions)(D3Q27System::ET_TW, x1 + 1, x2, x3) = f[D3Q27System::BE]; + if ((direction & EsoTwistD3Q27System::etBS) == EsoTwistD3Q27System::etBS) + (*this->localDistributions)(D3Q27System::ET_TN, x1, x2, x3) = f[D3Q27System::BS]; + if ((direction & EsoTwistD3Q27System::etTN) == EsoTwistD3Q27System::etTN) + (*this->nonLocalDistributions)(D3Q27System::ET_BS, x1, x2 + 1, x3 + 1) = f[D3Q27System::TN]; + if ((direction & EsoTwistD3Q27System::etTS) == EsoTwistD3Q27System::etTS) + (*this->nonLocalDistributions)(D3Q27System::ET_BN, x1, x2, x3 + 1) = f[D3Q27System::TS]; + if ((direction & EsoTwistD3Q27System::etBN) == EsoTwistD3Q27System::etBN) + (*this->localDistributions)(D3Q27System::ET_TS, x1, x2 + 1, x3) = f[D3Q27System::BN]; + if ((direction & EsoTwistD3Q27System::etBSW) == EsoTwistD3Q27System::etBSW) + (*this->localDistributions)(D3Q27System::ET_TNE, x1, x2, x3) = f[D3Q27System::BSW]; + if ((direction & EsoTwistD3Q27System::etTNE) == EsoTwistD3Q27System::etTNE) + (*this->nonLocalDistributions)(D3Q27System::ET_BSW, x1 + 1, x2 + 1, x3 + 1) = f[D3Q27System::TNE]; + if ((direction & EsoTwistD3Q27System::etBSE) == EsoTwistD3Q27System::etBSE) + (*this->localDistributions)(D3Q27System::ET_TNW, x1 + 1, x2, x3) = f[D3Q27System::BSE]; + if ((direction & EsoTwistD3Q27System::etTNW) == EsoTwistD3Q27System::etTNW) + (*this->nonLocalDistributions)(D3Q27System::ET_BSE, x1, x2 + 1, x3 + 1) = f[D3Q27System::TNW]; + if ((direction & EsoTwistD3Q27System::etBNW) == EsoTwistD3Q27System::etBNW) + (*this->localDistributions)(D3Q27System::ET_TSE, x1, x2 + 1, x3) = f[D3Q27System::BNW]; + if ((direction & EsoTwistD3Q27System::etTSE) == EsoTwistD3Q27System::etTSE) + (*this->nonLocalDistributions)(D3Q27System::ET_BNW, x1 + 1, x2, x3 + 1) = f[D3Q27System::TSE]; + if ((direction & EsoTwistD3Q27System::etBNE) == EsoTwistD3Q27System::etBNE) + (*this->localDistributions)(D3Q27System::ET_TSW, x1 + 1, x2 + 1, x3) = f[D3Q27System::BNE]; + if ((direction & EsoTwistD3Q27System::etTSW) == EsoTwistD3Q27System::etTSW) + (*this->nonLocalDistributions)(D3Q27System::ET_BNE, x1, x2, x3 + 1) = f[D3Q27System::TSW]; + if ((direction & EsoTwistD3Q27System::ZERO) == EsoTwistD3Q27System::ZERO) + (*this->zeroDistributions)(x1, x2, x3) = f[D3Q27System::ZERO]; } ////////////////////////////////////////////////////////////////////////// -void D3Q27EsoTwist3DSplittedVector::setDistributionForDirection(LBMReal f, size_t x1, size_t x2, size_t x3, int direction) +void D3Q27EsoTwist3DSplittedVector::setDistributionForDirection(LBMReal f, size_t x1, size_t x2, size_t x3, + int direction) { - switch (direction) - { - case D3Q27System::E : - (*this->nonLocalDistributions)(D3Q27System::ET_W,x1+1,x2, x3 ) = f; - break; - case D3Q27System::W : - (*this->localDistributions)(D3Q27System::ET_E,x1, x2, x3) = f; - break; - case D3Q27System::S : - (*this->localDistributions)(D3Q27System::ET_N,x1, x2, x3) = f; - break; - case D3Q27System::N : - (*this->nonLocalDistributions)(D3Q27System::ET_S,x1, x2+1,x3 ) = f; - break; - case D3Q27System::B : - (*this->localDistributions)(D3Q27System::ET_T,x1, x2, x3) = f; - break; - case D3Q27System::T : - (*this->nonLocalDistributions)(D3Q27System::ET_B,x1, x2, x3+1 ) = f; - break; - case D3Q27System::SW : - (*this->localDistributions)(D3Q27System::ET_NE,x1, x2, x3) = f; - break; - case D3Q27System::NE : - (*this->nonLocalDistributions)(D3Q27System::ET_SW,x1+1,x2+1,x3 ) = f; - break; - case D3Q27System::NW : - (*this->nonLocalDistributions)(D3Q27System::ET_SE,x1, x2+1,x3 ) = f; - break; - case D3Q27System::SE : - (*this->localDistributions)(D3Q27System::ET_NW,x1+1,x2, x3) = f; - break; - case D3Q27System::BW : - (*this->localDistributions)(D3Q27System::ET_TE,x1, x2, x3) = f; - break; - case D3Q27System::TE : - (*this->nonLocalDistributions)(D3Q27System::ET_BW,x1+1,x2, x3+1 ) = f; - break; - case D3Q27System::TW : - (*this->nonLocalDistributions)(D3Q27System::ET_BE,x1, x2, x3+1 ) = f; - break; - case D3Q27System::BE : - (*this->localDistributions)(D3Q27System::ET_TW,x1+1,x2, x3) = f; - break; - case D3Q27System::BS : - (*this->localDistributions)(D3Q27System::ET_TN,x1, x2, x3) = f; - break; - case D3Q27System::TN : - (*this->nonLocalDistributions)(D3Q27System::ET_BS,x1, x2+1,x3+1 ) = f; - break; - case D3Q27System::TS : - (*this->nonLocalDistributions)(D3Q27System::ET_BN,x1, x2, x3+1 ) = f; - break; - case D3Q27System::BN : - (*this->localDistributions)(D3Q27System::ET_TS,x1, x2+1,x3) = f; - break; - case D3Q27System::BSW : - (*this->localDistributions)(D3Q27System::ET_TNE,x1, x2, x3) = f; - break; - case D3Q27System::TNE : - (*this->nonLocalDistributions)(D3Q27System::ET_BSW,x1+1,x2+1,x3+1) = f; - break; - case D3Q27System::BSE : - (*this->localDistributions)(D3Q27System::ET_TNW,x1+1,x2, x3) = f; - break; - case D3Q27System::TNW : - (*this->nonLocalDistributions)(D3Q27System::ET_BSE,x1, x2+1,x3+1) = f; - break; - case D3Q27System::BNW : - (*this->localDistributions)(D3Q27System::ET_TSE,x1, x2+1,x3) = f; - break; - case D3Q27System::TSE : - (*this->nonLocalDistributions)(D3Q27System::ET_BNW,x1+1,x2, x3+1) = f; - break; - case D3Q27System::BNE : - (*this->localDistributions)(D3Q27System::ET_TSW,x1+1,x2+1,x3) = f; - break; - case D3Q27System::TSW : - (*this->nonLocalDistributions)(D3Q27System::ET_BNE,x1, x2, x3+1) = f; - break; - case D3Q27System::ZERO : - (*this->zeroDistributions)(x1,x2,x3) = f; - break; - default: - UB_THROW( UbException(UB_EXARGS, "Direction didn't find") ); - } + switch (direction) { + case D3Q27System::E: + (*this->nonLocalDistributions)(D3Q27System::ET_W, x1 + 1, x2, x3) = f; + break; + case D3Q27System::W: + (*this->localDistributions)(D3Q27System::ET_E, x1, x2, x3) = f; + break; + case D3Q27System::S: + (*this->localDistributions)(D3Q27System::ET_N, x1, x2, x3) = f; + break; + case D3Q27System::N: + (*this->nonLocalDistributions)(D3Q27System::ET_S, x1, x2 + 1, x3) = f; + break; + case D3Q27System::B: + (*this->localDistributions)(D3Q27System::ET_T, x1, x2, x3) = f; + break; + case D3Q27System::T: + (*this->nonLocalDistributions)(D3Q27System::ET_B, x1, x2, x3 + 1) = f; + break; + case D3Q27System::SW: + (*this->localDistributions)(D3Q27System::ET_NE, x1, x2, x3) = f; + break; + case D3Q27System::NE: + (*this->nonLocalDistributions)(D3Q27System::ET_SW, x1 + 1, x2 + 1, x3) = f; + break; + case D3Q27System::NW: + (*this->nonLocalDistributions)(D3Q27System::ET_SE, x1, x2 + 1, x3) = f; + break; + case D3Q27System::SE: + (*this->localDistributions)(D3Q27System::ET_NW, x1 + 1, x2, x3) = f; + break; + case D3Q27System::BW: + (*this->localDistributions)(D3Q27System::ET_TE, x1, x2, x3) = f; + break; + case D3Q27System::TE: + (*this->nonLocalDistributions)(D3Q27System::ET_BW, x1 + 1, x2, x3 + 1) = f; + break; + case D3Q27System::TW: + (*this->nonLocalDistributions)(D3Q27System::ET_BE, x1, x2, x3 + 1) = f; + break; + case D3Q27System::BE: + (*this->localDistributions)(D3Q27System::ET_TW, x1 + 1, x2, x3) = f; + break; + case D3Q27System::BS: + (*this->localDistributions)(D3Q27System::ET_TN, x1, x2, x3) = f; + break; + case D3Q27System::TN: + (*this->nonLocalDistributions)(D3Q27System::ET_BS, x1, x2 + 1, x3 + 1) = f; + break; + case D3Q27System::TS: + (*this->nonLocalDistributions)(D3Q27System::ET_BN, x1, x2, x3 + 1) = f; + break; + case D3Q27System::BN: + (*this->localDistributions)(D3Q27System::ET_TS, x1, x2 + 1, x3) = f; + break; + case D3Q27System::BSW: + (*this->localDistributions)(D3Q27System::ET_TNE, x1, x2, x3) = f; + break; + case D3Q27System::TNE: + (*this->nonLocalDistributions)(D3Q27System::ET_BSW, x1 + 1, x2 + 1, x3 + 1) = f; + break; + case D3Q27System::BSE: + (*this->localDistributions)(D3Q27System::ET_TNW, x1 + 1, x2, x3) = f; + break; + case D3Q27System::TNW: + (*this->nonLocalDistributions)(D3Q27System::ET_BSE, x1, x2 + 1, x3 + 1) = f; + break; + case D3Q27System::BNW: + (*this->localDistributions)(D3Q27System::ET_TSE, x1, x2 + 1, x3) = f; + break; + case D3Q27System::TSE: + (*this->nonLocalDistributions)(D3Q27System::ET_BNW, x1 + 1, x2, x3 + 1) = f; + break; + case D3Q27System::BNE: + (*this->localDistributions)(D3Q27System::ET_TSW, x1 + 1, x2 + 1, x3) = f; + break; + case D3Q27System::TSW: + (*this->nonLocalDistributions)(D3Q27System::ET_BNE, x1, x2, x3 + 1) = f; + break; + case D3Q27System::ZERO: + (*this->zeroDistributions)(x1, x2, x3) = f; + break; + default: + UB_THROW(UbException(UB_EXARGS, "Direction didn't find")); + } } ////////////////////////////////////////////////////////////////////////// -void D3Q27EsoTwist3DSplittedVector::setDistributionInvForDirection(const LBMReal* const f, size_t x1, size_t x2, size_t x3, unsigned long int direction) +void D3Q27EsoTwist3DSplittedVector::setDistributionInvForDirection(const LBMReal *const f, size_t x1, size_t x2, + size_t x3, unsigned long int direction) { - if ((direction & EsoTwistD3Q27System::etE) == EsoTwistD3Q27System::etE) - (*this->localDistributions)(D3Q27System::ET_E,x1, x2, x3) = f[D3Q27System::E]; - if ((direction & EsoTwistD3Q27System::etW) == EsoTwistD3Q27System::etW) - (*this->nonLocalDistributions)(D3Q27System::ET_W,x1+1,x2, x3 ) = f[D3Q27System::W]; - if ((direction & EsoTwistD3Q27System::etS) == EsoTwistD3Q27System::etS) - (*this->nonLocalDistributions)(D3Q27System::ET_S,x1, x2+1,x3 ) = f[D3Q27System::S]; - if ((direction & EsoTwistD3Q27System::etN) == EsoTwistD3Q27System::etN) - (*this->localDistributions)(D3Q27System::ET_N,x1, x2, x3) = f[D3Q27System::N]; - if ((direction & EsoTwistD3Q27System::etB) == EsoTwistD3Q27System::etB) - (*this->nonLocalDistributions)(D3Q27System::ET_B,x1, x2, x3+1 ) = f[D3Q27System::B]; - if ((direction & EsoTwistD3Q27System::etT) == EsoTwistD3Q27System::etT) - (*this->localDistributions)(D3Q27System::ET_T,x1, x2, x3) = f[D3Q27System::T]; - if ((direction & EsoTwistD3Q27System::etSW) == EsoTwistD3Q27System::etSW) - (*this->nonLocalDistributions)(D3Q27System::ET_SW,x1+1,x2+1,x3 ) = f[D3Q27System::SW]; - if ((direction & EsoTwistD3Q27System::etNE) == EsoTwistD3Q27System::etNE) - (*this->localDistributions)(D3Q27System::ET_NE,x1, x2, x3) = f[D3Q27System::NE]; - if ((direction & EsoTwistD3Q27System::etNW) == EsoTwistD3Q27System::etNW) - (*this->localDistributions)(D3Q27System::ET_NW,x1+1,x2, x3) = f[D3Q27System::NW]; - if ((direction & EsoTwistD3Q27System::etSE) == EsoTwistD3Q27System::etSE) - (*this->nonLocalDistributions)(D3Q27System::ET_SE,x1, x2+1,x3 ) = f[D3Q27System::SE]; - if ((direction & EsoTwistD3Q27System::etBW) == EsoTwistD3Q27System::etBW) - (*this->nonLocalDistributions)(D3Q27System::ET_BW,x1+1,x2, x3+1 ) = f[D3Q27System::BW]; - if ((direction & EsoTwistD3Q27System::etTE) == EsoTwistD3Q27System::etTE) - (*this->localDistributions)(D3Q27System::ET_TE,x1, x2, x3) = f[D3Q27System::TE]; - if ((direction & EsoTwistD3Q27System::etTW) == EsoTwistD3Q27System::etTW) - (*this->localDistributions)(D3Q27System::ET_TW,x1+1,x2, x3) = f[D3Q27System::TW]; - if ((direction & EsoTwistD3Q27System::etBE) == EsoTwistD3Q27System::etBE) - (*this->nonLocalDistributions)(D3Q27System::ET_BE,x1, x2, x3+1 ) = f[D3Q27System::BE]; - if ((direction & EsoTwistD3Q27System::etBS) == EsoTwistD3Q27System::etBS) - (*this->nonLocalDistributions)(D3Q27System::ET_BS,x1, x2+1,x3+1 ) = f[D3Q27System::BS]; - if ((direction & EsoTwistD3Q27System::etTN) == EsoTwistD3Q27System::etTN) - (*this->localDistributions)(D3Q27System::ET_TN,x1, x2, x3) = f[D3Q27System::TN]; - if ((direction & EsoTwistD3Q27System::etTS) == EsoTwistD3Q27System::etTS) - (*this->localDistributions)(D3Q27System::ET_TS,x1, x2+1,x3) = f[D3Q27System::TS]; - if ((direction & EsoTwistD3Q27System::etBN) == EsoTwistD3Q27System::etBN) - (*this->nonLocalDistributions)(D3Q27System::ET_BN,x1, x2, x3+1 ) = f[D3Q27System::BN]; - if ((direction & EsoTwistD3Q27System::etBSW) == EsoTwistD3Q27System::etBSW) - (*this->nonLocalDistributions)(D3Q27System::ET_BSW,x1+1,x2+1,x3+1) = f[D3Q27System::BSW]; - if ((direction & EsoTwistD3Q27System::etTNE) == EsoTwistD3Q27System::etTNE) - (*this->localDistributions)(D3Q27System::ET_TNE,x1, x2, x3) = f[D3Q27System::TNE]; - if ((direction & EsoTwistD3Q27System::etBSE) == EsoTwistD3Q27System::etBSE) - (*this->nonLocalDistributions)(D3Q27System::ET_BSE,x1, x2+1,x3+1) = f[D3Q27System::BSE]; - if ((direction & EsoTwistD3Q27System::etTNW) == EsoTwistD3Q27System::etTNW) - (*this->localDistributions)(D3Q27System::ET_TNW,x1+1,x2, x3) = f[D3Q27System::TNW]; - if ((direction & EsoTwistD3Q27System::etBNW) == EsoTwistD3Q27System::etBNW) - (*this->nonLocalDistributions)(D3Q27System::ET_BNW,x1+1,x2, x3+1) = f[D3Q27System::BNW]; - if ((direction & EsoTwistD3Q27System::etTSE) == EsoTwistD3Q27System::etTSE) - (*this->localDistributions)(D3Q27System::ET_TSE,x1, x2+1,x3) = f[D3Q27System::TSE]; - if ((direction & EsoTwistD3Q27System::etBNE) == EsoTwistD3Q27System::etBNE) - (*this->nonLocalDistributions)(D3Q27System::ET_BNE,x1, x2, x3+1)= f[D3Q27System::BNE]; - if ((direction & EsoTwistD3Q27System::etTSW) == EsoTwistD3Q27System::etTSW) - (*this->localDistributions)(D3Q27System::ET_TSW,x1+1,x2+1,x3) = f[D3Q27System::TSW]; - if ((direction & EsoTwistD3Q27System::ZERO) == EsoTwistD3Q27System::ZERO) - (*this->zeroDistributions)(x1,x2,x3) = f[D3Q27System::ZERO]; + if ((direction & EsoTwistD3Q27System::etE) == EsoTwistD3Q27System::etE) + (*this->localDistributions)(D3Q27System::ET_E, x1, x2, x3) = f[D3Q27System::E]; + if ((direction & EsoTwistD3Q27System::etW) == EsoTwistD3Q27System::etW) + (*this->nonLocalDistributions)(D3Q27System::ET_W, x1 + 1, x2, x3) = f[D3Q27System::W]; + if ((direction & EsoTwistD3Q27System::etS) == EsoTwistD3Q27System::etS) + (*this->nonLocalDistributions)(D3Q27System::ET_S, x1, x2 + 1, x3) = f[D3Q27System::S]; + if ((direction & EsoTwistD3Q27System::etN) == EsoTwistD3Q27System::etN) + (*this->localDistributions)(D3Q27System::ET_N, x1, x2, x3) = f[D3Q27System::N]; + if ((direction & EsoTwistD3Q27System::etB) == EsoTwistD3Q27System::etB) + (*this->nonLocalDistributions)(D3Q27System::ET_B, x1, x2, x3 + 1) = f[D3Q27System::B]; + if ((direction & EsoTwistD3Q27System::etT) == EsoTwistD3Q27System::etT) + (*this->localDistributions)(D3Q27System::ET_T, x1, x2, x3) = f[D3Q27System::T]; + if ((direction & EsoTwistD3Q27System::etSW) == EsoTwistD3Q27System::etSW) + (*this->nonLocalDistributions)(D3Q27System::ET_SW, x1 + 1, x2 + 1, x3) = f[D3Q27System::SW]; + if ((direction & EsoTwistD3Q27System::etNE) == EsoTwistD3Q27System::etNE) + (*this->localDistributions)(D3Q27System::ET_NE, x1, x2, x3) = f[D3Q27System::NE]; + if ((direction & EsoTwistD3Q27System::etNW) == EsoTwistD3Q27System::etNW) + (*this->localDistributions)(D3Q27System::ET_NW, x1 + 1, x2, x3) = f[D3Q27System::NW]; + if ((direction & EsoTwistD3Q27System::etSE) == EsoTwistD3Q27System::etSE) + (*this->nonLocalDistributions)(D3Q27System::ET_SE, x1, x2 + 1, x3) = f[D3Q27System::SE]; + if ((direction & EsoTwistD3Q27System::etBW) == EsoTwistD3Q27System::etBW) + (*this->nonLocalDistributions)(D3Q27System::ET_BW, x1 + 1, x2, x3 + 1) = f[D3Q27System::BW]; + if ((direction & EsoTwistD3Q27System::etTE) == EsoTwistD3Q27System::etTE) + (*this->localDistributions)(D3Q27System::ET_TE, x1, x2, x3) = f[D3Q27System::TE]; + if ((direction & EsoTwistD3Q27System::etTW) == EsoTwistD3Q27System::etTW) + (*this->localDistributions)(D3Q27System::ET_TW, x1 + 1, x2, x3) = f[D3Q27System::TW]; + if ((direction & EsoTwistD3Q27System::etBE) == EsoTwistD3Q27System::etBE) + (*this->nonLocalDistributions)(D3Q27System::ET_BE, x1, x2, x3 + 1) = f[D3Q27System::BE]; + if ((direction & EsoTwistD3Q27System::etBS) == EsoTwistD3Q27System::etBS) + (*this->nonLocalDistributions)(D3Q27System::ET_BS, x1, x2 + 1, x3 + 1) = f[D3Q27System::BS]; + if ((direction & EsoTwistD3Q27System::etTN) == EsoTwistD3Q27System::etTN) + (*this->localDistributions)(D3Q27System::ET_TN, x1, x2, x3) = f[D3Q27System::TN]; + if ((direction & EsoTwistD3Q27System::etTS) == EsoTwistD3Q27System::etTS) + (*this->localDistributions)(D3Q27System::ET_TS, x1, x2 + 1, x3) = f[D3Q27System::TS]; + if ((direction & EsoTwistD3Q27System::etBN) == EsoTwistD3Q27System::etBN) + (*this->nonLocalDistributions)(D3Q27System::ET_BN, x1, x2, x3 + 1) = f[D3Q27System::BN]; + if ((direction & EsoTwistD3Q27System::etBSW) == EsoTwistD3Q27System::etBSW) + (*this->nonLocalDistributions)(D3Q27System::ET_BSW, x1 + 1, x2 + 1, x3 + 1) = f[D3Q27System::BSW]; + if ((direction & EsoTwistD3Q27System::etTNE) == EsoTwistD3Q27System::etTNE) + (*this->localDistributions)(D3Q27System::ET_TNE, x1, x2, x3) = f[D3Q27System::TNE]; + if ((direction & EsoTwistD3Q27System::etBSE) == EsoTwistD3Q27System::etBSE) + (*this->nonLocalDistributions)(D3Q27System::ET_BSE, x1, x2 + 1, x3 + 1) = f[D3Q27System::BSE]; + if ((direction & EsoTwistD3Q27System::etTNW) == EsoTwistD3Q27System::etTNW) + (*this->localDistributions)(D3Q27System::ET_TNW, x1 + 1, x2, x3) = f[D3Q27System::TNW]; + if ((direction & EsoTwistD3Q27System::etBNW) == EsoTwistD3Q27System::etBNW) + (*this->nonLocalDistributions)(D3Q27System::ET_BNW, x1 + 1, x2, x3 + 1) = f[D3Q27System::BNW]; + if ((direction & EsoTwistD3Q27System::etTSE) == EsoTwistD3Q27System::etTSE) + (*this->localDistributions)(D3Q27System::ET_TSE, x1, x2 + 1, x3) = f[D3Q27System::TSE]; + if ((direction & EsoTwistD3Q27System::etBNE) == EsoTwistD3Q27System::etBNE) + (*this->nonLocalDistributions)(D3Q27System::ET_BNE, x1, x2, x3 + 1) = f[D3Q27System::BNE]; + if ((direction & EsoTwistD3Q27System::etTSW) == EsoTwistD3Q27System::etTSW) + (*this->localDistributions)(D3Q27System::ET_TSW, x1 + 1, x2 + 1, x3) = f[D3Q27System::TSW]; + if ((direction & EsoTwistD3Q27System::ZERO) == EsoTwistD3Q27System::ZERO) + (*this->zeroDistributions)(x1, x2, x3) = f[D3Q27System::ZERO]; } ////////////////////////////////////////////////////////////////////////// -void D3Q27EsoTwist3DSplittedVector::setDistributionInvForDirection(LBMReal f, size_t x1, size_t x2, size_t x3, unsigned long int direction) +void D3Q27EsoTwist3DSplittedVector::setDistributionInvForDirection(LBMReal f, size_t x1, size_t x2, size_t x3, + unsigned long int direction) { - switch (direction) - { - case D3Q27System::E : - (*this->localDistributions)(D3Q27System::ET_E,x1, x2, x3) = f; - break; - case D3Q27System::W : - (*this->nonLocalDistributions)(D3Q27System::ET_W,x1+1,x2, x3 ) = f; - break; - case D3Q27System::S : - (*this->nonLocalDistributions)(D3Q27System::ET_S,x1, x2+1,x3 ) = f; - break; - case D3Q27System::N : - (*this->localDistributions)(D3Q27System::ET_N,x1, x2, x3) = f; - break; - case D3Q27System::B : - (*this->nonLocalDistributions)(D3Q27System::ET_B,x1, x2, x3+1 ) = f; - break; - case D3Q27System::T : - (*this->localDistributions)(D3Q27System::ET_T,x1, x2, x3) = f; - break; - case D3Q27System::SW : - (*this->nonLocalDistributions)(D3Q27System::ET_SW,x1+1,x2+1,x3 ) = f; - break; - case D3Q27System::NE : - (*this->localDistributions)(D3Q27System::ET_NE,x1, x2, x3) = f; - break; - case D3Q27System::NW : - (*this->localDistributions)(D3Q27System::ET_NW,x1+1,x2, x3) = f; - break; - case D3Q27System::SE : - (*this->nonLocalDistributions)(D3Q27System::ET_SE,x1, x2+1,x3 ) = f; - break; - case D3Q27System::BW : - (*this->nonLocalDistributions)(D3Q27System::ET_BW,x1+1,x2, x3+1 ) = f; - break; - case D3Q27System::TE : - (*this->localDistributions)(D3Q27System::ET_TE,x1, x2, x3) = f; - break; - case D3Q27System::TW : - (*this->localDistributions)(D3Q27System::ET_TW,x1+1,x2, x3) = f; - break; - case D3Q27System::BE : - (*this->nonLocalDistributions)(D3Q27System::ET_BE,x1, x2, x3+1 ) = f; - break; - case D3Q27System::BS : - (*this->nonLocalDistributions)(D3Q27System::ET_BS,x1, x2+1,x3+1 ) = f; - break; - case D3Q27System::TN : - (*this->localDistributions)(D3Q27System::ET_TN,x1, x2, x3) = f; - break; - case D3Q27System::TS : - (*this->localDistributions)(D3Q27System::ET_TS,x1, x2+1,x3) = f; - break; - case D3Q27System::BN : - (*this->nonLocalDistributions)(D3Q27System::ET_BN,x1, x2, x3+1 ) = f; - break; - case D3Q27System::BSW : - (*this->nonLocalDistributions)(D3Q27System::ET_BSW,x1+1,x2+1,x3+1) = f; - break; - case D3Q27System::TNE : - (*this->localDistributions)(D3Q27System::ET_TNE,x1, x2, x3) = f; - break; - case D3Q27System::BSE : - (*this->nonLocalDistributions)(D3Q27System::ET_BSE,x1, x2+1,x3+1) = f; - break; - case D3Q27System::TNW : - (*this->localDistributions)(D3Q27System::ET_TNW,x1+1,x2, x3) = f; - break; - case D3Q27System::BNW : - (*this->nonLocalDistributions)(D3Q27System::ET_BNW,x1+1,x2, x3+1) = f; - break; - case D3Q27System::TSE : - (*this->localDistributions)(D3Q27System::ET_TSE,x1, x2+1,x3) = f; - break; - case D3Q27System::BNE : - (*this->nonLocalDistributions)(D3Q27System::ET_BNE,x1, x2, x3+1) = f; - break; - case D3Q27System::TSW : - (*this->localDistributions)(D3Q27System::ET_TSW,x1+1,x2+1,x3) = f; - break; - case D3Q27System::ZERO : - (*this->zeroDistributions)(x1,x2,x3) = f; - break; - default: - UB_THROW( UbException(UB_EXARGS, "Direction didn't find") ); - } + switch (direction) { + case D3Q27System::E: + (*this->localDistributions)(D3Q27System::ET_E, x1, x2, x3) = f; + break; + case D3Q27System::W: + (*this->nonLocalDistributions)(D3Q27System::ET_W, x1 + 1, x2, x3) = f; + break; + case D3Q27System::S: + (*this->nonLocalDistributions)(D3Q27System::ET_S, x1, x2 + 1, x3) = f; + break; + case D3Q27System::N: + (*this->localDistributions)(D3Q27System::ET_N, x1, x2, x3) = f; + break; + case D3Q27System::B: + (*this->nonLocalDistributions)(D3Q27System::ET_B, x1, x2, x3 + 1) = f; + break; + case D3Q27System::T: + (*this->localDistributions)(D3Q27System::ET_T, x1, x2, x3) = f; + break; + case D3Q27System::SW: + (*this->nonLocalDistributions)(D3Q27System::ET_SW, x1 + 1, x2 + 1, x3) = f; + break; + case D3Q27System::NE: + (*this->localDistributions)(D3Q27System::ET_NE, x1, x2, x3) = f; + break; + case D3Q27System::NW: + (*this->localDistributions)(D3Q27System::ET_NW, x1 + 1, x2, x3) = f; + break; + case D3Q27System::SE: + (*this->nonLocalDistributions)(D3Q27System::ET_SE, x1, x2 + 1, x3) = f; + break; + case D3Q27System::BW: + (*this->nonLocalDistributions)(D3Q27System::ET_BW, x1 + 1, x2, x3 + 1) = f; + break; + case D3Q27System::TE: + (*this->localDistributions)(D3Q27System::ET_TE, x1, x2, x3) = f; + break; + case D3Q27System::TW: + (*this->localDistributions)(D3Q27System::ET_TW, x1 + 1, x2, x3) = f; + break; + case D3Q27System::BE: + (*this->nonLocalDistributions)(D3Q27System::ET_BE, x1, x2, x3 + 1) = f; + break; + case D3Q27System::BS: + (*this->nonLocalDistributions)(D3Q27System::ET_BS, x1, x2 + 1, x3 + 1) = f; + break; + case D3Q27System::TN: + (*this->localDistributions)(D3Q27System::ET_TN, x1, x2, x3) = f; + break; + case D3Q27System::TS: + (*this->localDistributions)(D3Q27System::ET_TS, x1, x2 + 1, x3) = f; + break; + case D3Q27System::BN: + (*this->nonLocalDistributions)(D3Q27System::ET_BN, x1, x2, x3 + 1) = f; + break; + case D3Q27System::BSW: + (*this->nonLocalDistributions)(D3Q27System::ET_BSW, x1 + 1, x2 + 1, x3 + 1) = f; + break; + case D3Q27System::TNE: + (*this->localDistributions)(D3Q27System::ET_TNE, x1, x2, x3) = f; + break; + case D3Q27System::BSE: + (*this->nonLocalDistributions)(D3Q27System::ET_BSE, x1, x2 + 1, x3 + 1) = f; + break; + case D3Q27System::TNW: + (*this->localDistributions)(D3Q27System::ET_TNW, x1 + 1, x2, x3) = f; + break; + case D3Q27System::BNW: + (*this->nonLocalDistributions)(D3Q27System::ET_BNW, x1 + 1, x2, x3 + 1) = f; + break; + case D3Q27System::TSE: + (*this->localDistributions)(D3Q27System::ET_TSE, x1, x2 + 1, x3) = f; + break; + case D3Q27System::BNE: + (*this->nonLocalDistributions)(D3Q27System::ET_BNE, x1, x2, x3 + 1) = f; + break; + case D3Q27System::TSW: + (*this->localDistributions)(D3Q27System::ET_TSW, x1 + 1, x2 + 1, x3) = f; + break; + case D3Q27System::ZERO: + (*this->zeroDistributions)(x1, x2, x3) = f; + break; + default: + UB_THROW(UbException(UB_EXARGS, "Direction didn't find")); + } } ////////////////////////////////////////////////////////////////////////// LBMReal D3Q27EsoTwist3DSplittedVector::getDistributionForDirection(size_t x1, size_t x2, size_t x3, int direction) { - switch (direction) - { - case D3Q27System::W : - return (*this->nonLocalDistributions)(D3Q27System::ET_W,x1+1,x2, x3 ); - case D3Q27System::E : - return (*this->localDistributions)(D3Q27System::ET_E,x1, x2, x3); - case D3Q27System::N : - return (*this->localDistributions)(D3Q27System::ET_N,x1, x2, x3); - case D3Q27System::S : - return (*this->nonLocalDistributions)(D3Q27System::ET_S,x1, x2+1,x3 ); - case D3Q27System::T : - return (*this->localDistributions)(D3Q27System::ET_T,x1, x2, x3); - case D3Q27System::B : - return (*this->nonLocalDistributions)(D3Q27System::ET_B,x1, x2, x3+1 ); - case D3Q27System::NE : - return (*this->localDistributions)(D3Q27System::ET_NE,x1, x2, x3); - case D3Q27System::SW : - return (*this->nonLocalDistributions)(D3Q27System::ET_SW,x1+1,x2+1,x3 ); - case D3Q27System::SE : - return (*this->nonLocalDistributions)(D3Q27System::ET_SE,x1, x2+1,x3 ); - case D3Q27System::NW : - return (*this->localDistributions)(D3Q27System::ET_NW,x1+1,x2, x3); - case D3Q27System::TE : - return (*this->localDistributions)(D3Q27System::ET_TE,x1, x2, x3); - case D3Q27System::BW : - return (*this->nonLocalDistributions)(D3Q27System::ET_BW,x1+1,x2, x3+1 ); - case D3Q27System::BE : - return (*this->nonLocalDistributions)(D3Q27System::ET_BE,x1, x2, x3+1 ); - case D3Q27System::TW : - return (*this->localDistributions)(D3Q27System::ET_TW,x1+1,x2, x3); - case D3Q27System::TN : - return (*this->localDistributions)(D3Q27System::ET_TN,x1, x2, x3); - case D3Q27System::BS : - return (*this->nonLocalDistributions)(D3Q27System::ET_BS,x1, x2+1,x3+1 ); - case D3Q27System::BN : - return (*this->nonLocalDistributions)(D3Q27System::ET_BN,x1, x2, x3+1 ); - case D3Q27System::TS : - return (*this->localDistributions)(D3Q27System::ET_TS,x1, x2+1,x3); - case D3Q27System::TNE : - return (*this->localDistributions)(D3Q27System::ET_TNE,x1, x2, x3); - case D3Q27System::BSW : - return (*this->nonLocalDistributions)(D3Q27System::ET_BSW,x1+1,x2+1,x3+1); - case D3Q27System::TNW : - return (*this->localDistributions)(D3Q27System::ET_TNW,x1+1,x2, x3); - case D3Q27System::BSE : - return (*this->nonLocalDistributions)(D3Q27System::ET_BSE,x1, x2+1,x3+1); - case D3Q27System::TSE : - return (*this->localDistributions)(D3Q27System::ET_TSE,x1, x2+1,x3); - case D3Q27System::BNW : - return (*this->nonLocalDistributions)(D3Q27System::ET_BNW,x1+1,x2, x3+1); - case D3Q27System::TSW : - return (*this->localDistributions)(D3Q27System::ET_TSW,x1+1,x2+1,x3); - case D3Q27System::BNE : - return (*this->nonLocalDistributions)(D3Q27System::ET_BNE,x1, x2, x3+1); - case D3Q27System::ZERO : - return (*this->zeroDistributions)(x1,x2,x3); - default: - UB_THROW( UbException(UB_EXARGS, "Direction didn't find") ); - } + switch (direction) { + case D3Q27System::W: + return (*this->nonLocalDistributions)(D3Q27System::ET_W, x1 + 1, x2, x3); + case D3Q27System::E: + return (*this->localDistributions)(D3Q27System::ET_E, x1, x2, x3); + case D3Q27System::N: + return (*this->localDistributions)(D3Q27System::ET_N, x1, x2, x3); + case D3Q27System::S: + return (*this->nonLocalDistributions)(D3Q27System::ET_S, x1, x2 + 1, x3); + case D3Q27System::T: + return (*this->localDistributions)(D3Q27System::ET_T, x1, x2, x3); + case D3Q27System::B: + return (*this->nonLocalDistributions)(D3Q27System::ET_B, x1, x2, x3 + 1); + case D3Q27System::NE: + return (*this->localDistributions)(D3Q27System::ET_NE, x1, x2, x3); + case D3Q27System::SW: + return (*this->nonLocalDistributions)(D3Q27System::ET_SW, x1 + 1, x2 + 1, x3); + case D3Q27System::SE: + return (*this->nonLocalDistributions)(D3Q27System::ET_SE, x1, x2 + 1, x3); + case D3Q27System::NW: + return (*this->localDistributions)(D3Q27System::ET_NW, x1 + 1, x2, x3); + case D3Q27System::TE: + return (*this->localDistributions)(D3Q27System::ET_TE, x1, x2, x3); + case D3Q27System::BW: + return (*this->nonLocalDistributions)(D3Q27System::ET_BW, x1 + 1, x2, x3 + 1); + case D3Q27System::BE: + return (*this->nonLocalDistributions)(D3Q27System::ET_BE, x1, x2, x3 + 1); + case D3Q27System::TW: + return (*this->localDistributions)(D3Q27System::ET_TW, x1 + 1, x2, x3); + case D3Q27System::TN: + return (*this->localDistributions)(D3Q27System::ET_TN, x1, x2, x3); + case D3Q27System::BS: + return (*this->nonLocalDistributions)(D3Q27System::ET_BS, x1, x2 + 1, x3 + 1); + case D3Q27System::BN: + return (*this->nonLocalDistributions)(D3Q27System::ET_BN, x1, x2, x3 + 1); + case D3Q27System::TS: + return (*this->localDistributions)(D3Q27System::ET_TS, x1, x2 + 1, x3); + case D3Q27System::TNE: + return (*this->localDistributions)(D3Q27System::ET_TNE, x1, x2, x3); + case D3Q27System::BSW: + return (*this->nonLocalDistributions)(D3Q27System::ET_BSW, x1 + 1, x2 + 1, x3 + 1); + case D3Q27System::TNW: + return (*this->localDistributions)(D3Q27System::ET_TNW, x1 + 1, x2, x3); + case D3Q27System::BSE: + return (*this->nonLocalDistributions)(D3Q27System::ET_BSE, x1, x2 + 1, x3 + 1); + case D3Q27System::TSE: + return (*this->localDistributions)(D3Q27System::ET_TSE, x1, x2 + 1, x3); + case D3Q27System::BNW: + return (*this->nonLocalDistributions)(D3Q27System::ET_BNW, x1 + 1, x2, x3 + 1); + case D3Q27System::TSW: + return (*this->localDistributions)(D3Q27System::ET_TSW, x1 + 1, x2 + 1, x3); + case D3Q27System::BNE: + return (*this->nonLocalDistributions)(D3Q27System::ET_BNE, x1, x2, x3 + 1); + case D3Q27System::ZERO: + return (*this->zeroDistributions)(x1, x2, x3); + default: + UB_THROW(UbException(UB_EXARGS, "Direction didn't find")); + } } ////////////////////////////////////////////////////////////////////////// LBMReal D3Q27EsoTwist3DSplittedVector::getDistributionInvForDirection(size_t x1, size_t x2, size_t x3, int direction) { - switch (direction) - { - case D3Q27System::E : - return (*this->nonLocalDistributions)(D3Q27System::ET_W,x1+1,x2, x3 ); - case D3Q27System::W : - return (*this->localDistributions)(D3Q27System::ET_E,x1, x2, x3); - case D3Q27System::S : - return (*this->localDistributions)(D3Q27System::ET_N,x1, x2, x3); - case D3Q27System::N : - return (*this->nonLocalDistributions)(D3Q27System::ET_S,x1, x2+1,x3 ); - case D3Q27System::B : - return (*this->localDistributions)(D3Q27System::ET_T,x1, x2, x3); - case D3Q27System::T : - return (*this->nonLocalDistributions)(D3Q27System::ET_B,x1, x2, x3+1 ); - case D3Q27System::SW : - return (*this->localDistributions)(D3Q27System::ET_NE,x1, x2, x3); - case D3Q27System::NE : - return (*this->nonLocalDistributions)(D3Q27System::ET_SW,x1+1,x2+1,x3 ); - case D3Q27System::NW : - return (*this->nonLocalDistributions)(D3Q27System::ET_SE,x1, x2+1,x3 ); - case D3Q27System::SE : - return (*this->localDistributions)(D3Q27System::ET_NW,x1+1,x2, x3); - case D3Q27System::BW : - return (*this->localDistributions)(D3Q27System::ET_TE,x1, x2, x3); - case D3Q27System::TE : - return (*this->nonLocalDistributions)(D3Q27System::ET_BW,x1+1,x2, x3+1 ); - case D3Q27System::TW : - return (*this->nonLocalDistributions)(D3Q27System::ET_BE,x1, x2, x3+1 ); - case D3Q27System::BE : - return (*this->localDistributions)(D3Q27System::ET_TW,x1+1,x2, x3); - case D3Q27System::BS : - return (*this->localDistributions)(D3Q27System::ET_TN,x1, x2, x3); - case D3Q27System::TN : - return (*this->nonLocalDistributions)(D3Q27System::ET_BS,x1, x2+1,x3+1 ); - case D3Q27System::TS : - return (*this->nonLocalDistributions)(D3Q27System::ET_BN,x1, x2, x3+1 ); - case D3Q27System::BN : - return (*this->localDistributions)(D3Q27System::ET_TS,x1, x2+1,x3); - case D3Q27System::BSW : - return (*this->localDistributions)(D3Q27System::ET_TNE,x1, x2, x3); - case D3Q27System::TNE : - return (*this->nonLocalDistributions)(D3Q27System::ET_BSW,x1+1,x2+1,x3+1); - case D3Q27System::BSE : - return (*this->localDistributions)(D3Q27System::ET_TNW,x1+1,x2, x3); - case D3Q27System::TNW : - return (*this->nonLocalDistributions)(D3Q27System::ET_BSE,x1, x2+1,x3+1); - case D3Q27System::BNW : - return (*this->localDistributions)(D3Q27System::ET_TSE,x1, x2+1,x3); - case D3Q27System::TSE : - return (*this->nonLocalDistributions)(D3Q27System::ET_BNW,x1+1,x2, x3+1); - case D3Q27System::BNE : - return (*this->localDistributions)(D3Q27System::ET_TSW,x1+1,x2+1,x3); - case D3Q27System::TSW : - return (*this->nonLocalDistributions)(D3Q27System::ET_BNE,x1, x2, x3+1); - case D3Q27System::ZERO : - return (*this->zeroDistributions)(x1,x2,x3); - default: - UB_THROW( UbException(UB_EXARGS, "Direction didn't find") ); - } + switch (direction) { + case D3Q27System::E: + return (*this->nonLocalDistributions)(D3Q27System::ET_W, x1 + 1, x2, x3); + case D3Q27System::W: + return (*this->localDistributions)(D3Q27System::ET_E, x1, x2, x3); + case D3Q27System::S: + return (*this->localDistributions)(D3Q27System::ET_N, x1, x2, x3); + case D3Q27System::N: + return (*this->nonLocalDistributions)(D3Q27System::ET_S, x1, x2 + 1, x3); + case D3Q27System::B: + return (*this->localDistributions)(D3Q27System::ET_T, x1, x2, x3); + case D3Q27System::T: + return (*this->nonLocalDistributions)(D3Q27System::ET_B, x1, x2, x3 + 1); + case D3Q27System::SW: + return (*this->localDistributions)(D3Q27System::ET_NE, x1, x2, x3); + case D3Q27System::NE: + return (*this->nonLocalDistributions)(D3Q27System::ET_SW, x1 + 1, x2 + 1, x3); + case D3Q27System::NW: + return (*this->nonLocalDistributions)(D3Q27System::ET_SE, x1, x2 + 1, x3); + case D3Q27System::SE: + return (*this->localDistributions)(D3Q27System::ET_NW, x1 + 1, x2, x3); + case D3Q27System::BW: + return (*this->localDistributions)(D3Q27System::ET_TE, x1, x2, x3); + case D3Q27System::TE: + return (*this->nonLocalDistributions)(D3Q27System::ET_BW, x1 + 1, x2, x3 + 1); + case D3Q27System::TW: + return (*this->nonLocalDistributions)(D3Q27System::ET_BE, x1, x2, x3 + 1); + case D3Q27System::BE: + return (*this->localDistributions)(D3Q27System::ET_TW, x1 + 1, x2, x3); + case D3Q27System::BS: + return (*this->localDistributions)(D3Q27System::ET_TN, x1, x2, x3); + case D3Q27System::TN: + return (*this->nonLocalDistributions)(D3Q27System::ET_BS, x1, x2 + 1, x3 + 1); + case D3Q27System::TS: + return (*this->nonLocalDistributions)(D3Q27System::ET_BN, x1, x2, x3 + 1); + case D3Q27System::BN: + return (*this->localDistributions)(D3Q27System::ET_TS, x1, x2 + 1, x3); + case D3Q27System::BSW: + return (*this->localDistributions)(D3Q27System::ET_TNE, x1, x2, x3); + case D3Q27System::TNE: + return (*this->nonLocalDistributions)(D3Q27System::ET_BSW, x1 + 1, x2 + 1, x3 + 1); + case D3Q27System::BSE: + return (*this->localDistributions)(D3Q27System::ET_TNW, x1 + 1, x2, x3); + case D3Q27System::TNW: + return (*this->nonLocalDistributions)(D3Q27System::ET_BSE, x1, x2 + 1, x3 + 1); + case D3Q27System::BNW: + return (*this->localDistributions)(D3Q27System::ET_TSE, x1, x2 + 1, x3); + case D3Q27System::TSE: + return (*this->nonLocalDistributions)(D3Q27System::ET_BNW, x1 + 1, x2, x3 + 1); + case D3Q27System::BNE: + return (*this->localDistributions)(D3Q27System::ET_TSW, x1 + 1, x2 + 1, x3); + case D3Q27System::TSW: + return (*this->nonLocalDistributions)(D3Q27System::ET_BNE, x1, x2, x3 + 1); + case D3Q27System::ZERO: + return (*this->zeroDistributions)(x1, x2, x3); + default: + UB_THROW(UbException(UB_EXARGS, "Direction didn't find")); + } } ////////////////////////////////////////////////////////////////////////// -size_t D3Q27EsoTwist3DSplittedVector::getNX1() const -{ - return NX1; -} +size_t D3Q27EsoTwist3DSplittedVector::getNX1() const { return NX1; } ////////////////////////////////////////////////////////////////////////// -size_t D3Q27EsoTwist3DSplittedVector::getNX2() const -{ - return NX2; -} +size_t D3Q27EsoTwist3DSplittedVector::getNX2() const { return NX2; } ////////////////////////////////////////////////////////////////////////// -size_t D3Q27EsoTwist3DSplittedVector::getNX3() const -{ - return NX3; -} +size_t D3Q27EsoTwist3DSplittedVector::getNX3() const { return NX3; } ////////////////////////////////////////////////////////////////////////// -CbArray4D<LBMReal,IndexerX4X3X2X1>::CbArray4DPtr D3Q27EsoTwist3DSplittedVector::getLocalDistributions() +CbArray4D<LBMReal, IndexerX4X3X2X1>::CbArray4DPtr D3Q27EsoTwist3DSplittedVector::getLocalDistributions() { - return this->localDistributions; + return this->localDistributions; } ////////////////////////////////////////////////////////////////////////// -CbArray4D<LBMReal,IndexerX4X3X2X1>::CbArray4DPtr D3Q27EsoTwist3DSplittedVector::getNonLocalDistributions() +CbArray4D<LBMReal, IndexerX4X3X2X1>::CbArray4DPtr D3Q27EsoTwist3DSplittedVector::getNonLocalDistributions() { - return this->nonLocalDistributions; + return this->nonLocalDistributions; } ////////////////////////////////////////////////////////////////////////// -CbArray3D<LBMReal,IndexerX3X2X1>::CbArray3DPtr D3Q27EsoTwist3DSplittedVector::getZeroDistributions() +CbArray3D<LBMReal, IndexerX3X2X1>::CbArray3DPtr D3Q27EsoTwist3DSplittedVector::getZeroDistributions() { - return this->zeroDistributions; + return this->zeroDistributions; } ////////////////////////////////////////////////////////////////////////// -void D3Q27EsoTwist3DSplittedVector::setNX1(size_t newNX1) -{ - NX1 = newNX1; -} +void D3Q27EsoTwist3DSplittedVector::setNX1(size_t newNX1) { NX1 = newNX1; } ////////////////////////////////////////////////////////////////////////// -void D3Q27EsoTwist3DSplittedVector::setNX2(size_t newNX2) -{ - NX2 = newNX2; -} +void D3Q27EsoTwist3DSplittedVector::setNX2(size_t newNX2) { NX2 = newNX2; } ////////////////////////////////////////////////////////////////////////// -void D3Q27EsoTwist3DSplittedVector::setNX3(size_t newNX3) -{ - NX3 = newNX3; -} +void D3Q27EsoTwist3DSplittedVector::setNX3(size_t newNX3) { NX3 = newNX3; } ////////////////////////////////////////////////////////////////////////// void D3Q27EsoTwist3DSplittedVector::setLocalDistributions(CbArray4D<LBMReal, IndexerX4X3X2X1>::CbArray4DPtr array) { - localDistributions = array; + localDistributions = array; } ////////////////////////////////////////////////////////////////////////// void D3Q27EsoTwist3DSplittedVector::setNonLocalDistributions(CbArray4D<LBMReal, IndexerX4X3X2X1>::CbArray4DPtr array) { - nonLocalDistributions = array; + nonLocalDistributions = array; } ////////////////////////////////////////////////////////////////////////// void D3Q27EsoTwist3DSplittedVector::setZeroDistributions(CbArray3D<LBMReal, IndexerX3X2X1>::CbArray3DPtr array) { - zeroDistributions = array; + zeroDistributions = array; } ////////////////////////////////////////////////////////////////////////// - diff --git a/src/cpu/VirtualFluidsCore/Data/D3Q27EsoTwist3DSplittedVector.h b/src/cpu/VirtualFluidsCore/Data/D3Q27EsoTwist3DSplittedVector.h index 1e92809c0c429b0d72bc29e17806b17795fc4a67..1c0d7d05f1392c8c116863e9e0b41000c90ed15e 100644 --- a/src/cpu/VirtualFluidsCore/Data/D3Q27EsoTwist3DSplittedVector.h +++ b/src/cpu/VirtualFluidsCore/Data/D3Q27EsoTwist3DSplittedVector.h @@ -1,28 +1,28 @@ //======================================================================================= -// ____ ____ __ ______ __________ __ __ __ __ -// \ \ | | | | | _ \ |___ ___| | | | | / \ | | -// \ \ | | | | | |_) | | | | | | | / \ | | -// \ \ | | | | | _ / | | | | | | / /\ \ | | -// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ -// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| -// \ \ | | ________________________________________________________________ -// \ \ | | | ______________________________________________________________| -// \ \| | | | __ __ __ __ ______ _______ -// \ | | |_____ | | | | | | | | | _ \ / _____) -// \ | | _____| | | | | | | | | | | \ \ \_______ +// ____ ____ __ ______ __________ __ __ __ __ +// \ \ | | | | | _ \ |___ ___| | | | | / \ | | +// \ \ | | | | | |_) | | | | | | | / \ | | +// \ \ | | | | | _ / | | | | | | / /\ \ | | +// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ +// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| +// \ \ | | ________________________________________________________________ +// \ \ | | | ______________________________________________________________| +// \ \| | | | __ __ __ __ ______ _______ +// \ | | |_____ | | | | | | | | | _ \ / _____) +// \ | | _____| | | | | | | | | | | \ \ \_______ // \ | | | | |_____ | \_/ | | | | |_/ / _____ | -// \ _____| |__| |________| \_______/ |__| |______/ (_______/ +// \ _____| |__| |________| \_______/ |__| |______/ (_______/ // -// This file is part of VirtualFluids. VirtualFluids is free software: you can +// This file is part of VirtualFluids. VirtualFluids is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of +// License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. -// -// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// +// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License along // with VirtualFluids (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>. // @@ -34,75 +34,77 @@ #ifndef D3Q27EsoTwist3DSplittedVector_h #define D3Q27EsoTwist3DSplittedVector_h -#include "EsoTwist3D.h" #include "D3Q27System.h" -#include "basics/container/CbArray4D.h" +#include "EsoTwist3D.h" #include "basics/container/CbArray3D.h" +#include "basics/container/CbArray4D.h" //! \brief Class implements EsoTwist3D //! \details D3Q27EsoTwist3DSplittedVector uses three vectors to implement Esoteric Twist method class D3Q27EsoTwist3DSplittedVector : public EsoTwist3D { public: - D3Q27EsoTwist3DSplittedVector(); - //! \param nx1 number of nodes in x1 direction - //! \param nx2 number of nodes in x2 direction - //! \param nx3 number of nodes in x3 direction - //! \param value initialisation value - D3Q27EsoTwist3DSplittedVector(size_t nx1, size_t nx2, size_t nx3, LBMReal value); - ////////////////////////////////////////////////////////////////////////// - ~D3Q27EsoTwist3DSplittedVector() override; - ////////////////////////////////////////////////////////////////////////// - void swap() override; - ////////////////////////////////////////////////////////////////////////// - void getDistribution( LBMReal* const f, size_t x1, size_t x2, size_t x3) override; - ////////////////////////////////////////////////////////////////////////// - void setDistribution(const LBMReal* const f, size_t x1, size_t x2, size_t x3) override; - //////////////////////////////////////////////////////////////////////// - void getDistributionInv( LBMReal* const f, size_t x1, size_t x2, size_t x3) override; - ////////////////////////////////////////////////////////////////////////// - void setDistributionInv(const LBMReal* const f, size_t x1, size_t x2, size_t x3) override; - ////////////////////////////////////////////////////////////////////////// - void setDistributionForDirection(const LBMReal* const f, size_t x1, size_t x2, size_t x3, unsigned long int direction) override; - ////////////////////////////////////////////////////////////////////////// - void setDistributionForDirection(LBMReal f, size_t x1, size_t x2, size_t x3, int direction) override; - ////////////////////////////////////////////////////////////////////////// - LBMReal getDistributionInvForDirection(size_t x1, size_t x2, size_t x3, int direction) override; - ////////////////////////////////////////////////////////////////////////// - void setDistributionInvForDirection(const LBMReal* const f, size_t x1, size_t x2, size_t x3, unsigned long int direction) override; - ////////////////////////////////////////////////////////////////////////// - void setDistributionInvForDirection(LBMReal f, size_t x1, size_t x2, size_t x3, unsigned long int direction) override; - ////////////////////////////////////////////////////////////////////////// - LBMReal getDistributionForDirection(size_t x1, size_t x2, size_t x3, int direction) override; - ////////////////////////////////////////////////////////////////////////// - size_t getNX1() const override; - ////////////////////////////////////////////////////////////////////////// - size_t getNX2() const override; - ////////////////////////////////////////////////////////////////////////// - size_t getNX3() const override; - ////////////////////////////////////////////////////////////////////////// - CbArray4D<LBMReal,IndexerX4X3X2X1>::CbArray4DPtr getLocalDistributions(); - ////////////////////////////////////////////////////////////////////////// - CbArray4D<LBMReal,IndexerX4X3X2X1>::CbArray4DPtr getNonLocalDistributions(); - ////////////////////////////////////////////////////////////////////////// - CbArray3D<LBMReal,IndexerX3X2X1>::CbArray3DPtr getZeroDistributions(); - ////////////////////////////////////////////////////////////////////////// - void setNX1(size_t newNX1); - void setNX2(size_t newNX2); - void setNX3(size_t newNX3); - void setLocalDistributions(CbArray4D<LBMReal, IndexerX4X3X2X1>::CbArray4DPtr array); - void setNonLocalDistributions(CbArray4D<LBMReal, IndexerX4X3X2X1>::CbArray4DPtr array); - void setZeroDistributions(CbArray3D<LBMReal, IndexerX3X2X1>::CbArray3DPtr array); - -protected: - CbArray4D<LBMReal,IndexerX4X3X2X1>::CbArray4DPtr localDistributions; - CbArray4D<LBMReal,IndexerX4X3X2X1>::CbArray4DPtr nonLocalDistributions; - CbArray3D<LBMReal,IndexerX3X2X1>::CbArray3DPtr zeroDistributions; - size_t NX1, NX2, NX3; + D3Q27EsoTwist3DSplittedVector(); + //! \param nx1 number of nodes in x1 direction + //! \param nx2 number of nodes in x2 direction + //! \param nx3 number of nodes in x3 direction + //! \param value initialisation value + D3Q27EsoTwist3DSplittedVector(size_t nx1, size_t nx2, size_t nx3, LBMReal value); + ////////////////////////////////////////////////////////////////////////// + ~D3Q27EsoTwist3DSplittedVector() override; + ////////////////////////////////////////////////////////////////////////// + void swap() override; + ////////////////////////////////////////////////////////////////////////// + void getDistribution(LBMReal *const f, size_t x1, size_t x2, size_t x3) override; + ////////////////////////////////////////////////////////////////////////// + void setDistribution(const LBMReal *const f, size_t x1, size_t x2, size_t x3) override; + //////////////////////////////////////////////////////////////////////// + void getDistributionInv(LBMReal *const f, size_t x1, size_t x2, size_t x3) override; + ////////////////////////////////////////////////////////////////////////// + void setDistributionInv(const LBMReal *const f, size_t x1, size_t x2, size_t x3) override; + ////////////////////////////////////////////////////////////////////////// + void setDistributionForDirection(const LBMReal *const f, size_t x1, size_t x2, size_t x3, + unsigned long int direction) override; + ////////////////////////////////////////////////////////////////////////// + void setDistributionForDirection(LBMReal f, size_t x1, size_t x2, size_t x3, int direction) override; + ////////////////////////////////////////////////////////////////////////// + LBMReal getDistributionInvForDirection(size_t x1, size_t x2, size_t x3, int direction) override; + ////////////////////////////////////////////////////////////////////////// + void setDistributionInvForDirection(const LBMReal *const f, size_t x1, size_t x2, size_t x3, + unsigned long int direction) override; + ////////////////////////////////////////////////////////////////////////// + void setDistributionInvForDirection(LBMReal f, size_t x1, size_t x2, size_t x3, + unsigned long int direction) override; + ////////////////////////////////////////////////////////////////////////// + LBMReal getDistributionForDirection(size_t x1, size_t x2, size_t x3, int direction) override; + ////////////////////////////////////////////////////////////////////////// + size_t getNX1() const override; + ////////////////////////////////////////////////////////////////////////// + size_t getNX2() const override; + ////////////////////////////////////////////////////////////////////////// + size_t getNX3() const override; + ////////////////////////////////////////////////////////////////////////// + CbArray4D<LBMReal, IndexerX4X3X2X1>::CbArray4DPtr getLocalDistributions(); + ////////////////////////////////////////////////////////////////////////// + CbArray4D<LBMReal, IndexerX4X3X2X1>::CbArray4DPtr getNonLocalDistributions(); + ////////////////////////////////////////////////////////////////////////// + CbArray3D<LBMReal, IndexerX3X2X1>::CbArray3DPtr getZeroDistributions(); + ////////////////////////////////////////////////////////////////////////// + void setNX1(size_t newNX1); + void setNX2(size_t newNX2); + void setNX3(size_t newNX3); + void setLocalDistributions(CbArray4D<LBMReal, IndexerX4X3X2X1>::CbArray4DPtr array); + void setNonLocalDistributions(CbArray4D<LBMReal, IndexerX4X3X2X1>::CbArray4DPtr array); + void setZeroDistributions(CbArray3D<LBMReal, IndexerX3X2X1>::CbArray3DPtr array); - friend class MPIIORestartCoProcessor; - friend class MPIIOMigrationCoProcessor; +protected: + CbArray4D<LBMReal, IndexerX4X3X2X1>::CbArray4DPtr localDistributions; + CbArray4D<LBMReal, IndexerX4X3X2X1>::CbArray4DPtr nonLocalDistributions; + CbArray3D<LBMReal, IndexerX3X2X1>::CbArray3DPtr zeroDistributions; + size_t NX1, NX2, NX3; + friend class MPIIORestartCoProcessor; + friend class MPIIOMigrationCoProcessor; }; #endif diff --git a/src/cpu/VirtualFluidsCore/Data/D3Q27EsoTwist3DSplittedVectorEx.cpp b/src/cpu/VirtualFluidsCore/Data/D3Q27EsoTwist3DSplittedVectorEx.cpp index 6a8ccc1492fe6880183ab8b750a0e68a534a7099..d67341e1af96b3914df478994f3097b64bf78302 100644 --- a/src/cpu/VirtualFluidsCore/Data/D3Q27EsoTwist3DSplittedVectorEx.cpp +++ b/src/cpu/VirtualFluidsCore/Data/D3Q27EsoTwist3DSplittedVectorEx.cpp @@ -1,13 +1,16 @@ #include "D3Q27EsoTwist3DSplittedVectorEx.h" -D3Q27EsoTwist3DSplittedVectorEx::D3Q27EsoTwist3DSplittedVectorEx( int nx1, int nx2, int nx3, LBMReal value ) +D3Q27EsoTwist3DSplittedVectorEx::D3Q27EsoTwist3DSplittedVectorEx(int nx1, int nx2, int nx3, LBMReal value) { - this->NX1 = nx1; - this->NX2 = nx2; - this->NX3 = nx3; + this->NX1 = nx1; + this->NX2 = nx2; + this->NX3 = nx3; - this->localDistributions = CbArray4D<LBMReal,IndexerX4X3X2X1>::CbArray4DPtr(new CbArray4D<LBMReal,IndexerX4X3X2X1>(13, nx1, nx2, nx3, value)); - this->nonLocalDistributions = CbArray4D<LBMReal,IndexerX4X3X2X1>::CbArray4DPtr(new CbArray4D<LBMReal,IndexerX4X3X2X1>(13, nx1, nx2, nx3, value)); + this->localDistributions = CbArray4D<LBMReal, IndexerX4X3X2X1>::CbArray4DPtr( + new CbArray4D<LBMReal, IndexerX4X3X2X1>(13, nx1, nx2, nx3, value)); + this->nonLocalDistributions = CbArray4D<LBMReal, IndexerX4X3X2X1>::CbArray4DPtr( + new CbArray4D<LBMReal, IndexerX4X3X2X1>(13, nx1, nx2, nx3, value)); - this->zeroDistributions = CbArray3D<LBMReal,IndexerX3X2X1>::CbArray3DPtr(new CbArray3D<LBMReal,IndexerX3X2X1>(nx1, nx2, nx3, value)); + this->zeroDistributions = + CbArray3D<LBMReal, IndexerX3X2X1>::CbArray3DPtr(new CbArray3D<LBMReal, IndexerX3X2X1>(nx1, nx2, nx3, value)); } diff --git a/src/cpu/VirtualFluidsCore/Data/D3Q27EsoTwist3DSplittedVectorEx.h b/src/cpu/VirtualFluidsCore/Data/D3Q27EsoTwist3DSplittedVectorEx.h index 9e41d877b40231c06f6f94f67b51c836b209dd4b..54f9d55e5c4df0891cf40cc058a4ceaae934626a 100644 --- a/src/cpu/VirtualFluidsCore/Data/D3Q27EsoTwist3DSplittedVectorEx.h +++ b/src/cpu/VirtualFluidsCore/Data/D3Q27EsoTwist3DSplittedVectorEx.h @@ -6,10 +6,10 @@ class D3Q27EsoTwist3DSplittedVectorEx : public D3Q27EsoTwist3DSplittedVector { public: - D3Q27EsoTwist3DSplittedVectorEx(int nx1, int nx2, int nx3, LBMReal value); + D3Q27EsoTwist3DSplittedVectorEx(int nx1, int nx2, int nx3, LBMReal value); + protected: private: }; #endif - diff --git a/src/cpu/VirtualFluidsCore/Data/DataSet3D.h b/src/cpu/VirtualFluidsCore/Data/DataSet3D.h index 66fefb15ad256b9f0161dae938fe58795d5911f8..c0171588bcd4a74680326c44db062dba63d4c41c 100644 --- a/src/cpu/VirtualFluidsCore/Data/DataSet3D.h +++ b/src/cpu/VirtualFluidsCore/Data/DataSet3D.h @@ -1,28 +1,28 @@ //======================================================================================= -// ____ ____ __ ______ __________ __ __ __ __ -// \ \ | | | | | _ \ |___ ___| | | | | / \ | | -// \ \ | | | | | |_) | | | | | | | / \ | | -// \ \ | | | | | _ / | | | | | | / /\ \ | | -// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ -// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| -// \ \ | | ________________________________________________________________ -// \ \ | | | ______________________________________________________________| -// \ \| | | | __ __ __ __ ______ _______ -// \ | | |_____ | | | | | | | | | _ \ / _____) -// \ | | _____| | | | | | | | | | | \ \ \_______ +// ____ ____ __ ______ __________ __ __ __ __ +// \ \ | | | | | _ \ |___ ___| | | | | / \ | | +// \ \ | | | | | |_) | | | | | | | / \ | | +// \ \ | | | | | _ / | | | | | | / /\ \ | | +// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ +// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| +// \ \ | | ________________________________________________________________ +// \ \ | | | ______________________________________________________________| +// \ \| | | | __ __ __ __ ______ _______ +// \ | | |_____ | | | | | | | | | _ \ / _____) +// \ | | _____| | | | | | | | | | | \ \ \_______ // \ | | | | |_____ | \_/ | | | | |_/ / _____ | -// \ _____| |__| |________| \_______/ |__| |______/ (_______/ +// \ _____| |__| |________| \_______/ |__| |______/ (_______/ // -// This file is part of VirtualFluids. VirtualFluids is free software: you can +// This file is part of VirtualFluids. VirtualFluids is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of +// License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. -// -// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// +// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License along // with VirtualFluids (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>. // @@ -36,134 +36,89 @@ #include <PointerDefinitions.h> -#include "basics/container/CbArray4D.h" -#include "basics/container/CbArray3D.h" #include "DistributionArray3D.h" +#include "basics/container/CbArray3D.h" +#include "basics/container/CbArray4D.h" -using AverageValuesArray3D = CbArray4D<LBMReal, IndexerX4X3X2X1>; +using AverageValuesArray3D = CbArray4D<LBMReal, IndexerX4X3X2X1>; using ShearStressValuesArray3D = CbArray4D<LBMReal, IndexerX4X3X2X1>; -using RelaxationFactorArray3D = CbArray3D<LBMReal, IndexerX3X2X1>; +using RelaxationFactorArray3D = CbArray3D<LBMReal, IndexerX3X2X1>; //! A class provides an interface for data structures in the kernel. class DataSet3D { public: - SPtr<DistributionArray3D> getFdistributions() const; - void setFdistributions(SPtr<DistributionArray3D> distributions); + SPtr<DistributionArray3D> getFdistributions() const; + void setFdistributions(SPtr<DistributionArray3D> distributions); + + SPtr<AverageValuesArray3D> getAverageDensity() const; + void setAverageDensity(SPtr<AverageValuesArray3D> values); + + SPtr<AverageValuesArray3D> getAverageVelocity() const; + void setAverageVelocity(SPtr<AverageValuesArray3D> values); + + SPtr<AverageValuesArray3D> getAverageFluctuations() const; + void setAverageFluctuations(SPtr<AverageValuesArray3D> values); - SPtr<AverageValuesArray3D> getAverageDensity() const; - void setAverageDensity(SPtr<AverageValuesArray3D> values); + SPtr<AverageValuesArray3D> getAverageTriplecorrelations() const; + void setAverageTriplecorrelations(SPtr<AverageValuesArray3D> values); - SPtr<AverageValuesArray3D> getAverageVelocity() const; - void setAverageVelocity(SPtr<AverageValuesArray3D> values); + SPtr<AverageValuesArray3D> getAverageValues() const; + void setAverageValues(SPtr<AverageValuesArray3D> values); - SPtr<AverageValuesArray3D> getAverageFluctuations() const; - void setAverageFluctuations(SPtr<AverageValuesArray3D> values); + SPtr<ShearStressValuesArray3D> getShearStressValues() const; + void setShearStressValues(SPtr<ShearStressValuesArray3D> values); - SPtr<AverageValuesArray3D> getAverageTriplecorrelations() const; - void setAverageTriplecorrelations(SPtr<AverageValuesArray3D> values); - - SPtr<AverageValuesArray3D> getAverageValues() const; - void setAverageValues(SPtr<AverageValuesArray3D> values); - - SPtr<ShearStressValuesArray3D> getShearStressValues() const; - void setShearStressValues(SPtr<ShearStressValuesArray3D> values); + SPtr<RelaxationFactorArray3D> getRelaxationFactor() const; + void setRelaxationFactor(SPtr<RelaxationFactorArray3D> values); - SPtr<RelaxationFactorArray3D> getRelaxationFactor() const; - void setRelaxationFactor(SPtr<RelaxationFactorArray3D> values); protected: private: - SPtr<DistributionArray3D> fdistributions; - SPtr<AverageValuesArray3D> averageValues; + SPtr<DistributionArray3D> fdistributions; + SPtr<AverageValuesArray3D> averageValues; - SPtr<AverageValuesArray3D> averageDensity; - SPtr<AverageValuesArray3D> averageVelocity; - SPtr<AverageValuesArray3D> averageFluktuations; - SPtr<AverageValuesArray3D> averageTriplecorrelations; + SPtr<AverageValuesArray3D> averageDensity; + SPtr<AverageValuesArray3D> averageVelocity; + SPtr<AverageValuesArray3D> averageFluktuations; + SPtr<AverageValuesArray3D> averageTriplecorrelations; - SPtr<ShearStressValuesArray3D> shearStressValues; - - SPtr<RelaxationFactorArray3D> relaxationFactor; + SPtr<ShearStressValuesArray3D> shearStressValues; + SPtr<RelaxationFactorArray3D> relaxationFactor; }; -inline SPtr<DistributionArray3D> DataSet3D::getFdistributions() const -{ - return fdistributions; -} +inline SPtr<DistributionArray3D> DataSet3D::getFdistributions() const { return fdistributions; } -inline void DataSet3D::setFdistributions(SPtr<DistributionArray3D> distributions) -{ - fdistributions = distributions; -} +inline void DataSet3D::setFdistributions(SPtr<DistributionArray3D> distributions) { fdistributions = distributions; } -inline SPtr<AverageValuesArray3D> DataSet3D::getAverageValues() const -{ - return averageValues; -} +inline SPtr<AverageValuesArray3D> DataSet3D::getAverageValues() const { return averageValues; } -inline void DataSet3D::setAverageValues(SPtr<AverageValuesArray3D> values) -{ - averageValues = values; -} +inline void DataSet3D::setAverageValues(SPtr<AverageValuesArray3D> values) { averageValues = values; } -inline SPtr<AverageValuesArray3D> DataSet3D::getAverageDensity() const -{ - return averageDensity; -} +inline SPtr<AverageValuesArray3D> DataSet3D::getAverageDensity() const { return averageDensity; } -inline void DataSet3D::setAverageDensity(SPtr<AverageValuesArray3D> values) -{ - averageDensity = values; -} +inline void DataSet3D::setAverageDensity(SPtr<AverageValuesArray3D> values) { averageDensity = values; } -inline SPtr<AverageValuesArray3D> DataSet3D::getAverageVelocity() const -{ - return averageVelocity; -} +inline SPtr<AverageValuesArray3D> DataSet3D::getAverageVelocity() const { return averageVelocity; } -inline void DataSet3D::setAverageVelocity(SPtr<AverageValuesArray3D> values) -{ - averageVelocity = values; -} +inline void DataSet3D::setAverageVelocity(SPtr<AverageValuesArray3D> values) { averageVelocity = values; } -inline SPtr<AverageValuesArray3D> DataSet3D::getAverageFluctuations() const -{ - return averageFluktuations; -} +inline SPtr<AverageValuesArray3D> DataSet3D::getAverageFluctuations() const { return averageFluktuations; } -inline void DataSet3D::setAverageFluctuations(SPtr<AverageValuesArray3D> values) -{ - averageFluktuations = values; -} +inline void DataSet3D::setAverageFluctuations(SPtr<AverageValuesArray3D> values) { averageFluktuations = values; } -inline SPtr<AverageValuesArray3D> DataSet3D::getAverageTriplecorrelations() const -{ - return averageTriplecorrelations; -} +inline SPtr<AverageValuesArray3D> DataSet3D::getAverageTriplecorrelations() const { return averageTriplecorrelations; } inline void DataSet3D::setAverageTriplecorrelations(SPtr<AverageValuesArray3D> values) { - averageTriplecorrelations = values; + averageTriplecorrelations = values; } -inline SPtr<ShearStressValuesArray3D> DataSet3D::getShearStressValues() const -{ - return shearStressValues; -} +inline SPtr<ShearStressValuesArray3D> DataSet3D::getShearStressValues() const { return shearStressValues; } -inline void DataSet3D::setShearStressValues(SPtr<ShearStressValuesArray3D> values) -{ - shearStressValues = values; -} +inline void DataSet3D::setShearStressValues(SPtr<ShearStressValuesArray3D> values) { shearStressValues = values; } -inline SPtr<RelaxationFactorArray3D> DataSet3D::getRelaxationFactor() const -{ - return relaxationFactor; -} +inline SPtr<RelaxationFactorArray3D> DataSet3D::getRelaxationFactor() const { return relaxationFactor; } -inline void DataSet3D::setRelaxationFactor(SPtr<RelaxationFactorArray3D> values) -{ - relaxationFactor = values; -} +inline void DataSet3D::setRelaxationFactor(SPtr<RelaxationFactorArray3D> values) { relaxationFactor = values; } #endif diff --git a/src/cpu/VirtualFluidsCore/Data/DistributionArray3D.h b/src/cpu/VirtualFluidsCore/Data/DistributionArray3D.h index 89da1577ffe6c57f9ef77c96dec4dd92a73c569a..593778cd08af4dff957def1dfd837bc2430935bd 100644 --- a/src/cpu/VirtualFluidsCore/Data/DistributionArray3D.h +++ b/src/cpu/VirtualFluidsCore/Data/DistributionArray3D.h @@ -6,26 +6,31 @@ class DistributionArray3D { public: - DistributionArray3D() = default;; - virtual ~DistributionArray3D()= default;; + DistributionArray3D() = default; + ; + virtual ~DistributionArray3D() = default; + ; + + virtual size_t getNX1() const = 0; + virtual size_t getNX2() const = 0; + virtual size_t getNX3() const = 0; + virtual void getDistribution(LBMReal *const f, size_t x1, size_t x2, size_t x3) = 0; + virtual void setDistribution(const LBMReal *const f, size_t x1, size_t x2, size_t x3) = 0; + virtual void getDistributionInv(LBMReal *const f, size_t x1, size_t x2, size_t x3) = 0; + virtual void setDistributionInv(const LBMReal *const f, size_t x1, size_t x2, size_t x3) = 0; + virtual void setDistributionForDirection(const LBMReal *const f, size_t x1, size_t x2, size_t x3, + unsigned long int direction) = 0; + virtual void setDistributionForDirection(LBMReal f, size_t x1, size_t x2, size_t x3, int direction) = 0; + virtual LBMReal getDistributionInvForDirection(size_t x1, size_t x2, size_t x3, int direction) = 0; + virtual void setDistributionInvForDirection(const LBMReal *const f, size_t x1, size_t x2, size_t x3, + unsigned long int direction) = 0; + virtual void setDistributionInvForDirection(LBMReal f, size_t x1, size_t x2, size_t x3, + unsigned long int direction) = 0; + virtual LBMReal getDistributionForDirection(size_t x1, size_t x2, size_t x3, int direction) = 0; + virtual void swap() = 0; - virtual size_t getNX1() const = 0; - virtual size_t getNX2() const = 0; - virtual size_t getNX3() const = 0; - virtual void getDistribution(LBMReal* const f, size_t x1, size_t x2, size_t x3) = 0; - virtual void setDistribution(const LBMReal* const f, size_t x1, size_t x2, size_t x3) = 0; - virtual void getDistributionInv( LBMReal* const f, size_t x1, size_t x2, size_t x3) = 0; - virtual void setDistributionInv(const LBMReal* const f, size_t x1, size_t x2, size_t x3) = 0; - virtual void setDistributionForDirection(const LBMReal* const f, size_t x1, size_t x2, size_t x3, unsigned long int direction) = 0; - virtual void setDistributionForDirection(LBMReal f, size_t x1, size_t x2, size_t x3, int direction) = 0; - virtual LBMReal getDistributionInvForDirection(size_t x1, size_t x2, size_t x3, int direction) = 0; - virtual void setDistributionInvForDirection(const LBMReal* const f, size_t x1, size_t x2, size_t x3, unsigned long int direction) = 0; - virtual void setDistributionInvForDirection(LBMReal f, size_t x1, size_t x2, size_t x3, unsigned long int direction) = 0; - virtual LBMReal getDistributionForDirection(size_t x1, size_t x2, size_t x3, int direction) = 0; - virtual void swap() = 0; protected: private: - }; #endif diff --git a/src/cpu/VirtualFluidsCore/Data/EsoTwist3D.h b/src/cpu/VirtualFluidsCore/Data/EsoTwist3D.h index 2e0475f1d76faa992431d1e8ebbeb64760178e13..e7d9b90de4c1490fa4a7d9c3ad0c05600467aa29 100644 --- a/src/cpu/VirtualFluidsCore/Data/EsoTwist3D.h +++ b/src/cpu/VirtualFluidsCore/Data/EsoTwist3D.h @@ -1,28 +1,28 @@ //======================================================================================= -// ____ ____ __ ______ __________ __ __ __ __ -// \ \ | | | | | _ \ |___ ___| | | | | / \ | | -// \ \ | | | | | |_) | | | | | | | / \ | | -// \ \ | | | | | _ / | | | | | | / /\ \ | | -// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ -// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| -// \ \ | | ________________________________________________________________ -// \ \ | | | ______________________________________________________________| -// \ \| | | | __ __ __ __ ______ _______ -// \ | | |_____ | | | | | | | | | _ \ / _____) -// \ | | _____| | | | | | | | | | | \ \ \_______ +// ____ ____ __ ______ __________ __ __ __ __ +// \ \ | | | | | _ \ |___ ___| | | | | / \ | | +// \ \ | | | | | |_) | | | | | | | / \ | | +// \ \ | | | | | _ / | | | | | | / /\ \ | | +// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ +// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| +// \ \ | | ________________________________________________________________ +// \ \ | | | ______________________________________________________________| +// \ \| | | | __ __ __ __ ______ _______ +// \ | | |_____ | | | | | | | | | _ \ / _____) +// \ | | _____| | | | | | | | | | | \ \ \_______ // \ | | | | |_____ | \_/ | | | | |_/ / _____ | -// \ _____| |__| |________| \_______/ |__| |______/ (_______/ +// \ _____| |__| |________| \_______/ |__| |______/ (_______/ // -// This file is part of VirtualFluids. VirtualFluids is free software: you can +// This file is part of VirtualFluids. VirtualFluids is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of +// License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. -// -// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// +// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License along // with VirtualFluids (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>. // @@ -38,52 +38,63 @@ #include <LBMSystem.h> //! \brief Abstract class for implementation of Esoteric Twist method -//! \details EsoTwist3D provide an interface for different implementations of Esoteric Twist method -//! <a href="https://doi.org/10.3390/computation5020019"><b>[ Geier et al., (2017), 10.3390/computation5020019]</b></a> -// Geier, M., & Schönherr, M. (2017). Esoteric twist: an efficient in-place streaming algorithmus for the lattice Boltzmann method on massively parallel hardware. Computation, 5(2), 19. - +//! \details EsoTwist3D provide an interface for different implementations of Esoteric Twist method +//! <a href="https://doi.org/10.3390/computation5020019"><b>[ Geier et al., (2017), 10.3390/computation5020019]</b></a> +// Geier, M., & Schönherr, M. (2017). Esoteric twist: an efficient in-place streaming algorithmus for the lattice +// Boltzmann method on massively parallel hardware. Computation, 5(2), 19. -class EsoTwistD3Q27UnrollArray{}; -class EsoTwistPlusD3Q27UnrollArray{}; -class EsoTwistPlusD3Q19UnrollArray{}; +class EsoTwistD3Q27UnrollArray +{ +}; +class EsoTwistPlusD3Q27UnrollArray +{ +}; +class EsoTwistPlusD3Q19UnrollArray +{ +}; class EsoTwist3D : public DistributionArray3D { public: - EsoTwist3D()= default;; - ~EsoTwist3D() override= default;; - ////////////////////////////////////////////////////////////////////////// - void swap() override = 0; - ////////////////////////////////////////////////////////////////////////// - void getDistribution(LBMReal* const f, size_t x1, size_t x2, size_t x3) override = 0; - ////////////////////////////////////////////////////////////////////////// - void setDistribution(const LBMReal* const f, size_t x1, size_t x2, size_t x3) override = 0; - //////////////////////////////////////////////////////////////////////// - void getDistributionInv( LBMReal* const f, size_t x1, size_t x2, size_t x3) override = 0; - ////////////////////////////////////////////////////////////////////////// - void setDistributionInv(const LBMReal* const f, size_t x1, size_t x2, size_t x3) override = 0; - ////////////////////////////////////////////////////////////////////////// - void setDistributionForDirection(const LBMReal* const f, size_t x1, size_t x2, size_t x3, unsigned long int direction) override = 0; - ////////////////////////////////////////////////////////////////////////// - void setDistributionForDirection(LBMReal f, size_t x1, size_t x2, size_t x3, int direction) override = 0; - ////////////////////////////////////////////////////////////////////////// - //virtual void getDistributionInvForDirection(LBMReal* const& f, const size_t& x1, const size_t& x2, const size_t& x3, const unsigned long int& direction) = 0; - ////////////////////////////////////////////////////////////////////////// - LBMReal getDistributionInvForDirection(size_t x1, size_t x2, size_t x3, int direction) override = 0; - ////////////////////////////////////////////////////////////////////////// - void setDistributionInvForDirection(const LBMReal* const f, size_t x1, size_t x2, size_t x3, unsigned long int direction) override = 0; - ////////////////////////////////////////////////////////////////////////// - void setDistributionInvForDirection(LBMReal f, size_t x1, size_t x2, size_t x3, unsigned long int direction) override = 0; - ////////////////////////////////////////////////////////////////////////// - LBMReal getDistributionForDirection(size_t x1, size_t x2, size_t x3, int direction) override = 0; - ////////////////////////////////////////////////////////////////////////// - size_t getNX1() const override = 0; - ////////////////////////////////////////////////////////////////////////// - size_t getNX2() const override = 0; - ////////////////////////////////////////////////////////////////////////// - size_t getNX3() const override = 0; - ////////////////////////////////////////////////////////////////////////// - + EsoTwist3D() = default; + ; + ~EsoTwist3D() override = default; + ; + ////////////////////////////////////////////////////////////////////////// + void swap() override = 0; + ////////////////////////////////////////////////////////////////////////// + void getDistribution(LBMReal *const f, size_t x1, size_t x2, size_t x3) override = 0; + ////////////////////////////////////////////////////////////////////////// + void setDistribution(const LBMReal *const f, size_t x1, size_t x2, size_t x3) override = 0; + //////////////////////////////////////////////////////////////////////// + void getDistributionInv(LBMReal *const f, size_t x1, size_t x2, size_t x3) override = 0; + ////////////////////////////////////////////////////////////////////////// + void setDistributionInv(const LBMReal *const f, size_t x1, size_t x2, size_t x3) override = 0; + ////////////////////////////////////////////////////////////////////////// + void setDistributionForDirection(const LBMReal *const f, size_t x1, size_t x2, size_t x3, + unsigned long int direction) override = 0; + ////////////////////////////////////////////////////////////////////////// + void setDistributionForDirection(LBMReal f, size_t x1, size_t x2, size_t x3, int direction) override = 0; + ////////////////////////////////////////////////////////////////////////// + // virtual void getDistributionInvForDirection(LBMReal* const& f, const size_t& x1, const size_t& x2, const size_t& + // x3, const unsigned long int& direction) = 0; + ////////////////////////////////////////////////////////////////////////// + LBMReal getDistributionInvForDirection(size_t x1, size_t x2, size_t x3, int direction) override = 0; + ////////////////////////////////////////////////////////////////////////// + void setDistributionInvForDirection(const LBMReal *const f, size_t x1, size_t x2, size_t x3, + unsigned long int direction) override = 0; + ////////////////////////////////////////////////////////////////////////// + void setDistributionInvForDirection(LBMReal f, size_t x1, size_t x2, size_t x3, + unsigned long int direction) override = 0; + ////////////////////////////////////////////////////////////////////////// + LBMReal getDistributionForDirection(size_t x1, size_t x2, size_t x3, int direction) override = 0; + ////////////////////////////////////////////////////////////////////////// + size_t getNX1() const override = 0; + ////////////////////////////////////////////////////////////////////////// + size_t getNX2() const override = 0; + ////////////////////////////////////////////////////////////////////////// + size_t getNX3() const override = 0; + ////////////////////////////////////////////////////////////////////////// }; #endif diff --git a/src/cpu/VirtualFluidsCore/Data/EsoTwistD3Q27System.cpp b/src/cpu/VirtualFluidsCore/Data/EsoTwistD3Q27System.cpp index 64fa72bd09570cf41a25f18feaab108a73cd78f3..1a13aa008ab49a48f1d16c7a2a71ea39dfb191ab 100644 --- a/src/cpu/VirtualFluidsCore/Data/EsoTwistD3Q27System.cpp +++ b/src/cpu/VirtualFluidsCore/Data/EsoTwistD3Q27System.cpp @@ -1,28 +1,28 @@ //======================================================================================= -// ____ ____ __ ______ __________ __ __ __ __ -// \ \ | | | | | _ \ |___ ___| | | | | / \ | | -// \ \ | | | | | |_) | | | | | | | / \ | | -// \ \ | | | | | _ / | | | | | | / /\ \ | | -// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ -// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| -// \ \ | | ________________________________________________________________ -// \ \ | | | ______________________________________________________________| -// \ \| | | | __ __ __ __ ______ _______ -// \ | | |_____ | | | | | | | | | _ \ / _____) -// \ | | _____| | | | | | | | | | | \ \ \_______ +// ____ ____ __ ______ __________ __ __ __ __ +// \ \ | | | | | _ \ |___ ___| | | | | / \ | | +// \ \ | | | | | |_) | | | | | | | / \ | | +// \ \ | | | | | _ / | | | | | | / /\ \ | | +// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ +// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| +// \ \ | | ________________________________________________________________ +// \ \ | | | ______________________________________________________________| +// \ \| | | | __ __ __ __ ______ _______ +// \ | | |_____ | | | | | | | | | _ \ / _____) +// \ | | _____| | | | | | | | | | | \ \ \_______ // \ | | | | |_____ | \_/ | | | | |_/ / _____ | -// \ _____| |__| |________| \_______/ |__| |______/ (_______/ +// \ _____| |__| |________| \_______/ |__| |______/ (_______/ // -// This file is part of VirtualFluids. VirtualFluids is free software: you can +// This file is part of VirtualFluids. VirtualFluids is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of +// License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. -// -// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// +// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License along // with VirtualFluids (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>. // @@ -33,93 +33,54 @@ #include "EsoTwistD3Q27System.h" -//index 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 -//f: E, W, N, S, T, B, NE, SW, SE, NW, TE, BW, BE, TW, TN, BS, BN, TS, TNE TNW TSE TSW BNE BNW BSE BSW ZERO -const int EsoTwistD3Q27System::ETX1[EsoTwistD3Q27System::ENDF+1] = { 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0 }; -const int EsoTwistD3Q27System::ETX2[EsoTwistD3Q27System::ENDF+1] = { 0, 0, 0, 1, 0, 0, 0, 1, 0, -1, 0, 0, 0, 0, 0, 1, -1, 0, 0, -1, 0, 1, 0, -1, 0, 1, 0 }; -const int EsoTwistD3Q27System::ETX3[EsoTwistD3Q27System::ENDF+1] = { 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, -1, 0, 1, 1, 0, 0, -1, 0, -1, 0, 1, 0, 1, 0 }; - -const int EsoTwistD3Q27System::etINVDIR[EsoTwistD3Q27System::ENDF+1] = { D3Q27System::INV_E, - D3Q27System::INV_W, - D3Q27System::INV_N, - D3Q27System::INV_S, - D3Q27System::INV_T, - D3Q27System::INV_B, - D3Q27System::INV_NE, - D3Q27System::INV_SW, - D3Q27System::INV_SE, - D3Q27System::INV_NW, - D3Q27System::INV_TE, - D3Q27System::INV_BW, - D3Q27System::INV_BE, - D3Q27System::INV_TW, - D3Q27System::INV_TN, - D3Q27System::INV_BS, - D3Q27System::INV_BN, - D3Q27System::INV_TS, - D3Q27System::INV_TNE, - D3Q27System::INV_TNW, - D3Q27System::INV_TSE, - D3Q27System::INV_TSW, - D3Q27System::INV_BNE, - D3Q27System::INV_BNW, - D3Q27System::INV_BSE, - D3Q27System::INV_BSW, - D3Q27System::ZERO}; +// index 0 1 2 3 4 5 6 7 8 9 10 11 12 +// 13 14 15 16 17 18 19 20 21 22 23 24 25 26 f: E, W, N, S, T, B, NE, SW, SE, NW, TE, BW, BE, TW, TN, +// BS, BN, TS, TNE TNW TSE TSW BNE BNW BSE BSW ZERO +const int EsoTwistD3Q27System::ETX1[EsoTwistD3Q27System::ENDF + 1] = { 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1, + 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0 }; +const int EsoTwistD3Q27System::ETX2[EsoTwistD3Q27System::ENDF + 1] = { 0, 0, 0, 1, 0, 0, 0, 1, 0, -1, 0, 0, 0, 0, + 0, 1, -1, 0, 0, -1, 0, 1, 0, -1, 0, 1, 0 }; +const int EsoTwistD3Q27System::ETX3[EsoTwistD3Q27System::ENDF + 1] = { 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, -1, + 0, 1, 1, 0, 0, -1, 0, -1, 0, 1, 0, 1, 0 }; -const unsigned long int EsoTwistD3Q27System::etDIR[EsoTwistD3Q27System::ENDF+1] = { etE, - etW, - etN, - etS, - etT, - etB, - etNE, - etSW, - etSE, - etNW, - etTE, - etBW, - etBE, - etTW, - etTN, - etBS, - etBN, - etTS, - etTNE, - etTNW, - etTSE, - etTSW, - etBNE, - etBNW, - etBSE, - etBSW, - etZERO}; +const int EsoTwistD3Q27System::etINVDIR[EsoTwistD3Q27System::ENDF + 1] = { + D3Q27System::INV_E, D3Q27System::INV_W, D3Q27System::INV_N, D3Q27System::INV_S, D3Q27System::INV_T, + D3Q27System::INV_B, D3Q27System::INV_NE, D3Q27System::INV_SW, D3Q27System::INV_SE, D3Q27System::INV_NW, + D3Q27System::INV_TE, D3Q27System::INV_BW, D3Q27System::INV_BE, D3Q27System::INV_TW, D3Q27System::INV_TN, + D3Q27System::INV_BS, D3Q27System::INV_BN, D3Q27System::INV_TS, D3Q27System::INV_TNE, D3Q27System::INV_TNW, + D3Q27System::INV_TSE, D3Q27System::INV_TSW, D3Q27System::INV_BNE, D3Q27System::INV_BNW, D3Q27System::INV_BSE, + D3Q27System::INV_BSW, D3Q27System::ZERO +}; - const unsigned long int EsoTwistD3Q27System::etZERO = 1;/*f0 */ - const unsigned long int EsoTwistD3Q27System::etE = 2; /*f1 */ - const unsigned long int EsoTwistD3Q27System::etW = 4; /*f2 */ - const unsigned long int EsoTwistD3Q27System::etN = 8; /*f3 */ - const unsigned long int EsoTwistD3Q27System::etS = 16; /*f4 */ - const unsigned long int EsoTwistD3Q27System::etT = 32; /*f5 */ - const unsigned long int EsoTwistD3Q27System::etB = 64; /*f6 */ - const unsigned long int EsoTwistD3Q27System::etNE = 128; /*f7 */ - const unsigned long int EsoTwistD3Q27System::etSW = 256; /*f8 */ - const unsigned long int EsoTwistD3Q27System::etSE = 512; /*f9 */ - const unsigned long int EsoTwistD3Q27System::etNW = 1024; /*f10*/ - const unsigned long int EsoTwistD3Q27System::etTE = 2048; /*f11*/ - const unsigned long int EsoTwistD3Q27System::etBW = 4096; /*f12*/ - const unsigned long int EsoTwistD3Q27System::etBE = 8192; /*f13*/ - const unsigned long int EsoTwistD3Q27System::etTW = 16384; /*f14*/ - const unsigned long int EsoTwistD3Q27System::etTN = 32768; /*f15*/ - const unsigned long int EsoTwistD3Q27System::etBS = 65536; /*f16*/ - const unsigned long int EsoTwistD3Q27System::etBN = 131072; /*f17*/ - const unsigned long int EsoTwistD3Q27System::etTS = 262144; /*f18*/ - const unsigned long int EsoTwistD3Q27System::etTNE = 524288; - const unsigned long int EsoTwistD3Q27System::etTNW = 1048576; - const unsigned long int EsoTwistD3Q27System::etTSE = 2097152; - const unsigned long int EsoTwistD3Q27System::etTSW = 4194304; - const unsigned long int EsoTwistD3Q27System::etBNE = 8388608; - const unsigned long int EsoTwistD3Q27System::etBNW = 16777216; - const unsigned long int EsoTwistD3Q27System::etBSE = 33554432; -const unsigned long int EsoTwistD3Q27System::etBSW = 67108864; +const unsigned long int EsoTwistD3Q27System::etDIR[EsoTwistD3Q27System::ENDF + 1] = { + etE, etW, etN, etS, etT, etB, etNE, etSW, etSE, etNW, etTE, etBW, etBE, etTW, + etTN, etBS, etBN, etTS, etTNE, etTNW, etTSE, etTSW, etBNE, etBNW, etBSE, etBSW, etZERO +}; +const unsigned long int EsoTwistD3Q27System::etZERO = 1; /*f0 */ +const unsigned long int EsoTwistD3Q27System::etE = 2; /*f1 */ +const unsigned long int EsoTwistD3Q27System::etW = 4; /*f2 */ +const unsigned long int EsoTwistD3Q27System::etN = 8; /*f3 */ +const unsigned long int EsoTwistD3Q27System::etS = 16; /*f4 */ +const unsigned long int EsoTwistD3Q27System::etT = 32; /*f5 */ +const unsigned long int EsoTwistD3Q27System::etB = 64; /*f6 */ +const unsigned long int EsoTwistD3Q27System::etNE = 128; /*f7 */ +const unsigned long int EsoTwistD3Q27System::etSW = 256; /*f8 */ +const unsigned long int EsoTwistD3Q27System::etSE = 512; /*f9 */ +const unsigned long int EsoTwistD3Q27System::etNW = 1024; /*f10*/ +const unsigned long int EsoTwistD3Q27System::etTE = 2048; /*f11*/ +const unsigned long int EsoTwistD3Q27System::etBW = 4096; /*f12*/ +const unsigned long int EsoTwistD3Q27System::etBE = 8192; /*f13*/ +const unsigned long int EsoTwistD3Q27System::etTW = 16384; /*f14*/ +const unsigned long int EsoTwistD3Q27System::etTN = 32768; /*f15*/ +const unsigned long int EsoTwistD3Q27System::etBS = 65536; /*f16*/ +const unsigned long int EsoTwistD3Q27System::etBN = 131072; /*f17*/ +const unsigned long int EsoTwistD3Q27System::etTS = 262144; /*f18*/ +const unsigned long int EsoTwistD3Q27System::etTNE = 524288; +const unsigned long int EsoTwistD3Q27System::etTNW = 1048576; +const unsigned long int EsoTwistD3Q27System::etTSE = 2097152; +const unsigned long int EsoTwistD3Q27System::etTSW = 4194304; +const unsigned long int EsoTwistD3Q27System::etBNE = 8388608; +const unsigned long int EsoTwistD3Q27System::etBNW = 16777216; +const unsigned long int EsoTwistD3Q27System::etBSE = 33554432; +const unsigned long int EsoTwistD3Q27System::etBSW = 67108864; diff --git a/src/cpu/VirtualFluidsCore/Data/EsoTwistD3Q27System.h b/src/cpu/VirtualFluidsCore/Data/EsoTwistD3Q27System.h index 2c21e65ac3f39d85661f53062d42132c6667cc05..a9214673ec4b4a66a52fa53f9b625ead0180768b 100644 --- a/src/cpu/VirtualFluidsCore/Data/EsoTwistD3Q27System.h +++ b/src/cpu/VirtualFluidsCore/Data/EsoTwistD3Q27System.h @@ -1,28 +1,28 @@ //======================================================================================= -// ____ ____ __ ______ __________ __ __ __ __ -// \ \ | | | | | _ \ |___ ___| | | | | / \ | | -// \ \ | | | | | |_) | | | | | | | / \ | | -// \ \ | | | | | _ / | | | | | | / /\ \ | | -// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ -// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| -// \ \ | | ________________________________________________________________ -// \ \ | | | ______________________________________________________________| -// \ \| | | | __ __ __ __ ______ _______ -// \ | | |_____ | | | | | | | | | _ \ / _____) -// \ | | _____| | | | | | | | | | | \ \ \_______ +// ____ ____ __ ______ __________ __ __ __ __ +// \ \ | | | | | _ \ |___ ___| | | | | / \ | | +// \ \ | | | | | |_) | | | | | | | / \ | | +// \ \ | | | | | _ / | | | | | | / /\ \ | | +// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ +// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| +// \ \ | | ________________________________________________________________ +// \ \ | | | ______________________________________________________________| +// \ \| | | | __ __ __ __ ______ _______ +// \ | | |_____ | | | | | | | | | _ \ / _____) +// \ | | _____| | | | | | | | | | | \ \ \_______ // \ | | | | |_____ | \_/ | | | | |_/ / _____ | -// \ _____| |__| |________| \_______/ |__| |______/ (_______/ +// \ _____| |__| |________| \_______/ |__| |______/ (_______/ // -// This file is part of VirtualFluids. VirtualFluids is free software: you can +// This file is part of VirtualFluids. VirtualFluids is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of +// License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. -// -// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// +// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License along // with VirtualFluids (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>. // @@ -36,107 +36,105 @@ #include "D3Q27System.h" -//! -struct EsoTwistD3Q27System -{ - const static int FSTARTDIR = D3Q27System::FSTARTDIR; - const static int FENDDIR = D3Q27System::FENDDIR; //gellerstyle: meint alle frichtungen OHNE f0 +//! +struct EsoTwistD3Q27System { + const static int FSTARTDIR = D3Q27System::FSTARTDIR; + const static int FENDDIR = D3Q27System::FENDDIR; // gellerstyle: meint alle frichtungen OHNE f0 - const static int STARTF = D3Q27System::STARTF; - const static int ENDF = D3Q27System::ENDF; + const static int STARTF = D3Q27System::STARTF; + const static int ENDF = D3Q27System::ENDF; - const static int STARTDIR = D3Q27System::STARTDIR; - const static int ENDDIR = D3Q27System::ENDDIR; + const static int STARTDIR = D3Q27System::STARTDIR; + const static int ENDDIR = D3Q27System::ENDDIR; - static const int ZERO = D3Q27System::ZERO;/*f0 */ - static const int E = D3Q27System::E; /*f1 */ - static const int W = D3Q27System::W; /*f2 */ - static const int N = D3Q27System::N; /*f3 */ - static const int S = D3Q27System::S; /*f4 */ - static const int T = D3Q27System::T; /*f5 */ - static const int B = D3Q27System::B; /*f6 */ - static const int NE = D3Q27System::NE; /*f7 */ - static const int SW = D3Q27System::SW; /*f8 */ - static const int SE = D3Q27System::SE; /*f9 */ - static const int NW = D3Q27System::NW; /*f10*/ - static const int TE = D3Q27System::TE; /*f11*/ - static const int BW = D3Q27System::BW; /*f12*/ - static const int BE = D3Q27System::BE; /*f13*/ - static const int TW = D3Q27System::TW; /*f14*/ - static const int TN = D3Q27System::TN; /*f15*/ - static const int BS = D3Q27System::BS; /*f16*/ - static const int BN = D3Q27System::BN; /*f17*/ - static const int TS = D3Q27System::TS; /*f18*/ - static const int TNE = D3Q27System::TNE; - static const int TNW = D3Q27System::TNW; - static const int TSE = D3Q27System::TSE; - static const int TSW = D3Q27System::TSW; - static const int BNE = D3Q27System::BNE; - static const int BNW = D3Q27System::BNW; - static const int BSE = D3Q27System::BSE; - static const int BSW = D3Q27System::BSW; - + static const int ZERO = D3Q27System::ZERO; /*f0 */ + static const int E = D3Q27System::E; /*f1 */ + static const int W = D3Q27System::W; /*f2 */ + static const int N = D3Q27System::N; /*f3 */ + static const int S = D3Q27System::S; /*f4 */ + static const int T = D3Q27System::T; /*f5 */ + static const int B = D3Q27System::B; /*f6 */ + static const int NE = D3Q27System::NE; /*f7 */ + static const int SW = D3Q27System::SW; /*f8 */ + static const int SE = D3Q27System::SE; /*f9 */ + static const int NW = D3Q27System::NW; /*f10*/ + static const int TE = D3Q27System::TE; /*f11*/ + static const int BW = D3Q27System::BW; /*f12*/ + static const int BE = D3Q27System::BE; /*f13*/ + static const int TW = D3Q27System::TW; /*f14*/ + static const int TN = D3Q27System::TN; /*f15*/ + static const int BS = D3Q27System::BS; /*f16*/ + static const int BN = D3Q27System::BN; /*f17*/ + static const int TS = D3Q27System::TS; /*f18*/ + static const int TNE = D3Q27System::TNE; + static const int TNW = D3Q27System::TNW; + static const int TSE = D3Q27System::TSE; + static const int TSW = D3Q27System::TSW; + static const int BNE = D3Q27System::BNE; + static const int BNW = D3Q27System::BNW; + static const int BSE = D3Q27System::BSE; + static const int BSW = D3Q27System::BSW; - static const int INV_E = D3Q27System::W; - static const int INV_W = D3Q27System::E; - static const int INV_N = D3Q27System::S; - static const int INV_S = D3Q27System::N; - static const int INV_T = D3Q27System::B; - static const int INV_B = D3Q27System::T; - static const int INV_NE = D3Q27System::SW; - static const int INV_SW = D3Q27System::NE; - static const int INV_SE = D3Q27System::NW; - static const int INV_NW = D3Q27System::SE; - static const int INV_TE = D3Q27System::BW; - static const int INV_BW = D3Q27System::TE; - static const int INV_BE = D3Q27System::TW; - static const int INV_TW = D3Q27System::BE; - static const int INV_TN = D3Q27System::BS; - static const int INV_BS = D3Q27System::TN; - static const int INV_BN = D3Q27System::TS; - static const int INV_TS = D3Q27System::BN; - static const int INV_TNE = D3Q27System::BSW; - static const int INV_TNW = D3Q27System::BSE; - static const int INV_TSE = D3Q27System::BNW; - static const int INV_TSW = D3Q27System::BNE; - static const int INV_BNE = D3Q27System::TSW; - static const int INV_BNW = D3Q27System::TSE; - static const int INV_BSE = D3Q27System::TNW; - static const int INV_BSW = D3Q27System::TNE; + static const int INV_E = D3Q27System::W; + static const int INV_W = D3Q27System::E; + static const int INV_N = D3Q27System::S; + static const int INV_S = D3Q27System::N; + static const int INV_T = D3Q27System::B; + static const int INV_B = D3Q27System::T; + static const int INV_NE = D3Q27System::SW; + static const int INV_SW = D3Q27System::NE; + static const int INV_SE = D3Q27System::NW; + static const int INV_NW = D3Q27System::SE; + static const int INV_TE = D3Q27System::BW; + static const int INV_BW = D3Q27System::TE; + static const int INV_BE = D3Q27System::TW; + static const int INV_TW = D3Q27System::BE; + static const int INV_TN = D3Q27System::BS; + static const int INV_BS = D3Q27System::TN; + static const int INV_BN = D3Q27System::TS; + static const int INV_TS = D3Q27System::BN; + static const int INV_TNE = D3Q27System::BSW; + static const int INV_TNW = D3Q27System::BSE; + static const int INV_TSE = D3Q27System::BNW; + static const int INV_TSW = D3Q27System::BNE; + static const int INV_BNE = D3Q27System::TSW; + static const int INV_BNW = D3Q27System::TSE; + static const int INV_BSE = D3Q27System::TNW; + static const int INV_BSW = D3Q27System::TNE; - static const unsigned long int etZERO;// 1;/*f0 */ - static const unsigned long int etE;// 2; /*f1 */ - static const unsigned long int etW;// 4; /*f2 */ - static const unsigned long int etN;// 8; /*f3 */ - static const unsigned long int etS;// 16; /*f4 */ - static const unsigned long int etT;// 32; /*f5 */ - static const unsigned long int etB;// 64; /*f6 */ - static const unsigned long int etNE;// 128; /*f7 */ - static const unsigned long int etSW;// 256; /*f8 */ - static const unsigned long int etSE;// 512; /*f9 */ - static const unsigned long int etNW;// 1024; /*f10*/ - static const unsigned long int etTE;// 2048; /*f11*/ - static const unsigned long int etBW;// 4096; /*f12*/ - static const unsigned long int etBE;// 8192; /*f13*/ - static const unsigned long int etTW;// 16384; /*f14*/ - static const unsigned long int etTN;// 32768; /*f15*/ - static const unsigned long int etBS;// 65536; /*f16*/ - static const unsigned long int etBN;// 131072; /*f17*/ - static const unsigned long int etTS;// 262144; /*f18*/ - static const unsigned long int etTNE;// 524288; - static const unsigned long int etTNW;// 1048576; - static const unsigned long int etTSE;// 2097152; - static const unsigned long int etTSW;// 4194304; - static const unsigned long int etBNE;// 8388608; - static const unsigned long int etBNW;// 16777216; - static const unsigned long int etBSE;// 33554432; - static const unsigned long int etBSW;// = 67108864; + static const unsigned long int etZERO; // 1;/*f0 */ + static const unsigned long int etE; // 2; /*f1 */ + static const unsigned long int etW; // 4; /*f2 */ + static const unsigned long int etN; // 8; /*f3 */ + static const unsigned long int etS; // 16; /*f4 */ + static const unsigned long int etT; // 32; /*f5 */ + static const unsigned long int etB; // 64; /*f6 */ + static const unsigned long int etNE; // 128; /*f7 */ + static const unsigned long int etSW; // 256; /*f8 */ + static const unsigned long int etSE; // 512; /*f9 */ + static const unsigned long int etNW; // 1024; /*f10*/ + static const unsigned long int etTE; // 2048; /*f11*/ + static const unsigned long int etBW; // 4096; /*f12*/ + static const unsigned long int etBE; // 8192; /*f13*/ + static const unsigned long int etTW; // 16384; /*f14*/ + static const unsigned long int etTN; // 32768; /*f15*/ + static const unsigned long int etBS; // 65536; /*f16*/ + static const unsigned long int etBN; // 131072; /*f17*/ + static const unsigned long int etTS; // 262144; /*f18*/ + static const unsigned long int etTNE; // 524288; + static const unsigned long int etTNW; // 1048576; + static const unsigned long int etTSE; // 2097152; + static const unsigned long int etTSW; // 4194304; + static const unsigned long int etBNE; // 8388608; + static const unsigned long int etBNW; // 16777216; + static const unsigned long int etBSE; // 33554432; + static const unsigned long int etBSW; // = 67108864; - const static int ETX1[ENDF+1]; - const static int ETX2[ENDF+1]; - const static int ETX3[ENDF+1]; - const static int etINVDIR[ENDF+1]; - const static unsigned long int etDIR[ENDF+1]; + const static int ETX1[ENDF + 1]; + const static int ETX2[ENDF + 1]; + const static int ETX3[ENDF + 1]; + const static int etINVDIR[ENDF + 1]; + const static unsigned long int etDIR[ENDF + 1]; }; #endif diff --git a/src/cpu/VirtualFluidsCore/Data/VoidData3D.h b/src/cpu/VirtualFluidsCore/Data/VoidData3D.h index b4a9b2ff6010c7c2997691a435329fd14156ff5d..bab8eca0d62670e65275034cd3b67ace2953a349 100644 --- a/src/cpu/VirtualFluidsCore/Data/VoidData3D.h +++ b/src/cpu/VirtualFluidsCore/Data/VoidData3D.h @@ -3,35 +3,52 @@ #include "EsoTwist3D.h" - class VoidData3D : public EsoTwist3D { public: - VoidData3D() = default;; - VoidData3D (size_t nx1, size_t nx2, size_t nx3, LBMReal /*value*/) - { - this->NX1 = nx1; - this->NX2 = nx2; - this->NX3 = nx3; - } - ~VoidData3D() override = default;; - size_t getNX1() const override { return NX1;} - size_t getNX2() const override { return NX2;} - size_t getNX3() const override { return NX3;} - void getDistribution(LBMReal* const f, size_t x1, size_t x2, size_t x3) override {} - void setDistribution(const LBMReal* const f, size_t x1, size_t x2, size_t x3) override{} - void getDistributionInv(LBMReal* const f, size_t x1, size_t x2, size_t x3) override {} - void setDistributionInv(const LBMReal* const f, size_t x1, size_t x2, size_t x3) override {} - void setDistributionForDirection(const LBMReal* const f, size_t x1, size_t x2, size_t x3, unsigned long int direction) override {} + VoidData3D() = default; + ; + VoidData3D(size_t nx1, size_t nx2, size_t nx3, LBMReal /*value*/) + { + this->NX1 = nx1; + this->NX2 = nx2; + this->NX3 = nx3; + } + ~VoidData3D() override = default; + ; + size_t getNX1() const override { return NX1; } + size_t getNX2() const override { return NX2; } + size_t getNX3() const override { return NX3; } + void getDistribution(LBMReal *const f, size_t x1, size_t x2, size_t x3) override {} + void setDistribution(const LBMReal *const f, size_t x1, size_t x2, size_t x3) override {} + void getDistributionInv(LBMReal *const f, size_t x1, size_t x2, size_t x3) override {} + void setDistributionInv(const LBMReal *const f, size_t x1, size_t x2, size_t x3) override {} + void setDistributionForDirection(const LBMReal *const f, size_t x1, size_t x2, size_t x3, + unsigned long int direction) override + { + } void setDistributionForDirection(LBMReal f, size_t x1, size_t x2, size_t x3, int direction) override {} - LBMReal getDistributionInvForDirection(size_t /*x1*/, size_t /*x2*/, size_t /*x3*/, int /*direction*/) override {return 0.0;} - void setDistributionInvForDirection(const LBMReal* const f, size_t x1, size_t x2, size_t x3, unsigned long int direction) override {} - void setDistributionInvForDirection(LBMReal f, size_t x1, size_t x2, size_t x3, unsigned long int direction) override {} - LBMReal getDistributionForDirection(size_t /*x1*/, size_t /*x2*/, size_t /*x3*/, int /*direction*/) override {return 0.0;} + LBMReal getDistributionInvForDirection(size_t /*x1*/, size_t /*x2*/, size_t /*x3*/, int /*direction*/) override + { + return 0.0; + } + void setDistributionInvForDirection(const LBMReal *const f, size_t x1, size_t x2, size_t x3, + unsigned long int direction) override + { + } + void setDistributionInvForDirection(LBMReal f, size_t x1, size_t x2, size_t x3, + unsigned long int direction) override + { + } + LBMReal getDistributionForDirection(size_t /*x1*/, size_t /*x2*/, size_t /*x3*/, int /*direction*/) override + { + return 0.0; + } void swap() override {} + protected: private: - size_t NX1, NX2, NX3; + size_t NX1, NX2, NX3; }; #endif diff --git a/src/cpu/VirtualFluidsCore/Grid/BasicCalculator.cpp b/src/cpu/VirtualFluidsCore/Grid/BasicCalculator.cpp index 55c35a9cd465799f7877d88a3f4c4a81524f518a..362225638cf12f73c397493c9e38e839d681b754 100644 --- a/src/cpu/VirtualFluidsCore/Grid/BasicCalculator.cpp +++ b/src/cpu/VirtualFluidsCore/Grid/BasicCalculator.cpp @@ -1,28 +1,28 @@ //======================================================================================= -// ____ ____ __ ______ __________ __ __ __ __ -// \ \ | | | | | _ \ |___ ___| | | | | / \ | | -// \ \ | | | | | |_) | | | | | | | / \ | | -// \ \ | | | | | _ / | | | | | | / /\ \ | | -// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ -// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| -// \ \ | | ________________________________________________________________ -// \ \ | | | ______________________________________________________________| -// \ \| | | | __ __ __ __ ______ _______ -// \ | | |_____ | | | | | | | | | _ \ / _____) -// \ | | _____| | | | | | | | | | | \ \ \_______ +// ____ ____ __ ______ __________ __ __ __ __ +// \ \ | | | | | _ \ |___ ___| | | | | / \ | | +// \ \ | | | | | |_) | | | | | | | / \ | | +// \ \ | | | | | _ / | | | | | | / /\ \ | | +// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ +// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| +// \ \ | | ________________________________________________________________ +// \ \ | | | ______________________________________________________________| +// \ \| | | | __ __ __ __ ______ _______ +// \ | | |_____ | | | | | | | | | _ \ / _____) +// \ | | _____| | | | | | | | | | | \ \ \_______ // \ | | | | |_____ | \_/ | | | | |_/ / _____ | -// \ _____| |__| |________| \_______/ |__| |______/ (_______/ +// \ _____| |__| |________| \_______/ |__| |______/ (_______/ // -// This file is part of VirtualFluids. VirtualFluids is free software: you can +// This file is part of VirtualFluids. VirtualFluids is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of +// License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. -// -// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// +// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License along // with VirtualFluids (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>. // @@ -33,12 +33,12 @@ #include "BasicCalculator.h" -#include "Block3D.h" #include "BCProcessor.h" -#include "LBMKernel.h" +#include "Block3D.h" #include "Block3DConnector.h" -#include "UbScheduler.h" +#include "LBMKernel.h" #include "UbLogger.h" +#include "UbScheduler.h" #ifdef _OPENMP #include <omp.h> @@ -48,136 +48,126 @@ //#define TIMING //#include "UbTiming.h" -BasicCalculator::BasicCalculator(SPtr<Grid3D> grid, SPtr<UbScheduler> additionalGhostLayerUpdateScheduler, int numberOfTimeSteps) : - Calculator(grid, additionalGhostLayerUpdateScheduler, numberOfTimeSteps) +BasicCalculator::BasicCalculator(SPtr<Grid3D> grid, SPtr<UbScheduler> additionalGhostLayerUpdateScheduler, + int numberOfTimeSteps) + : Calculator(grid, additionalGhostLayerUpdateScheduler, numberOfTimeSteps) { - } ////////////////////////////////////////////////////////////////////////// void BasicCalculator::calculate() { - UBLOG(logDEBUG1, "OMPCalculator::calculate() - started"); - int calcStep = 0; - try - { - int minInitLevel = minLevel; - int maxInitLevel = maxLevel - minLevel; - int straightStartLevel = minInitLevel; - int internalIterations = 1 << (maxInitLevel - minInitLevel); -// int forwardStartLevel; - int threshold; + UBLOG(logDEBUG1, "OMPCalculator::calculate() - started"); + int calcStep = 0; + try { + int minInitLevel = minLevel; + int maxInitLevel = maxLevel - minLevel; + int straightStartLevel = minInitLevel; + int internalIterations = 1 << (maxInitLevel - minInitLevel); + // int forwardStartLevel; + int threshold; #ifdef TIMING - UbTimer timer; - double time[6]; + UbTimer timer; + double time[6]; #endif - for (calcStep = startTimeStep; calcStep <= numberOfTimeSteps; calcStep++) - { - ////////////////////////////////////////////////////////////////////////// + for (calcStep = startTimeStep; calcStep <= numberOfTimeSteps; calcStep++) { + ////////////////////////////////////////////////////////////////////////// #ifdef TIMING - UBLOG(logINFO, "calcStep = " << calcStep); + UBLOG(logINFO, "calcStep = " << calcStep); #endif - ////////////////////////////////////////////////////////////////////////// - - for (int staggeredStep = 1; staggeredStep <= internalIterations; staggeredStep++) - { -// forwardStartLevel = straightStartLevel; - if (staggeredStep == internalIterations) straightStartLevel = minInitLevel; - else - { - for (straightStartLevel = maxInitLevel, threshold = 1; - (staggeredStep & threshold) != threshold; straightStartLevel--, threshold <<= 1); - } ////////////////////////////////////////////////////////////////////////// + + for (int staggeredStep = 1; staggeredStep <= internalIterations; staggeredStep++) { + // forwardStartLevel = straightStartLevel; + if (staggeredStep == internalIterations) + straightStartLevel = minInitLevel; + else { + for (straightStartLevel = maxInitLevel, threshold = 1; (staggeredStep & threshold) != threshold; + straightStartLevel--, threshold <<= 1) + ; + } + ////////////////////////////////////////////////////////////////////////// #ifdef TIMING - timer.resetAndStart(); + timer.resetAndStart(); #endif - ////////////////////////////////////////////////////////////////////////// - applyPreCollisionBC(straightStartLevel, maxInitLevel); + ////////////////////////////////////////////////////////////////////////// + applyPreCollisionBC(straightStartLevel, maxInitLevel); - //do collision for all blocks - calculateBlocks(straightStartLevel, maxInitLevel, calcStep); - ////////////////////////////////////////////////////////////////////////// + // do collision for all blocks + calculateBlocks(straightStartLevel, maxInitLevel, calcStep); + ////////////////////////////////////////////////////////////////////////// #ifdef TIMING - time[0] = timer.stop(); - UBLOG(logINFO, "calculateBlocks time = " << time[0]); + time[0] = timer.stop(); + UBLOG(logINFO, "calculateBlocks time = " << time[0]); #endif - ////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////// - //exchange data between blocks - exchangeBlockData(straightStartLevel, maxInitLevel); - ////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////// + // exchange data between blocks + exchangeBlockData(straightStartLevel, maxInitLevel); + ////////////////////////////////////////////////////////////////////////// #ifdef TIMING - time[1] = timer.stop(); - UBLOG(logINFO, "exchangeBlockData time = " << time[1]); + time[1] = timer.stop(); + UBLOG(logINFO, "exchangeBlockData time = " << time[1]); #endif - ////////////////////////////////////////////////////////////////////////// - applyPostCollisionBC(straightStartLevel, maxInitLevel); - ////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////// + applyPostCollisionBC(straightStartLevel, maxInitLevel); + ////////////////////////////////////////////////////////////////////////// #ifdef TIMING - time[2] = timer.stop(); - UBLOG(logINFO, "applyBCs time = " << time[2]); + time[2] = timer.stop(); + UBLOG(logINFO, "applyBCs time = " << time[2]); #endif - ////////////////////////////////////////////////////////////////////////// - //swap distributions in kernel - swapDistributions(straightStartLevel, maxInitLevel); - ////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////// + // swap distributions in kernel + swapDistributions(straightStartLevel, maxInitLevel); + ////////////////////////////////////////////////////////////////////////// #ifdef TIMING - time[3] = timer.stop(); - UBLOG(logINFO, "swapDistributions time = " << time[3]); + time[3] = timer.stop(); + UBLOG(logINFO, "swapDistributions time = " << time[3]); #endif - ////////////////////////////////////////////////////////////////////////// - if (refinement) - { - if (straightStartLevel < maxInitLevel) - exchangeBlockData(straightStartLevel, maxInitLevel); - ////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////// + if (refinement) { + if (straightStartLevel < maxInitLevel) + exchangeBlockData(straightStartLevel, maxInitLevel); + ////////////////////////////////////////////////////////////////////////// #ifdef TIMING - time[4] = timer.stop(); - UBLOG(logINFO, "refinement exchangeBlockData time = " << time[4]); + time[4] = timer.stop(); + UBLOG(logINFO, "refinement exchangeBlockData time = " << time[4]); #endif - ////////////////////////////////////////////////////////////////////////// - //now ghost nodes have actual values - //interpolation of interface nodes between grid levels - interpolation(straightStartLevel, maxInitLevel); - ////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////// + // now ghost nodes have actual values + // interpolation of interface nodes between grid levels + interpolation(straightStartLevel, maxInitLevel); + ////////////////////////////////////////////////////////////////////////// #ifdef TIMING - time[5] = timer.stop(); - UBLOG(logINFO, "refinement interpolation time = " << time[5]); + time[5] = timer.stop(); + UBLOG(logINFO, "refinement interpolation time = " << time[5]); #endif - ////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////// + } } - } - //exchange data between blocks for visualization - if (additionalGhostLayerUpdateScheduler->isDue(calcStep)) - { - exchangeBlockData(straightStartLevel, maxInitLevel); - } - coProcess((double)(calcStep)); - //now ghost nodes have actual values - } - UBLOG(logDEBUG1, "OMPCalculator::calculate() - stoped"); - } - catch (std::exception & e) - { - UBLOG(logERROR, e.what()); - UBLOG(logERROR, " step = " << calcStep); - //throw e; - //exit(EXIT_FAILURE); - } - catch (std::string & s) - { - UBLOG(logERROR, s); - //exit(EXIT_FAILURE); - //throw s; - } - catch (...) - { - UBLOG(logERROR, "unknown exception"); - //exit(EXIT_FAILURE); - //throw; - } + // exchange data between blocks for visualization + if (additionalGhostLayerUpdateScheduler->isDue(calcStep)) { + exchangeBlockData(straightStartLevel, maxInitLevel); + } + coProcess((double)(calcStep)); + // now ghost nodes have actual values + } + UBLOG(logDEBUG1, "OMPCalculator::calculate() - stoped"); + } catch (std::exception &e) { + UBLOG(logERROR, e.what()); + UBLOG(logERROR, " step = " << calcStep); + // throw e; + // exit(EXIT_FAILURE); + } catch (std::string &s) { + UBLOG(logERROR, s); + // exit(EXIT_FAILURE); + // throw s; + } catch (...) { + UBLOG(logERROR, "unknown exception"); + // exit(EXIT_FAILURE); + // throw; + } } ////////////////////////////////////////////////////////////////////////// void BasicCalculator::calculateBlocks(int startLevel, int maxInitLevel, int calcStep) @@ -185,50 +175,45 @@ void BasicCalculator::calculateBlocks(int startLevel, int maxInitLevel, int calc #ifdef _OPENMP #pragma omp parallel #endif - { - SPtr<Block3D> blockTemp; - //startLevel bis maxInitLevel - for (int level = startLevel; level <= maxInitLevel; level++) - { - //timer.resetAndStart(); - //call LBM kernel - int size = (int)blocks[level].size(); + { + SPtr<Block3D> blockTemp; + // startLevel bis maxInitLevel + for (int level = startLevel; level <= maxInitLevel; level++) { + // timer.resetAndStart(); + // call LBM kernel + int size = (int)blocks[level].size(); #ifdef _OPENMP #pragma omp for schedule(OMP_SCHEDULE) #endif - for (int i = 0; i < size; i++) - { - try - { - blockTemp = blocks[level][i]; - blockTemp->getKernel()->calculate(calcStep); - } - catch (std::exception & e) - { - UBLOG(logERROR, e.what()); - UBLOG(logERROR, blockTemp->toString() << " step = " << calcStep); - std::exit(EXIT_FAILURE); + for (int i = 0; i < size; i++) { + try { + blockTemp = blocks[level][i]; + blockTemp->getKernel()->calculate(calcStep); + } catch (std::exception &e) { + UBLOG(logERROR, e.what()); + UBLOG(logERROR, blockTemp->toString() << " step = " << calcStep); + std::exit(EXIT_FAILURE); + } } - } - //timer.stop(); - //UBLOG(logINFO, "level = " << level << " blocks = " << blocks[level].size() << " collision time = " << timer.getTotalTime()); - } - } + // timer.stop(); + // UBLOG(logINFO, "level = " << level << " blocks = " << blocks[level].size() << " collision time = " << + // timer.getTotalTime()); + } + } } ////////////////////////////////////////////////////////////////////////// void BasicCalculator::exchangeBlockData(int startLevel, int maxInitLevel) { - //startLevel bis maxInitLevel - for (int level = startLevel; level <= maxInitLevel; level++) - { - //connectorsPrepareLocal(localConns[level]); - connectorsSendLocal(localConns[level]); - //connectorsReceiveLocal(localConns[level]); + // startLevel bis maxInitLevel + for (int level = startLevel; level <= maxInitLevel; level++) { + // connectorsPrepareLocal(localConns[level]); + connectorsSendLocal(localConns[level]); + // connectorsReceiveLocal(localConns[level]); - connectorsPrepareRemote(remoteConns[level]); - connectorsSendRemote(remoteConns[level]); - connectorsReceiveRemote(remoteConns[level]); - } + connectorsPrepareRemote(remoteConns[level]); + connectorsSendRemote(remoteConns[level]); + connectorsReceiveRemote(remoteConns[level]); + } } ////////////////////////////////////////////////////////////////////////// void BasicCalculator::swapDistributions(int startLevel, int maxInitLevel) @@ -236,192 +221,156 @@ void BasicCalculator::swapDistributions(int startLevel, int maxInitLevel) #ifdef _OPENMP #pragma omp parallel #endif - { - //startLevel bis maxInitLevel - for (int level = startLevel; level <= maxInitLevel; level++) - { - int size = (int)blocks[level].size(); + { + // startLevel bis maxInitLevel + for (int level = startLevel; level <= maxInitLevel; level++) { + int size = (int)blocks[level].size(); #ifdef _OPENMP #pragma omp for schedule(OMP_SCHEDULE) #endif - for (int i = 0; i < size; i++) - { - blocks[level][i]->getKernel()->swapDistributions(); - } - } - } + for (int i = 0; i < size; i++) { + blocks[level][i]->getKernel()->swapDistributions(); + } + } + } } ////////////////////////////////////////////////////////////////////////// -void BasicCalculator::connectorsPrepareLocal(std::vector< SPtr<Block3DConnector> >& connectors) +void BasicCalculator::connectorsPrepareLocal(std::vector<SPtr<Block3DConnector>> &connectors) { - int size = (int)connectors.size(); + int size = (int)connectors.size(); #ifdef _OPENMP #pragma omp parallel for schedule(OMP_SCHEDULE) #endif - for (int i = 0; i < size; i++) - { - try - { - connectors[i]->prepareForReceive(); - connectors[i]->prepareForSend(); - } - catch (std::exception & e) - { - UBLOG(logERROR, e.what()); - std::exit(EXIT_FAILURE); - } - } + for (int i = 0; i < size; i++) { + try { + connectors[i]->prepareForReceive(); + connectors[i]->prepareForSend(); + } catch (std::exception &e) { + UBLOG(logERROR, e.what()); + std::exit(EXIT_FAILURE); + } + } } ////////////////////////////////////////////////////////////////////////// -void BasicCalculator::connectorsSendLocal(std::vector< SPtr<Block3DConnector> >& connectors) +void BasicCalculator::connectorsSendLocal(std::vector<SPtr<Block3DConnector>> &connectors) { - int size = (int)connectors.size(); + int size = (int)connectors.size(); #ifdef _OPENMP #pragma omp parallel for schedule(OMP_SCHEDULE) #endif - for (int i = 0; i < size; i++) - { - try - { - connectors[i]->fillSendVectors(); - connectors[i]->sendVectors(); - } - catch (std::exception & e) - { - UBLOG(logERROR, e.what()); - std::exit(EXIT_FAILURE); - } - } + for (int i = 0; i < size; i++) { + try { + connectors[i]->fillSendVectors(); + connectors[i]->sendVectors(); + } catch (std::exception &e) { + UBLOG(logERROR, e.what()); + std::exit(EXIT_FAILURE); + } + } } ////////////////////////////////////////////////////////////////////////// -void BasicCalculator::connectorsReceiveLocal(std::vector< SPtr<Block3DConnector> >& connectors) +void BasicCalculator::connectorsReceiveLocal(std::vector<SPtr<Block3DConnector>> &connectors) { - int size = (int)connectors.size(); + int size = (int)connectors.size(); #ifdef _OPENMP #pragma omp parallel for schedule(OMP_SCHEDULE) #endif - for (int i = 0; i < size; i++) - { - connectors[i]->receiveVectors(); - connectors[i]->distributeReceiveVectors(); - } + for (int i = 0; i < size; i++) { + connectors[i]->receiveVectors(); + connectors[i]->distributeReceiveVectors(); + } } -void BasicCalculator::connectorsPrepareRemote(std::vector< SPtr<Block3DConnector> >& connectors) +void BasicCalculator::connectorsPrepareRemote(std::vector<SPtr<Block3DConnector>> &connectors) { - int size = (int)connectors.size(); - for (int i = 0; i < size; i++) - { - connectors[i]->prepareForReceive(); - connectors[i]->prepareForSend(); - } + int size = (int)connectors.size(); + for (int i = 0; i < size; i++) { + connectors[i]->prepareForReceive(); + connectors[i]->prepareForSend(); + } } ////////////////////////////////////////////////////////////////////////// -void BasicCalculator::connectorsSendRemote(std::vector< SPtr<Block3DConnector> >& connectors) +void BasicCalculator::connectorsSendRemote(std::vector<SPtr<Block3DConnector>> &connectors) { - int size = (int)connectors.size(); - for (int i = 0; i < size; i++) - { - connectors[i]->fillSendVectors(); - connectors[i]->sendVectors(); - } + int size = (int)connectors.size(); + for (int i = 0; i < size; i++) { + connectors[i]->fillSendVectors(); + connectors[i]->sendVectors(); + } } ////////////////////////////////////////////////////////////////////////// -void BasicCalculator::connectorsReceiveRemote(std::vector< SPtr<Block3DConnector> >& connectors) +void BasicCalculator::connectorsReceiveRemote(std::vector<SPtr<Block3DConnector>> &connectors) { - int size = (int)connectors.size(); - for (int i = 0; i < size; i++) - { - connectors[i]->receiveVectors(); - connectors[i]->distributeReceiveVectors(); - } + int size = (int)connectors.size(); + for (int i = 0; i < size; i++) { + connectors[i]->receiveVectors(); + connectors[i]->distributeReceiveVectors(); + } } ////////////////////////////////////////////////////////////////////////// void BasicCalculator::interpolation(int startLevel, int maxInitLevel) { - for (int level = startLevel; level < maxInitLevel; level++) - { - connectorsPrepareLocal(localInterConns[level]); - connectorsPrepareRemote(remoteInterConns[level]); - } + for (int level = startLevel; level < maxInitLevel; level++) { + connectorsPrepareLocal(localInterConns[level]); + connectorsPrepareRemote(remoteInterConns[level]); + } - for (int level = startLevel; level < maxInitLevel; level++) - { - connectorsSendLocal(localInterConns[level]); - connectorsSendRemote(remoteInterConns[level]); - } + for (int level = startLevel; level < maxInitLevel; level++) { + connectorsSendLocal(localInterConns[level]); + connectorsSendRemote(remoteInterConns[level]); + } - for (int level = startLevel; level < maxInitLevel; level++) - { - connectorsReceiveLocal(localInterConns[level]); - connectorsReceiveRemote(remoteInterConns[level]); - } + for (int level = startLevel; level < maxInitLevel; level++) { + connectorsReceiveLocal(localInterConns[level]); + connectorsReceiveRemote(remoteInterConns[level]); + } } ////////////////////////////////////////////////////////////////////////// void BasicCalculator::applyPreCollisionBC(int startLevel, int maxInitLevel) { - //startLevel bis maxInitLevel - for (int level = startLevel; level <= maxInitLevel; level++) - { - int size = (int)blocks[level].size(); + // startLevel bis maxInitLevel + for (int level = startLevel; level <= maxInitLevel; level++) { + int size = (int)blocks[level].size(); #ifdef _OPENMP #pragma omp parallel for schedule(OMP_SCHEDULE) #endif - for (int i = 0; i < size; i++) - { - try - { - blocks[level][i]->getKernel()->getBCProcessor()->applyPreCollisionBC(); - } - catch (std::exception & e) - { - UBLOG(logERROR, e.what()); - exit(EXIT_FAILURE); - } - catch (std::string & s) - { - UBLOG(logERROR, s); - exit(EXIT_FAILURE); - } - catch (...) - { - UBLOG(logERROR, "unknown exception"); - exit(EXIT_FAILURE); - } - } - } + for (int i = 0; i < size; i++) { + try { + blocks[level][i]->getKernel()->getBCProcessor()->applyPreCollisionBC(); + } catch (std::exception &e) { + UBLOG(logERROR, e.what()); + exit(EXIT_FAILURE); + } catch (std::string &s) { + UBLOG(logERROR, s); + exit(EXIT_FAILURE); + } catch (...) { + UBLOG(logERROR, "unknown exception"); + exit(EXIT_FAILURE); + } + } + } } ////////////////////////////////////////////////////////////////////////// void BasicCalculator::applyPostCollisionBC(int startLevel, int maxInitLevel) { - //startLevel bis maxInitLevel - for (int level = startLevel; level <= maxInitLevel; level++) - { - int size = (int)blocks[level].size(); + // startLevel bis maxInitLevel + for (int level = startLevel; level <= maxInitLevel; level++) { + int size = (int)blocks[level].size(); #ifdef _OPENMP #pragma omp parallel for schedule(OMP_SCHEDULE) #endif - for (int i = 0; i < size; i++) - { - try - { - blocks[level][i]->getKernel()->getBCProcessor()->applyPostCollisionBC(); - } - catch (std::exception & e) - { - UBLOG(logERROR, e.what()); - exit(EXIT_FAILURE); - } - catch (std::string & s) - { - UBLOG(logERROR, s); - exit(EXIT_FAILURE); - } - catch (...) - { - UBLOG(logERROR, "unknown exception"); - exit(EXIT_FAILURE); - } - } - } + for (int i = 0; i < size; i++) { + try { + blocks[level][i]->getKernel()->getBCProcessor()->applyPostCollisionBC(); + } catch (std::exception &e) { + UBLOG(logERROR, e.what()); + exit(EXIT_FAILURE); + } catch (std::string &s) { + UBLOG(logERROR, s); + exit(EXIT_FAILURE); + } catch (...) { + UBLOG(logERROR, "unknown exception"); + exit(EXIT_FAILURE); + } + } + } } - diff --git a/src/cpu/VirtualFluidsCore/Grid/BasicCalculator.h b/src/cpu/VirtualFluidsCore/Grid/BasicCalculator.h index 7585f53ce3651c8d80328c5cc3a0821e5e7cda43..3ef1f4c712e552ea5d5b5e82306e2bd94d74d7ab 100644 --- a/src/cpu/VirtualFluidsCore/Grid/BasicCalculator.h +++ b/src/cpu/VirtualFluidsCore/Grid/BasicCalculator.h @@ -1,28 +1,28 @@ //======================================================================================= -// ____ ____ __ ______ __________ __ __ __ __ -// \ \ | | | | | _ \ |___ ___| | | | | / \ | | -// \ \ | | | | | |_) | | | | | | | / \ | | -// \ \ | | | | | _ / | | | | | | / /\ \ | | -// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ -// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| -// \ \ | | ________________________________________________________________ -// \ \ | | | ______________________________________________________________| -// \ \| | | | __ __ __ __ ______ _______ -// \ | | |_____ | | | | | | | | | _ \ / _____) -// \ | | _____| | | | | | | | | | | \ \ \_______ +// ____ ____ __ ______ __________ __ __ __ __ +// \ \ | | | | | _ \ |___ ___| | | | | / \ | | +// \ \ | | | | | |_) | | | | | | | / \ | | +// \ \ | | | | | _ / | | | | | | / /\ \ | | +// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ +// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| +// \ \ | | ________________________________________________________________ +// \ \ | | | ______________________________________________________________| +// \ \| | | | __ __ __ __ ______ _______ +// \ | | |_____ | | | | | | | | | _ \ / _____) +// \ | | _____| | | | | | | | | | | \ \ \_______ // \ | | | | |_____ | \_/ | | | | |_/ / _____ | -// \ _____| |__| |________| \_______/ |__| |______/ (_______/ +// \ _____| |__| |________| \_______/ |__| |______/ (_______/ // -// This file is part of VirtualFluids. VirtualFluids is free software: you can +// This file is part of VirtualFluids. VirtualFluids is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of +// License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. -// -// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// +// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License along // with VirtualFluids (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>. // @@ -38,34 +38,32 @@ class Block3DConnector; -//! \class BasicCalculator -//! \brief Class implements basic functionality with MPI + OpenMP parallelization for main calculation loop -//! \author Konstantin Kutscher +//! \class BasicCalculator +//! \brief Class implements basic functionality with MPI + OpenMP parallelization for main calculation loop +//! \author Konstantin Kutscher class BasicCalculator : public Calculator { public: - BasicCalculator(SPtr<Grid3D> grid, SPtr<UbScheduler> additionalGhostLayerUpdateScheduler, int numberOfTimeSteps); - ~BasicCalculator() override = default; - void calculate() override; + BasicCalculator(SPtr<Grid3D> grid, SPtr<UbScheduler> additionalGhostLayerUpdateScheduler, int numberOfTimeSteps); + ~BasicCalculator() override = default; + void calculate() override; protected: - void calculateBlocks(int startLevel, int maxInitLevel, int calcStep); - void swapDistributions(int startLevel, int maxInitLevel); - void exchangeBlockData(int startLevel, int maxInitLevel); - void connectorsPrepareLocal(std::vector< SPtr<Block3DConnector> >& connectors); - void connectorsSendLocal(std::vector< SPtr<Block3DConnector> >& connectors); - void connectorsReceiveLocal(std::vector< SPtr<Block3DConnector> >& connectors); - void connectorsPrepareRemote(std::vector< SPtr<Block3DConnector> >& connectors); - void connectorsSendRemote(std::vector< SPtr<Block3DConnector> >& connectors); - void connectorsReceiveRemote(std::vector< SPtr<Block3DConnector> >& connectors); - void interpolation(int startLevel, int maxInitLevel); - void applyPreCollisionBC(int startLevel, int maxInitLevel); - void applyPostCollisionBC(int startLevel, int maxInitLevel); + void calculateBlocks(int startLevel, int maxInitLevel, int calcStep); + void swapDistributions(int startLevel, int maxInitLevel); + void exchangeBlockData(int startLevel, int maxInitLevel); + void connectorsPrepareLocal(std::vector<SPtr<Block3DConnector>> &connectors); + void connectorsSendLocal(std::vector<SPtr<Block3DConnector>> &connectors); + void connectorsReceiveLocal(std::vector<SPtr<Block3DConnector>> &connectors); + void connectorsPrepareRemote(std::vector<SPtr<Block3DConnector>> &connectors); + void connectorsSendRemote(std::vector<SPtr<Block3DConnector>> &connectors); + void connectorsReceiveRemote(std::vector<SPtr<Block3DConnector>> &connectors); + void interpolation(int startLevel, int maxInitLevel); + void applyPreCollisionBC(int startLevel, int maxInitLevel); + void applyPostCollisionBC(int startLevel, int maxInitLevel); + private: }; #endif // BasicCalculator_h__ - - - diff --git a/src/cpu/VirtualFluidsCore/Grid/Block3D.cpp b/src/cpu/VirtualFluidsCore/Grid/Block3D.cpp index 23fc3903bfa7877211ff9e47d5993f0f7b39d742..79753c144f5cfff831f1d0415e9434c50b11bcea 100644 --- a/src/cpu/VirtualFluidsCore/Grid/Block3D.cpp +++ b/src/cpu/VirtualFluidsCore/Grid/Block3D.cpp @@ -1,28 +1,28 @@ //======================================================================================= -// ____ ____ __ ______ __________ __ __ __ __ -// \ \ | | | | | _ \ |___ ___| | | | | / \ | | -// \ \ | | | | | |_) | | | | | | | / \ | | -// \ \ | | | | | _ / | | | | | | / /\ \ | | -// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ -// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| -// \ \ | | ________________________________________________________________ -// \ \ | | | ______________________________________________________________| -// \ \| | | | __ __ __ __ ______ _______ -// \ | | |_____ | | | | | | | | | _ \ / _____) -// \ | | _____| | | | | | | | | | | \ \ \_______ +// ____ ____ __ ______ __________ __ __ __ __ +// \ \ | | | | | _ \ |___ ___| | | | | / \ | | +// \ \ | | | | | |_) | | | | | | | / \ | | +// \ \ | | | | | _ / | | | | | | / /\ \ | | +// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ +// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| +// \ \ | | ________________________________________________________________ +// \ \ | | | ______________________________________________________________| +// \ \| | | | __ __ __ __ ______ _______ +// \ | | |_____ | | | | | | | | | _ \ / _____) +// \ | | _____| | | | | | | | | | | \ \ \_______ // \ | | | | |_____ | \_/ | | | | |_/ / _____ | -// \ _____| |__| |________| \_______/ |__| |______/ (_______/ +// \ _____| |__| |________| \_______/ |__| |______/ (_______/ // -// This file is part of VirtualFluids. VirtualFluids is free software: you can +// This file is part of VirtualFluids. VirtualFluids is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of +// License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. -// -// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// +// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License along // with VirtualFluids (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>. // @@ -33,488 +33,352 @@ #include "Block3D.h" -#include "Grid3DSystem.h" #include "Block3DConnector.h" +#include "Grid3DSystem.h" #include "LBMKernel.h" - int Block3D::counter = 0; ////////////////////////////////////////////////////////////////////////// -Block3D::Block3D(int x1, int x2, int x3, int level) - : x1(x1), x2(x2), x3(x3), - rank(0),part(0), - level(level), bundle(0) - +Block3D::Block3D(int x1, int x2, int x3, int level) : x1(x1), x2(x2), x3(x3), rank(0), part(0), level(level), bundle(0) + { - globalID = counter++; + globalID = counter++; } ////////////////////////////////////////////////////////////////////////// -Block3D::~Block3D() -= default; +Block3D::~Block3D() = default; ////////////////////////////////////////////////////////////////////////// -bool Block3D::operator==(const Block3D& src) const -{ - return (x1==src.x1 && x2==src.x2 && x3==src.x3); -} +bool Block3D::operator==(const Block3D &src) const { return (x1 == src.x1 && x2 == src.x2 && x3 == src.x3); } ////////////////////////////////////////////////////////////////////////// -bool Block3D::operator!=(const Block3D& src) const -{ - return !(*this==src); -} +bool Block3D::operator!=(const Block3D &src) const { return !(*this == src); } ////////////////////////////////////////////////////////////////////////// -int Block3D::getX1() const -{ - return this->x1; -} +int Block3D::getX1() const { return this->x1; } ////////////////////////////////////////////////////////////////////////// -int Block3D::getX2() const -{ - return this->x2; -} +int Block3D::getX2() const { return this->x2; } ////////////////////////////////////////////////////////////////////////// -int Block3D::getX3() const -{ - return this->x3; -} +int Block3D::getX3() const { return this->x3; } ////////////////////////////////////////////////////////////////////////// -void Block3D::setActive(bool active) -{ - this->active = active; -} +void Block3D::setActive(bool active) { this->active = active; } ////////////////////////////////////////////////////////////////////////// -bool Block3D::isActive() const -{ - return this->active; -} +bool Block3D::isActive() const { return this->active; } ////////////////////////////////////////////////////////////////////////// -bool Block3D::isNotActive() const -{ - return(!this->active); -} +bool Block3D::isNotActive() const { return (!this->active); } ////////////////////////////////////////////////////////////////////////// -void Block3D::setKernel(SPtr<LBMKernel> kernel) -{ - this->kernel = kernel; -} +void Block3D::setKernel(SPtr<LBMKernel> kernel) { this->kernel = kernel; } ////////////////////////////////////////////////////////////////////////// -SPtr<ILBMKernel> Block3D::getKernel() const -{ - return this->kernel; -} +SPtr<ILBMKernel> Block3D::getKernel() const { return this->kernel; } ////////////////////////////////////////////////////////////////////////// -void Block3D::deleteKernel() -{ - this->kernel = SPtr<LBMKernel>(); -} +void Block3D::deleteKernel() { this->kernel = SPtr<LBMKernel>(); } ////////////////////////////////////////////////////////////////////////// -int Block3D::getBundle() const -{ - return bundle; -} +int Block3D::getBundle() const { return bundle; } ////////////////////////////////////////////////////////////////////////// -void Block3D::setBundle(int bundle) -{ - this->bundle = bundle; -} +void Block3D::setBundle(int bundle) { this->bundle = bundle; } ////////////////////////////////////////////////////////////////////////// -void Block3D::setRank(int rank) -{ - this->rank = rank; -} +void Block3D::setRank(int rank) { this->rank = rank; } ////////////////////////////////////////////////////////////////////////// -int Block3D::getRank() const -{ - return this->rank; -} +int Block3D::getRank() const { return this->rank; } ////////////////////////////////////////////////////////////////////////// -void Block3D::setLocalRank(int rank) -{ - this->lrank = rank; -} +void Block3D::setLocalRank(int rank) { this->lrank = rank; } ////////////////////////////////////////////////////////////////////////// -int Block3D::getLocalRank() const -{ - return this->lrank; -} +int Block3D::getLocalRank() const { return this->lrank; } ////////////////////////////////////////////////////////////////////////// -int Block3D::getGlobalID() const -{ - return this->globalID; -} +int Block3D::getGlobalID() const { return this->globalID; } ////////////////////////////////////////////////////////////////////////// -void Block3D::setGlobalID(int id) -{ - this->globalID = id; -} +void Block3D::setGlobalID(int id) { this->globalID = id; } ////////////////////////////////////////////////////////////////////////// -int Block3D::getLocalID() const -{ - return this->localID; -} +int Block3D::getLocalID() const { return this->localID; } ////////////////////////////////////////////////////////////////////////// -void Block3D::setLocalID(int id) -{ - this->localID = id; -} +void Block3D::setLocalID(int id) { this->localID = id; } ////////////////////////////////////////////////////////////////////////// -int Block3D::getPart() const -{ - return this->part; -} +int Block3D::getPart() const { return this->part; } ////////////////////////////////////////////////////////////////////////// -void Block3D::setPart(int part) -{ - this->part = part; -} +void Block3D::setPart(int part) { this->part = part; } ////////////////////////////////////////////////////////////////////////// -int Block3D::getLevel() const -{ - return this->level; -} +int Block3D::getLevel() const { return this->level; } ////////////////////////////////////////////////////////////////////////// -void Block3D::setLevel(int level) -{ - this->level = level; -} +void Block3D::setLevel(int level) { this->level = level; } ////////////////////////////////////////////////////////////////////////// SPtr<Block3DConnector> Block3D::getConnector(int dir) const -{ - for(SPtr<Block3DConnector> c : connectors) - { - if( c ) - { - if(c->getSendDir() == dir) return c; - } - } - return SPtr<Block3DConnector>(); -} -////////////////////////////////////////////////////////////////////////// -void Block3D::setConnector(SPtr<Block3DConnector> connector) { - connectors.push_back(connector); + for (SPtr<Block3DConnector> c : connectors) { + if (c) { + if (c->getSendDir() == dir) + return c; + } + } + return SPtr<Block3DConnector>(); } ////////////////////////////////////////////////////////////////////////// -void Block3D::deleteConnectors() -{ - connectors.clear(); -} +void Block3D::setConnector(SPtr<Block3DConnector> connector) { connectors.push_back(connector); } +////////////////////////////////////////////////////////////////////////// +void Block3D::deleteConnectors() { connectors.clear(); } ////////////////////////////////////////////////////////////////////////// bool Block3D::hasConnectors() { - for(SPtr<Block3DConnector> c : connectors) - if( c ) return true; - - return false; + for (SPtr<Block3DConnector> c : connectors) + if (c) + return true; + + return false; } ////////////////////////////////////////////////////////////////////////// -void Block3D::pushBackSameLevelConnectors( std::vector<SPtr<Block3DConnector>>& localSameLevelConnectors - , std::vector<SPtr<Block3DConnector>>& remoteSameLevelConnectors ) +void Block3D::pushBackSameLevelConnectors(std::vector<SPtr<Block3DConnector>> &localSameLevelConnectors, + std::vector<SPtr<Block3DConnector>> &remoteSameLevelConnectors) { - for(int i=0; i<(int)connectors.size(); i++) - { - SPtr<Block3DConnector> connector = this->connectors[i]; - if( this->connectors[i] ) - { - if( connector->isLocalConnector() && !connector->isInterpolationConnectorCF() && !connector->isInterpolationConnectorFC() ) - localSameLevelConnectors.push_back(this->connectors[i]); - else - remoteSameLevelConnectors.push_back(this->connectors[i]); - } - } + for (int i = 0; i < (int)connectors.size(); i++) { + SPtr<Block3DConnector> connector = this->connectors[i]; + if (this->connectors[i]) { + if (connector->isLocalConnector() && !connector->isInterpolationConnectorCF() && + !connector->isInterpolationConnectorFC()) + localSameLevelConnectors.push_back(this->connectors[i]); + else + remoteSameLevelConnectors.push_back(this->connectors[i]); + } + } } ////////////////////////////////////////////////////////////////////////// -void Block3D::pushBackLocalSameLevelConnectors( std::vector<SPtr<Block3DConnector>>& localSameLevelConnectors ) +void Block3D::pushBackLocalSameLevelConnectors(std::vector<SPtr<Block3DConnector>> &localSameLevelConnectors) { - for(int i=0; i<(int)connectors.size(); i++) - { - SPtr<Block3DConnector> connector = this->connectors[i]; - if( this->connectors[i] ) - { - if( connector->isLocalConnector() && !connector->isInterpolationConnectorCF() && !connector->isInterpolationConnectorFC() ) - localSameLevelConnectors.push_back(this->connectors[i]); - } - } + for (int i = 0; i < (int)connectors.size(); i++) { + SPtr<Block3DConnector> connector = this->connectors[i]; + if (this->connectors[i]) { + if (connector->isLocalConnector() && !connector->isInterpolationConnectorCF() && + !connector->isInterpolationConnectorFC()) + localSameLevelConnectors.push_back(this->connectors[i]); + } + } } ////////////////////////////////////////////////////////////////////////// -void Block3D::pushBackLocalSameLevelConnectors( std::vector<SPtr<Block3DConnector>>& localSameLevelConnectors, const int& dir) +void Block3D::pushBackLocalSameLevelConnectors(std::vector<SPtr<Block3DConnector>> &localSameLevelConnectors, + const int &dir) { - SPtr<Block3DConnector> connector = this->connectors[dir]; - if( this->connectors[dir] ) - { - if( connector->isLocalConnector() && !connector->isInterpolationConnectorCF() && !connector->isInterpolationConnectorFC() ) - localSameLevelConnectors.push_back(this->connectors[dir]); - } + SPtr<Block3DConnector> connector = this->connectors[dir]; + if (this->connectors[dir]) { + if (connector->isLocalConnector() && !connector->isInterpolationConnectorCF() && + !connector->isInterpolationConnectorFC()) + localSameLevelConnectors.push_back(this->connectors[dir]); + } } ////////////////////////////////////////////////////////////////////////// -void Block3D::pushBackRemoteSameLevelConnectors( std::vector<SPtr<Block3DConnector>>& remoteSameLevelConnectors ) +void Block3D::pushBackRemoteSameLevelConnectors(std::vector<SPtr<Block3DConnector>> &remoteSameLevelConnectors) { - for(int i=0; i<(int)connectors.size(); i++) - { - SPtr<Block3DConnector> connector = this->connectors[i]; - if( this->connectors[i] ) - { - if( connector->isRemoteConnector() && !connector->isInterpolationConnectorCF() && !connector->isInterpolationConnectorFC() ) - remoteSameLevelConnectors.push_back(this->connectors[i]); - } - } + for (int i = 0; i < (int)connectors.size(); i++) { + SPtr<Block3DConnector> connector = this->connectors[i]; + if (this->connectors[i]) { + if (connector->isRemoteConnector() && !connector->isInterpolationConnectorCF() && + !connector->isInterpolationConnectorFC()) + remoteSameLevelConnectors.push_back(this->connectors[i]); + } + } } ////////////////////////////////////////////////////////////////////////// -void Block3D::pushBackRemoteSameLevelConnectors( std::vector<SPtr<Block3DConnector>>& remoteSameLevelConnectors, const int& dir ) +void Block3D::pushBackRemoteSameLevelConnectors(std::vector<SPtr<Block3DConnector>> &remoteSameLevelConnectors, + const int &dir) { - SPtr<Block3DConnector> connector = this->connectors[dir]; - if( this->connectors[dir] ) - { - if( connector->isRemoteConnector() && !connector->isInterpolationConnectorCF() && !connector->isInterpolationConnectorFC() ) - remoteSameLevelConnectors.push_back(this->connectors[dir]); - } + SPtr<Block3DConnector> connector = this->connectors[dir]; + if (this->connectors[dir]) { + if (connector->isRemoteConnector() && !connector->isInterpolationConnectorCF() && + !connector->isInterpolationConnectorFC()) + remoteSameLevelConnectors.push_back(this->connectors[dir]); + } } ////////////////////////////////////////////////////////////////////////// -void Block3D::pushBackLocalInterpolationConnectorsCF( std::vector<SPtr<Block3DConnector>>& localInterpolationConnectors ) +void Block3D::pushBackLocalInterpolationConnectorsCF(std::vector<SPtr<Block3DConnector>> &localInterpolationConnectors) { - for(int i=0; i<(int)connectors.size(); i++) - { - SPtr<Block3DConnector> connector = this->connectors[i]; - if( this->connectors[i] ) - { - if( connector->isLocalConnector() && connector->isInterpolationConnectorCF() ) - localInterpolationConnectors.push_back(this->connectors[i]); - } - } + for (int i = 0; i < (int)connectors.size(); i++) { + SPtr<Block3DConnector> connector = this->connectors[i]; + if (this->connectors[i]) { + if (connector->isLocalConnector() && connector->isInterpolationConnectorCF()) + localInterpolationConnectors.push_back(this->connectors[i]); + } + } } ////////////////////////////////////////////////////////////////////////// -void Block3D::pushBackRemoteInterpolationConnectorsCF( std::vector<SPtr<Block3DConnector>>& remoteInterpolationConnectors ) +void Block3D::pushBackRemoteInterpolationConnectorsCF( + std::vector<SPtr<Block3DConnector>> &remoteInterpolationConnectors) { - for(int i=0; i<(int)connectors.size(); i++) - { - SPtr<Block3DConnector> connector = this->connectors[i]; - if( this->connectors[i] ) - { - if( connector->isRemoteConnector() && connector->isInterpolationConnectorCF() ) - remoteInterpolationConnectors.push_back(this->connectors[i]); - } - } + for (int i = 0; i < (int)connectors.size(); i++) { + SPtr<Block3DConnector> connector = this->connectors[i]; + if (this->connectors[i]) { + if (connector->isRemoteConnector() && connector->isInterpolationConnectorCF()) + remoteInterpolationConnectors.push_back(this->connectors[i]); + } + } } ////////////////////////////////////////////////////////////////////////// -void Block3D::pushBackLocalInterpolationConnectorsFC( std::vector<SPtr<Block3DConnector>>& localInterpolationConnectors ) +void Block3D::pushBackLocalInterpolationConnectorsFC(std::vector<SPtr<Block3DConnector>> &localInterpolationConnectors) { - for(int i=0; i<(int)connectors.size(); i++) - { - SPtr<Block3DConnector> connector = this->connectors[i]; - if( this->connectors[i] ) - { - if( connector->isLocalConnector() && connector->isInterpolationConnectorFC() ) - localInterpolationConnectors.push_back(this->connectors[i]); - } - } + for (int i = 0; i < (int)connectors.size(); i++) { + SPtr<Block3DConnector> connector = this->connectors[i]; + if (this->connectors[i]) { + if (connector->isLocalConnector() && connector->isInterpolationConnectorFC()) + localInterpolationConnectors.push_back(this->connectors[i]); + } + } } ////////////////////////////////////////////////////////////////////////// -void Block3D::pushBackRemoteInterpolationConnectorsFC( std::vector<SPtr<Block3DConnector>>& remoteInterpolationConnectors ) +void Block3D::pushBackRemoteInterpolationConnectorsFC( + std::vector<SPtr<Block3DConnector>> &remoteInterpolationConnectors) { - for(int i=0; i<(int)connectors.size(); i++) - { - SPtr<Block3DConnector> connector = this->connectors[i]; - if( this->connectors[i] ) - { - if( connector->isRemoteConnector() && connector->isInterpolationConnectorFC() ) - remoteInterpolationConnectors.push_back(this->connectors[i]); - } - } + for (int i = 0; i < (int)connectors.size(); i++) { + SPtr<Block3DConnector> connector = this->connectors[i]; + if (this->connectors[i]) { + if (connector->isRemoteConnector() && connector->isInterpolationConnectorFC()) + remoteInterpolationConnectors.push_back(this->connectors[i]); + } + } } ////////////////////////////////////////////////////////////////////////// int Block3D::getNumberOfLocalConnectors() { - int count = 0; - for(int i=0; i<(int)connectors.size(); i++) - { - SPtr<Block3DConnector> connector = this->connectors[i]; - if( this->connectors[i] ) - { - if( connector->isLocalConnector() ) count++; - } - } - return count; + int count = 0; + for (int i = 0; i < (int)connectors.size(); i++) { + SPtr<Block3DConnector> connector = this->connectors[i]; + if (this->connectors[i]) { + if (connector->isLocalConnector()) + count++; + } + } + return count; } ////////////////////////////////////////////////////////////////////////// int Block3D::getNumberOfRemoteConnectors() { - int count = 0; - for(int i=0; i<(int)connectors.size(); i++) - { - SPtr<Block3DConnector> connector = this->connectors[i]; - if( this->connectors[i] ) - { - if( connector->isRemoteConnector() ) count++; - } - } - return count; + int count = 0; + for (int i = 0; i < (int)connectors.size(); i++) { + SPtr<Block3DConnector> connector = this->connectors[i]; + if (this->connectors[i]) { + if (connector->isRemoteConnector()) + count++; + } + } + return count; } ////////////////////////////////////////////////////////////////////////// int Block3D::getNumberOfLocalConnectorsForSurfaces() { - int count = 0; - - if(connectors.size() < 6) - return count; + int count = 0; + + if (connectors.size() < 6) + return count; - for(int dir=0; dir<=5; dir++) //Hard coding. It works if you have 0...5 for E, N ... B - { - SPtr<Block3DConnector> connector = this->connectors[dir]; - if( this->connectors[dir] ) - { - if( connector->isLocalConnector() ) count++; - } - } - return count; + for (int dir = 0; dir <= 5; dir++) // Hard coding. It works if you have 0...5 for E, N ... B + { + SPtr<Block3DConnector> connector = this->connectors[dir]; + if (this->connectors[dir]) { + if (connector->isLocalConnector()) + count++; + } + } + return count; } ////////////////////////////////////////////////////////////////////////// int Block3D::getNumberOfRemoteConnectorsForSurfaces() { - int count = 0; - for(int dir=0; dir<=5; dir++) //Hard coding. It works if you have 0...5 for E, N ... B - { - SPtr<Block3DConnector> connector = this->connectors[dir]; - if( this->connectors[dir] ) - { - if( connector->isRemoteConnector() ) count++; - } - } - return count; -} -void Block3D::setCollectionOfInterpolationFlagCF(int flags) -{ - interpolationFlagCF = flags; + int count = 0; + for (int dir = 0; dir <= 5; dir++) // Hard coding. It works if you have 0...5 for E, N ... B + { + SPtr<Block3DConnector> connector = this->connectors[dir]; + if (this->connectors[dir]) { + if (connector->isRemoteConnector()) + count++; + } + } + return count; } +void Block3D::setCollectionOfInterpolationFlagCF(int flags) { interpolationFlagCF = flags; } ////////////////////////////////////////////////////////////////////////// -void Block3D::setInterpolationFlagCF(int dir) -{ - UbSystem::setBit(interpolationFlagCF, 1<<dir); -} -////////////////////////////////////////////////////////////////////////// -int Block3D::getCollectionOfInterpolationFlagCF() -{ - return interpolationFlagCF; -} +void Block3D::setInterpolationFlagCF(int dir) { UbSystem::setBit(interpolationFlagCF, 1 << dir); } ////////////////////////////////////////////////////////////////////////// -bool Block3D::hasInterpolationFlagCF(int dir) -{ - return UbSystem::bitCheck( interpolationFlagCF, 1<<dir ); -} -void Block3D::setCollectionOfInterpolationFlagFC(int flags) -{ - interpolationFlagFC = flags; -} +int Block3D::getCollectionOfInterpolationFlagCF() { return interpolationFlagCF; } ////////////////////////////////////////////////////////////////////////// -void Block3D::setInterpolationFlagFC(int dir) -{ - UbSystem::setBit(interpolationFlagFC, 1<<dir); -} +bool Block3D::hasInterpolationFlagCF(int dir) { return UbSystem::bitCheck(interpolationFlagCF, 1 << dir); } +void Block3D::setCollectionOfInterpolationFlagFC(int flags) { interpolationFlagFC = flags; } ////////////////////////////////////////////////////////////////////////// -int Block3D::getCollectionOfInterpolationFlagFC() -{ - return interpolationFlagFC; -} +void Block3D::setInterpolationFlagFC(int dir) { UbSystem::setBit(interpolationFlagFC, 1 << dir); } ////////////////////////////////////////////////////////////////////////// -bool Block3D::hasInterpolationFlagFC(int dir) -{ - return UbSystem::bitCheck( interpolationFlagFC, 1<<dir ); -} +int Block3D::getCollectionOfInterpolationFlagFC() { return interpolationFlagFC; } ////////////////////////////////////////////////////////////////////////// -bool Block3D::hasInterpolationFlag() -{ - return(interpolationFlagCF!=0 || interpolationFlagFC!=0); -} +bool Block3D::hasInterpolationFlagFC(int dir) { return UbSystem::bitCheck(interpolationFlagFC, 1 << dir); } ////////////////////////////////////////////////////////////////////////// -bool Block3D::hasInterpolationFlag(int direction) -{ - return(hasInterpolationFlagCF(direction) || hasInterpolationFlagFC(direction)); -} +bool Block3D::hasInterpolationFlag() { return (interpolationFlagCF != 0 || interpolationFlagFC != 0); } ////////////////////////////////////////////////////////////////////////// -bool Block3D::hasInterpolationFlagCF() +bool Block3D::hasInterpolationFlag(int direction) { - return(interpolationFlagCF!=0); + return (hasInterpolationFlagCF(direction) || hasInterpolationFlagFC(direction)); } ////////////////////////////////////////////////////////////////////////// -bool Block3D::hasInterpolationFlagFC() -{ - return(interpolationFlagFC!=0); -} +bool Block3D::hasInterpolationFlagCF() { return (interpolationFlagCF != 0); } +////////////////////////////////////////////////////////////////////////// +bool Block3D::hasInterpolationFlagFC() { return (interpolationFlagFC != 0); } ////////////////////////////////////////////////////////////////////////// void Block3D::deleteInterpolationFlag() { - interpolationFlagFC = 0; - interpolationFlagCF = 0; + interpolationFlagFC = 0; + interpolationFlagCF = 0; } ////////////////////////////////////////////////////////////////////////// double Block3D::getWorkLoad() { - double l = kernel->getCalculationTime(); - l *= static_cast<double>(1<<level); - return l; + double l = kernel->getCalculationTime(); + l *= static_cast<double>(1 << level); + return l; } ////////////////////////////////////////////////////////////////////////// -std::string Block3D::toString() +std::string Block3D::toString() { - std::stringstream ss; - ss<<"Block3D[(x1,x2,x3,level),"; - ss<<" ("<<this->x1<<", "<<this->x2<<", "<<this->x3<<", "<<this->level<<"), id=" << globalID; - ss<< ", active="<<this->active<< ", bundle="<<this->bundle<< ", rank="<<this->rank<<"]"; - ss<<" connectors:"; - for(std::size_t i=0; i<connectors.size(); i++) - if( connectors[i] ) - { - if(connectors[i]->isLocalConnector()) - ss <<"l."<< Grid3DSystem::getDirectionString(connectors[i]->getSendDir()) << ", "; - if(connectors[i]->isRemoteConnector()) - ss <<"r."<< Grid3DSystem::getDirectionString(connectors[i]->getSendDir()) << ", "; - if(connectors[i]->isInterpolationConnectorCF()) - ss <<"cf."<< Grid3DSystem::getDirectionString(connectors[i]->getSendDir()) << ", "; - if(connectors[i]->isInterpolationConnectorFC()) - ss <<"fc."<< Grid3DSystem::getDirectionString(connectors[i]->getSendDir()) << ", "; - } - return ss.str(); + std::stringstream ss; + ss << "Block3D[(x1,x2,x3,level),"; + ss << " (" << this->x1 << ", " << this->x2 << ", " << this->x3 << ", " << this->level << "), id=" << globalID; + ss << ", active=" << this->active << ", bundle=" << this->bundle << ", rank=" << this->rank << "]"; + ss << " connectors:"; + for (std::size_t i = 0; i < connectors.size(); i++) + if (connectors[i]) { + if (connectors[i]->isLocalConnector()) + ss << "l." << Grid3DSystem::getDirectionString(connectors[i]->getSendDir()) << ", "; + if (connectors[i]->isRemoteConnector()) + ss << "r." << Grid3DSystem::getDirectionString(connectors[i]->getSendDir()) << ", "; + if (connectors[i]->isInterpolationConnectorCF()) + ss << "cf." << Grid3DSystem::getDirectionString(connectors[i]->getSendDir()) << ", "; + if (connectors[i]->isInterpolationConnectorFC()) + ss << "fc." << Grid3DSystem::getDirectionString(connectors[i]->getSendDir()) << ", "; + } + return ss.str(); } ////////////////////////////////////////////////////////////////////////// -void Block3D::setWeight( int rank, int weight ) +void Block3D::setWeight(int rank, int weight) { - std::map<int, int>::iterator it; - if((it = this->weight.find(rank)) != this->weight.end()) - it->second = weight; - else - this->weight.insert(std::make_pair(rank, weight)); + std::map<int, int>::iterator it; + if ((it = this->weight.find(rank)) != this->weight.end()) + it->second = weight; + else + this->weight.insert(std::make_pair(rank, weight)); } ////////////////////////////////////////////////////////////////////////// -int Block3D::getWeight( int rank ) +int Block3D::getWeight(int rank) { - std::map<int, int>::iterator it; - if((it = this->weight.find(rank)) != this->weight.end()) - return it->second; - else - return 0; + std::map<int, int>::iterator it; + if ((it = this->weight.find(rank)) != this->weight.end()) + return it->second; + else + return 0; } ////////////////////////////////////////////////////////////////////////// -void Block3D::addWeight( int rank, int weight ) +void Block3D::addWeight(int rank, int weight) { - int weight_old = getWeight(rank); - weight += weight_old; - setWeight(rank, weight); + int weight_old = getWeight(rank); + weight += weight_old; + setWeight(rank, weight); } ////////////////////////////////////////////////////////////////////////// -void Block3D::addWeightForAll( int weight ) +void Block3D::addWeightForAll(int weight) { - using wMap = std::map<int, int>; - for (wMap::value_type &w : this->weight) - { - w.second += weight; - } + using wMap = std::map<int, int>; + for (wMap::value_type &w : this->weight) { + w.second += weight; + } } ////////////////////////////////////////////////////////////////////////// -void Block3D::clearWeight() -{ - this->weight.clear(); -} +void Block3D::clearWeight() { this->weight.clear(); } ////////////////////////////////////////////////////////////////////////// -int Block3D::getWeightSize() -{ - return static_cast<int>(this->weight.size()); -} +int Block3D::getWeightSize() { return static_cast<int>(this->weight.size()); } diff --git a/src/cpu/VirtualFluidsCore/Grid/Block3D.h b/src/cpu/VirtualFluidsCore/Grid/Block3D.h index 0912f82ace8aed11bb04be55d08e0c579b1c63df..b2279b069e6ee322023d30419f8eed5c587f95e8 100644 --- a/src/cpu/VirtualFluidsCore/Grid/Block3D.h +++ b/src/cpu/VirtualFluidsCore/Grid/Block3D.h @@ -1,28 +1,28 @@ //======================================================================================= -// ____ ____ __ ______ __________ __ __ __ __ -// \ \ | | | | | _ \ |___ ___| | | | | / \ | | -// \ \ | | | | | |_) | | | | | | | / \ | | -// \ \ | | | | | _ / | | | | | | / /\ \ | | -// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ -// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| -// \ \ | | ________________________________________________________________ -// \ \ | | | ______________________________________________________________| -// \ \| | | | __ __ __ __ ______ _______ -// \ | | |_____ | | | | | | | | | _ \ / _____) -// \ | | _____| | | | | | | | | | | \ \ \_______ +// ____ ____ __ ______ __________ __ __ __ __ +// \ \ | | | | | _ \ |___ ___| | | | | / \ | | +// \ \ | | | | | |_) | | | | | | | / \ | | +// \ \ | | | | | _ / | | | | | | / /\ \ | | +// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ +// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| +// \ \ | | ________________________________________________________________ +// \ \ | | | ______________________________________________________________| +// \ \| | | | __ __ __ __ ______ _______ +// \ | | |_____ | | | | | | | | | _ \ / _____) +// \ | | _____| | | | | | | | | | | \ \ \_______ // \ | | | | |_____ | \_/ | | | | |_/ / _____ | -// \ _____| |__| |________| \_______/ |__| |______/ (_______/ +// \ _____| |__| |________| \_______/ |__| |______/ (_______/ // -// This file is part of VirtualFluids. VirtualFluids is free software: you can +// This file is part of VirtualFluids. VirtualFluids is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of +// License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. -// -// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// +// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License along // with VirtualFluids (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>. // @@ -35,9 +35,9 @@ #define BLOCK3D_H #include <PointerDefinitions.h> -#include <vector> #include <map> #include <string> +#include <vector> class Block3DConnector; class LBMKernel; @@ -47,121 +47,122 @@ class ILBMKernel; class Block3D { public: - Block3D() = default; - Block3D(int x1, int x2, int x3, int level); - virtual ~Block3D(); - bool operator==(const Block3D& src) const; - bool operator!=(const Block3D& src) const; - - int getX1() const; - int getX2() const; - int getX3() const; - - void setActive(bool active); - bool isActive() const; - bool isNotActive() const; - - void setKernel(SPtr<LBMKernel> kernel); - SPtr<ILBMKernel> getKernel() const; - void deleteKernel(); - - void setBundle(int bundle); - int getBundle() const; - - void setRank(int rank); - int getRank() const; - - void setLocalRank(int rank); - int getLocalRank() const; - - int getGlobalID() const; - void setGlobalID(int id); - - int getLocalID() const; - void setLocalID(int id); - - int getPart() const; - void setPart(int part); - - int getLevel() const; - void setLevel(int level); - - //Connector-Section - void setConnector(SPtr<Block3DConnector> connector); - SPtr<Block3DConnector> getConnector(int dir) const; - bool hasConnectors(); - void deleteConnectors(); - void pushBackSameLevelConnectors( std::vector<SPtr<Block3DConnector> >& localSameLevelConnectors - , std::vector<SPtr<Block3DConnector> >& remoteSameLevelConnectors ); - void pushBackLocalSameLevelConnectors( std::vector<SPtr<Block3DConnector> >& localSameLevelConnectors ); - void pushBackRemoteSameLevelConnectors( std::vector<SPtr<Block3DConnector> >& remoteSameLevelConnectors ); - void pushBackLocalInterpolationConnectorsCF( std::vector<SPtr<Block3DConnector> >& localInterpolationConnectors ); - void pushBackRemoteInterpolationConnectorsCF( std::vector<SPtr<Block3DConnector> >& remoteInterpolationConnectors ); - void pushBackLocalInterpolationConnectorsFC( std::vector<SPtr<Block3DConnector> >& localInterpolationConnectors ); - void pushBackRemoteInterpolationConnectorsFC( std::vector<SPtr<Block3DConnector> >& remoteInterpolationConnectors ); - void pushBackLocalSameLevelConnectors( std::vector<SPtr<Block3DConnector> >& localSameLevelConnectors, const int& dir); - void pushBackRemoteSameLevelConnectors( std::vector<SPtr<Block3DConnector> >& remoteSameLevelConnectors, const int& dir ); - int getNumberOfLocalConnectors(); - int getNumberOfRemoteConnectors(); - int getNumberOfLocalConnectorsForSurfaces(); - int getNumberOfRemoteConnectorsForSurfaces(); - - void setWeight(int rank, int weight); - int getWeight(int rank); - void addWeightForAll(int weight); - void addWeight(int rank, int weight); - void clearWeight(); - int getWeightSize(); - - //interpolation - bool hasInterpolationFlag(); - bool hasInterpolationFlag(int dir); - void deleteInterpolationFlag(); - - int getCollectionOfInterpolationFlagCF(); - void setCollectionOfInterpolationFlagCF(int flags); - - void setInterpolationFlagCF(int dir); - bool hasInterpolationFlagCF(int dir); - bool hasInterpolationFlagCF(); - - int getCollectionOfInterpolationFlagFC(); - void setCollectionOfInterpolationFlagFC(int flags); - - void setInterpolationFlagFC(int dir); - bool hasInterpolationFlagFC(int dir); - bool hasInterpolationFlagFC(); - - double getWorkLoad(); - - std::string toString() ; - - static int getMaxGlobalID() { return counter; } - static void setMaxGlobalID(int /*c*/) { counter = 0; } // FIXME ??? + Block3D() = default; + Block3D(int x1, int x2, int x3, int level); + virtual ~Block3D(); + bool operator==(const Block3D &src) const; + bool operator!=(const Block3D &src) const; + + int getX1() const; + int getX2() const; + int getX3() const; + + void setActive(bool active); + bool isActive() const; + bool isNotActive() const; + + void setKernel(SPtr<LBMKernel> kernel); + SPtr<ILBMKernel> getKernel() const; + void deleteKernel(); + + void setBundle(int bundle); + int getBundle() const; + + void setRank(int rank); + int getRank() const; + + void setLocalRank(int rank); + int getLocalRank() const; + + int getGlobalID() const; + void setGlobalID(int id); + + int getLocalID() const; + void setLocalID(int id); + + int getPart() const; + void setPart(int part); + + int getLevel() const; + void setLevel(int level); + + // Connector-Section + void setConnector(SPtr<Block3DConnector> connector); + SPtr<Block3DConnector> getConnector(int dir) const; + bool hasConnectors(); + void deleteConnectors(); + void pushBackSameLevelConnectors(std::vector<SPtr<Block3DConnector>> &localSameLevelConnectors, + std::vector<SPtr<Block3DConnector>> &remoteSameLevelConnectors); + void pushBackLocalSameLevelConnectors(std::vector<SPtr<Block3DConnector>> &localSameLevelConnectors); + void pushBackRemoteSameLevelConnectors(std::vector<SPtr<Block3DConnector>> &remoteSameLevelConnectors); + void pushBackLocalInterpolationConnectorsCF(std::vector<SPtr<Block3DConnector>> &localInterpolationConnectors); + void pushBackRemoteInterpolationConnectorsCF(std::vector<SPtr<Block3DConnector>> &remoteInterpolationConnectors); + void pushBackLocalInterpolationConnectorsFC(std::vector<SPtr<Block3DConnector>> &localInterpolationConnectors); + void pushBackRemoteInterpolationConnectorsFC(std::vector<SPtr<Block3DConnector>> &remoteInterpolationConnectors); + void pushBackLocalSameLevelConnectors(std::vector<SPtr<Block3DConnector>> &localSameLevelConnectors, + const int &dir); + void pushBackRemoteSameLevelConnectors(std::vector<SPtr<Block3DConnector>> &remoteSameLevelConnectors, + const int &dir); + int getNumberOfLocalConnectors(); + int getNumberOfRemoteConnectors(); + int getNumberOfLocalConnectorsForSurfaces(); + int getNumberOfRemoteConnectorsForSurfaces(); + + void setWeight(int rank, int weight); + int getWeight(int rank); + void addWeightForAll(int weight); + void addWeight(int rank, int weight); + void clearWeight(); + int getWeightSize(); + + // interpolation + bool hasInterpolationFlag(); + bool hasInterpolationFlag(int dir); + void deleteInterpolationFlag(); + + int getCollectionOfInterpolationFlagCF(); + void setCollectionOfInterpolationFlagCF(int flags); + + void setInterpolationFlagCF(int dir); + bool hasInterpolationFlagCF(int dir); + bool hasInterpolationFlagCF(); + + int getCollectionOfInterpolationFlagFC(); + void setCollectionOfInterpolationFlagFC(int flags); + + void setInterpolationFlagFC(int dir); + bool hasInterpolationFlagFC(int dir); + bool hasInterpolationFlagFC(); + + double getWorkLoad(); + + std::string toString(); + + static int getMaxGlobalID() { return counter; } + static void setMaxGlobalID(int /*c*/) { counter = 0; } // FIXME ??? private: - int x1{0}; - int x2{0}; - int x3{0}; - - bool active{true}; - - int interpolationFlagCF{0}; - int interpolationFlagFC{0}; - - SPtr<LBMKernel> kernel; - std::vector<SPtr<Block3DConnector> > connectors; - std::map<int, int> weight; - - int bundle{-1}; - int rank{-1}; - int lrank{-1}; - int globalID{-1}; - int localID{-1}; - int part{-1}; - int level{-1}; - static int counter; - + int x1{ 0 }; + int x2{ 0 }; + int x3{ 0 }; + + bool active{ true }; + + int interpolationFlagCF{ 0 }; + int interpolationFlagFC{ 0 }; + + SPtr<LBMKernel> kernel; + std::vector<SPtr<Block3DConnector>> connectors; + std::map<int, int> weight; + + int bundle{ -1 }; + int rank{ -1 }; + int lrank{ -1 }; + int globalID{ -1 }; + int localID{ -1 }; + int part{ -1 }; + int level{ -1 }; + static int counter; }; -#endif //BLOCK3D_H +#endif // BLOCK3D_H diff --git a/src/cpu/VirtualFluidsCore/Grid/Calculator.cpp b/src/cpu/VirtualFluidsCore/Grid/Calculator.cpp index 5fc3f8d42117876076e7c5e0185f3815346c6ab6..fbeb2de979bb31dfb87441b5cfcfdf3393f0043c 100644 --- a/src/cpu/VirtualFluidsCore/Grid/Calculator.cpp +++ b/src/cpu/VirtualFluidsCore/Grid/Calculator.cpp @@ -1,28 +1,28 @@ //======================================================================================= -// ____ ____ __ ______ __________ __ __ __ __ -// \ \ | | | | | _ \ |___ ___| | | | | / \ | | -// \ \ | | | | | |_) | | | | | | | / \ | | -// \ \ | | | | | _ / | | | | | | / /\ \ | | -// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ -// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| -// \ \ | | ________________________________________________________________ -// \ \ | | | ______________________________________________________________| -// \ \| | | | __ __ __ __ ______ _______ -// \ | | |_____ | | | | | | | | | _ \ / _____) -// \ | | _____| | | | | | | | | | | \ \ \_______ +// ____ ____ __ ______ __________ __ __ __ __ +// \ \ | | | | | _ \ |___ ___| | | | | / \ | | +// \ \ | | | | | |_) | | | | | | | / \ | | +// \ \ | | | | | _ / | | | | | | / /\ \ | | +// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ +// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| +// \ \ | | ________________________________________________________________ +// \ \ | | | ______________________________________________________________| +// \ \| | | | __ __ __ __ ______ _______ +// \ | | |_____ | | | | | | | | | _ \ / _____) +// \ | | _____| | | | | | | | | | | \ \ \_______ // \ | | | | |_____ | \_/ | | | | |_/ / _____ | -// \ _____| |__| |________| \_______/ |__| |______/ (_______/ +// \ _____| |__| |________| \_______/ |__| |______/ (_______/ // -// This file is part of VirtualFluids. VirtualFluids is free software: you can +// This file is part of VirtualFluids. VirtualFluids is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of +// License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. -// -// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// +// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License along // with VirtualFluids (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>. // @@ -33,214 +33,199 @@ #include "Calculator.h" -#include "Grid3D.h" -#include "Block3DConnector.h" #include "Block3D.h" -#include "UbScheduler.h" +#include "Block3DConnector.h" #include "CoProcessor.h" +#include "Grid3D.h" +#include "UbScheduler.h" #include <basics/utilities/UbException.h> -Calculator::Calculator(SPtr<Grid3D> grid, SPtr<UbScheduler> additionalGhostLayerUpdateScheduler, int numberOfTimeSteps) : - grid(grid), - additionalGhostLayerUpdateScheduler(additionalGhostLayerUpdateScheduler), - numberOfTimeSteps(numberOfTimeSteps) +Calculator::Calculator(SPtr<Grid3D> grid, SPtr<UbScheduler> additionalGhostLayerUpdateScheduler, int numberOfTimeSteps) + : grid(grid), additionalGhostLayerUpdateScheduler(additionalGhostLayerUpdateScheduler), + numberOfTimeSteps(numberOfTimeSteps) { - this->grid = grid; - startTimeStep = int(grid->getTimeStep())+1; - minLevel = grid->getCoarsestInitializedLevel(); - maxLevel = grid->getFinestInitializedLevel(); - if (maxLevel > 0) - refinement = true; - else - refinement = false; - blocks.resize(maxLevel+1); - localConns.resize(maxLevel+1); - remoteConns.resize(maxLevel+1); - localInterConns.resize(maxLevel); - remoteInterConns.resize(maxLevel); - - int gridRank = grid->getRank(); - - for (int level = minLevel; level <= maxLevel; level++) - { - std::vector<SPtr<Block3D>> blockVector; - grid->getBlocks(level, gridRank, true, blockVector); - for (const auto& block : blockVector) - if (block) - blocks[block->getLevel()].push_back(block); - } - - initLocalConnectors(); - initRemoteConnectors(); + this->grid = grid; + startTimeStep = int(grid->getTimeStep()) + 1; + minLevel = grid->getCoarsestInitializedLevel(); + maxLevel = grid->getFinestInitializedLevel(); + if (maxLevel > 0) + refinement = true; + else + refinement = false; + blocks.resize(maxLevel + 1); + localConns.resize(maxLevel + 1); + remoteConns.resize(maxLevel + 1); + localInterConns.resize(maxLevel); + remoteInterConns.resize(maxLevel); + + int gridRank = grid->getRank(); + + for (int level = minLevel; level <= maxLevel; level++) { + std::vector<SPtr<Block3D>> blockVector; + grid->getBlocks(level, gridRank, true, blockVector); + for (const auto &block : blockVector) + if (block) + blocks[block->getLevel()].push_back(block); + } + + initLocalConnectors(); + initRemoteConnectors(); } ////////////////////////////////////////////////////////////////////////// -Calculator::~Calculator() -= default; +Calculator::~Calculator() = default; ////////////////////////////////////////////////////////////////////////// -void Calculator::addCoProcessor(SPtr<CoProcessor> coProcessor) -{ - coProcessors.push_back(coProcessor); -} +void Calculator::addCoProcessor(SPtr<CoProcessor> coProcessor) { coProcessors.push_back(coProcessor); } ////////////////////////////////////////////////////////////////////////// void Calculator::coProcess(double step) { - for (SPtr<CoProcessor> cp : coProcessors) - { - cp->process(step); - } + for (SPtr<CoProcessor> cp : coProcessors) { + cp->process(step); + } } ////////////////////////////////////////////////////////////////////////// void Calculator::initLocalConnectors() { - UBLOG(logDEBUG1, "Calculator::initLocalConnectors() - start"); - - for (int l = minLevel; l <= maxLevel; l++) - { - for(SPtr<Block3D> block : blocks[l]) - { - block->pushBackLocalSameLevelConnectors(localConns[l]); - - if (l != maxLevel) - block->pushBackLocalInterpolationConnectorsCF(localInterConns[l]); - } - if (l != maxLevel) - { - for(SPtr<Block3D> block : blocks[l+1]) - { - block->pushBackLocalInterpolationConnectorsFC(localInterConns[l]); - } - } - UBLOG(logDEBUG5, "Calculator::initConnectors()-initConnectors(localConns["<<l<<"])"); - initConnectors(localConns[l]); - - if (l != maxLevel) - { - UBLOG(logDEBUG5, "Calculator::initConnectors()-initConnectors(localInterConns["<<l<<"])"); - initConnectors(localInterConns[l]); - } - } - - UBLOG(logDEBUG1, "Calculator::initLocalConnectors() - end"); + UBLOG(logDEBUG1, "Calculator::initLocalConnectors() - start"); + + for (int l = minLevel; l <= maxLevel; l++) { + for (SPtr<Block3D> block : blocks[l]) { + block->pushBackLocalSameLevelConnectors(localConns[l]); + + if (l != maxLevel) + block->pushBackLocalInterpolationConnectorsCF(localInterConns[l]); + } + if (l != maxLevel) { + for (SPtr<Block3D> block : blocks[l + 1]) { + block->pushBackLocalInterpolationConnectorsFC(localInterConns[l]); + } + } + UBLOG(logDEBUG5, "Calculator::initConnectors()-initConnectors(localConns[" << l << "])"); + initConnectors(localConns[l]); + + if (l != maxLevel) { + UBLOG(logDEBUG5, "Calculator::initConnectors()-initConnectors(localInterConns[" << l << "])"); + initConnectors(localInterConns[l]); + } + } + + UBLOG(logDEBUG1, "Calculator::initLocalConnectors() - end"); } ////////////////////////////////////////////////////////////////////////// void Calculator::initRemoteConnectors() { - std::vector< std::vector< SPtr<Block3DConnector> > > remoteInterConnsCF; - std::vector< std::vector< SPtr<Block3DConnector> > > remoteInterConnsFC; - remoteInterConnsCF.resize(maxLevel+1); - remoteInterConnsFC.resize(maxLevel+1); - - for(int l = minLevel; l<=maxLevel;l++) - { - std::vector<SPtr<Block3D>> blockVector; - //grid->getBlocks(level, gridRank, true, blockVector); - grid->getBlocks(l, blockVector); - for(SPtr<Block3D> block : blockVector) - { - int block_level = block->getLevel(); - block->pushBackRemoteSameLevelConnectors(remoteConns[block_level]); - - block->pushBackRemoteInterpolationConnectorsCF(remoteInterConnsCF[block_level]); - block->pushBackRemoteInterpolationConnectorsFC(remoteInterConnsFC[block_level]); - } - } - - for (int l = minLevel; l <= maxLevel; l++) - { - UBLOG(logDEBUG5, "Calculator::initRemoteConnectors()-initConnectors(remoteConns["<<l<<"])"); - initConnectors(remoteConns[l]); - if (l != maxLevel) - { - for(size_t i = 0; i < remoteInterConnsCF[l].size(); i++) - remoteInterConns[l].push_back(remoteInterConnsCF[l][i]); - for(size_t i = 0; i < remoteInterConnsFC[l+1].size(); i++) - remoteInterConns[l].push_back(remoteInterConnsFC[l+1][i]); - } - } - ////////////////////////////////////////////////////////////////////////// - //UBLOG(logDEBUG5, "Calculator::initConnectors() - connectoren initialisieren - start"); - for (int l = minLevel; l <= maxLevel; l++) - { - if (l != maxLevel) - { - UBLOG(logDEBUG5, "Calculator::initRemoteConnectors()-initConnectors(remoteInterConns["<<l<<"])"); - for(SPtr<Block3DConnector> c : remoteInterConns[l] ) c->init(); - } - } - //UBLOG(logDEBUG5, "Calculator::initConnectors() - connectoren initialisieren - end"); - ////////////////////////////////////////////////////////////////////////// - //sendTransmitterDataSize - //UBLOG(logDEBUG5, "Calculator::initConnectors() - sendTransmitterDataSize - start"); - for (int l = minLevel; l <= maxLevel; l++) - { - if (l != maxLevel) - { - UBLOG(logDEBUG5, "Calculator::initRemoteConnectors()-sendTransmitterDataSize(remoteInterConns["<<l<<"])"); - for(SPtr<Block3DConnector> c : remoteInterConns[l] ) c->sendTransmitterDataSize(); - } - } - //UBLOG(logDEBUG5, "Calculator::initConnectors() - sendTransmitterDataSize - end"); - ////////////////////////////////////////////////////////////////////////// - //receiveTransmitterDataSize - //wenn er hier bei verteilten berechnungen stopped, dann ist vermutlich auf einer seite ein nicht aktiver block!!! - //UBLOG(logDEBUG5, "Calculator::initConnectors() - receiveTransmitterDataSize - start"); - for (int l = minLevel; l <= maxLevel; l++) - { - if (l != maxLevel) - { - UBLOG(logDEBUG5, "Calculator::initRemoteConnectors()-receiveTransmitterDataSize(remoteInterConns["<<l<<"])"); - for(SPtr<Block3DConnector> c : remoteInterConns[l] ) c->receiveTransmitterDataSize(); - } - } - //UBLOG(logDEBUG5, "Calculator::initConnectors() - receiveTransmitterDataSize - end"); - ////////////////////////////////////////////////////////////////////////// + std::vector<std::vector<SPtr<Block3DConnector>>> remoteInterConnsCF; + std::vector<std::vector<SPtr<Block3DConnector>>> remoteInterConnsFC; + remoteInterConnsCF.resize(maxLevel + 1); + remoteInterConnsFC.resize(maxLevel + 1); + + for (int l = minLevel; l <= maxLevel; l++) { + std::vector<SPtr<Block3D>> blockVector; + // grid->getBlocks(level, gridRank, true, blockVector); + grid->getBlocks(l, blockVector); + for (SPtr<Block3D> block : blockVector) { + int block_level = block->getLevel(); + block->pushBackRemoteSameLevelConnectors(remoteConns[block_level]); + + block->pushBackRemoteInterpolationConnectorsCF(remoteInterConnsCF[block_level]); + block->pushBackRemoteInterpolationConnectorsFC(remoteInterConnsFC[block_level]); + } + } + + for (int l = minLevel; l <= maxLevel; l++) { + UBLOG(logDEBUG5, "Calculator::initRemoteConnectors()-initConnectors(remoteConns[" << l << "])"); + initConnectors(remoteConns[l]); + if (l != maxLevel) { + for (size_t i = 0; i < remoteInterConnsCF[l].size(); i++) + remoteInterConns[l].push_back(remoteInterConnsCF[l][i]); + for (size_t i = 0; i < remoteInterConnsFC[l + 1].size(); i++) + remoteInterConns[l].push_back(remoteInterConnsFC[l + 1][i]); + } + } + ////////////////////////////////////////////////////////////////////////// + // UBLOG(logDEBUG5, "Calculator::initConnectors() - connectoren initialisieren - start"); + for (int l = minLevel; l <= maxLevel; l++) { + if (l != maxLevel) { + UBLOG(logDEBUG5, "Calculator::initRemoteConnectors()-initConnectors(remoteInterConns[" << l << "])"); + for (SPtr<Block3DConnector> c : remoteInterConns[l]) + c->init(); + } + } + // UBLOG(logDEBUG5, "Calculator::initConnectors() - connectoren initialisieren - end"); + ////////////////////////////////////////////////////////////////////////// + // sendTransmitterDataSize + // UBLOG(logDEBUG5, "Calculator::initConnectors() - sendTransmitterDataSize - start"); + for (int l = minLevel; l <= maxLevel; l++) { + if (l != maxLevel) { + UBLOG(logDEBUG5, + "Calculator::initRemoteConnectors()-sendTransmitterDataSize(remoteInterConns[" << l << "])"); + for (SPtr<Block3DConnector> c : remoteInterConns[l]) + c->sendTransmitterDataSize(); + } + } + // UBLOG(logDEBUG5, "Calculator::initConnectors() - sendTransmitterDataSize - end"); + ////////////////////////////////////////////////////////////////////////// + // receiveTransmitterDataSize + // wenn er hier bei verteilten berechnungen stopped, dann ist vermutlich auf einer seite ein nicht aktiver block!!! + // UBLOG(logDEBUG5, "Calculator::initConnectors() - receiveTransmitterDataSize - start"); + for (int l = minLevel; l <= maxLevel; l++) { + if (l != maxLevel) { + UBLOG(logDEBUG5, + "Calculator::initRemoteConnectors()-receiveTransmitterDataSize(remoteInterConns[" << l << "])"); + for (SPtr<Block3DConnector> c : remoteInterConns[l]) + c->receiveTransmitterDataSize(); + } + } + // UBLOG(logDEBUG5, "Calculator::initConnectors() - receiveTransmitterDataSize - end"); + ////////////////////////////////////////////////////////////////////////// } ////////////////////////////////////////////////////////////////////////// -void Calculator::initConnectors(std::vector<SPtr<Block3DConnector>>& connectors) +void Calculator::initConnectors(std::vector<SPtr<Block3DConnector>> &connectors) { - UBLOG(logDEBUG1, "Calculator::initConnectors() - start"); - - //initialization - ////////////////////////////////////////////////////////////////////////// - //initialize connectors - UBLOG(logDEBUG5, "Calculator::initConnectors() - connectoren initialisieren - start"); - for(SPtr<Block3DConnector> c : connectors ) c->init(); - UBLOG(logDEBUG5, "Calculator::initConnectors() - connectoren initialisieren - end"); - ////////////////////////////////////////////////////////////////////////// - //sendTransmitterDataSize - UBLOG(logDEBUG5, "Calculator::initConnectors() - sendTransmitterDataSize - start"); - for(SPtr<Block3DConnector> c : connectors ) c->sendTransmitterDataSize(); - UBLOG(logDEBUG5, "Calculator::initConnectors() - sendTransmitterDataSize - end"); - ////////////////////////////////////////////////////////////////////////// - //receiveTransmitterDataSize - //wenn er hier bei verteilten berechnungen stopped, dann ist vermutlich auf einer seite ein nicht aktiver block!!! - UBLOG(logDEBUG5, "Calculator::initConnectors() - receiveTransmitterDataSize - start"); - for(SPtr<Block3DConnector> c : connectors ) c->receiveTransmitterDataSize(); - UBLOG(logDEBUG5, "Calculator::initConnectors() - receiveTransmitterDataSize - end"); - - UBLOG(logDEBUG1, "Calculator::initConnectors() - end"); + UBLOG(logDEBUG1, "Calculator::initConnectors() - start"); + + // initialization + ////////////////////////////////////////////////////////////////////////// + // initialize connectors + UBLOG(logDEBUG5, "Calculator::initConnectors() - connectoren initialisieren - start"); + for (SPtr<Block3DConnector> c : connectors) + c->init(); + UBLOG(logDEBUG5, "Calculator::initConnectors() - connectoren initialisieren - end"); + ////////////////////////////////////////////////////////////////////////// + // sendTransmitterDataSize + UBLOG(logDEBUG5, "Calculator::initConnectors() - sendTransmitterDataSize - start"); + for (SPtr<Block3DConnector> c : connectors) + c->sendTransmitterDataSize(); + UBLOG(logDEBUG5, "Calculator::initConnectors() - sendTransmitterDataSize - end"); + ////////////////////////////////////////////////////////////////////////// + // receiveTransmitterDataSize + // wenn er hier bei verteilten berechnungen stopped, dann ist vermutlich auf einer seite ein nicht aktiver block!!! + UBLOG(logDEBUG5, "Calculator::initConnectors() - receiveTransmitterDataSize - start"); + for (SPtr<Block3DConnector> c : connectors) + c->receiveTransmitterDataSize(); + UBLOG(logDEBUG5, "Calculator::initConnectors() - receiveTransmitterDataSize - end"); + + UBLOG(logDEBUG1, "Calculator::initConnectors() - end"); } ////////////////////////////////////////////////////////////////////////// void Calculator::deleteBlocks() { - for(std::vector< SPtr<Block3D> > &bs : blocks) - bs.resize(0); + for (std::vector<SPtr<Block3D>> &bs : blocks) + bs.resize(0); } ////////////////////////////////////////////////////////////////////////// void Calculator::deleteConnectors() { - deleteConnectors(localConns); - deleteConnectors(remoteConns); + deleteConnectors(localConns); + deleteConnectors(remoteConns); - deleteConnectors(localInterConns); - deleteConnectors(remoteInterConns); + deleteConnectors(localInterConns); + deleteConnectors(remoteInterConns); } ////////////////////////////////////////////////////////////////////////// -void Calculator::deleteConnectors(std::vector< std::vector< SPtr<Block3DConnector> > >& conns) +void Calculator::deleteConnectors(std::vector<std::vector<SPtr<Block3DConnector>>> &conns) { - for(std::vector< SPtr<Block3DConnector> > &c : conns) - c.resize(0); + for (std::vector<SPtr<Block3DConnector>> &c : conns) + c.resize(0); } ////////////////////////////////////////////////////////////////////////// - diff --git a/src/cpu/VirtualFluidsCore/Grid/Calculator.h b/src/cpu/VirtualFluidsCore/Grid/Calculator.h index dfa1fabae8b17790166e4fe5b9e5d9fea8f5a745..377e6eee7d765ba6888b2aec6045cb14eac484dc 100644 --- a/src/cpu/VirtualFluidsCore/Grid/Calculator.h +++ b/src/cpu/VirtualFluidsCore/Grid/Calculator.h @@ -1,28 +1,28 @@ //======================================================================================= -// ____ ____ __ ______ __________ __ __ __ __ -// \ \ | | | | | _ \ |___ ___| | | | | / \ | | -// \ \ | | | | | |_) | | | | | | | / \ | | -// \ \ | | | | | _ / | | | | | | / /\ \ | | -// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ -// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| -// \ \ | | ________________________________________________________________ -// \ \ | | | ______________________________________________________________| -// \ \| | | | __ __ __ __ ______ _______ -// \ | | |_____ | | | | | | | | | _ \ / _____) -// \ | | _____| | | | | | | | | | | \ \ \_______ +// ____ ____ __ ______ __________ __ __ __ __ +// \ \ | | | | | _ \ |___ ___| | | | | / \ | | +// \ \ | | | | | |_) | | | | | | | / \ | | +// \ \ | | | | | _ / | | | | | | / /\ \ | | +// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ +// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| +// \ \ | | ________________________________________________________________ +// \ \ | | | ______________________________________________________________| +// \ \| | | | __ __ __ __ ______ _______ +// \ | | |_____ | | | | | | | | | _ \ / _____) +// \ | | _____| | | | | | | | | | | \ \ \_______ // \ | | | | |_____ | \_/ | | | | |_/ / _____ | -// \ _____| |__| |________| \_______/ |__| |______/ (_______/ +// \ _____| |__| |________| \_______/ |__| |______/ (_______/ // -// This file is part of VirtualFluids. VirtualFluids is free software: you can +// This file is part of VirtualFluids. VirtualFluids is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of +// License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. -// -// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// +// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License along // with VirtualFluids (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>. // @@ -43,48 +43,49 @@ class Block3D; class Block3DConnector; class CoProcessor; -//! \class Calculator -//! \brief A base class for main calculation loop +//! \class Calculator +//! \brief A base class for main calculation loop -class Calculator +class Calculator { public: - Calculator(SPtr<Grid3D> grid, SPtr<UbScheduler> additionalGhostLayerUpdateScheduler, int numberOfTimeSteps); - virtual ~Calculator(); - //! control of coProcessors - void addCoProcessor(SPtr<CoProcessor> coProcessor); - void coProcess(double step); + Calculator(SPtr<Grid3D> grid, SPtr<UbScheduler> additionalGhostLayerUpdateScheduler, int numberOfTimeSteps); + virtual ~Calculator(); + //! control of coProcessors + void addCoProcessor(SPtr<CoProcessor> coProcessor); + void coProcess(double step); + + virtual void calculate() = 0; - virtual void calculate()=0; protected: - virtual void initLocalConnectors(); - virtual void initRemoteConnectors(); - void initConnectors(std::vector<SPtr<Block3DConnector> >& connectors); - void deleteBlocks(); - void deleteConnectors(); - void deleteConnectors(std::vector< std::vector< SPtr<Block3DConnector> > >& conns); + virtual void initLocalConnectors(); + virtual void initRemoteConnectors(); + void initConnectors(std::vector<SPtr<Block3DConnector>> &connectors); + void deleteBlocks(); + void deleteConnectors(); + void deleteConnectors(std::vector<std::vector<SPtr<Block3DConnector>>> &conns); - int minLevel, maxLevel; - int startTimeStep; - int numberOfTimeSteps; - std::vector< std::vector< SPtr<Block3DConnector> > > localConns; - std::vector< std::vector< SPtr<Block3DConnector> > > remoteConns; + int minLevel, maxLevel; + int startTimeStep; + int numberOfTimeSteps; + std::vector<std::vector<SPtr<Block3DConnector>>> localConns; + std::vector<std::vector<SPtr<Block3DConnector>>> remoteConns; - bool refinement; - SPtr<Grid3D> grid; - SPtr<UbScheduler> additionalGhostLayerUpdateScheduler; - std::vector< std::vector<SPtr<Block3D> > > blocks; + bool refinement; + SPtr<Grid3D> grid; + SPtr<UbScheduler> additionalGhostLayerUpdateScheduler; + std::vector<std::vector<SPtr<Block3D>>> blocks; - //localInterConns and remoteInterConns save interpolation connectors - //every element save CF connectors for current level and FC connectors for next level - //e.g. - //localInterConns[0] = CF(0), FC(1) - //localInterConns[1] = CF(1), FC(2) - //localInterConns[2] - std::vector< std::vector< SPtr<Block3DConnector> > > localInterConns; - std::vector< std::vector< SPtr<Block3DConnector> > > remoteInterConns; + // localInterConns and remoteInterConns save interpolation connectors + // every element save CF connectors for current level and FC connectors for next level + // e.g. + // localInterConns[0] = CF(0), FC(1) + // localInterConns[1] = CF(1), FC(2) + // localInterConns[2] + std::vector<std::vector<SPtr<Block3DConnector>>> localInterConns; + std::vector<std::vector<SPtr<Block3DConnector>>> remoteInterConns; - std::vector< SPtr<CoProcessor> > coProcessors; + std::vector<SPtr<CoProcessor>> coProcessors; }; #endif diff --git a/src/cpu/VirtualFluidsCore/Grid/Grid3D.cpp b/src/cpu/VirtualFluidsCore/Grid/Grid3D.cpp index 3cb76a8b263be5fe02d3c1667b9c8b8368147b50..520da83f6f7048ad2ff019051bd7cee8d188c60a 100644 --- a/src/cpu/VirtualFluidsCore/Grid/Grid3D.cpp +++ b/src/cpu/VirtualFluidsCore/Grid/Grid3D.cpp @@ -1,28 +1,28 @@ //======================================================================================= -// ____ ____ __ ______ __________ __ __ __ __ -// \ \ | | | | | _ \ |___ ___| | | | | / \ | | -// \ \ | | | | | |_) | | | | | | | / \ | | -// \ \ | | | | | _ / | | | | | | / /\ \ | | -// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ -// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| -// \ \ | | ________________________________________________________________ -// \ \ | | | ______________________________________________________________| -// \ \| | | | __ __ __ __ ______ _______ -// \ | | |_____ | | | | | | | | | _ \ / _____) -// \ | | _____| | | | | | | | | | | \ \ \_______ +// ____ ____ __ ______ __________ __ __ __ __ +// \ \ | | | | | _ \ |___ ___| | | | | / \ | | +// \ \ | | | | | |_) | | | | | | | / \ | | +// \ \ | | | | | _ / | | | | | | / /\ \ | | +// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ +// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| +// \ \ | | ________________________________________________________________ +// \ \ | | | ______________________________________________________________| +// \ \| | | | __ __ __ __ ______ _______ +// \ | | |_____ | | | | | | | | | _ \ / _____) +// \ | | _____| | | | | | | | | | | \ \ \_______ // \ | | | | |_____ | \_/ | | | | |_/ / _____ | -// \ _____| |__| |________| \_______/ |__| |______/ (_______/ +// \ _____| |__| |________| \_______/ |__| |______/ (_______/ // -// This file is part of VirtualFluids. VirtualFluids is free software: you can +// This file is part of VirtualFluids. VirtualFluids is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of +// License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. -// -// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// +// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License along // with VirtualFluids (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>. // @@ -35,1934 +35,2217 @@ #include <set> -#include <geometry3d/CoordinateTransformation3D.h> #include <basics/writer/WbWriterVtkXmlASCII.h> +#include <geometry3d/CoordinateTransformation3D.h> -#include "Grid3DVisitor.h" #include "Block3DVisitor.h" -#include "Interactor3D.h" #include "Grid3DSystem.h" +#include "Grid3DVisitor.h" +#include "Interactor3D.h" #include "LBMSystem.h" #include <Block3D.h> #include <Communicator.h> - using namespace std; -Grid3D::Grid3D() - -{ - levelSet.resize(Grid3DSystem::MAXLEVEL + 1); -} +Grid3D::Grid3D() { levelSet.resize(Grid3DSystem::MAXLEVEL + 1); } ////////////////////////////////////////////////////////////////////////// -Grid3D::Grid3D(SPtr<Communicator> comm) - +Grid3D::Grid3D(SPtr<Communicator> comm) + { - levelSet.resize(Grid3DSystem::MAXLEVEL + 1); - bundle = comm->getBundleID(); - rank = comm->getProcessID(); + levelSet.resize(Grid3DSystem::MAXLEVEL + 1); + bundle = comm->getBundleID(); + rank = comm->getProcessID(); } ////////////////////////////////////////////////////////////////////////// -Grid3D::Grid3D(SPtr<Communicator> comm, int blockNx1, int blockNx2, int blockNx3, int gridNx1, int gridNx2, int gridNx3) : - - blockNx1(blockNx1), - blockNx2(blockNx2), - blockNx3(blockNx2), - nx1(gridNx1), - nx2(gridNx2), - nx3(gridNx3) +Grid3D::Grid3D(SPtr<Communicator> comm, int blockNx1, int blockNx2, int blockNx3, int gridNx1, int gridNx2, int gridNx3) + : + + blockNx1(blockNx1), blockNx2(blockNx2), blockNx3(blockNx2), nx1(gridNx1), nx2(gridNx2), nx3(gridNx3) { - levelSet.resize(Grid3DSystem::MAXLEVEL + 1); - bundle = comm->getBundleID(); - rank = comm->getProcessID(); - trafo = std::make_shared<CoordinateTransformation3D>(0.0, 0.0, 0.0, (double)blockNx1, (double)blockNx2, (double)blockNx3); - UbTupleInt3 minInd(0, 0, 0); - UbTupleInt3 maxInd(gridNx1, gridNx2, gridNx3); - this->fillExtentWithBlocks(minInd, maxInd); + levelSet.resize(Grid3DSystem::MAXLEVEL + 1); + bundle = comm->getBundleID(); + rank = comm->getProcessID(); + trafo = std::make_shared<CoordinateTransformation3D>(0.0, 0.0, 0.0, (double)blockNx1, (double)blockNx2, + (double)blockNx3); + UbTupleInt3 minInd(0, 0, 0); + UbTupleInt3 maxInd(gridNx1, gridNx2, gridNx3); + this->fillExtentWithBlocks(minInd, maxInd); } ////////////////////////////////////////////////////////////////////////// -void Grid3D::addInteractor(SPtr<Interactor3D> interactor) -{ - interactors.push_back(interactor); -} +void Grid3D::addInteractor(SPtr<Interactor3D> interactor) { interactors.push_back(interactor); } ////////////////////////////////////////////////////////////////////////// void Grid3D::addAndInitInteractor(SPtr<Interactor3D> interactor, double timestep) { - interactors.push_back(interactor); - interactor->initInteractor(timestep); -} -////////////////////////////////////////////////////////////////////////// -Grid3D::Interactor3DSet Grid3D::getInteractors() -{ - return interactors; -} -////////////////////////////////////////////////////////////////////////// -void Grid3D::accept(Block3DVisitor& blockVisitor) -{ - int startLevel = blockVisitor.getStartLevel(); - int stopLevel = blockVisitor.getStopLevel(); - - if (startLevel < 0 || stopLevel < 0 || startLevel > Grid3DSystem::MAXLEVEL || stopLevel > Grid3DSystem::MAXLEVEL) - throw UbException(UB_EXARGS, "not valid level!"); - - bool dir = startLevel < stopLevel; - if (dir) stopLevel += 1; - else stopLevel -= 1; - - //#pragma omp parallel - // { - // for (int l = startLevel; l!=stopLevel;) - // { - // std::vector<SPtr<Block3D>> blockVector; - // getBlocks(l, blockVector); - // int sizeb = (int)blockVector.size(); - // - //#pragma omp for - // for (int i = 0; i < sizeb; i++) - // { - // blockVisitor.visit(shared_from_this(), blockVector[i]); - // } - // if (dir) l++; - // else l--; - // } - // } - for (int l = startLevel; l != stopLevel;) - { - std::vector<SPtr<Block3D>> blockVector; - getBlocks(l, blockVector); - for (SPtr<Block3D> b : blockVector) - { - blockVisitor.visit(shared_from_this(), b); - } - if (dir) l++; - else l--; - } -} -////////////////////////////////////////////////////////////////////////// -void Grid3D::accept(Grid3DVisitor& gridVisitor) -{ - gridVisitor.visit(shared_from_this()); -} -////////////////////////////////////////////////////////////////////////// -void Grid3D::accept(SPtr<Grid3DVisitor> gridVisitor) -{ - gridVisitor->visit(shared_from_this()); -} + interactors.push_back(interactor); + interactor->initInteractor(timestep); +} +////////////////////////////////////////////////////////////////////////// +Grid3D::Interactor3DSet Grid3D::getInteractors() { return interactors; } +////////////////////////////////////////////////////////////////////////// +void Grid3D::accept(Block3DVisitor &blockVisitor) +{ + int startLevel = blockVisitor.getStartLevel(); + int stopLevel = blockVisitor.getStopLevel(); + + if (startLevel < 0 || stopLevel < 0 || startLevel > Grid3DSystem::MAXLEVEL || stopLevel > Grid3DSystem::MAXLEVEL) + throw UbException(UB_EXARGS, "not valid level!"); + + bool dir = startLevel < stopLevel; + if (dir) + stopLevel += 1; + else + stopLevel -= 1; + + //#pragma omp parallel + // { + // for (int l = startLevel; l!=stopLevel;) + // { + // std::vector<SPtr<Block3D>> blockVector; + // getBlocks(l, blockVector); + // int sizeb = (int)blockVector.size(); + // + //#pragma omp for + // for (int i = 0; i < sizeb; i++) + // { + // blockVisitor.visit(shared_from_this(), blockVector[i]); + // } + // if (dir) l++; + // else l--; + // } + // } + for (int l = startLevel; l != stopLevel;) { + std::vector<SPtr<Block3D>> blockVector; + getBlocks(l, blockVector); + for (SPtr<Block3D> b : blockVector) { + blockVisitor.visit(shared_from_this(), b); + } + if (dir) + l++; + else + l--; + } +} +////////////////////////////////////////////////////////////////////////// +void Grid3D::accept(Grid3DVisitor &gridVisitor) { gridVisitor.visit(shared_from_this()); } +////////////////////////////////////////////////////////////////////////// +void Grid3D::accept(SPtr<Grid3DVisitor> gridVisitor) { gridVisitor->visit(shared_from_this()); } ////////////////////////////////////////////////////////////////////////// void Grid3D::addBlock(SPtr<Block3D> block) { - if (block) - { - this->blockIdMap.insert(std::make_pair(block->getGlobalID(), block)); - int level = block->getLevel(); - this->levelSet[level].insert(std::make_pair(Block3DKey(block->getX1(), block->getX2(), block->getX3()), block)); - } + if (block) { + this->blockIdMap.insert(std::make_pair(block->getGlobalID(), block)); + int level = block->getLevel(); + this->levelSet[level].insert(std::make_pair(Block3DKey(block->getX1(), block->getX2(), block->getX3()), block)); + } } ////////////////////////////////////////////////////////////////////////// bool Grid3D::deleteBlock(SPtr<Block3D> block) { - return this->deleteBlock(block->getX1(), block->getX2(), block->getX3(), block->getLevel()); + return this->deleteBlock(block->getX1(), block->getX2(), block->getX3(), block->getLevel()); } ////////////////////////////////////////////////////////////////////////// bool Grid3D::deleteBlock(int ix1, int ix2, int ix3, int level) { - SPtr<Block3D> block = this->getBlock(ix1, ix2, ix3, level); - if (block) - { - this->blockIdMap.erase(block->getGlobalID()); - return this->levelSet[level].erase(Block3DKey(ix1, ix2, ix3)) > 0; - } - else - { - return false; - } + SPtr<Block3D> block = this->getBlock(ix1, ix2, ix3, level); + if (block) { + this->blockIdMap.erase(block->getGlobalID()); + return this->levelSet[level].erase(Block3DKey(ix1, ix2, ix3)) > 0; + } else { + return false; + } } void Grid3D::deleteBlocks() { - std::vector < std::vector<SPtr<Block3D> > > blocksVector(25); - int minInitLevel = Grid3DSystem::MINLEVEL; - int maxInitLevel = Grid3DSystem::MAXLEVEL; - for (int level = minInitLevel; level < maxInitLevel; level++) - { - getBlocks(level, blocksVector[level]); - for (SPtr<Block3D> block : blocksVector[level]) // blocks of the current level - deleteBlock(block); - } + std::vector<std::vector<SPtr<Block3D>>> blocksVector(25); + int minInitLevel = Grid3DSystem::MINLEVEL; + int maxInitLevel = Grid3DSystem::MAXLEVEL; + for (int level = minInitLevel; level < maxInitLevel; level++) { + getBlocks(level, blocksVector[level]); + for (SPtr<Block3D> block : blocksVector[level]) // blocks of the current level + deleteBlock(block); + } } ////////////////////////////////////////////////////////////////////////// void Grid3D::replaceBlock(SPtr<Block3D> block) { - if (block) - { - this->deleteBlock(block); - this->addBlock(block); - } + if (block) { + this->deleteBlock(block); + this->addBlock(block); + } } ////////////////////////////////////////////////////////////////////////// SPtr<Block3D> Grid3D::getBlock(int ix1, int ix2, int ix3, int level) const { - if (!this->hasLevel(level)) return SPtr<Block3D>(); - - int N1 = (nx1 << level); - int N2 = (nx2 << level); - int N3 = (nx3 << level); - - if (!this->isPeriodicX1() && (ix1 > N1 - 1 || ix1 < 0)) return SPtr<Block3D>(); - else if (this->isPeriodicX1() && (ix1 >= N1 - 1 || ix1 < 0)) { ix1 = ((ix1 % N1) + N1) % N1; } - if (!this->isPeriodicX2() && (ix2 > N2 - 1 || ix2 < 0)) return SPtr<Block3D>(); - else if (this->isPeriodicX2() && (ix2 >= N2 - 1 || ix2 < 0)) { ix2 = ((ix2 % N2) + N2) % N2; } - if (!this->isPeriodicX3() && (ix3 > N3 - 1 || ix3 < 0)) return SPtr<Block3D>(); - else if (this->isPeriodicX3() && (ix3 >= N3 - 1 || ix3 < 0)) { ix3 = ((ix3 % N3) + N3) % N3; } - - Block3DMap::const_iterator it; - it = levelSet[level].find(Block3DKey(ix1, ix2, ix3)); - if (it == levelSet[level].end()) - return SPtr<Block3D>(); - else - return it->second; + if (!this->hasLevel(level)) + return SPtr<Block3D>(); + + int N1 = (nx1 << level); + int N2 = (nx2 << level); + int N3 = (nx3 << level); + + if (!this->isPeriodicX1() && (ix1 > N1 - 1 || ix1 < 0)) + return SPtr<Block3D>(); + else if (this->isPeriodicX1() && (ix1 >= N1 - 1 || ix1 < 0)) { + ix1 = ((ix1 % N1) + N1) % N1; + } + if (!this->isPeriodicX2() && (ix2 > N2 - 1 || ix2 < 0)) + return SPtr<Block3D>(); + else if (this->isPeriodicX2() && (ix2 >= N2 - 1 || ix2 < 0)) { + ix2 = ((ix2 % N2) + N2) % N2; + } + if (!this->isPeriodicX3() && (ix3 > N3 - 1 || ix3 < 0)) + return SPtr<Block3D>(); + else if (this->isPeriodicX3() && (ix3 >= N3 - 1 || ix3 < 0)) { + ix3 = ((ix3 % N3) + N3) % N3; + } + + Block3DMap::const_iterator it; + it = levelSet[level].find(Block3DKey(ix1, ix2, ix3)); + if (it == levelSet[level].end()) + return SPtr<Block3D>(); + else + return it->second; } ////////////////////////////////////////////////////////////////////////// SPtr<Block3D> Grid3D::getBlock(int id) const { - BlockIDMap::const_iterator it; - if ((it = blockIdMap.find(id)) == blockIdMap.end()) - { - return SPtr<Block3D>(); - } + BlockIDMap::const_iterator it; + if ((it = blockIdMap.find(id)) == blockIdMap.end()) { + return SPtr<Block3D>(); + } - return it->second; + return it->second; } ////////////////////////////////////////////////////////////////////////// -//const Grid3D::Block3DMap& Grid3D::getBlocks(int level) -//{ +// const Grid3D::Block3DMap& Grid3D::getBlocks(int level) +//{ // return levelSet[level]; //} ////////////////////////////////////////////////////////////////////////// -Grid3D::BlockIDMap& Grid3D::getBlockIDs() -{ - return blockIdMap; -} +Grid3D::BlockIDMap &Grid3D::getBlockIDs() { return blockIdMap; } ////////////////////////////////////////////////////////////////////////// SPtr<Block3D> Grid3D::getSuperBlock(SPtr<Block3D> block) { - int ix1 = block->getX1(); - int ix2 = block->getX2(); - int ix3 = block->getX3(); - int level = block->getLevel(); - return getSuperBlock(ix1, ix2, ix3, level); + int ix1 = block->getX1(); + int ix2 = block->getX2(); + int ix3 = block->getX3(); + int level = block->getLevel(); + return getSuperBlock(ix1, ix2, ix3, level); } ////////////////////////////////////////////////////////////////////////// SPtr<Block3D> Grid3D::getSuperBlock(int ix1, int ix2, int ix3, int level) { - if (!this->hasLevel(level)) return SPtr<Block3D>(); - if (level < 1) throw UbException(UB_EXARGS, "level <1"); - - //from Lower Level to higher: >> 1 in x1,x2,x3 - SPtr<Block3D> block; - for (int l = level - 1; l >= 0; l--) - { - ix1 = ix1 >> 1; - ix2 = ix2 >> 1; - ix3 = ix3 >> 1; - - block = this->getBlock(ix1, ix2, ix3, l); - if (block) return block; - } - return SPtr<Block3D>(); -} -////////////////////////////////////////////////////////////////////////// -void Grid3D::getSubBlocks(SPtr<Block3D> block, int levelDepth, std::vector<SPtr<Block3D>>& blocks) -{ - int ix1 = block->getX1(); - int ix2 = block->getX2(); - int ix3 = block->getX3(); - int level = block->getLevel(); - getSubBlocks(ix1, ix2, ix3, level, levelDepth, blocks); -} -////////////////////////////////////////////////////////////////////////// -void Grid3D::getSubBlocks(int ix1, int ix2, int ix3, int level, int levelDepth, std::vector<SPtr<Block3D>>& blocks) -{ - if (!this->getBlock(ix1, ix2, ix3, level)) return; - if (level > 0 && !this->getSuperBlock(ix1, ix2, ix3, level)) return; - if (level >= Grid3DSystem::MAXLEVEL) throw UbException(UB_EXARGS, "Level bigger then MAXLEVEL"); - - int x1[] = { ix1 << 1, (ix1 << 1) + 1 }; - int x2[] = { ix2 << 1, (ix2 << 1) + 1 }; - int x3[] = { ix3 << 1, (ix3 << 1) + 1 }; - int l = level + 1; - - for (int i = 0; i < 2; i++) - for (int j = 0; j < 2; j++) - for (int k = 0; k < 2; k++) - { - SPtr<Block3D> block = this->getBlock(x1[i], x2[j], x3[k], l); - if (block) blocks.push_back(block); - else if (l < levelDepth) this->getSubBlocks(x1[i], x2[j], x3[k], l, levelDepth, blocks); - } + if (!this->hasLevel(level)) + return SPtr<Block3D>(); + if (level < 1) + throw UbException(UB_EXARGS, "level <1"); + + // from Lower Level to higher: >> 1 in x1,x2,x3 + SPtr<Block3D> block; + for (int l = level - 1; l >= 0; l--) { + ix1 = ix1 >> 1; + ix2 = ix2 >> 1; + ix3 = ix3 >> 1; + + block = this->getBlock(ix1, ix2, ix3, l); + if (block) + return block; + } + return SPtr<Block3D>(); +} +////////////////////////////////////////////////////////////////////////// +void Grid3D::getSubBlocks(SPtr<Block3D> block, int levelDepth, std::vector<SPtr<Block3D>> &blocks) +{ + int ix1 = block->getX1(); + int ix2 = block->getX2(); + int ix3 = block->getX3(); + int level = block->getLevel(); + getSubBlocks(ix1, ix2, ix3, level, levelDepth, blocks); +} +////////////////////////////////////////////////////////////////////////// +void Grid3D::getSubBlocks(int ix1, int ix2, int ix3, int level, int levelDepth, std::vector<SPtr<Block3D>> &blocks) +{ + if (!this->getBlock(ix1, ix2, ix3, level)) + return; + if (level > 0 && !this->getSuperBlock(ix1, ix2, ix3, level)) + return; + if (level >= Grid3DSystem::MAXLEVEL) + throw UbException(UB_EXARGS, "Level bigger then MAXLEVEL"); + + int x1[] = { ix1 << 1, (ix1 << 1) + 1 }; + int x2[] = { ix2 << 1, (ix2 << 1) + 1 }; + int x3[] = { ix3 << 1, (ix3 << 1) + 1 }; + int l = level + 1; + + for (int i = 0; i < 2; i++) + for (int j = 0; j < 2; j++) + for (int k = 0; k < 2; k++) { + SPtr<Block3D> block = this->getBlock(x1[i], x2[j], x3[k], l); + if (block) + blocks.push_back(block); + else if (l < levelDepth) + this->getSubBlocks(x1[i], x2[j], x3[k], l, levelDepth, blocks); + } } ////////////////////////////////////////////////////////////////////////// bool Grid3D::expandBlock(int ix1, int ix2, int ix3, int level) { - this->checkLevel(level); - - SPtr<Block3D> block = this->getBlock(ix1, ix2, ix3, level); - if (!block) throw UbException(UB_EXARGS, "block(x1=" + UbSystem::toString(ix1) + ", x2=" + UbSystem::toString(ix2) + ", x3=" + UbSystem::toString(ix3) + ", l=" + UbSystem::toString(level) + ") is not exist"); - //if(!block->isActive()) throw UbException(UB_EXARGS,"block(x1="+UbSystem::toString(ix1)+", x2="+UbSystem::toString(ix2)+", x3="+UbSystem::toString(ix3)+", l="+UbSystem::toString(level)+") is not active"); - - //da bei periodic der eigentliche block andere indizes hat: - ix1 = block->getX1(); - ix2 = block->getX2(); - ix3 = block->getX3(); - - int l = level + 1; - if (l > Grid3DSystem::MAXLEVEL) throw UbException(UB_EXARGS, "level > Grid3D::MAXLEVEL"); - - int west = ix1 << 1; - int east = west + 1; - int south = ix2 << 1; - int north = south + 1; - int bottom = ix3 << 1; - int top = bottom + 1; - - auto blockBSW = std::make_shared<Block3D>(west, south, bottom, l); - auto blockBSE = std::make_shared<Block3D>(east, south, bottom, l); - auto blockBNW = std::make_shared<Block3D>(west, north, bottom, l); - auto blockBNE = std::make_shared<Block3D>(east, north, bottom, l); - auto blockTSW = std::make_shared<Block3D>(west, south, top, l); - auto blockTSE = std::make_shared<Block3D>(east, south, top, l); - auto blockTNW = std::make_shared<Block3D>(west, north, top, l); - auto blockTNE = std::make_shared<Block3D>(east, north, top, l); - - if (!this->deleteBlock(ix1, ix2, ix3, level)) - throw UbException(UB_EXARGS, "could not delete block"); - - this->addBlock(blockBSW); - this->addBlock(blockBSE); - this->addBlock(blockBNW); - this->addBlock(blockBNE); - this->addBlock(blockTSW); - this->addBlock(blockTSE); - this->addBlock(blockTNW); - this->addBlock(blockTNE); - - return true; + this->checkLevel(level); + + SPtr<Block3D> block = this->getBlock(ix1, ix2, ix3, level); + if (!block) + throw UbException(UB_EXARGS, "block(x1=" + UbSystem::toString(ix1) + ", x2=" + UbSystem::toString(ix2) + + ", x3=" + UbSystem::toString(ix3) + ", l=" + UbSystem::toString(level) + + ") is not exist"); + // if(!block->isActive()) throw UbException(UB_EXARGS,"block(x1="+UbSystem::toString(ix1)+", + // x2="+UbSystem::toString(ix2)+", x3="+UbSystem::toString(ix3)+", l="+UbSystem::toString(level)+") is not active"); + + // da bei periodic der eigentliche block andere indizes hat: + ix1 = block->getX1(); + ix2 = block->getX2(); + ix3 = block->getX3(); + + int l = level + 1; + if (l > Grid3DSystem::MAXLEVEL) + throw UbException(UB_EXARGS, "level > Grid3D::MAXLEVEL"); + + int west = ix1 << 1; + int east = west + 1; + int south = ix2 << 1; + int north = south + 1; + int bottom = ix3 << 1; + int top = bottom + 1; + + auto blockBSW = std::make_shared<Block3D>(west, south, bottom, l); + auto blockBSE = std::make_shared<Block3D>(east, south, bottom, l); + auto blockBNW = std::make_shared<Block3D>(west, north, bottom, l); + auto blockBNE = std::make_shared<Block3D>(east, north, bottom, l); + auto blockTSW = std::make_shared<Block3D>(west, south, top, l); + auto blockTSE = std::make_shared<Block3D>(east, south, top, l); + auto blockTNW = std::make_shared<Block3D>(west, north, top, l); + auto blockTNE = std::make_shared<Block3D>(east, north, top, l); + + if (!this->deleteBlock(ix1, ix2, ix3, level)) + throw UbException(UB_EXARGS, "could not delete block"); + + this->addBlock(blockBSW); + this->addBlock(blockBSE); + this->addBlock(blockBNW); + this->addBlock(blockBNE); + this->addBlock(blockTSW); + this->addBlock(blockTSE); + this->addBlock(blockTNW); + this->addBlock(blockTNE); + + return true; } ////////////////////////////////////////////////////////////////////////// SPtr<Block3D> Grid3D::collapseBlock(int fix1, int fix2, int fix3, int flevel, int levelDepth) { - using UbSystem::toString; - - SPtr<Block3D> fblock = this->getBlock(fix1, fix2, fix3, flevel); - if (flevel < 1) throw UbException(UB_EXARGS, "level of block (" + toString(fix1) + "," + toString(fix2) + "," + toString(fix3) + "," + toString(flevel) + ") is < 1"); - if (!fblock) - { - throw UbException(UB_EXARGS, "specific block(" + toString(fix1) + "," + toString(fix2) + "," + toString(fix3) + "," + toString(flevel) + ") doesn't exists"); - } - if (!fblock->isActive()) throw UbException(UB_EXARGS, "block(" + toString(fix1) + "," + toString(fix2) + "," + toString(fix3) + "," + toString(flevel) + ") is not active"); - - //da bei periodic der eigentliche block andere indizes hat: - fix1 = fblock->getX1(); - fix2 = fblock->getX2(); - fix3 = fblock->getX3(); - - int cix1 = fblock->getX1() >> 1; - int cix2 = fblock->getX2() >> 1; - int cix3 = fblock->getX3() >> 1; - - int fx1[2] = { cix1 << 1, (cix1 << 1) + 1 }; - int fx2[2] = { cix2 << 1, (cix2 << 1) + 1 }; - int fx3[2] = { cix3 << 1, (cix3 << 1) + 1 }; - int clevel = flevel - 1; - - vector<SPtr<Block3D>> blocks; - for (int i = 0; i < 2; i++) - for (int k = 0; k < 2; k++) - for (int l = 0; l < 2; l++) - { - this->getSubBlocks(fx1[k], fx2[i], fx3[l], flevel, levelDepth, blocks); - while (!blocks.empty()) - { - //man muss nur eine von den moeglichen acht "collapsen", die anderen werden - //dann (rekursiv) collapsed, da die schleife oben alle vier abfragt - this->collapseBlock(blocks[0]->getX1(), blocks[0]->getX2(), blocks[0]->getX3(), blocks[0]->getLevel(), levelDepth); - this->getSubBlocks(fx1[k], fx2[i], fx3[l], flevel, levelDepth, blocks); + using UbSystem::toString; + + SPtr<Block3D> fblock = this->getBlock(fix1, fix2, fix3, flevel); + if (flevel < 1) + throw UbException(UB_EXARGS, "level of block (" + toString(fix1) + "," + toString(fix2) + "," + toString(fix3) + + "," + toString(flevel) + ") is < 1"); + if (!fblock) { + throw UbException(UB_EXARGS, "specific block(" + toString(fix1) + "," + toString(fix2) + "," + toString(fix3) + + "," + toString(flevel) + ") doesn't exists"); + } + if (!fblock->isActive()) + throw UbException(UB_EXARGS, "block(" + toString(fix1) + "," + toString(fix2) + "," + toString(fix3) + "," + + toString(flevel) + ") is not active"); + + // da bei periodic der eigentliche block andere indizes hat: + fix1 = fblock->getX1(); + fix2 = fblock->getX2(); + fix3 = fblock->getX3(); + + int cix1 = fblock->getX1() >> 1; + int cix2 = fblock->getX2() >> 1; + int cix3 = fblock->getX3() >> 1; + + int fx1[2] = { cix1 << 1, (cix1 << 1) + 1 }; + int fx2[2] = { cix2 << 1, (cix2 << 1) + 1 }; + int fx3[2] = { cix3 << 1, (cix3 << 1) + 1 }; + int clevel = flevel - 1; + + vector<SPtr<Block3D>> blocks; + for (int i = 0; i < 2; i++) + for (int k = 0; k < 2; k++) + for (int l = 0; l < 2; l++) { + this->getSubBlocks(fx1[k], fx2[i], fx3[l], flevel, levelDepth, blocks); + while (!blocks.empty()) { + // man muss nur eine von den moeglichen acht "collapsen", die anderen werden + // dann (rekursiv) collapsed, da die schleife oben alle vier abfragt + this->collapseBlock(blocks[0]->getX1(), blocks[0]->getX2(), blocks[0]->getX3(), + blocks[0]->getLevel(), levelDepth); + this->getSubBlocks(fx1[k], fx2[i], fx3[l], flevel, levelDepth, blocks); + } } - } - vector<SPtr<Block3D>> fineBlocks(8); - /*BSW*/fineBlocks[0] = this->getBlock(fx1[0], fx2[0], fx3[0], flevel); - /*BSE*/fineBlocks[1] = this->getBlock(fx1[1], fx2[0], fx3[0], flevel); - /*BNE*/fineBlocks[2] = this->getBlock(fx1[1], fx2[1], fx3[0], flevel); - /*BNW*/fineBlocks[3] = this->getBlock(fx1[0], fx2[1], fx3[0], flevel); - /*TSW*/fineBlocks[4] = this->getBlock(fx1[0], fx2[0], fx3[1], flevel); - /*TSE*/fineBlocks[5] = this->getBlock(fx1[1], fx2[0], fx3[1], flevel); - /*TNE*/fineBlocks[6] = this->getBlock(fx1[1], fx2[1], fx3[1], flevel); - /*TNW*/fineBlocks[7] = this->getBlock(fx1[0], fx2[1], fx3[1], flevel); + vector<SPtr<Block3D>> fineBlocks(8); + /*BSW*/ fineBlocks[0] = this->getBlock(fx1[0], fx2[0], fx3[0], flevel); + /*BSE*/ fineBlocks[1] = this->getBlock(fx1[1], fx2[0], fx3[0], flevel); + /*BNE*/ fineBlocks[2] = this->getBlock(fx1[1], fx2[1], fx3[0], flevel); + /*BNW*/ fineBlocks[3] = this->getBlock(fx1[0], fx2[1], fx3[0], flevel); + /*TSW*/ fineBlocks[4] = this->getBlock(fx1[0], fx2[0], fx3[1], flevel); + /*TSE*/ fineBlocks[5] = this->getBlock(fx1[1], fx2[0], fx3[1], flevel); + /*TNE*/ fineBlocks[6] = this->getBlock(fx1[1], fx2[1], fx3[1], flevel); + /*TNW*/ fineBlocks[7] = this->getBlock(fx1[0], fx2[1], fx3[1], flevel); - auto cblock = std::make_shared<Block3D>(cix1, cix2, cix3, clevel); + auto cblock = std::make_shared<Block3D>(cix1, cix2, cix3, clevel); - for (int i = 0; i < 2; i++) - for (int k = 0; k < 2; k++) - for (int l = 0; l < 2; l++) - if (!this->deleteBlock(fx1[k], fx2[i], fx3[l], flevel)) - throw UbException(UB_EXARGS, "could not delete block"); + for (int i = 0; i < 2; i++) + for (int k = 0; k < 2; k++) + for (int l = 0; l < 2; l++) + if (!this->deleteBlock(fx1[k], fx2[i], fx3[l], flevel)) + throw UbException(UB_EXARGS, "could not delete block"); - this->addBlock(cblock); + this->addBlock(cblock); - return cblock; + return cblock; } ////////////////////////////////////////////////////////////////////////// // TODO: make visitor for this void Grid3D::deleteConnectors() { - for (Block3DMap blockMap : levelSet) - { - for (Block3DMap::value_type b : blockMap) - { - SPtr<Block3D> block = b.second; - block->deleteConnectors(); - //block->deleteInterpolationConnectors(); - } - } + for (Block3DMap blockMap : levelSet) { + for (Block3DMap::value_type b : blockMap) { + SPtr<Block3D> block = b.second; + block->deleteConnectors(); + // block->deleteInterpolationConnectors(); + } + } } ////////////////////////////////////////////////////////////////////////// -void Grid3D::setRank(int rank) -{ - this->rank = rank; -} +void Grid3D::setRank(int rank) { this->rank = rank; } ////////////////////////////////////////////////////////////////////////// -int Grid3D::getRank() const -{ - return rank; -} +int Grid3D::getRank() const { return rank; } ////////////////////////////////////////////////////////////////////////// -int Grid3D::getBundle() const -{ - return bundle; -} +int Grid3D::getBundle() const { return bundle; } ////////////////////////////////////////////////////////////////////////// -void Grid3D::setBundle(int bundle) -{ - this->bundle = bundle; -} +void Grid3D::setBundle(int bundle) { this->bundle = bundle; } ////////////////////////////////////////////////////////////////////////// -bool Grid3D::isPeriodicX1() const -{ - return this->periodicX1; -} +bool Grid3D::isPeriodicX1() const { return this->periodicX1; } ////////////////////////////////////////////////////////////////////////// -bool Grid3D::isPeriodicX2() const -{ - return this->periodicX2; -} +bool Grid3D::isPeriodicX2() const { return this->periodicX2; } ////////////////////////////////////////////////////////////////////////// -bool Grid3D::isPeriodicX3() const -{ - return this->periodicX3; -} +bool Grid3D::isPeriodicX3() const { return this->periodicX3; } ////////////////////////////////////////////////////////////////////////// -void Grid3D::setPeriodicX1(bool value) -{ - this->periodicX1 = value; -} +void Grid3D::setPeriodicX1(bool value) { this->periodicX1 = value; } ////////////////////////////////////////////////////////////////////////// -void Grid3D::setPeriodicX2(bool value) -{ - this->periodicX2 = value; -} +void Grid3D::setPeriodicX2(bool value) { this->periodicX2 = value; } ////////////////////////////////////////////////////////////////////////// -void Grid3D::setPeriodicX3(bool value) -{ - this->periodicX3 = value; -} +void Grid3D::setPeriodicX3(bool value) { this->periodicX3 = value; } ////////////////////////////////////////////////////////////////////////// -UbTupleInt3 Grid3D::getBlockIndexes(double blockX1Coord, double blockX2Coord, double blockX3Coord) const +UbTupleInt3 Grid3D::getBlockIndexes(double blockX1Coord, double blockX2Coord, double blockX3Coord) const { - if (!trafo) - { - return makeUbTuple((int)blockX1Coord, (int)blockX2Coord, (int)blockX3Coord); - } - - return makeUbTuple((int)trafo->transformForwardToX1Coordinate(blockX1Coord, blockX2Coord, blockX3Coord) - , (int)trafo->transformForwardToX2Coordinate(blockX1Coord, blockX2Coord, blockX3Coord) - , (int)trafo->transformForwardToX3Coordinate(blockX1Coord, blockX2Coord, blockX3Coord)); + if (!trafo) { + return makeUbTuple((int)blockX1Coord, (int)blockX2Coord, (int)blockX3Coord); + } + return makeUbTuple((int)trafo->transformForwardToX1Coordinate(blockX1Coord, blockX2Coord, blockX3Coord), + (int)trafo->transformForwardToX2Coordinate(blockX1Coord, blockX2Coord, blockX3Coord), + (int)trafo->transformForwardToX3Coordinate(blockX1Coord, blockX2Coord, blockX3Coord)); } ////////////////////////////////////////////////////////////////////////// -UbTupleInt3 Grid3D::getBlockIndexes(double blockX1Coord, double blockX2Coord, double blockX3Coord, int level) const +UbTupleInt3 Grid3D::getBlockIndexes(double blockX1Coord, double blockX2Coord, double blockX3Coord, int level) const { - if (!trafo) - { - return makeUbTuple((int)blockX1Coord, (int)blockX2Coord, (int)blockX3Coord); - } - - double dx = getDeltaX(level); - double blockLentghX1, blockLentghX2, blockLentghX3; - blockLentghX1 = blockNx1 * dx; - blockLentghX2 = blockNx2 * dx; - blockLentghX3 = blockNx3 * dx; - UbTupleDouble3 org = getBlockWorldCoordinates(0, 0, 0, 0); + if (!trafo) { + return makeUbTuple((int)blockX1Coord, (int)blockX2Coord, (int)blockX3Coord); + } - SPtr<CoordinateTransformation3D> trafo_temp(new CoordinateTransformation3D(val<1>(org), val<2>(org), val<3>(org), blockLentghX1, blockLentghX2, blockLentghX3)); + double dx = getDeltaX(level); + double blockLentghX1, blockLentghX2, blockLentghX3; + blockLentghX1 = blockNx1 * dx; + blockLentghX2 = blockNx2 * dx; + blockLentghX3 = blockNx3 * dx; + UbTupleDouble3 org = getBlockWorldCoordinates(0, 0, 0, 0); - if (!trafo_temp) - { - return makeUbTuple((int)blockX1Coord, (int)blockX2Coord, (int)blockX3Coord); - } + SPtr<CoordinateTransformation3D> trafo_temp(new CoordinateTransformation3D( + val<1>(org), val<2>(org), val<3>(org), blockLentghX1, blockLentghX2, blockLentghX3)); - return makeUbTuple((int)trafo_temp->transformForwardToX1Coordinate(blockX1Coord, blockX2Coord, blockX3Coord) - , (int)trafo_temp->transformForwardToX2Coordinate(blockX1Coord, blockX2Coord, blockX3Coord) - , (int)trafo_temp->transformForwardToX3Coordinate(blockX1Coord, blockX2Coord, blockX3Coord)); + if (!trafo_temp) { + return makeUbTuple((int)blockX1Coord, (int)blockX2Coord, (int)blockX3Coord); + } + return makeUbTuple((int)trafo_temp->transformForwardToX1Coordinate(blockX1Coord, blockX2Coord, blockX3Coord), + (int)trafo_temp->transformForwardToX2Coordinate(blockX1Coord, blockX2Coord, blockX3Coord), + (int)trafo_temp->transformForwardToX3Coordinate(blockX1Coord, blockX2Coord, blockX3Coord)); } ////////////////////////////////////////////////////////////////////////// -UbTupleDouble3 Grid3D::getBlockLengths(const SPtr<Block3D> block) const +UbTupleDouble3 Grid3D::getBlockLengths(const SPtr<Block3D> block) const { - int level = block->getLevel(); - double delta = 1.0 / (double)(1 << level); + int level = block->getLevel(); + double delta = 1.0 / (double)(1 << level); - if (!trafo) makeUbTuple<double, double, double>(delta, delta, delta); + if (!trafo) + makeUbTuple<double, double, double>(delta, delta, delta); - return makeUbTuple(trafo->getX1CoordinateScaling() * delta, - trafo->getX2CoordinateScaling() * delta, - trafo->getX3CoordinateScaling() * delta); + return makeUbTuple(trafo->getX1CoordinateScaling() * delta, trafo->getX2CoordinateScaling() * delta, + trafo->getX3CoordinateScaling() * delta); } ////////////////////////////////////////////////////////////////////////// -UbTupleDouble6 Grid3D::getBlockOversize() const -{ - return makeUbTuple(0.0, 0.0, 0.0, 0.0, 0.0, 0.0); -} +UbTupleDouble6 Grid3D::getBlockOversize() const { return makeUbTuple(0.0, 0.0, 0.0, 0.0, 0.0, 0.0); } ////////////////////////////////////////////////////////////////////////// -void Grid3D::setCoordinateTransformator(SPtr<CoordinateTransformation3D> trafo) -{ - this->trafo = trafo; -} +void Grid3D::setCoordinateTransformator(SPtr<CoordinateTransformation3D> trafo) { this->trafo = trafo; } ////////////////////////////////////////////////////////////////////////// -const SPtr<CoordinateTransformation3D> Grid3D::getCoordinateTransformator() const -{ - return this->trafo; -} +const SPtr<CoordinateTransformation3D> Grid3D::getCoordinateTransformator() const { return this->trafo; } ////////////////////////////////////////////////////////////////////////// -void Grid3D::setDeltaX(double dx) -{ - this->orgDeltaX = dx; -} +void Grid3D::setDeltaX(double dx) { this->orgDeltaX = dx; } ////////////////////////////////////////////////////////////////////////// -void Grid3D::setDeltaX(double worldUnit, double gridUnit) -{ - this->orgDeltaX = worldUnit / gridUnit; -} +void Grid3D::setDeltaX(double worldUnit, double gridUnit) { this->orgDeltaX = worldUnit / gridUnit; } ////////////////////////////////////////////////////////////////////////// double Grid3D::getDeltaX(int level) const { - double delta = this->orgDeltaX / (double)(1 << level); - return delta; + double delta = this->orgDeltaX / (double)(1 << level); + return delta; } ////////////////////////////////////////////////////////////////////////// -double Grid3D::getDeltaX(SPtr<Block3D> block) const -{ - return getDeltaX(block->getLevel()); -} +double Grid3D::getDeltaX(SPtr<Block3D> block) const { return getDeltaX(block->getLevel()); } ////////////////////////////////////////////////////////////////////////// -UbTupleDouble3 Grid3D::getNodeOffset(SPtr<Block3D> block) const +UbTupleDouble3 Grid3D::getNodeOffset(SPtr<Block3D> block) const { - double delta = this->getDeltaX(block); - return makeUbTuple(OFFSET * delta, OFFSET * delta, OFFSET * delta); + double delta = this->getDeltaX(block); + return makeUbTuple(OFFSET * delta, OFFSET * delta, OFFSET * delta); } //////////////////////////////////////////////////////////////////////////// Vector3D Grid3D::getNodeCoordinates(SPtr<Block3D> block, int ix1, int ix2, int ix3) const { - UbTupleDouble3 org = this->getBlockWorldCoordinates(block); - UbTupleDouble3 nodeOffset = this->getNodeOffset(block); - double deltaX = getDeltaX(block); + UbTupleDouble3 org = this->getBlockWorldCoordinates(block); + UbTupleDouble3 nodeOffset = this->getNodeOffset(block); + double deltaX = getDeltaX(block); - double x1 = val<1>(org) - val<1>(nodeOffset) + (double)ix1 * deltaX; - double x2 = val<2>(org) - val<2>(nodeOffset) + (double)ix2 * deltaX; - double x3 = val<3>(org) - val<3>(nodeOffset) + (double)ix3 * deltaX; + double x1 = val<1>(org) - val<1>(nodeOffset) + (double)ix1 * deltaX; + double x2 = val<2>(org) - val<2>(nodeOffset) + (double)ix2 * deltaX; + double x3 = val<3>(org) - val<3>(nodeOffset) + (double)ix3 * deltaX; - return Vector3D(x1, x2, x3); + return Vector3D(x1, x2, x3); } //////////////////////////////////////////////////////////////////////////// -UbTupleInt3 Grid3D::getNodeIndexes(SPtr<Block3D> block, double nodeX1Coord, double nodeX2Coord, double nodeX3Coord) const -{ - UbTupleDouble3 org = this->getBlockWorldCoordinates(block); - UbTupleDouble3 nodeOffset = this->getNodeOffset(block); - double deltaX = getDeltaX(block); - - int ix1, ix2, ix3; - double ixx1 = (abs(nodeX1Coord - val<1>(org) + val<1>(nodeOffset)) / deltaX); - double ixx2 = (abs(nodeX2Coord - val<2>(org) + val<2>(nodeOffset)) / deltaX); - double ixx3 = (abs(nodeX3Coord - val<3>(org) + val<3>(nodeOffset)) / deltaX); - if (ixx1 - (int)ixx1 > .9999999999) ix1 = (int)ixx1 + 1; else ix1 = (int)ixx1; - if (ixx2 - (int)ixx2 > .9999999999) ix2 = (int)ixx2 + 1; else ix2 = (int)ixx2; - if (ixx3 - (int)ixx3 > .9999999999) ix3 = (int)ixx3 + 1; else ix3 = (int)ixx3; - - return makeUbTuple(ix1, ix2, ix3); -} -////////////////////////////////////////////////////////////////////////// -//returns tuple with origin of block in world-coordinates +UbTupleInt3 Grid3D::getNodeIndexes(SPtr<Block3D> block, double nodeX1Coord, double nodeX2Coord, + double nodeX3Coord) const +{ + UbTupleDouble3 org = this->getBlockWorldCoordinates(block); + UbTupleDouble3 nodeOffset = this->getNodeOffset(block); + double deltaX = getDeltaX(block); + + int ix1, ix2, ix3; + double ixx1 = (abs(nodeX1Coord - val<1>(org) + val<1>(nodeOffset)) / deltaX); + double ixx2 = (abs(nodeX2Coord - val<2>(org) + val<2>(nodeOffset)) / deltaX); + double ixx3 = (abs(nodeX3Coord - val<3>(org) + val<3>(nodeOffset)) / deltaX); + if (ixx1 - (int)ixx1 > .9999999999) + ix1 = (int)ixx1 + 1; + else + ix1 = (int)ixx1; + if (ixx2 - (int)ixx2 > .9999999999) + ix2 = (int)ixx2 + 1; + else + ix2 = (int)ixx2; + if (ixx3 - (int)ixx3 > .9999999999) + ix3 = (int)ixx3 + 1; + else + ix3 = (int)ixx3; + + return makeUbTuple(ix1, ix2, ix3); +} +////////////////////////////////////////////////////////////////////////// +// returns tuple with origin of block in world-coordinates UbTupleDouble3 Grid3D::getBlockWorldCoordinates(SPtr<Block3D> block) const { - if (!block) - throw UbException(UB_EXARGS, "block " + block->toString() + "is not exist"); + if (!block) + throw UbException(UB_EXARGS, "block " + block->toString() + "is not exist"); - int blockX1Index = block->getX1(); - int blockX2Index = block->getX2(); - int blockX3Index = block->getX3(); - int level = block->getLevel(); + int blockX1Index = block->getX1(); + int blockX2Index = block->getX2(); + int blockX3Index = block->getX3(); + int level = block->getLevel(); - return this->getBlockWorldCoordinates(blockX1Index, blockX2Index, blockX3Index, level); + return this->getBlockWorldCoordinates(blockX1Index, blockX2Index, blockX3Index, level); } ////////////////////////////////////////////////////////////////////////// UbTupleDouble3 Grid3D::getBlockWorldCoordinates(int blockX1Index, int blockX2Index, int blockX3Index, int level) const { - double c1oShiftedLevel = 1.0 / (double)(1 << level); - double x1 = (double)blockX1Index * c1oShiftedLevel; - double x2 = (double)blockX2Index * c1oShiftedLevel; - double x3 = (double)blockX3Index * c1oShiftedLevel; + double c1oShiftedLevel = 1.0 / (double)(1 << level); + double x1 = (double)blockX1Index * c1oShiftedLevel; + double x2 = (double)blockX2Index * c1oShiftedLevel; + double x3 = (double)blockX3Index * c1oShiftedLevel; - if (!trafo) - return { x1, x2, x3 }; + if (!trafo) + return { x1, x2, x3 }; - return {trafo->transformBackwardToX1Coordinate(x1, x2, x3) - , trafo->transformBackwardToX2Coordinate(x1, x2, x3) - , trafo->transformBackwardToX3Coordinate(x1, x2, x3) }; + return { trafo->transformBackwardToX1Coordinate(x1, x2, x3), trafo->transformBackwardToX2Coordinate(x1, x2, x3), + trafo->transformBackwardToX3Coordinate(x1, x2, x3) }; } ////////////////////////////////////////////////////////////////////////// -//double Grid3D::getDeltaT(SPtr<Block3D> block) const -//{ +// double Grid3D::getDeltaT(SPtr<Block3D> block) const +//{ // int level = block->getLevel(); // double delta = 1.0/(double)(1<<level); -// return delta; +// return delta; //} ////////////////////////////////////////////////////////////////////////// void Grid3D::checkLevel(int level) { - if (level < 0) - { - throw UbException(UB_EXARGS, "l(" + UbSystem::toString(level) + (string)")<0"); - } - if (level > Grid3DSystem::MAXLEVEL) - { - throw UbException(UB_EXARGS, "l(" + UbSystem::toString(level) + (string)")>MAXLEVEL"); - } - if (this->levelSet[level].size() == 0) - { - throw UbException(UB_EXARGS, "levelMap for level(" + UbSystem::toString(level) + (string)")==NULL"); - } + if (level < 0) { + throw UbException(UB_EXARGS, "l(" + UbSystem::toString(level) + (string) ")<0"); + } + if (level > Grid3DSystem::MAXLEVEL) { + throw UbException(UB_EXARGS, "l(" + UbSystem::toString(level) + (string) ")>MAXLEVEL"); + } + if (this->levelSet[level].size() == 0) { + throw UbException(UB_EXARGS, "levelMap for level(" + UbSystem::toString(level) + (string) ")==NULL"); + } } ////////////////////////////////////////////////////////////////////////// bool Grid3D::hasLevel(int level) const { - if (level < 0) return false; - if (level > Grid3DSystem::MAXLEVEL) return false; - if (this->levelSet[level].size() == 0) return false; + if (level < 0) + return false; + if (level > Grid3DSystem::MAXLEVEL) + return false; + if (this->levelSet[level].size() == 0) + return false; - return true; + return true; } ////////////////////////////////////////////////////////////////////////// void Grid3D::setBlockNX(int nx1, int nx2, int nx3) { - blockNx1 = nx1; - blockNx2 = nx2; - blockNx3 = nx3; + blockNx1 = nx1; + blockNx2 = nx2; + blockNx3 = nx3; } ////////////////////////////////////////////////////////////////////////// -UbTupleInt3 Grid3D::getBlockNX() const -{ - return makeUbTuple(blockNx1, blockNx2, blockNx3); -} +UbTupleInt3 Grid3D::getBlockNX() const { return makeUbTuple(blockNx1, blockNx2, blockNx3); } ////////////////////////////////////////////////////////////////////////// SPtr<Block3D> Grid3D::getNeighborBlock(int dir, int ix1, int ix2, int ix3, int level) const { - return this->getBlock(ix1 + Grid3DSystem::EX1[dir], ix2 + Grid3DSystem::EX2[dir], ix3 + Grid3DSystem::EX3[dir], level); + return this->getBlock(ix1 + Grid3DSystem::EX1[dir], ix2 + Grid3DSystem::EX2[dir], ix3 + Grid3DSystem::EX3[dir], + level); } ////////////////////////////////////////////////////////////////////////// SPtr<Block3D> Grid3D::getNeighborBlock(int dir, SPtr<Block3D> block) const { - int x1 = block->getX1(); - int x2 = block->getX2(); - int x3 = block->getX3(); - int level = block->getLevel(); - return this->getNeighborBlock(dir, x1, x2, x3, level); + int x1 = block->getX1(); + int x2 = block->getX2(); + int x3 = block->getX3(); + int level = block->getLevel(); + return this->getNeighborBlock(dir, x1, x2, x3, level); } ////////////////////////////////////////////////////////////////////////// -void Grid3D::getAllNeighbors(int ix1, int ix2, int ix3, int level, int levelDepth, std::vector<SPtr<Block3D>>& blocks) +void Grid3D::getAllNeighbors(int ix1, int ix2, int ix3, int level, int levelDepth, std::vector<SPtr<Block3D>> &blocks) { - for (int dir = Grid3DSystem::STARTDIR; dir <= Grid3DSystem::ENDDIR; dir++) - //for (int dir = Grid3DSystem::STARTDIR; dir<=Grid3DSystem::TS; dir++) - { - this->getNeighborBlocksForDirection(dir, ix1, ix2, ix3, level, levelDepth, blocks); - } + for (int dir = Grid3DSystem::STARTDIR; dir <= Grid3DSystem::ENDDIR; dir++) + // for (int dir = Grid3DSystem::STARTDIR; dir<=Grid3DSystem::TS; dir++) + { + this->getNeighborBlocksForDirection(dir, ix1, ix2, ix3, level, levelDepth, blocks); + } } ////////////////////////////////////////////////////////////////////////// -void Grid3D::getAllNeighbors(SPtr<Block3D> block, int level, int levelDepth, std::vector<SPtr<Block3D>>& blocks) +void Grid3D::getAllNeighbors(SPtr<Block3D> block, int level, int levelDepth, std::vector<SPtr<Block3D>> &blocks) { - int x1 = block->getX1(); - int x2 = block->getX2(); - int x3 = block->getX3(); - getAllNeighbors(x1, x2, x3, level, levelDepth, blocks); + int x1 = block->getX1(); + int x2 = block->getX2(); + int x3 = block->getX3(); + getAllNeighbors(x1, x2, x3, level, levelDepth, blocks); } ////////////////////////////////////////////////////////////////////////// - /** - * Returns all direct northern neighbor cells of the specified grid cell (may be NULL!). - * @param ix1 index in x1 direction - * @param ix2 index in x2 direction - * @param ix3 index in x3 direction - * @param level the level - */ -void Grid3D::getNeighborsNorth(int ix1, int ix2, int ix3, int level, int levelDepth, std::vector<SPtr<Block3D>>& blocks) +/** + * Returns all direct northern neighbor cells of the specified grid cell (may be NULL!). + * @param ix1 index in x1 direction + * @param ix2 index in x2 direction + * @param ix3 index in x3 direction + * @param level the level + */ +void Grid3D::getNeighborsNorth(int ix1, int ix2, int ix3, int level, int levelDepth, std::vector<SPtr<Block3D>> &blocks) { - SPtr<Block3D> block = this->getBlock(ix1, ix2 + 1, ix3, level); - if (block) { blocks.push_back(block); } + SPtr<Block3D> block = this->getBlock(ix1, ix2 + 1, ix3, level); + if (block) { + blocks.push_back(block); + } - if (level > 0) - { - block = this->getSuperBlock(ix1, ix2 + 1, ix3, level); - if (block) { blocks.push_back(block); } - } - this->getSubBlocksSouth(ix1, ix2 + 1, ix3, level, blocks, levelDepth); + if (level > 0) { + block = this->getSuperBlock(ix1, ix2 + 1, ix3, level); + if (block) { + blocks.push_back(block); + } + } + this->getSubBlocksSouth(ix1, ix2 + 1, ix3, level, blocks, levelDepth); } ////////////////////////////////////////////////////////////////////////// -void Grid3D::getNeighborsTop(int ix1, int ix2, int ix3, int level, int levelDepth, std::vector<SPtr<Block3D>>& blocks) +void Grid3D::getNeighborsTop(int ix1, int ix2, int ix3, int level, int levelDepth, std::vector<SPtr<Block3D>> &blocks) { - SPtr<Block3D> block = this->getBlock(ix1, ix2, ix3 + 1, level); - if (block) { blocks.push_back(block); } + SPtr<Block3D> block = this->getBlock(ix1, ix2, ix3 + 1, level); + if (block) { + blocks.push_back(block); + } - if (level > 0) - { - block = this->getSuperBlock(ix1, ix2, ix3 + 1, level); - if (block) { blocks.push_back(block); } - } - this->getSubBlocksBottom(ix1, ix2, ix3 + 1, level, blocks, levelDepth); + if (level > 0) { + block = this->getSuperBlock(ix1, ix2, ix3 + 1, level); + if (block) { + blocks.push_back(block); + } + } + this->getSubBlocksBottom(ix1, ix2, ix3 + 1, level, blocks, levelDepth); } ////////////////////////////////////////////////////////////////////////// -void Grid3D::getNeighborsBottom(int ix1, int ix2, int ix3, int level, int levelDepth, std::vector<SPtr<Block3D>>& blocks) +void Grid3D::getNeighborsBottom(int ix1, int ix2, int ix3, int level, int levelDepth, + std::vector<SPtr<Block3D>> &blocks) { - SPtr<Block3D> block = this->getBlock(ix1, ix2, ix3 - 1, level); - if (block) { blocks.push_back(block); } - - if (level > 0) - { - block = this->getSuperBlock(ix1, ix2, ix3 - 1, level); - if (block) { blocks.push_back(block); } + SPtr<Block3D> block = this->getBlock(ix1, ix2, ix3 - 1, level); + if (block) { + blocks.push_back(block); + } - } - this->getSubBlocksTop(ix1, ix2, ix3 - 1, level, blocks, levelDepth); -} + if (level > 0) { + block = this->getSuperBlock(ix1, ix2, ix3 - 1, level); + if (block) { + blocks.push_back(block); + } + } + this->getSubBlocksTop(ix1, ix2, ix3 - 1, level, blocks, levelDepth); +} ////////////////////////////////////////////////////////////////////////// -void Grid3D::getNeighborsSouth(int ix1, int ix2, int ix3, int level, int levelDepth, std::vector<SPtr<Block3D>>& blocks) +void Grid3D::getNeighborsSouth(int ix1, int ix2, int ix3, int level, int levelDepth, std::vector<SPtr<Block3D>> &blocks) { - SPtr<Block3D> block = this->getBlock(ix1, ix2 - 1, ix3, level); - if (block) { blocks.push_back(block); } - - if (level > 0) - { - block = this->getSuperBlock(ix1, ix2 - 1, ix3, level); - if (block) { blocks.push_back(block); } + SPtr<Block3D> block = this->getBlock(ix1, ix2 - 1, ix3, level); + if (block) { + blocks.push_back(block); + } - } - this->getSubBlocksNorth(ix1, ix2 - 1, ix3, level, blocks, levelDepth); -} -////////////////////////////////////////////////////////////////////////// -void Grid3D::getNeighborsEast(int ix1, int ix2, int ix3, int level, int levelDepth, std::vector<SPtr<Block3D>>& blocks) + if (level > 0) { + block = this->getSuperBlock(ix1, ix2 - 1, ix3, level); + if (block) { + blocks.push_back(block); + } + } + this->getSubBlocksNorth(ix1, ix2 - 1, ix3, level, blocks, levelDepth); +} +////////////////////////////////////////////////////////////////////////// +void Grid3D::getNeighborsEast(int ix1, int ix2, int ix3, int level, int levelDepth, std::vector<SPtr<Block3D>> &blocks) { - SPtr<Block3D> block = this->getBlock(ix1 + 1, ix2, ix3, level); - if (block) { blocks.push_back(block); } - - if (level > 0) - { - block = this->getSuperBlock(ix1 + 1, ix2, ix3, level); - if (block) { blocks.push_back(block); } - } - this->getSubBlocksWest(ix1 + 1, ix2, ix3, level, blocks, levelDepth); -} -////////////////////////////////////////////////////////////////////////// -void Grid3D::getNeighborsWest(int ix1, int ix2, int ix3, int level, int levelDepth, std::vector<SPtr<Block3D>>& blocks) -{ - SPtr<Block3D> block = this->getBlock(ix1 - 1, ix2, ix3, level); - if (block) { blocks.push_back(block); } + SPtr<Block3D> block = this->getBlock(ix1 + 1, ix2, ix3, level); + if (block) { + blocks.push_back(block); + } + if (level > 0) { + block = this->getSuperBlock(ix1 + 1, ix2, ix3, level); + if (block) { + blocks.push_back(block); + } + } + this->getSubBlocksWest(ix1 + 1, ix2, ix3, level, blocks, levelDepth); +} +////////////////////////////////////////////////////////////////////////// +void Grid3D::getNeighborsWest(int ix1, int ix2, int ix3, int level, int levelDepth, std::vector<SPtr<Block3D>> &blocks) +{ + SPtr<Block3D> block = this->getBlock(ix1 - 1, ix2, ix3, level); + if (block) { + blocks.push_back(block); + } + + if (level > 0) { + block = this->getSuperBlock(ix1 - 1, ix2, ix3, level); + if (block) { + blocks.push_back(block); + } + } + this->getSubBlocksEast(ix1 - 1, ix2, ix3, level, blocks, levelDepth); +} +////////////////////////////////////////////////////////////////////////// +// diagonals +////////////////////////////////////////////////////////////////////////// +void Grid3D::getNeighborsNorthEast(int ix1, int ix2, int ix3, int level, int levelDepth, + std::vector<SPtr<Block3D>> &blocks) +{ + SPtr<Block3D> block = this->getBlock(ix1 + 1, ix2 + 1, ix3, level); + if (block) { + blocks.push_back(block); + } - if (level > 0) - { - block = this->getSuperBlock(ix1 - 1, ix2, ix3, level); - if (block) { blocks.push_back(block); } - } - this->getSubBlocksEast(ix1 - 1, ix2, ix3, level, blocks, levelDepth); + if (level > 0) { + block = this->getSuperBlock(ix1 + 1, ix2 + 1, ix3, level); + if (block) { + blocks.push_back(block); + } + } + this->getSubBlocksSouthWest(ix1 + 1, ix2 + 1, ix3, level, blocks, levelDepth); } -////////////////////////////////////////////////////////////////////////// -// diagonals -////////////////////////////////////////////////////////////////////////// -void Grid3D::getNeighborsNorthEast(int ix1, int ix2, int ix3, int level, int levelDepth, std::vector<SPtr<Block3D>>& blocks) -{ - SPtr<Block3D> block = this->getBlock(ix1 + 1, ix2 + 1, ix3, level); - if (block) { blocks.push_back(block); } - - if (level > 0) - { - block = this->getSuperBlock(ix1 + 1, ix2 + 1, ix3, level); - if (block) { blocks.push_back(block); } - } - this->getSubBlocksSouthWest(ix1 + 1, ix2 + 1, ix3, level, blocks, levelDepth); +////////////////////////////////////////////////////////////////////////// +void Grid3D::getNeighborsNorthWest(int ix1, int ix2, int ix3, int level, int levelDepth, + std::vector<SPtr<Block3D>> &blocks) +{ + SPtr<Block3D> block = this->getBlock(ix1 - 1, ix2 + 1, ix3, level); + if (block) { + blocks.push_back(block); + } + + if (level > 0) { + block = this->getSuperBlock(ix1 - 1, ix2 + 1, ix3, level); + if (block) { + blocks.push_back(block); + } + } + this->getSubBlocksSouthEast(ix1 - 1, ix2 + 1, ix3, level, blocks, levelDepth); +} +////////////////////////////////////////////////////////////////////////// +void Grid3D::getNeighborsSouthEast(int ix1, int ix2, int ix3, int level, int levelDepth, + std::vector<SPtr<Block3D>> &blocks) +{ + SPtr<Block3D> block = this->getBlock(ix1 + 1, ix2 - 1, ix3, level); + if (block) { + blocks.push_back(block); + } + + if (level > 0) { + block = this->getSuperBlock(ix1 + 1, ix2 - 1, ix3, level); + if (block) { + blocks.push_back(block); + } + } + this->getSubBlocksNorthWest(ix1 + 1, ix2 - 1, ix3, level, blocks, levelDepth); } -////////////////////////////////////////////////////////////////////////// -void Grid3D::getNeighborsNorthWest(int ix1, int ix2, int ix3, int level, int levelDepth, std::vector<SPtr<Block3D>>& blocks) -{ - SPtr<Block3D> block = this->getBlock(ix1 - 1, ix2 + 1, ix3, level); - if (block) { blocks.push_back(block); } +////////////////////////////////////////////////////////////////////////// +void Grid3D::getNeighborsSouthWest(int ix1, int ix2, int ix3, int level, int levelDepth, + std::vector<SPtr<Block3D>> &blocks) +{ + SPtr<Block3D> block = this->getBlock(ix1 - 1, ix2 - 1, ix3, level); + if (block) { + blocks.push_back(block); + } + + if (level > 0) { + block = this->getSuperBlock(ix1 - 1, ix2 - 1, ix3, level); + if (block) { + blocks.push_back(block); + } + } + this->getSubBlocksNorthEast(ix1 - 1, ix2 - 1, ix3, level, blocks, levelDepth); +} +////////////////////////////////////////////////////////////////////////// +// diagonals top +////////////////////////////////////////////////////////////////////////// +void Grid3D::getNeighborsTopEast(int ix1, int ix2, int ix3, int level, int levelDepth, + std::vector<SPtr<Block3D>> &blocks) +{ + SPtr<Block3D> block = this->getBlock(ix1 + 1, ix2, ix3 + 1, level); + if (block) { + blocks.push_back(block); + } - if (level > 0) - { - block = this->getSuperBlock(ix1 - 1, ix2 + 1, ix3, level); - if (block) { blocks.push_back(block); } - } - this->getSubBlocksSouthEast(ix1 - 1, ix2 + 1, ix3, level, blocks, levelDepth); -} -////////////////////////////////////////////////////////////////////////// -void Grid3D::getNeighborsSouthEast(int ix1, int ix2, int ix3, int level, int levelDepth, std::vector<SPtr<Block3D>>& blocks) -{ - SPtr<Block3D> block = this->getBlock(ix1 + 1, ix2 - 1, ix3, level); - if (block) { blocks.push_back(block); } - - if (level > 0) - { - block = this->getSuperBlock(ix1 + 1, ix2 - 1, ix3, level); - if (block) { blocks.push_back(block); } - } - this->getSubBlocksNorthWest(ix1 + 1, ix2 - 1, ix3, level, blocks, levelDepth); -} -////////////////////////////////////////////////////////////////////////// -void Grid3D::getNeighborsSouthWest(int ix1, int ix2, int ix3, int level, int levelDepth, std::vector<SPtr<Block3D>>& blocks) -{ - SPtr<Block3D> block = this->getBlock(ix1 - 1, ix2 - 1, ix3, level); - if (block) { blocks.push_back(block); } - - if (level > 0) - { - block = this->getSuperBlock(ix1 - 1, ix2 - 1, ix3, level); - if (block) { blocks.push_back(block); } - } - this->getSubBlocksNorthEast(ix1 - 1, ix2 - 1, ix3, level, blocks, levelDepth); -} -////////////////////////////////////////////////////////////////////////// -// diagonals top -////////////////////////////////////////////////////////////////////////// -void Grid3D::getNeighborsTopEast(int ix1, int ix2, int ix3, int level, int levelDepth, std::vector<SPtr<Block3D>>& blocks) -{ - SPtr<Block3D> block = this->getBlock(ix1 + 1, ix2, ix3 + 1, level); - if (block) { blocks.push_back(block); } - - if (level > 0) - { - block = this->getSuperBlock(ix1 + 1, ix2, ix3 + 1, level); - if (block) { blocks.push_back(block); } - } - this->getSubBlocksBottomWest(ix1 + 1, ix2, ix3 + 1, level, blocks, levelDepth); -} -////////////////////////////////////////////////////////////////////////// -void Grid3D::getNeighborsTopWest(int ix1, int ix2, int ix3, int level, int levelDepth, std::vector<SPtr<Block3D>>& blocks) -{ - SPtr<Block3D> block = this->getBlock(ix1 - 1, ix2, ix3 + 1, level); - if (block) { blocks.push_back(block); } - - if (level > 0) - { - block = this->getSuperBlock(ix1 - 1, ix2, ix3 + 1, level); - if (block) { blocks.push_back(block); } - } - this->getSubBlocksBottomEast(ix1 - 1, ix2, ix3 + 1, level, blocks, levelDepth); -} -////////////////////////////////////////////////////////////////////////// -void Grid3D::getNeighborsTopNorth(int ix1, int ix2, int ix3, int level, int levelDepth, std::vector<SPtr<Block3D>>& blocks) -{ - SPtr<Block3D> block = this->getBlock(ix1, ix2 + 1, ix3 + 1, level); - if (block) { blocks.push_back(block); } - - if (level > 0) - { - block = this->getSuperBlock(ix1, ix2 + 1, ix3 + 1, level); - if (block) { blocks.push_back(block); } - } - this->getSubBlocksBottomSouth(ix1, ix2 + 1, ix3 + 1, level, blocks, levelDepth); -} -////////////////////////////////////////////////////////////////////////// -void Grid3D::getNeighborsTopSouth(int ix1, int ix2, int ix3, int level, int levelDepth, std::vector<SPtr<Block3D>>& blocks) -{ - SPtr<Block3D> block = this->getBlock(ix1, ix2 - 1, ix3 + 1, level); - if (block) { blocks.push_back(block); } - - if (level > 0) - { - block = this->getSuperBlock(ix1, ix2 - 1, ix3 + 1, level); - if (block) { blocks.push_back(block); } - } - this->getSubBlocksBottomNorth(ix1, ix2 - 1, ix3 + 1, level, blocks, levelDepth); -} -////////////////////////////////////////////////////////////////////////// -// diagonals bottom -////////////////////////////////////////////////////////////////////////// -void Grid3D::getNeighborsBottomEast(int ix1, int ix2, int ix3, int level, int levelDepth, std::vector<SPtr<Block3D>>& blocks) -{ - SPtr<Block3D> block = this->getBlock(ix1 + 1, ix2, ix3 - 1, level); - if (block) { blocks.push_back(block); } - - if (level > 0) - { - block = this->getSuperBlock(ix1 + 1, ix2, ix3 - 1, level); - if (block) { blocks.push_back(block); } - } - this->getSubBlocksTopWest(ix1 + 1, ix2, ix3 - 1, level, blocks, levelDepth); -} -////////////////////////////////////////////////////////////////////////// -void Grid3D::getNeighborsBottomWest(int ix1, int ix2, int ix3, int level, int levelDepth, std::vector<SPtr<Block3D>>& blocks) -{ - SPtr<Block3D> block = this->getBlock(ix1 - 1, ix2, ix3 - 1, level); - if (block) { blocks.push_back(block); } - - if (level > 0) - { - block = this->getSuperBlock(ix1 - 1, ix2, ix3 - 1, level); - if (block) { blocks.push_back(block); } - } - this->getSubBlocksTopEast(ix1 - 1, ix2, ix3 - 1, level, blocks, levelDepth); -} -////////////////////////////////////////////////////////////////////////// -void Grid3D::getNeighborsBottomNorth(int ix1, int ix2, int ix3, int level, int levelDepth, std::vector<SPtr<Block3D>>& blocks) -{ - SPtr<Block3D> block = this->getBlock(ix1, ix2 + 1, ix3 - 1, level); - if (block) { blocks.push_back(block); } + if (level > 0) { + block = this->getSuperBlock(ix1 + 1, ix2, ix3 + 1, level); + if (block) { + blocks.push_back(block); + } + } + this->getSubBlocksBottomWest(ix1 + 1, ix2, ix3 + 1, level, blocks, levelDepth); +} +////////////////////////////////////////////////////////////////////////// +void Grid3D::getNeighborsTopWest(int ix1, int ix2, int ix3, int level, int levelDepth, + std::vector<SPtr<Block3D>> &blocks) +{ + SPtr<Block3D> block = this->getBlock(ix1 - 1, ix2, ix3 + 1, level); + if (block) { + blocks.push_back(block); + } - if (level > 0) - { - block = this->getSuperBlock(ix1, ix2 + 1, ix3 - 1, level); - if (block) { blocks.push_back(block); } - } - this->getSubBlocksTopSouth(ix1, ix2 + 1, ix3 - 1, level, blocks, levelDepth); -} -////////////////////////////////////////////////////////////////////////// -void Grid3D::getNeighborsBottomSouth(int ix1, int ix2, int ix3, int level, int levelDepth, std::vector<SPtr<Block3D>>& blocks) -{ - SPtr<Block3D> block = this->getBlock(ix1, ix2 - 1, ix3 - 1, level); - if (block) { blocks.push_back(block); } - - if (level > 0) - { - block = this->getSuperBlock(ix1, ix2 - 1, ix3 - 1, level); - if (block) { blocks.push_back(block); } - } - this->getSubBlocksTopNorth(ix1, ix2 - 1, ix3 - 1, level, blocks, levelDepth); -} -////////////////////////////////////////////////////////////////////////// -void Grid3D::getNeighborsTopNorthEast(int ix1, int ix2, int ix3, int level, int levelDepth, std::vector<SPtr<Block3D>>& blocks) -{ - SPtr<Block3D> block = this->getBlock(ix1 + 1, ix2 + 1, ix3 + 1, level); - if (block) { blocks.push_back(block); } - - if (level > 0) - { - block = this->getSuperBlock(ix1 + 1, ix2 + 1, ix3 + 1, level); - if (block) { blocks.push_back(block); } - } - this->getSubBlocksBottomSouthWest(ix1 + 1, ix2 + 1, ix3 + 1, level, blocks, levelDepth); -} -////////////////////////////////////////////////////////////////////////// -void Grid3D::getNeighborsTopNorthWest(int ix1, int ix2, int ix3, int level, int levelDepth, std::vector<SPtr<Block3D>>& blocks) -{ - SPtr<Block3D> block = this->getBlock(ix1 - 1, ix2 + 1, ix3 + 1, level); - if (block) { blocks.push_back(block); } - - if (level > 0) - { - block = this->getSuperBlock(ix1 - 1, ix2 + 1, ix3 + 1, level); - if (block) { blocks.push_back(block); } - } - this->getSubBlocksBottomSouthEast(ix1 - 1, ix2 + 1, ix3 + 1, level, blocks, levelDepth); -} -////////////////////////////////////////////////////////////////////////// -void Grid3D::getNeighborsTopSouthEast(int ix1, int ix2, int ix3, int level, int levelDepth, std::vector<SPtr<Block3D>>& blocks) -{ - SPtr<Block3D> block = this->getBlock(ix1 + 1, ix2 - 1, ix3 + 1, level); - if (block) { blocks.push_back(block); } - - if (level > 0) - { - block = this->getSuperBlock(ix1 + 1, ix2 - 1, ix3 + 1, level); - if (block) { blocks.push_back(block); } - } - this->getSubBlocksBottomNorthWest(ix1 + 1, ix2 - 1, ix3 + 1, level, blocks, levelDepth); -} -////////////////////////////////////////////////////////////////////////// -void Grid3D::getNeighborsTopSouthWest(int ix1, int ix2, int ix3, int level, int levelDepth, std::vector<SPtr<Block3D>>& blocks) -{ - SPtr<Block3D> block = this->getBlock(ix1 - 1, ix2 - 1, ix3 + 1, level); - if (block) { blocks.push_back(block); } - - if (level > 0) - { - block = this->getSuperBlock(ix1 - 1, ix2 - 1, ix3 + 1, level); - if (block) { blocks.push_back(block); } - } - this->getSubBlocksBottomNorthEast(ix1 - 1, ix2 - 1, ix3 + 1, level, blocks, levelDepth); -} -////////////////////////////////////////////////////////////////////////// -void Grid3D::getNeighborsBottomNorthEast(int ix1, int ix2, int ix3, int level, int levelDepth, std::vector<SPtr<Block3D>>& blocks) -{ - SPtr<Block3D> block = this->getBlock(ix1 + 1, ix2 + 1, ix3 - 1, level); - if (block) { blocks.push_back(block); } - - if (level > 0) - { - block = this->getSuperBlock(ix1 + 1, ix2 + 1, ix3 - 1, level); - if (block) { blocks.push_back(block); } - } - this->getSubBlocksTopSouthWest(ix1 + 1, ix2 + 1, ix3 - 1, level, blocks, levelDepth); -} -////////////////////////////////////////////////////////////////////////// -void Grid3D::getNeighborsBottomNorthWest(int ix1, int ix2, int ix3, int level, int levelDepth, std::vector<SPtr<Block3D>>& blocks) -{ - SPtr<Block3D> block = this->getBlock(ix1 - 1, ix2 + 1, ix3 - 1, level); - if (block) { blocks.push_back(block); } - - if (level > 0) - { - block = this->getSuperBlock(ix1 - 1, ix2 + 1, ix3 - 1, level); - if (block) { blocks.push_back(block); } - } - this->getSubBlocksTopSouthEast(ix1 - 1, ix2 + 1, ix3 - 1, level, blocks, levelDepth); -} -////////////////////////////////////////////////////////////////////////// -void Grid3D::getNeighborsBottomSouthEast(int ix1, int ix2, int ix3, int level, int levelDepth, std::vector<SPtr<Block3D>>& blocks) -{ - SPtr<Block3D> block = this->getBlock(ix1 + 1, ix2 - 1, ix3 - 1, level); - if (block) { blocks.push_back(block); } - - if (level > 0) - { - block = this->getSuperBlock(ix1 + 1, ix2 - 1, ix3 - 1, level); - if (block) { blocks.push_back(block); } - } - this->getSubBlocksTopNorthWest(ix1 + 1, ix2 - 1, ix3 - 1, level, blocks, levelDepth); -} -////////////////////////////////////////////////////////////////////////// -void Grid3D::getNeighborsBottomSouthWest(int ix1, int ix2, int ix3, int level, int levelDepth, std::vector<SPtr<Block3D>>& blocks) -{ - SPtr<Block3D> block = this->getBlock(ix1 - 1, ix2 - 1, ix3 - 1, level); - if (block) { blocks.push_back(block); } - - if (level > 0) - { - block = this->getSuperBlock(ix1 - 1, ix2 - 1, ix3 - 1, level); - if (block) { blocks.push_back(block); } - } - this->getSubBlocksTopNorthEast(ix1 - 1, ix2 - 1, ix3 - 1, level, blocks, levelDepth); -} -////////////////////////////////////////////////////////////////////////// -void Grid3D::getNeighborBlocksForDirection(int dir, int ix1, int ix2, int ix3, int level, int levelDepth, std::vector<SPtr<Block3D>>& blocks) -{ - switch (dir) - { - case Grid3DSystem::E: this->getNeighborsEast(ix1, ix2, ix3, level, levelDepth, blocks); break; - case Grid3DSystem::W: this->getNeighborsWest(ix1, ix2, ix3, level, levelDepth, blocks); break; - case Grid3DSystem::N: this->getNeighborsNorth(ix1, ix2, ix3, level, levelDepth, blocks); break; - case Grid3DSystem::S: this->getNeighborsSouth(ix1, ix2, ix3, level, levelDepth, blocks); break; - case Grid3DSystem::T: this->getNeighborsTop(ix1, ix2, ix3, level, levelDepth, blocks); break; - case Grid3DSystem::B: this->getNeighborsBottom(ix1, ix2, ix3, level, levelDepth, blocks); break; - case Grid3DSystem::NE: this->getNeighborsNorthEast(ix1, ix2, ix3, level, levelDepth, blocks); break; - case Grid3DSystem::SW: this->getNeighborsSouthWest(ix1, ix2, ix3, level, levelDepth, blocks); break; - case Grid3DSystem::SE: this->getNeighborsSouthEast(ix1, ix2, ix3, level, levelDepth, blocks); break; - case Grid3DSystem::NW: this->getNeighborsNorthWest(ix1, ix2, ix3, level, levelDepth, blocks); break; - case Grid3DSystem::TE: this->getNeighborsTopEast(ix1, ix2, ix3, level, levelDepth, blocks); break; - case Grid3DSystem::BW: this->getNeighborsBottomWest(ix1, ix2, ix3, level, levelDepth, blocks); break; - case Grid3DSystem::BE: this->getNeighborsBottomEast(ix1, ix2, ix3, level, levelDepth, blocks); break; - case Grid3DSystem::TW: this->getNeighborsTopWest(ix1, ix2, ix3, level, levelDepth, blocks); break; - case Grid3DSystem::TN: this->getNeighborsTopNorth(ix1, ix2, ix3, level, levelDepth, blocks); break; - case Grid3DSystem::BS: this->getNeighborsBottomSouth(ix1, ix2, ix3, level, levelDepth, blocks); break; - case Grid3DSystem::BN: this->getNeighborsBottomNorth(ix1, ix2, ix3, level, levelDepth, blocks); break; - case Grid3DSystem::TS: this->getNeighborsTopSouth(ix1, ix2, ix3, level, levelDepth, blocks); break; - case Grid3DSystem::TNE: this->getNeighborsTopNorthEast(ix1, ix2, ix3, level, levelDepth, blocks); break; - case Grid3DSystem::TNW: this->getNeighborsTopNorthWest(ix1, ix2, ix3, level, levelDepth, blocks); break; - case Grid3DSystem::TSE: this->getNeighborsTopSouthEast(ix1, ix2, ix3, level, levelDepth, blocks); break; - case Grid3DSystem::TSW: this->getNeighborsTopSouthWest(ix1, ix2, ix3, level, levelDepth, blocks); break; - case Grid3DSystem::BNE: this->getNeighborsBottomNorthEast(ix1, ix2, ix3, level, levelDepth, blocks); break; - case Grid3DSystem::BNW: this->getNeighborsBottomNorthWest(ix1, ix2, ix3, level, levelDepth, blocks); break; - case Grid3DSystem::BSE: this->getNeighborsBottomSouthEast(ix1, ix2, ix3, level, levelDepth, blocks); break; - case Grid3DSystem::BSW: this->getNeighborsBottomSouthWest(ix1, ix2, ix3, level, levelDepth, blocks); break; - default:throw UbException(UB_EXARGS, "direction " + UbSystem::toString(dir) + " is not exist"); - } -} -////////////////////////////////////////////////////////////////////////// -void Grid3D::getNeighborsZero(int ix1, int ix2, int ix3, int level, int levelDepth, std::vector<SPtr<Block3D>>& blocks) -{ - SPtr<Block3D> block = this->getBlock(ix1, ix2, ix3, level); - if (block) { blocks.push_back(block); } - - if (level > 0) - { - block = this->getSuperBlock(ix1, ix2, ix3, level); - if (block) { blocks.push_back(block); } - } - // this->getSubBlocksNull(ix1, ix2, ix3, level, blocks, levelDepth); - this->getSubBlocks(ix1, ix2, ix3, level, levelDepth, blocks); -} -////////////////////////////////////////////////////////////////////////// -void Grid3D::getSubBlocksZero(int ix1, int ix2, int ix3, int level, vector<SPtr<Block3D>>& blockVector, int levelDepth) -{ - int x1E = (ix1 << 1) + 1; - int x1W = (ix1 << 1); - int x2S = ix2 << 1; - int x2N = x2S + 1; - int x3B = ix3 << 1; - int x3T = x3B + 1; - int l = level + 1; - - SPtr<Block3D> block = this->getBlock(x1E, x2S, x3B, l); - if (block != NULL) blockVector.push_back(block); - else if (l < levelDepth) this->getSubBlocksEast(x1E, x2S, x3B, l, blockVector, levelDepth); - - block = this->getBlock(x1E, x2N, x3B, l); - if (block != NULL) blockVector.push_back(block); - else if (l < levelDepth) this->getSubBlocksEast(x1E, x2N, x3B, l, blockVector, levelDepth); - - block = this->getBlock(x1E, x2S, x3T, l); - if (block != NULL) blockVector.push_back(block); - else if (l < levelDepth) this->getSubBlocksEast(x1E, x2S, x3T, l, blockVector, levelDepth); - - block = this->getBlock(x1E, x2N, x3T, l); - if (block != NULL) blockVector.push_back(block); - else if (l < levelDepth) this->getSubBlocksEast(x1E, x2N, x3T, l, blockVector, levelDepth); - - block = this->getBlock(x1W, x2S, x3B, l); - if (block != NULL) blockVector.push_back(block); - else if (l < levelDepth) this->getSubBlocksEast(x1W, x2S, x3B, l, blockVector, levelDepth); - - block = this->getBlock(x1W, x2N, x3B, l); - if (block != NULL) blockVector.push_back(block); - else if (l < levelDepth) this->getSubBlocksEast(x1W, x2N, x3B, l, blockVector, levelDepth); - - block = this->getBlock(x1W, x2S, x3T, l); - if (block != NULL) blockVector.push_back(block); - else if (l < levelDepth) this->getSubBlocksEast(x1W, x2S, x3T, l, blockVector, levelDepth); - - block = this->getBlock(x1W, x2N, x3T, l); - if (block != NULL) blockVector.push_back(block); - else if (l < levelDepth) this->getSubBlocksEast(x1W, x2N, x3T, l, blockVector, levelDepth); -} -////////////////////////////////////////////////////////////////////////// -void Grid3D::getNeighborBlocksForDirectionWithDirZero(int dir, int ix1, int ix2, int ix3, int level, int levelDepth, std::vector<SPtr<Block3D>>& blocks) -{ - switch (dir) - { - case Grid3DSystem::E: this->getNeighborsEast(ix1, ix2, ix3, level, levelDepth, blocks); break; - case Grid3DSystem::W: this->getNeighborsWest(ix1, ix2, ix3, level, levelDepth, blocks); break; - case Grid3DSystem::N: this->getNeighborsNorth(ix1, ix2, ix3, level, levelDepth, blocks); break; - case Grid3DSystem::S: this->getNeighborsSouth(ix1, ix2, ix3, level, levelDepth, blocks); break; - case Grid3DSystem::T: this->getNeighborsTop(ix1, ix2, ix3, level, levelDepth, blocks); break; - case Grid3DSystem::B: this->getNeighborsBottom(ix1, ix2, ix3, level, levelDepth, blocks); break; - case Grid3DSystem::NE: this->getNeighborsNorthEast(ix1, ix2, ix3, level, levelDepth, blocks); break; - case Grid3DSystem::SW: this->getNeighborsSouthWest(ix1, ix2, ix3, level, levelDepth, blocks); break; - case Grid3DSystem::SE: this->getNeighborsSouthEast(ix1, ix2, ix3, level, levelDepth, blocks); break; - case Grid3DSystem::NW: this->getNeighborsNorthWest(ix1, ix2, ix3, level, levelDepth, blocks); break; - case Grid3DSystem::TE: this->getNeighborsTopEast(ix1, ix2, ix3, level, levelDepth, blocks); break; - case Grid3DSystem::BW: this->getNeighborsBottomWest(ix1, ix2, ix3, level, levelDepth, blocks); break; - case Grid3DSystem::BE: this->getNeighborsBottomEast(ix1, ix2, ix3, level, levelDepth, blocks); break; - case Grid3DSystem::TW: this->getNeighborsTopWest(ix1, ix2, ix3, level, levelDepth, blocks); break; - case Grid3DSystem::TN: this->getNeighborsTopNorth(ix1, ix2, ix3, level, levelDepth, blocks); break; - case Grid3DSystem::BS: this->getNeighborsBottomSouth(ix1, ix2, ix3, level, levelDepth, blocks); break; - case Grid3DSystem::BN: this->getNeighborsBottomNorth(ix1, ix2, ix3, level, levelDepth, blocks); break; - case Grid3DSystem::TS: this->getNeighborsTopSouth(ix1, ix2, ix3, level, levelDepth, blocks); break; - case Grid3DSystem::TNE: this->getNeighborsTopNorthEast(ix1, ix2, ix3, level, levelDepth, blocks); break; - case Grid3DSystem::TNW: this->getNeighborsTopNorthWest(ix1, ix2, ix3, level, levelDepth, blocks); break; - case Grid3DSystem::TSE: this->getNeighborsTopSouthEast(ix1, ix2, ix3, level, levelDepth, blocks); break; - case Grid3DSystem::TSW: this->getNeighborsTopSouthWest(ix1, ix2, ix3, level, levelDepth, blocks); break; - case Grid3DSystem::BNE: this->getNeighborsBottomNorthEast(ix1, ix2, ix3, level, levelDepth, blocks); break; - case Grid3DSystem::BNW: this->getNeighborsBottomNorthWest(ix1, ix2, ix3, level, levelDepth, blocks); break; - case Grid3DSystem::BSE: this->getNeighborsBottomSouthEast(ix1, ix2, ix3, level, levelDepth, blocks); break; - case Grid3DSystem::BSW: this->getNeighborsBottomSouthWest(ix1, ix2, ix3, level, levelDepth, blocks); break; - case Grid3DSystem::ZERO: this->getNeighborsZero(ix1, ix2, ix3, level, levelDepth, blocks); break; - default:throw UbException(UB_EXARGS, "direction " + UbSystem::toString(dir) + " is not exist"); - } -} -////////////////////////////////////////////////////////////////////////// -void Grid3D::getSubBlocksEast(int ix1, int ix2, int ix3, int level, vector<SPtr<Block3D>>& blockVector, int levelDepth) -{ - int x1 = (ix1 << 1) + 1; - int x2S = ix2 << 1; - int x2N = x2S + 1; - int x3B = ix3 << 1; - int x3T = x3B + 1; - int l = level + 1; - - SPtr<Block3D> block = this->getBlock(x1, x2S, x3B, l); - if (block != NULL) blockVector.push_back(block); - else if (l < levelDepth) this->getSubBlocksEast(x1, x2S, x3B, l, blockVector, levelDepth); - - block = this->getBlock(x1, x2N, x3B, l); - if (block != NULL) blockVector.push_back(block); - else if (l < levelDepth) this->getSubBlocksEast(x1, x2N, x3B, l, blockVector, levelDepth); - - block = this->getBlock(x1, x2S, x3T, l); - if (block != NULL) blockVector.push_back(block); - else if (l < levelDepth) this->getSubBlocksEast(x1, x2S, x3T, l, blockVector, levelDepth); - - block = this->getBlock(x1, x2N, x3T, l); - if (block != NULL) blockVector.push_back(block); - else if (l < levelDepth) this->getSubBlocksEast(x1, x2N, x3T, l, blockVector, levelDepth); -} - -////////////////////////////////////////////////////////////////////////// -void Grid3D::getSubBlocksWest(int ix1, int ix2, int ix3, int level, vector<SPtr<Block3D>>& blockVector, int levelDepth) -{ - int x1 = ix1 << 1; - int x2S = ix2 << 1; - int x2N = x2S + 1; - int x3B = ix3 << 1; - int x3T = x3B + 1; - int l = level + 1; - - SPtr<Block3D> block = this->getBlock(x1, x2S, x3B, l); - if (block != NULL) blockVector.push_back(block); - else if (l < levelDepth) this->getSubBlocksWest(x1, x2S, x3B, l, blockVector, levelDepth); - - block = this->getBlock(x1, x2N, x3B, l); - if (block != NULL) blockVector.push_back(block); - else if (l < levelDepth) this->getSubBlocksWest(x1, x2N, x3B, l, blockVector, levelDepth); - - block = this->getBlock(x1, x2S, x3T, l); - if (block != NULL) blockVector.push_back(block); - else if (l < levelDepth) this->getSubBlocksWest(x1, x2S, x3T, l, blockVector, levelDepth); - - block = this->getBlock(x1, x2N, x3T, l); - if (block != NULL) blockVector.push_back(block); - else if (l < levelDepth) this->getSubBlocksWest(x1, x2N, x3T, l, blockVector, levelDepth); -} -////////////////////////////////////////////////////////////////////////// -void Grid3D::getSubBlocksNorth(int ix1, int ix2, int ix3, int level, vector<SPtr<Block3D>>& blockVector, int levelDepth) -{ - int x1W = ix1 << 1; - int x1E = x1W + 1; - int x2 = (ix2 << 1) + 1; - int x3B = ix3 << 1; - int x3T = x3B + 1; - int l = level + 1; - - SPtr<Block3D> block = this->getBlock(x1W, x2, x3B, l); - if (block != NULL) blockVector.push_back(block); - else if (l < levelDepth) this->getSubBlocksNorth(x1W, x2, x3B, l, blockVector, levelDepth); - - block = this->getBlock(x1E, x2, x3B, l); - if (block != NULL) blockVector.push_back(block); - else if (l < levelDepth) this->getSubBlocksNorth(x1E, x2, x3B, l, blockVector, levelDepth); - - block = this->getBlock(x1W, x2, x3T, l); - if (block != NULL) blockVector.push_back(block); - else if (l < levelDepth) this->getSubBlocksNorth(x1W, x2, x3T, l, blockVector, levelDepth); - - block = this->getBlock(x1E, x2, x3T, l); - if (block != NULL) blockVector.push_back(block); - else if (l < levelDepth) this->getSubBlocksNorth(x1E, x2, x3T, l, blockVector, levelDepth); -} -////////////////////////////////////////////////////////////////////////// -void Grid3D::getSubBlocksSouth(int ix1, int ix2, int ix3, int level, vector<SPtr<Block3D>>& blockVector, int levelDepth) -{ - int x1W = ix1 << 1; - int x1E = x1W + 1; - int x2 = ix2 << 1; - int x3B = ix3 << 1; - int x3T = x3B + 1; - int l = level + 1; - - SPtr<Block3D> block = this->getBlock(x1W, x2, x3B, l); - if (block != NULL) blockVector.push_back(block); - else if (l < levelDepth) this->getSubBlocksSouth(x1W, x2, x3B, l, blockVector, levelDepth); - - block = this->getBlock(x1E, x2, x3B, l); - if (block != NULL) blockVector.push_back(block); - else if (l < levelDepth) this->getSubBlocksSouth(x1E, x2, x3B, l, blockVector, levelDepth); - - block = this->getBlock(x1W, x2, x3T, l); - if (block != NULL) blockVector.push_back(block); - else if (l < levelDepth) this->getSubBlocksSouth(x1W, x2, x3T, l, blockVector, levelDepth); - - block = this->getBlock(x1E, x2, x3T, l); - if (block != NULL) blockVector.push_back(block); - else if (l < levelDepth) this->getSubBlocksSouth(x1E, x2, x3T, l, blockVector, levelDepth); -} -////////////////////////////////////////////////////////////////////////// -void Grid3D::getSubBlocksTop(int ix1, int ix2, int ix3, int level, vector<SPtr<Block3D>>& blockVector, int levelDepth) -{ - int x1W = ix1 << 1; - int x1E = x1W + 1; - int x2S = ix2 << 1; - int x2N = x2S + 1; - int x3 = (ix3 << 1) + 1; - int l = level + 1; - - SPtr<Block3D> block = this->getBlock(x1W, x2N, x3, l); - if (block != NULL) blockVector.push_back(block); - else if (l < levelDepth) this->getSubBlocksTop(x1W, x2N, x3, l, blockVector, levelDepth); - - block = this->getBlock(x1E, x2N, x3, l); - if (block != NULL) blockVector.push_back(block); - else if (l < levelDepth) this->getSubBlocksTop(x1E, x2N, x3, l, blockVector, levelDepth); - - block = this->getBlock(x1W, x2S, x3, l); - if (block != NULL) blockVector.push_back(block); - else if (l < levelDepth) this->getSubBlocksTop(x1W, x2S, x3, l, blockVector, levelDepth); - - block = this->getBlock(x1E, x2S, x3, l); - if (block != NULL) blockVector.push_back(block); - else if (l < levelDepth) this->getSubBlocksTop(x1E, x2S, x3, l, blockVector, levelDepth); -} -////////////////////////////////////////////////////////////////////////// -void Grid3D::getSubBlocksBottom(int ix1, int ix2, int ix3, int level, vector<SPtr<Block3D>>& blockVector, int levelDepth) -{ - int x1W = ix1 << 1; - int x1E = x1W + 1; - int x2S = ix2 << 1; - int x2N = x2S + 1; - int x3 = ix3 << 1; - int l = level + 1; - - SPtr<Block3D> block = this->getBlock(x1W, x2N, x3, l); - if (block != NULL) blockVector.push_back(block); - else if (l < levelDepth) this->getSubBlocksBottom(x1W, x2N, x3, l, blockVector, levelDepth); - - block = this->getBlock(x1E, x2N, x3, l); - if (block != NULL) blockVector.push_back(block); - else if (l < levelDepth) this->getSubBlocksBottom(x1E, x2N, x3, l, blockVector, levelDepth); - - block = this->getBlock(x1W, x2S, x3, l); - if (block != NULL) blockVector.push_back(block); - else if (l < levelDepth) this->getSubBlocksBottom(x1W, x2S, x3, l, blockVector, levelDepth); - - block = this->getBlock(x1E, x2S, x3, l); - if (block != NULL) blockVector.push_back(block); - else if (l < levelDepth) this->getSubBlocksBottom(x1E, x2S, x3, l, blockVector, levelDepth); + if (level > 0) { + block = this->getSuperBlock(ix1 - 1, ix2, ix3 + 1, level); + if (block) { + blocks.push_back(block); + } + } + this->getSubBlocksBottomEast(ix1 - 1, ix2, ix3 + 1, level, blocks, levelDepth); +} +////////////////////////////////////////////////////////////////////////// +void Grid3D::getNeighborsTopNorth(int ix1, int ix2, int ix3, int level, int levelDepth, + std::vector<SPtr<Block3D>> &blocks) +{ + SPtr<Block3D> block = this->getBlock(ix1, ix2 + 1, ix3 + 1, level); + if (block) { + blocks.push_back(block); + } + + if (level > 0) { + block = this->getSuperBlock(ix1, ix2 + 1, ix3 + 1, level); + if (block) { + blocks.push_back(block); + } + } + this->getSubBlocksBottomSouth(ix1, ix2 + 1, ix3 + 1, level, blocks, levelDepth); +} +////////////////////////////////////////////////////////////////////////// +void Grid3D::getNeighborsTopSouth(int ix1, int ix2, int ix3, int level, int levelDepth, + std::vector<SPtr<Block3D>> &blocks) +{ + SPtr<Block3D> block = this->getBlock(ix1, ix2 - 1, ix3 + 1, level); + if (block) { + blocks.push_back(block); + } + + if (level > 0) { + block = this->getSuperBlock(ix1, ix2 - 1, ix3 + 1, level); + if (block) { + blocks.push_back(block); + } + } + this->getSubBlocksBottomNorth(ix1, ix2 - 1, ix3 + 1, level, blocks, levelDepth); +} +////////////////////////////////////////////////////////////////////////// +// diagonals bottom +////////////////////////////////////////////////////////////////////////// +void Grid3D::getNeighborsBottomEast(int ix1, int ix2, int ix3, int level, int levelDepth, + std::vector<SPtr<Block3D>> &blocks) +{ + SPtr<Block3D> block = this->getBlock(ix1 + 1, ix2, ix3 - 1, level); + if (block) { + blocks.push_back(block); + } + + if (level > 0) { + block = this->getSuperBlock(ix1 + 1, ix2, ix3 - 1, level); + if (block) { + blocks.push_back(block); + } + } + this->getSubBlocksTopWest(ix1 + 1, ix2, ix3 - 1, level, blocks, levelDepth); +} +////////////////////////////////////////////////////////////////////////// +void Grid3D::getNeighborsBottomWest(int ix1, int ix2, int ix3, int level, int levelDepth, + std::vector<SPtr<Block3D>> &blocks) +{ + SPtr<Block3D> block = this->getBlock(ix1 - 1, ix2, ix3 - 1, level); + if (block) { + blocks.push_back(block); + } + + if (level > 0) { + block = this->getSuperBlock(ix1 - 1, ix2, ix3 - 1, level); + if (block) { + blocks.push_back(block); + } + } + this->getSubBlocksTopEast(ix1 - 1, ix2, ix3 - 1, level, blocks, levelDepth); +} +////////////////////////////////////////////////////////////////////////// +void Grid3D::getNeighborsBottomNorth(int ix1, int ix2, int ix3, int level, int levelDepth, + std::vector<SPtr<Block3D>> &blocks) +{ + SPtr<Block3D> block = this->getBlock(ix1, ix2 + 1, ix3 - 1, level); + if (block) { + blocks.push_back(block); + } + + if (level > 0) { + block = this->getSuperBlock(ix1, ix2 + 1, ix3 - 1, level); + if (block) { + blocks.push_back(block); + } + } + this->getSubBlocksTopSouth(ix1, ix2 + 1, ix3 - 1, level, blocks, levelDepth); +} +////////////////////////////////////////////////////////////////////////// +void Grid3D::getNeighborsBottomSouth(int ix1, int ix2, int ix3, int level, int levelDepth, + std::vector<SPtr<Block3D>> &blocks) +{ + SPtr<Block3D> block = this->getBlock(ix1, ix2 - 1, ix3 - 1, level); + if (block) { + blocks.push_back(block); + } + + if (level > 0) { + block = this->getSuperBlock(ix1, ix2 - 1, ix3 - 1, level); + if (block) { + blocks.push_back(block); + } + } + this->getSubBlocksTopNorth(ix1, ix2 - 1, ix3 - 1, level, blocks, levelDepth); +} +////////////////////////////////////////////////////////////////////////// +void Grid3D::getNeighborsTopNorthEast(int ix1, int ix2, int ix3, int level, int levelDepth, + std::vector<SPtr<Block3D>> &blocks) +{ + SPtr<Block3D> block = this->getBlock(ix1 + 1, ix2 + 1, ix3 + 1, level); + if (block) { + blocks.push_back(block); + } + + if (level > 0) { + block = this->getSuperBlock(ix1 + 1, ix2 + 1, ix3 + 1, level); + if (block) { + blocks.push_back(block); + } + } + this->getSubBlocksBottomSouthWest(ix1 + 1, ix2 + 1, ix3 + 1, level, blocks, levelDepth); +} +////////////////////////////////////////////////////////////////////////// +void Grid3D::getNeighborsTopNorthWest(int ix1, int ix2, int ix3, int level, int levelDepth, + std::vector<SPtr<Block3D>> &blocks) +{ + SPtr<Block3D> block = this->getBlock(ix1 - 1, ix2 + 1, ix3 + 1, level); + if (block) { + blocks.push_back(block); + } + + if (level > 0) { + block = this->getSuperBlock(ix1 - 1, ix2 + 1, ix3 + 1, level); + if (block) { + blocks.push_back(block); + } + } + this->getSubBlocksBottomSouthEast(ix1 - 1, ix2 + 1, ix3 + 1, level, blocks, levelDepth); +} +////////////////////////////////////////////////////////////////////////// +void Grid3D::getNeighborsTopSouthEast(int ix1, int ix2, int ix3, int level, int levelDepth, + std::vector<SPtr<Block3D>> &blocks) +{ + SPtr<Block3D> block = this->getBlock(ix1 + 1, ix2 - 1, ix3 + 1, level); + if (block) { + blocks.push_back(block); + } + + if (level > 0) { + block = this->getSuperBlock(ix1 + 1, ix2 - 1, ix3 + 1, level); + if (block) { + blocks.push_back(block); + } + } + this->getSubBlocksBottomNorthWest(ix1 + 1, ix2 - 1, ix3 + 1, level, blocks, levelDepth); +} +////////////////////////////////////////////////////////////////////////// +void Grid3D::getNeighborsTopSouthWest(int ix1, int ix2, int ix3, int level, int levelDepth, + std::vector<SPtr<Block3D>> &blocks) +{ + SPtr<Block3D> block = this->getBlock(ix1 - 1, ix2 - 1, ix3 + 1, level); + if (block) { + blocks.push_back(block); + } + + if (level > 0) { + block = this->getSuperBlock(ix1 - 1, ix2 - 1, ix3 + 1, level); + if (block) { + blocks.push_back(block); + } + } + this->getSubBlocksBottomNorthEast(ix1 - 1, ix2 - 1, ix3 + 1, level, blocks, levelDepth); +} +////////////////////////////////////////////////////////////////////////// +void Grid3D::getNeighborsBottomNorthEast(int ix1, int ix2, int ix3, int level, int levelDepth, + std::vector<SPtr<Block3D>> &blocks) +{ + SPtr<Block3D> block = this->getBlock(ix1 + 1, ix2 + 1, ix3 - 1, level); + if (block) { + blocks.push_back(block); + } + + if (level > 0) { + block = this->getSuperBlock(ix1 + 1, ix2 + 1, ix3 - 1, level); + if (block) { + blocks.push_back(block); + } + } + this->getSubBlocksTopSouthWest(ix1 + 1, ix2 + 1, ix3 - 1, level, blocks, levelDepth); +} +////////////////////////////////////////////////////////////////////////// +void Grid3D::getNeighborsBottomNorthWest(int ix1, int ix2, int ix3, int level, int levelDepth, + std::vector<SPtr<Block3D>> &blocks) +{ + SPtr<Block3D> block = this->getBlock(ix1 - 1, ix2 + 1, ix3 - 1, level); + if (block) { + blocks.push_back(block); + } + + if (level > 0) { + block = this->getSuperBlock(ix1 - 1, ix2 + 1, ix3 - 1, level); + if (block) { + blocks.push_back(block); + } + } + this->getSubBlocksTopSouthEast(ix1 - 1, ix2 + 1, ix3 - 1, level, blocks, levelDepth); +} +////////////////////////////////////////////////////////////////////////// +void Grid3D::getNeighborsBottomSouthEast(int ix1, int ix2, int ix3, int level, int levelDepth, + std::vector<SPtr<Block3D>> &blocks) +{ + SPtr<Block3D> block = this->getBlock(ix1 + 1, ix2 - 1, ix3 - 1, level); + if (block) { + blocks.push_back(block); + } + + if (level > 0) { + block = this->getSuperBlock(ix1 + 1, ix2 - 1, ix3 - 1, level); + if (block) { + blocks.push_back(block); + } + } + this->getSubBlocksTopNorthWest(ix1 + 1, ix2 - 1, ix3 - 1, level, blocks, levelDepth); +} +////////////////////////////////////////////////////////////////////////// +void Grid3D::getNeighborsBottomSouthWest(int ix1, int ix2, int ix3, int level, int levelDepth, + std::vector<SPtr<Block3D>> &blocks) +{ + SPtr<Block3D> block = this->getBlock(ix1 - 1, ix2 - 1, ix3 - 1, level); + if (block) { + blocks.push_back(block); + } + + if (level > 0) { + block = this->getSuperBlock(ix1 - 1, ix2 - 1, ix3 - 1, level); + if (block) { + blocks.push_back(block); + } + } + this->getSubBlocksTopNorthEast(ix1 - 1, ix2 - 1, ix3 - 1, level, blocks, levelDepth); +} +////////////////////////////////////////////////////////////////////////// +void Grid3D::getNeighborBlocksForDirection(int dir, int ix1, int ix2, int ix3, int level, int levelDepth, + std::vector<SPtr<Block3D>> &blocks) +{ + switch (dir) { + case Grid3DSystem::E: + this->getNeighborsEast(ix1, ix2, ix3, level, levelDepth, blocks); + break; + case Grid3DSystem::W: + this->getNeighborsWest(ix1, ix2, ix3, level, levelDepth, blocks); + break; + case Grid3DSystem::N: + this->getNeighborsNorth(ix1, ix2, ix3, level, levelDepth, blocks); + break; + case Grid3DSystem::S: + this->getNeighborsSouth(ix1, ix2, ix3, level, levelDepth, blocks); + break; + case Grid3DSystem::T: + this->getNeighborsTop(ix1, ix2, ix3, level, levelDepth, blocks); + break; + case Grid3DSystem::B: + this->getNeighborsBottom(ix1, ix2, ix3, level, levelDepth, blocks); + break; + case Grid3DSystem::NE: + this->getNeighborsNorthEast(ix1, ix2, ix3, level, levelDepth, blocks); + break; + case Grid3DSystem::SW: + this->getNeighborsSouthWest(ix1, ix2, ix3, level, levelDepth, blocks); + break; + case Grid3DSystem::SE: + this->getNeighborsSouthEast(ix1, ix2, ix3, level, levelDepth, blocks); + break; + case Grid3DSystem::NW: + this->getNeighborsNorthWest(ix1, ix2, ix3, level, levelDepth, blocks); + break; + case Grid3DSystem::TE: + this->getNeighborsTopEast(ix1, ix2, ix3, level, levelDepth, blocks); + break; + case Grid3DSystem::BW: + this->getNeighborsBottomWest(ix1, ix2, ix3, level, levelDepth, blocks); + break; + case Grid3DSystem::BE: + this->getNeighborsBottomEast(ix1, ix2, ix3, level, levelDepth, blocks); + break; + case Grid3DSystem::TW: + this->getNeighborsTopWest(ix1, ix2, ix3, level, levelDepth, blocks); + break; + case Grid3DSystem::TN: + this->getNeighborsTopNorth(ix1, ix2, ix3, level, levelDepth, blocks); + break; + case Grid3DSystem::BS: + this->getNeighborsBottomSouth(ix1, ix2, ix3, level, levelDepth, blocks); + break; + case Grid3DSystem::BN: + this->getNeighborsBottomNorth(ix1, ix2, ix3, level, levelDepth, blocks); + break; + case Grid3DSystem::TS: + this->getNeighborsTopSouth(ix1, ix2, ix3, level, levelDepth, blocks); + break; + case Grid3DSystem::TNE: + this->getNeighborsTopNorthEast(ix1, ix2, ix3, level, levelDepth, blocks); + break; + case Grid3DSystem::TNW: + this->getNeighborsTopNorthWest(ix1, ix2, ix3, level, levelDepth, blocks); + break; + case Grid3DSystem::TSE: + this->getNeighborsTopSouthEast(ix1, ix2, ix3, level, levelDepth, blocks); + break; + case Grid3DSystem::TSW: + this->getNeighborsTopSouthWest(ix1, ix2, ix3, level, levelDepth, blocks); + break; + case Grid3DSystem::BNE: + this->getNeighborsBottomNorthEast(ix1, ix2, ix3, level, levelDepth, blocks); + break; + case Grid3DSystem::BNW: + this->getNeighborsBottomNorthWest(ix1, ix2, ix3, level, levelDepth, blocks); + break; + case Grid3DSystem::BSE: + this->getNeighborsBottomSouthEast(ix1, ix2, ix3, level, levelDepth, blocks); + break; + case Grid3DSystem::BSW: + this->getNeighborsBottomSouthWest(ix1, ix2, ix3, level, levelDepth, blocks); + break; + default: + throw UbException(UB_EXARGS, "direction " + UbSystem::toString(dir) + " is not exist"); + } +} +////////////////////////////////////////////////////////////////////////// +void Grid3D::getNeighborsZero(int ix1, int ix2, int ix3, int level, int levelDepth, std::vector<SPtr<Block3D>> &blocks) +{ + SPtr<Block3D> block = this->getBlock(ix1, ix2, ix3, level); + if (block) { + blocks.push_back(block); + } + + if (level > 0) { + block = this->getSuperBlock(ix1, ix2, ix3, level); + if (block) { + blocks.push_back(block); + } + } + // this->getSubBlocksNull(ix1, ix2, ix3, level, blocks, levelDepth); + this->getSubBlocks(ix1, ix2, ix3, level, levelDepth, blocks); +} +////////////////////////////////////////////////////////////////////////// +void Grid3D::getSubBlocksZero(int ix1, int ix2, int ix3, int level, vector<SPtr<Block3D>> &blockVector, int levelDepth) +{ + int x1E = (ix1 << 1) + 1; + int x1W = (ix1 << 1); + int x2S = ix2 << 1; + int x2N = x2S + 1; + int x3B = ix3 << 1; + int x3T = x3B + 1; + int l = level + 1; + + SPtr<Block3D> block = this->getBlock(x1E, x2S, x3B, l); + if (block != NULL) + blockVector.push_back(block); + else if (l < levelDepth) + this->getSubBlocksEast(x1E, x2S, x3B, l, blockVector, levelDepth); + + block = this->getBlock(x1E, x2N, x3B, l); + if (block != NULL) + blockVector.push_back(block); + else if (l < levelDepth) + this->getSubBlocksEast(x1E, x2N, x3B, l, blockVector, levelDepth); + + block = this->getBlock(x1E, x2S, x3T, l); + if (block != NULL) + blockVector.push_back(block); + else if (l < levelDepth) + this->getSubBlocksEast(x1E, x2S, x3T, l, blockVector, levelDepth); + + block = this->getBlock(x1E, x2N, x3T, l); + if (block != NULL) + blockVector.push_back(block); + else if (l < levelDepth) + this->getSubBlocksEast(x1E, x2N, x3T, l, blockVector, levelDepth); + + block = this->getBlock(x1W, x2S, x3B, l); + if (block != NULL) + blockVector.push_back(block); + else if (l < levelDepth) + this->getSubBlocksEast(x1W, x2S, x3B, l, blockVector, levelDepth); + + block = this->getBlock(x1W, x2N, x3B, l); + if (block != NULL) + blockVector.push_back(block); + else if (l < levelDepth) + this->getSubBlocksEast(x1W, x2N, x3B, l, blockVector, levelDepth); + + block = this->getBlock(x1W, x2S, x3T, l); + if (block != NULL) + blockVector.push_back(block); + else if (l < levelDepth) + this->getSubBlocksEast(x1W, x2S, x3T, l, blockVector, levelDepth); + + block = this->getBlock(x1W, x2N, x3T, l); + if (block != NULL) + blockVector.push_back(block); + else if (l < levelDepth) + this->getSubBlocksEast(x1W, x2N, x3T, l, blockVector, levelDepth); +} +////////////////////////////////////////////////////////////////////////// +void Grid3D::getNeighborBlocksForDirectionWithDirZero(int dir, int ix1, int ix2, int ix3, int level, int levelDepth, + std::vector<SPtr<Block3D>> &blocks) +{ + switch (dir) { + case Grid3DSystem::E: + this->getNeighborsEast(ix1, ix2, ix3, level, levelDepth, blocks); + break; + case Grid3DSystem::W: + this->getNeighborsWest(ix1, ix2, ix3, level, levelDepth, blocks); + break; + case Grid3DSystem::N: + this->getNeighborsNorth(ix1, ix2, ix3, level, levelDepth, blocks); + break; + case Grid3DSystem::S: + this->getNeighborsSouth(ix1, ix2, ix3, level, levelDepth, blocks); + break; + case Grid3DSystem::T: + this->getNeighborsTop(ix1, ix2, ix3, level, levelDepth, blocks); + break; + case Grid3DSystem::B: + this->getNeighborsBottom(ix1, ix2, ix3, level, levelDepth, blocks); + break; + case Grid3DSystem::NE: + this->getNeighborsNorthEast(ix1, ix2, ix3, level, levelDepth, blocks); + break; + case Grid3DSystem::SW: + this->getNeighborsSouthWest(ix1, ix2, ix3, level, levelDepth, blocks); + break; + case Grid3DSystem::SE: + this->getNeighborsSouthEast(ix1, ix2, ix3, level, levelDepth, blocks); + break; + case Grid3DSystem::NW: + this->getNeighborsNorthWest(ix1, ix2, ix3, level, levelDepth, blocks); + break; + case Grid3DSystem::TE: + this->getNeighborsTopEast(ix1, ix2, ix3, level, levelDepth, blocks); + break; + case Grid3DSystem::BW: + this->getNeighborsBottomWest(ix1, ix2, ix3, level, levelDepth, blocks); + break; + case Grid3DSystem::BE: + this->getNeighborsBottomEast(ix1, ix2, ix3, level, levelDepth, blocks); + break; + case Grid3DSystem::TW: + this->getNeighborsTopWest(ix1, ix2, ix3, level, levelDepth, blocks); + break; + case Grid3DSystem::TN: + this->getNeighborsTopNorth(ix1, ix2, ix3, level, levelDepth, blocks); + break; + case Grid3DSystem::BS: + this->getNeighborsBottomSouth(ix1, ix2, ix3, level, levelDepth, blocks); + break; + case Grid3DSystem::BN: + this->getNeighborsBottomNorth(ix1, ix2, ix3, level, levelDepth, blocks); + break; + case Grid3DSystem::TS: + this->getNeighborsTopSouth(ix1, ix2, ix3, level, levelDepth, blocks); + break; + case Grid3DSystem::TNE: + this->getNeighborsTopNorthEast(ix1, ix2, ix3, level, levelDepth, blocks); + break; + case Grid3DSystem::TNW: + this->getNeighborsTopNorthWest(ix1, ix2, ix3, level, levelDepth, blocks); + break; + case Grid3DSystem::TSE: + this->getNeighborsTopSouthEast(ix1, ix2, ix3, level, levelDepth, blocks); + break; + case Grid3DSystem::TSW: + this->getNeighborsTopSouthWest(ix1, ix2, ix3, level, levelDepth, blocks); + break; + case Grid3DSystem::BNE: + this->getNeighborsBottomNorthEast(ix1, ix2, ix3, level, levelDepth, blocks); + break; + case Grid3DSystem::BNW: + this->getNeighborsBottomNorthWest(ix1, ix2, ix3, level, levelDepth, blocks); + break; + case Grid3DSystem::BSE: + this->getNeighborsBottomSouthEast(ix1, ix2, ix3, level, levelDepth, blocks); + break; + case Grid3DSystem::BSW: + this->getNeighborsBottomSouthWest(ix1, ix2, ix3, level, levelDepth, blocks); + break; + case Grid3DSystem::ZERO: + this->getNeighborsZero(ix1, ix2, ix3, level, levelDepth, blocks); + break; + default: + throw UbException(UB_EXARGS, "direction " + UbSystem::toString(dir) + " is not exist"); + } +} +////////////////////////////////////////////////////////////////////////// +void Grid3D::getSubBlocksEast(int ix1, int ix2, int ix3, int level, vector<SPtr<Block3D>> &blockVector, int levelDepth) +{ + int x1 = (ix1 << 1) + 1; + int x2S = ix2 << 1; + int x2N = x2S + 1; + int x3B = ix3 << 1; + int x3T = x3B + 1; + int l = level + 1; + + SPtr<Block3D> block = this->getBlock(x1, x2S, x3B, l); + if (block != NULL) + blockVector.push_back(block); + else if (l < levelDepth) + this->getSubBlocksEast(x1, x2S, x3B, l, blockVector, levelDepth); + + block = this->getBlock(x1, x2N, x3B, l); + if (block != NULL) + blockVector.push_back(block); + else if (l < levelDepth) + this->getSubBlocksEast(x1, x2N, x3B, l, blockVector, levelDepth); + + block = this->getBlock(x1, x2S, x3T, l); + if (block != NULL) + blockVector.push_back(block); + else if (l < levelDepth) + this->getSubBlocksEast(x1, x2S, x3T, l, blockVector, levelDepth); + + block = this->getBlock(x1, x2N, x3T, l); + if (block != NULL) + blockVector.push_back(block); + else if (l < levelDepth) + this->getSubBlocksEast(x1, x2N, x3T, l, blockVector, levelDepth); +} + +////////////////////////////////////////////////////////////////////////// +void Grid3D::getSubBlocksWest(int ix1, int ix2, int ix3, int level, vector<SPtr<Block3D>> &blockVector, int levelDepth) +{ + int x1 = ix1 << 1; + int x2S = ix2 << 1; + int x2N = x2S + 1; + int x3B = ix3 << 1; + int x3T = x3B + 1; + int l = level + 1; + + SPtr<Block3D> block = this->getBlock(x1, x2S, x3B, l); + if (block != NULL) + blockVector.push_back(block); + else if (l < levelDepth) + this->getSubBlocksWest(x1, x2S, x3B, l, blockVector, levelDepth); + + block = this->getBlock(x1, x2N, x3B, l); + if (block != NULL) + blockVector.push_back(block); + else if (l < levelDepth) + this->getSubBlocksWest(x1, x2N, x3B, l, blockVector, levelDepth); + + block = this->getBlock(x1, x2S, x3T, l); + if (block != NULL) + blockVector.push_back(block); + else if (l < levelDepth) + this->getSubBlocksWest(x1, x2S, x3T, l, blockVector, levelDepth); + + block = this->getBlock(x1, x2N, x3T, l); + if (block != NULL) + blockVector.push_back(block); + else if (l < levelDepth) + this->getSubBlocksWest(x1, x2N, x3T, l, blockVector, levelDepth); +} +////////////////////////////////////////////////////////////////////////// +void Grid3D::getSubBlocksNorth(int ix1, int ix2, int ix3, int level, vector<SPtr<Block3D>> &blockVector, int levelDepth) +{ + int x1W = ix1 << 1; + int x1E = x1W + 1; + int x2 = (ix2 << 1) + 1; + int x3B = ix3 << 1; + int x3T = x3B + 1; + int l = level + 1; + + SPtr<Block3D> block = this->getBlock(x1W, x2, x3B, l); + if (block != NULL) + blockVector.push_back(block); + else if (l < levelDepth) + this->getSubBlocksNorth(x1W, x2, x3B, l, blockVector, levelDepth); + + block = this->getBlock(x1E, x2, x3B, l); + if (block != NULL) + blockVector.push_back(block); + else if (l < levelDepth) + this->getSubBlocksNorth(x1E, x2, x3B, l, blockVector, levelDepth); + + block = this->getBlock(x1W, x2, x3T, l); + if (block != NULL) + blockVector.push_back(block); + else if (l < levelDepth) + this->getSubBlocksNorth(x1W, x2, x3T, l, blockVector, levelDepth); + + block = this->getBlock(x1E, x2, x3T, l); + if (block != NULL) + blockVector.push_back(block); + else if (l < levelDepth) + this->getSubBlocksNorth(x1E, x2, x3T, l, blockVector, levelDepth); +} +////////////////////////////////////////////////////////////////////////// +void Grid3D::getSubBlocksSouth(int ix1, int ix2, int ix3, int level, vector<SPtr<Block3D>> &blockVector, int levelDepth) +{ + int x1W = ix1 << 1; + int x1E = x1W + 1; + int x2 = ix2 << 1; + int x3B = ix3 << 1; + int x3T = x3B + 1; + int l = level + 1; + + SPtr<Block3D> block = this->getBlock(x1W, x2, x3B, l); + if (block != NULL) + blockVector.push_back(block); + else if (l < levelDepth) + this->getSubBlocksSouth(x1W, x2, x3B, l, blockVector, levelDepth); + + block = this->getBlock(x1E, x2, x3B, l); + if (block != NULL) + blockVector.push_back(block); + else if (l < levelDepth) + this->getSubBlocksSouth(x1E, x2, x3B, l, blockVector, levelDepth); + + block = this->getBlock(x1W, x2, x3T, l); + if (block != NULL) + blockVector.push_back(block); + else if (l < levelDepth) + this->getSubBlocksSouth(x1W, x2, x3T, l, blockVector, levelDepth); + + block = this->getBlock(x1E, x2, x3T, l); + if (block != NULL) + blockVector.push_back(block); + else if (l < levelDepth) + this->getSubBlocksSouth(x1E, x2, x3T, l, blockVector, levelDepth); +} +////////////////////////////////////////////////////////////////////////// +void Grid3D::getSubBlocksTop(int ix1, int ix2, int ix3, int level, vector<SPtr<Block3D>> &blockVector, int levelDepth) +{ + int x1W = ix1 << 1; + int x1E = x1W + 1; + int x2S = ix2 << 1; + int x2N = x2S + 1; + int x3 = (ix3 << 1) + 1; + int l = level + 1; + + SPtr<Block3D> block = this->getBlock(x1W, x2N, x3, l); + if (block != NULL) + blockVector.push_back(block); + else if (l < levelDepth) + this->getSubBlocksTop(x1W, x2N, x3, l, blockVector, levelDepth); + + block = this->getBlock(x1E, x2N, x3, l); + if (block != NULL) + blockVector.push_back(block); + else if (l < levelDepth) + this->getSubBlocksTop(x1E, x2N, x3, l, blockVector, levelDepth); + + block = this->getBlock(x1W, x2S, x3, l); + if (block != NULL) + blockVector.push_back(block); + else if (l < levelDepth) + this->getSubBlocksTop(x1W, x2S, x3, l, blockVector, levelDepth); + + block = this->getBlock(x1E, x2S, x3, l); + if (block != NULL) + blockVector.push_back(block); + else if (l < levelDepth) + this->getSubBlocksTop(x1E, x2S, x3, l, blockVector, levelDepth); +} +////////////////////////////////////////////////////////////////////////// +void Grid3D::getSubBlocksBottom(int ix1, int ix2, int ix3, int level, vector<SPtr<Block3D>> &blockVector, + int levelDepth) +{ + int x1W = ix1 << 1; + int x1E = x1W + 1; + int x2S = ix2 << 1; + int x2N = x2S + 1; + int x3 = ix3 << 1; + int l = level + 1; + + SPtr<Block3D> block = this->getBlock(x1W, x2N, x3, l); + if (block != NULL) + blockVector.push_back(block); + else if (l < levelDepth) + this->getSubBlocksBottom(x1W, x2N, x3, l, blockVector, levelDepth); + + block = this->getBlock(x1E, x2N, x3, l); + if (block != NULL) + blockVector.push_back(block); + else if (l < levelDepth) + this->getSubBlocksBottom(x1E, x2N, x3, l, blockVector, levelDepth); + + block = this->getBlock(x1W, x2S, x3, l); + if (block != NULL) + blockVector.push_back(block); + else if (l < levelDepth) + this->getSubBlocksBottom(x1W, x2S, x3, l, blockVector, levelDepth); + + block = this->getBlock(x1E, x2S, x3, l); + if (block != NULL) + blockVector.push_back(block); + else if (l < levelDepth) + this->getSubBlocksBottom(x1E, x2S, x3, l, blockVector, levelDepth); } ////////////////////////////////////////////////////////////////////////// // diagonals ////////////////////////////////////////////////////////////////////////// -void Grid3D::getSubBlocksNorthEast(int ix1, int ix2, int ix3, int level, vector<SPtr<Block3D>>& blockVector, int levelDepth) -{ - int x1 = (ix1 << 1) + 1; - int x2 = (ix2 << 1) + 1; - int x3B = (ix3 << 1); - int x3T = x3B + 1; - int l = level + 1; - - SPtr<Block3D> blockB = this->getBlock(x1, x2, x3B, l); - if (blockB) blockVector.push_back(blockB); - else if (l < levelDepth) this->getSubBlocksNorthEast(x1, x2, x3B, l, blockVector, levelDepth); - - SPtr<Block3D> blockT = this->getBlock(x1, x2, x3T, l); - if (blockT) blockVector.push_back(blockT); - else if (l < levelDepth) this->getSubBlocksNorthEast(x1, x2, x3T, l, blockVector, levelDepth); -} -////////////////////////////////////////////////////////////////////////// -void Grid3D::getSubBlocksNorthWest(int ix1, int ix2, int ix3, int level, vector<SPtr<Block3D>>& blockVector, int levelDepth) -{ - int x1 = (ix1 << 1); - int x2 = (ix2 << 1) + 1; - int x3B = (ix3 << 1); - int x3T = x3B + 1; - int l = level + 1; - - SPtr<Block3D> blockB = this->getBlock(x1, x2, x3B, l); - if (blockB) blockVector.push_back(blockB); - else if (l < levelDepth) this->getSubBlocksNorthWest(x1, x2, x3B, l, blockVector, levelDepth); - - SPtr<Block3D> blockT = this->getBlock(x1, x2, x3T, l); - if (blockT) blockVector.push_back(blockT); - else if (l < levelDepth) this->getSubBlocksNorthWest(x1, x2, x3T, l, blockVector, levelDepth); -} -////////////////////////////////////////////////////////////////////////// -void Grid3D::getSubBlocksSouthWest(int ix1, int ix2, int ix3, int level, vector<SPtr<Block3D>>& blockVector, int levelDepth) -{ - int x1 = ix1 << 1; - int x2 = ix2 << 1; - int x3B = (ix3 << 1); - int x3T = x3B + 1; - int l = level + 1; - - SPtr<Block3D> blockB = this->getBlock(x1, x2, x3B, l); - if (blockB) blockVector.push_back(blockB); - else if (l < levelDepth) this->getSubBlocksSouthWest(x1, x2, x3B, l, blockVector, levelDepth); - - SPtr<Block3D> blockT = this->getBlock(x1, x2, x3T, l); - if (blockT) blockVector.push_back(blockT); - else if (l < levelDepth) this->getSubBlocksSouthWest(x1, x2, x3T, l, blockVector, levelDepth); -} -////////////////////////////////////////////////////////////////////////// -void Grid3D::getSubBlocksSouthEast(int ix1, int ix2, int ix3, int level, vector<SPtr<Block3D>>& blockVector, int levelDepth) -{ - int x1 = (ix1 << 1) + 1; - int x2 = ix2 << 1; - int x3B = (ix3 << 1); - int x3T = x3B + 1; - int l = level + 1; - - SPtr<Block3D> blockB = this->getBlock(x1, x2, x3B, l); - if (blockB) blockVector.push_back(blockB); - else if (l < levelDepth) this->getSubBlocksSouthEast(x1, x2, x3B, l, blockVector, levelDepth); - - SPtr<Block3D> blockT = this->getBlock(x1, x2, x3T, l); - if (blockT) blockVector.push_back(blockT); - else if (l < levelDepth) this->getSubBlocksSouthEast(x1, x2, x3T, l, blockVector, levelDepth); +void Grid3D::getSubBlocksNorthEast(int ix1, int ix2, int ix3, int level, vector<SPtr<Block3D>> &blockVector, + int levelDepth) +{ + int x1 = (ix1 << 1) + 1; + int x2 = (ix2 << 1) + 1; + int x3B = (ix3 << 1); + int x3T = x3B + 1; + int l = level + 1; + + SPtr<Block3D> blockB = this->getBlock(x1, x2, x3B, l); + if (blockB) + blockVector.push_back(blockB); + else if (l < levelDepth) + this->getSubBlocksNorthEast(x1, x2, x3B, l, blockVector, levelDepth); + + SPtr<Block3D> blockT = this->getBlock(x1, x2, x3T, l); + if (blockT) + blockVector.push_back(blockT); + else if (l < levelDepth) + this->getSubBlocksNorthEast(x1, x2, x3T, l, blockVector, levelDepth); +} +////////////////////////////////////////////////////////////////////////// +void Grid3D::getSubBlocksNorthWest(int ix1, int ix2, int ix3, int level, vector<SPtr<Block3D>> &blockVector, + int levelDepth) +{ + int x1 = (ix1 << 1); + int x2 = (ix2 << 1) + 1; + int x3B = (ix3 << 1); + int x3T = x3B + 1; + int l = level + 1; + + SPtr<Block3D> blockB = this->getBlock(x1, x2, x3B, l); + if (blockB) + blockVector.push_back(blockB); + else if (l < levelDepth) + this->getSubBlocksNorthWest(x1, x2, x3B, l, blockVector, levelDepth); + + SPtr<Block3D> blockT = this->getBlock(x1, x2, x3T, l); + if (blockT) + blockVector.push_back(blockT); + else if (l < levelDepth) + this->getSubBlocksNorthWest(x1, x2, x3T, l, blockVector, levelDepth); +} +////////////////////////////////////////////////////////////////////////// +void Grid3D::getSubBlocksSouthWest(int ix1, int ix2, int ix3, int level, vector<SPtr<Block3D>> &blockVector, + int levelDepth) +{ + int x1 = ix1 << 1; + int x2 = ix2 << 1; + int x3B = (ix3 << 1); + int x3T = x3B + 1; + int l = level + 1; + + SPtr<Block3D> blockB = this->getBlock(x1, x2, x3B, l); + if (blockB) + blockVector.push_back(blockB); + else if (l < levelDepth) + this->getSubBlocksSouthWest(x1, x2, x3B, l, blockVector, levelDepth); + + SPtr<Block3D> blockT = this->getBlock(x1, x2, x3T, l); + if (blockT) + blockVector.push_back(blockT); + else if (l < levelDepth) + this->getSubBlocksSouthWest(x1, x2, x3T, l, blockVector, levelDepth); +} +////////////////////////////////////////////////////////////////////////// +void Grid3D::getSubBlocksSouthEast(int ix1, int ix2, int ix3, int level, vector<SPtr<Block3D>> &blockVector, + int levelDepth) +{ + int x1 = (ix1 << 1) + 1; + int x2 = ix2 << 1; + int x3B = (ix3 << 1); + int x3T = x3B + 1; + int l = level + 1; + + SPtr<Block3D> blockB = this->getBlock(x1, x2, x3B, l); + if (blockB) + blockVector.push_back(blockB); + else if (l < levelDepth) + this->getSubBlocksSouthEast(x1, x2, x3B, l, blockVector, levelDepth); + + SPtr<Block3D> blockT = this->getBlock(x1, x2, x3T, l); + if (blockT) + blockVector.push_back(blockT); + else if (l < levelDepth) + this->getSubBlocksSouthEast(x1, x2, x3T, l, blockVector, levelDepth); } ////////////////////////////////////////////////////////////////////////// // diagonals ////////////////////////////////////////////////////////////////////////// -void Grid3D::getSubBlocksTopEast(int ix1, int ix2, int ix3, int level, vector<SPtr<Block3D>>& blockVector, int levelDepth) +void Grid3D::getSubBlocksTopEast(int ix1, int ix2, int ix3, int level, vector<SPtr<Block3D>> &blockVector, + int levelDepth) { - int x1 = (ix1 << 1) + 1; - int x2S = (ix2 << 1); - int x2N = x2S + 1; - int x3 = (ix3 << 1) + 1; - int l = level + 1; + int x1 = (ix1 << 1) + 1; + int x2S = (ix2 << 1); + int x2N = x2S + 1; + int x3 = (ix3 << 1) + 1; + int l = level + 1; - SPtr<Block3D> blockN = this->getBlock(x1, x2N, x3, l); - if (blockN) blockVector.push_back(blockN); - else if (l < levelDepth) this->getSubBlocksTopEast(x1, x2N, x3, l, blockVector, levelDepth); + SPtr<Block3D> blockN = this->getBlock(x1, x2N, x3, l); + if (blockN) + blockVector.push_back(blockN); + else if (l < levelDepth) + this->getSubBlocksTopEast(x1, x2N, x3, l, blockVector, levelDepth); - SPtr<Block3D> blockS = this->getBlock(x1, x2S, x3, l); - if (blockS) blockVector.push_back(blockS); - else if (l < levelDepth) this->getSubBlocksTopEast(x1, x2S, x3, l, blockVector, levelDepth); + SPtr<Block3D> blockS = this->getBlock(x1, x2S, x3, l); + if (blockS) + blockVector.push_back(blockS); + else if (l < levelDepth) + this->getSubBlocksTopEast(x1, x2S, x3, l, blockVector, levelDepth); } ////////////////////////////////////////////////////////////////////////// -void Grid3D::getSubBlocksTopWest(int ix1, int ix2, int ix3, int level, vector<SPtr<Block3D>>& blockVector, int levelDepth) +void Grid3D::getSubBlocksTopWest(int ix1, int ix2, int ix3, int level, vector<SPtr<Block3D>> &blockVector, + int levelDepth) { - int x1 = ix1 << 1; - int x2S = ix2 << 1; - int x2N = x2S + 1; - int x3 = (ix3 << 1) + 1; - int l = level + 1; + int x1 = ix1 << 1; + int x2S = ix2 << 1; + int x2N = x2S + 1; + int x3 = (ix3 << 1) + 1; + int l = level + 1; - SPtr<Block3D> blockN = this->getBlock(x1, x2N, x3, l); - if (blockN) blockVector.push_back(blockN); - else if (l < levelDepth) this->getSubBlocksTopEast(x1, x2N, x3, l, blockVector, levelDepth); + SPtr<Block3D> blockN = this->getBlock(x1, x2N, x3, l); + if (blockN) + blockVector.push_back(blockN); + else if (l < levelDepth) + this->getSubBlocksTopEast(x1, x2N, x3, l, blockVector, levelDepth); - SPtr<Block3D> blockS = this->getBlock(x1, x2S, x3, l); - if (blockS) blockVector.push_back(blockS); - else if (l < levelDepth) this->getSubBlocksTopEast(x1, x2S, x3, l, blockVector, levelDepth); + SPtr<Block3D> blockS = this->getBlock(x1, x2S, x3, l); + if (blockS) + blockVector.push_back(blockS); + else if (l < levelDepth) + this->getSubBlocksTopEast(x1, x2S, x3, l, blockVector, levelDepth); } ////////////////////////////////////////////////////////////////////////// -void Grid3D::getSubBlocksBottomEast(int ix1, int ix2, int ix3, int level, vector<SPtr<Block3D>>& blockVector, int levelDepth) +void Grid3D::getSubBlocksBottomEast(int ix1, int ix2, int ix3, int level, vector<SPtr<Block3D>> &blockVector, + int levelDepth) { - int x1 = (ix1 << 1) + 1; - int x2S = ix2 << 1; - int x2N = x2S + 1; - int x3 = ix3 << 1; - int l = level + 1; + int x1 = (ix1 << 1) + 1; + int x2S = ix2 << 1; + int x2N = x2S + 1; + int x3 = ix3 << 1; + int l = level + 1; - SPtr<Block3D> blockN = this->getBlock(x1, x2N, x3, l); - if (blockN) blockVector.push_back(blockN); - else if (l < levelDepth) this->getSubBlocksTopEast(x1, x2N, x3, l, blockVector, levelDepth); + SPtr<Block3D> blockN = this->getBlock(x1, x2N, x3, l); + if (blockN) + blockVector.push_back(blockN); + else if (l < levelDepth) + this->getSubBlocksTopEast(x1, x2N, x3, l, blockVector, levelDepth); - SPtr<Block3D> blockS = this->getBlock(x1, x2S, x3, l); - if (blockS) blockVector.push_back(blockS); - else if (l < levelDepth) this->getSubBlocksTopEast(x1, x2S, x3, l, blockVector, levelDepth); + SPtr<Block3D> blockS = this->getBlock(x1, x2S, x3, l); + if (blockS) + blockVector.push_back(blockS); + else if (l < levelDepth) + this->getSubBlocksTopEast(x1, x2S, x3, l, blockVector, levelDepth); } ////////////////////////////////////////////////////////////////////////// -void Grid3D::getSubBlocksBottomWest(int ix1, int ix2, int ix3, int level, vector<SPtr<Block3D>>& blockVector, int levelDepth) +void Grid3D::getSubBlocksBottomWest(int ix1, int ix2, int ix3, int level, vector<SPtr<Block3D>> &blockVector, + int levelDepth) { - int x1 = (ix1 << 1); - int x2S = (ix2 << 1); - int x2N = x2S + 1; - int x3 = ix3 << 1; - int l = level + 1; + int x1 = (ix1 << 1); + int x2S = (ix2 << 1); + int x2N = x2S + 1; + int x3 = ix3 << 1; + int l = level + 1; - SPtr<Block3D> blockN = this->getBlock(x1, x2N, x3, l); - if (blockN) blockVector.push_back(blockN); - else if (l < levelDepth) this->getSubBlocksTopEast(x1, x2N, x3, l, blockVector, levelDepth); + SPtr<Block3D> blockN = this->getBlock(x1, x2N, x3, l); + if (blockN) + blockVector.push_back(blockN); + else if (l < levelDepth) + this->getSubBlocksTopEast(x1, x2N, x3, l, blockVector, levelDepth); - SPtr<Block3D> blockS = this->getBlock(x1, x2S, x3, l); - if (blockS) blockVector.push_back(blockS); - else if (l < levelDepth) this->getSubBlocksTopEast(x1, x2S, x3, l, blockVector, levelDepth); + SPtr<Block3D> blockS = this->getBlock(x1, x2S, x3, l); + if (blockS) + blockVector.push_back(blockS); + else if (l < levelDepth) + this->getSubBlocksTopEast(x1, x2S, x3, l, blockVector, levelDepth); } ////////////////////////////////////////////////////////////////////////// // edge-diagonals ////////////////////////////////////////////////////////////////////////// -void Grid3D::getSubBlocksTopNorth(int ix1, int ix2, int ix3, int level, vector<SPtr<Block3D>>& blockVector, int levelDepth) -{ - int x1E = (ix1 << 1); - int x1W = x1E + 1; - int x2 = (ix2 << 1) + 1; - int x3 = (ix3 << 1) + 1; - int l = level + 1; - - SPtr<Block3D> blockE = this->getBlock(x1E, x2, x3, l); - if (blockE) blockVector.push_back(blockE); - else if (l < levelDepth) this->getSubBlocksTopNorth(x1E, x2, x3, l, blockVector, levelDepth); - - SPtr<Block3D> blockW = this->getBlock(x1W, x2, x3, l); - if (blockW) blockVector.push_back(blockW); - else if (l < levelDepth) this->getSubBlocksTopNorth(x1W, x2, x3, l, blockVector, levelDepth); -} -////////////////////////////////////////////////////////////////////////// -void Grid3D::getSubBlocksTopSouth(int ix1, int ix2, int ix3, int level, vector<SPtr<Block3D>>& blockVector, int levelDepth) -{ - int x1E = (ix1 << 1); - int x1W = x1E + 1; - int x2 = (ix2 << 1); - int x3 = (ix3 << 1) + 1; - int l = level + 1; - - SPtr<Block3D> blockE = this->getBlock(x1E, x2, x3, l); - if (blockE) blockVector.push_back(blockE); - else if (l < levelDepth) this->getSubBlocksTopSouth(x1E, x2, x3, l, blockVector, levelDepth); - - SPtr<Block3D> blockW = this->getBlock(x1W, x2, x3, l); - if (blockW) blockVector.push_back(blockW); - else if (l < levelDepth) this->getSubBlocksTopSouth(x1W, x2, x3, l, blockVector, levelDepth); -} -////////////////////////////////////////////////////////////////////////// -void Grid3D::getSubBlocksBottomNorth(int ix1, int ix2, int ix3, int level, vector<SPtr<Block3D>>& blockVector, int levelDepth) -{ - int x1E = ix1 << 1; - int x1W = x1E + 1; - int x2 = (ix2 << 1) + 1; - int x3 = ix3 << 1; - int l = level + 1; - - SPtr<Block3D> blockE = this->getBlock(x1E, x2, x3, l); - if (blockE) blockVector.push_back(blockE); - else if (l < levelDepth) this->getSubBlocksBottomNorth(x1E, x2, x3, l, blockVector, levelDepth); - - SPtr<Block3D> blockW = this->getBlock(x1W, x2, x3, l); - if (blockW) blockVector.push_back(blockW); - else if (l < levelDepth) this->getSubBlocksBottomNorth(x1W, x2, x3, l, blockVector, levelDepth); -} -////////////////////////////////////////////////////////////////////////// -void Grid3D::getSubBlocksBottomSouth(int ix1, int ix2, int ix3, int level, vector<SPtr<Block3D>>& blockVector, int levelDepth) -{ - int x1E = (ix1 << 1); - int x1W = x1E + 1; - int x2 = ix2 << 1; - int x3 = ix3 << 1; - int l = level + 1; - - SPtr<Block3D> blockE = this->getBlock(x1E, x2, x3, l); - if (blockE) blockVector.push_back(blockE); - else if (l < levelDepth) this->getSubBlocksBottomSouth(x1E, x2, x3, l, blockVector, levelDepth); - - SPtr<Block3D> blockW = this->getBlock(x1W, x2, x3, l); - if (blockW) blockVector.push_back(blockW); - else if (l < levelDepth) this->getSubBlocksBottomSouth(x1W, x2, x3, l, blockVector, levelDepth); +void Grid3D::getSubBlocksTopNorth(int ix1, int ix2, int ix3, int level, vector<SPtr<Block3D>> &blockVector, + int levelDepth) +{ + int x1E = (ix1 << 1); + int x1W = x1E + 1; + int x2 = (ix2 << 1) + 1; + int x3 = (ix3 << 1) + 1; + int l = level + 1; + + SPtr<Block3D> blockE = this->getBlock(x1E, x2, x3, l); + if (blockE) + blockVector.push_back(blockE); + else if (l < levelDepth) + this->getSubBlocksTopNorth(x1E, x2, x3, l, blockVector, levelDepth); + + SPtr<Block3D> blockW = this->getBlock(x1W, x2, x3, l); + if (blockW) + blockVector.push_back(blockW); + else if (l < levelDepth) + this->getSubBlocksTopNorth(x1W, x2, x3, l, blockVector, levelDepth); +} +////////////////////////////////////////////////////////////////////////// +void Grid3D::getSubBlocksTopSouth(int ix1, int ix2, int ix3, int level, vector<SPtr<Block3D>> &blockVector, + int levelDepth) +{ + int x1E = (ix1 << 1); + int x1W = x1E + 1; + int x2 = (ix2 << 1); + int x3 = (ix3 << 1) + 1; + int l = level + 1; + + SPtr<Block3D> blockE = this->getBlock(x1E, x2, x3, l); + if (blockE) + blockVector.push_back(blockE); + else if (l < levelDepth) + this->getSubBlocksTopSouth(x1E, x2, x3, l, blockVector, levelDepth); + + SPtr<Block3D> blockW = this->getBlock(x1W, x2, x3, l); + if (blockW) + blockVector.push_back(blockW); + else if (l < levelDepth) + this->getSubBlocksTopSouth(x1W, x2, x3, l, blockVector, levelDepth); +} +////////////////////////////////////////////////////////////////////////// +void Grid3D::getSubBlocksBottomNorth(int ix1, int ix2, int ix3, int level, vector<SPtr<Block3D>> &blockVector, + int levelDepth) +{ + int x1E = ix1 << 1; + int x1W = x1E + 1; + int x2 = (ix2 << 1) + 1; + int x3 = ix3 << 1; + int l = level + 1; + + SPtr<Block3D> blockE = this->getBlock(x1E, x2, x3, l); + if (blockE) + blockVector.push_back(blockE); + else if (l < levelDepth) + this->getSubBlocksBottomNorth(x1E, x2, x3, l, blockVector, levelDepth); + + SPtr<Block3D> blockW = this->getBlock(x1W, x2, x3, l); + if (blockW) + blockVector.push_back(blockW); + else if (l < levelDepth) + this->getSubBlocksBottomNorth(x1W, x2, x3, l, blockVector, levelDepth); +} +////////////////////////////////////////////////////////////////////////// +void Grid3D::getSubBlocksBottomSouth(int ix1, int ix2, int ix3, int level, vector<SPtr<Block3D>> &blockVector, + int levelDepth) +{ + int x1E = (ix1 << 1); + int x1W = x1E + 1; + int x2 = ix2 << 1; + int x3 = ix3 << 1; + int l = level + 1; + + SPtr<Block3D> blockE = this->getBlock(x1E, x2, x3, l); + if (blockE) + blockVector.push_back(blockE); + else if (l < levelDepth) + this->getSubBlocksBottomSouth(x1E, x2, x3, l, blockVector, levelDepth); + + SPtr<Block3D> blockW = this->getBlock(x1W, x2, x3, l); + if (blockW) + blockVector.push_back(blockW); + else if (l < levelDepth) + this->getSubBlocksBottomSouth(x1W, x2, x3, l, blockVector, levelDepth); } ////////////////////////////////////////////////////////////////////////// // space-diagonals ////////////////////////////////////////////////////////////////////////// -void Grid3D::getSubBlocksTopNorthEast(int ix1, int ix2, int ix3, int level, std::vector<SPtr<Block3D>>& blockVector, int levelDepth) +void Grid3D::getSubBlocksTopNorthEast(int ix1, int ix2, int ix3, int level, std::vector<SPtr<Block3D>> &blockVector, + int levelDepth) { - int x1 = (ix1 << 1) + 1; - int x2 = (ix2 << 1) + 1; - int x3 = (ix3 << 1) + 1; - int l = level + 1; + int x1 = (ix1 << 1) + 1; + int x2 = (ix2 << 1) + 1; + int x3 = (ix3 << 1) + 1; + int l = level + 1; - SPtr<Block3D> blockTNE = this->getBlock(x1, x2, x3, l); - if (blockTNE) blockVector.push_back(blockTNE); - else if (l < levelDepth) this->getSubBlocksTopNorthEast(x1, x2, x3, l, blockVector, levelDepth); + SPtr<Block3D> blockTNE = this->getBlock(x1, x2, x3, l); + if (blockTNE) + blockVector.push_back(blockTNE); + else if (l < levelDepth) + this->getSubBlocksTopNorthEast(x1, x2, x3, l, blockVector, levelDepth); } ////////////////////////////////////////////////////////////////////////// -void Grid3D::getSubBlocksTopNorthWest(int ix1, int ix2, int ix3, int level, std::vector<SPtr<Block3D>>& blockVector, int levelDepth) +void Grid3D::getSubBlocksTopNorthWest(int ix1, int ix2, int ix3, int level, std::vector<SPtr<Block3D>> &blockVector, + int levelDepth) { - int x1 = ix1 << 1; - int x2 = (ix2 << 1) + 1; - int x3 = (ix3 << 1) + 1; - int l = level + 1; + int x1 = ix1 << 1; + int x2 = (ix2 << 1) + 1; + int x3 = (ix3 << 1) + 1; + int l = level + 1; - SPtr<Block3D> blockTNW = this->getBlock(x1, x2, x3, l); - if (blockTNW) blockVector.push_back(blockTNW); - else if (l < levelDepth) this->getSubBlocksTopNorthWest(x1, x2, x3, l, blockVector, levelDepth); + SPtr<Block3D> blockTNW = this->getBlock(x1, x2, x3, l); + if (blockTNW) + blockVector.push_back(blockTNW); + else if (l < levelDepth) + this->getSubBlocksTopNorthWest(x1, x2, x3, l, blockVector, levelDepth); } ////////////////////////////////////////////////////////////////////////// -void Grid3D::getSubBlocksTopSouthEast(int ix1, int ix2, int ix3, int level, std::vector<SPtr<Block3D>>& blockVector, int levelDepth) +void Grid3D::getSubBlocksTopSouthEast(int ix1, int ix2, int ix3, int level, std::vector<SPtr<Block3D>> &blockVector, + int levelDepth) { - int x1 = (ix1 << 1) + 1; - int x2 = ix2 << 1; - int x3 = (ix3 << 1) + 1; - int l = level + 1; + int x1 = (ix1 << 1) + 1; + int x2 = ix2 << 1; + int x3 = (ix3 << 1) + 1; + int l = level + 1; - SPtr<Block3D> blockTNW = this->getBlock(x1, x2, x3, l); - if (blockTNW) blockVector.push_back(blockTNW); - else if (l < levelDepth) this->getSubBlocksTopSouthEast(x1, x2, x3, l, blockVector, levelDepth); + SPtr<Block3D> blockTNW = this->getBlock(x1, x2, x3, l); + if (blockTNW) + blockVector.push_back(blockTNW); + else if (l < levelDepth) + this->getSubBlocksTopSouthEast(x1, x2, x3, l, blockVector, levelDepth); } ////////////////////////////////////////////////////////////////////////// -void Grid3D::getSubBlocksTopSouthWest(int ix1, int ix2, int ix3, int level, std::vector<SPtr<Block3D>>& blockVector, int levelDepth) +void Grid3D::getSubBlocksTopSouthWest(int ix1, int ix2, int ix3, int level, std::vector<SPtr<Block3D>> &blockVector, + int levelDepth) { - int x1 = ix1 << 1; - int x2 = ix2 << 1; - int x3 = (ix3 << 1) + 1; - int l = level + 1; + int x1 = ix1 << 1; + int x2 = ix2 << 1; + int x3 = (ix3 << 1) + 1; + int l = level + 1; - SPtr<Block3D> blockTSW = this->getBlock(x1, x2, x3, l); - if (blockTSW) blockVector.push_back(blockTSW); - else if (l < levelDepth) this->getSubBlocksTopSouthWest(x1, x2, x3, l, blockVector, levelDepth); + SPtr<Block3D> blockTSW = this->getBlock(x1, x2, x3, l); + if (blockTSW) + blockVector.push_back(blockTSW); + else if (l < levelDepth) + this->getSubBlocksTopSouthWest(x1, x2, x3, l, blockVector, levelDepth); } ////////////////////////////////////////////////////////////////////////// -void Grid3D::getSubBlocksBottomNorthEast(int ix1, int ix2, int ix3, int level, std::vector<SPtr<Block3D>>& blockVector, int levelDepth) +void Grid3D::getSubBlocksBottomNorthEast(int ix1, int ix2, int ix3, int level, std::vector<SPtr<Block3D>> &blockVector, + int levelDepth) { - int x1 = (ix1 << 1) + 1; - int x2 = (ix2 << 1) + 1; - int x3 = ix3 << 1; - int l = level + 1; + int x1 = (ix1 << 1) + 1; + int x2 = (ix2 << 1) + 1; + int x3 = ix3 << 1; + int l = level + 1; - SPtr<Block3D> blockBNE = this->getBlock(x1, x2, x3, l); - if (blockBNE) blockVector.push_back(blockBNE); - else if (l < levelDepth) this->getSubBlocksBottomNorthEast(x1, x2, x3, l, blockVector, levelDepth); + SPtr<Block3D> blockBNE = this->getBlock(x1, x2, x3, l); + if (blockBNE) + blockVector.push_back(blockBNE); + else if (l < levelDepth) + this->getSubBlocksBottomNorthEast(x1, x2, x3, l, blockVector, levelDepth); } ////////////////////////////////////////////////////////////////////////// -void Grid3D::getSubBlocksBottomNorthWest(int ix1, int ix2, int ix3, int level, std::vector<SPtr<Block3D>>& blockVector, int levelDepth) +void Grid3D::getSubBlocksBottomNorthWest(int ix1, int ix2, int ix3, int level, std::vector<SPtr<Block3D>> &blockVector, + int levelDepth) { - int x1 = ix1 << 1; - int x2 = (ix2 << 1) + 1; - int x3 = ix3 << 1; - int l = level + 1; + int x1 = ix1 << 1; + int x2 = (ix2 << 1) + 1; + int x3 = ix3 << 1; + int l = level + 1; - SPtr<Block3D> blockBNW = this->getBlock(x1, x2, x3, l); - if (blockBNW) blockVector.push_back(blockBNW); - else if (l < levelDepth) this->getSubBlocksBottomNorthWest(x1, x2, x3, l, blockVector, levelDepth); + SPtr<Block3D> blockBNW = this->getBlock(x1, x2, x3, l); + if (blockBNW) + blockVector.push_back(blockBNW); + else if (l < levelDepth) + this->getSubBlocksBottomNorthWest(x1, x2, x3, l, blockVector, levelDepth); } ////////////////////////////////////////////////////////////////////////// -void Grid3D::getSubBlocksBottomSouthEast(int ix1, int ix2, int ix3, int level, std::vector<SPtr<Block3D>>& blockVector, int levelDepth) +void Grid3D::getSubBlocksBottomSouthEast(int ix1, int ix2, int ix3, int level, std::vector<SPtr<Block3D>> &blockVector, + int levelDepth) { - int x1 = (ix1 << 1) + 1; - int x2 = ix2 << 1; - int x3 = ix3 << 1; - int l = level + 1; + int x1 = (ix1 << 1) + 1; + int x2 = ix2 << 1; + int x3 = ix3 << 1; + int l = level + 1; - SPtr<Block3D> blockBSE = this->getBlock(x1, x2, x3, l); - if (blockBSE) blockVector.push_back(blockBSE); - else if (l < levelDepth) this->getSubBlocksBottomSouthEast(x1, x2, x3, l, blockVector, levelDepth); + SPtr<Block3D> blockBSE = this->getBlock(x1, x2, x3, l); + if (blockBSE) + blockVector.push_back(blockBSE); + else if (l < levelDepth) + this->getSubBlocksBottomSouthEast(x1, x2, x3, l, blockVector, levelDepth); } ////////////////////////////////////////////////////////////////////////// -void Grid3D::getSubBlocksBottomSouthWest(int ix1, int ix2, int ix3, int level, std::vector<SPtr<Block3D>>& blockVector, int levelDepth) +void Grid3D::getSubBlocksBottomSouthWest(int ix1, int ix2, int ix3, int level, std::vector<SPtr<Block3D>> &blockVector, + int levelDepth) { - int x1 = ix1 << 1; - int x2 = ix2 << 1; - int x3 = ix3 << 1; - int l = level + 1; + int x1 = ix1 << 1; + int x2 = ix2 << 1; + int x3 = ix3 << 1; + int l = level + 1; - SPtr<Block3D> blockBSW = this->getBlock(x1, x2, x3, l); - if (blockBSW) blockVector.push_back(blockBSW); - else if (l < levelDepth) this->getSubBlocksBottomSouthWest(x1, x2, x3, l, blockVector, levelDepth); + SPtr<Block3D> blockBSW = this->getBlock(x1, x2, x3, l); + if (blockBSW) + blockVector.push_back(blockBSW); + else if (l < levelDepth) + this->getSubBlocksBottomSouthWest(x1, x2, x3, l, blockVector, levelDepth); } ////////////////////////////////////////////////////////////////////////// -void Grid3D::getBlocks(int level, std::vector<SPtr<Block3D>>& blockVector) +void Grid3D::getBlocks(int level, std::vector<SPtr<Block3D>> &blockVector) { - for (Block3DMap::value_type b : levelSet[level]) - { - blockVector.push_back(b.second); - } - + for (Block3DMap::value_type b : levelSet[level]) { + blockVector.push_back(b.second); + } } ////////////////////////////////////////////////////////////////////////// -void Grid3D::getBlocks(int level, int rank, std::vector<SPtr<Block3D>>& blockVector) +void Grid3D::getBlocks(int level, int rank, std::vector<SPtr<Block3D>> &blockVector) { - for (Block3DMap::value_type b : levelSet[level]) - { - SPtr<Block3D> block = b.second; - int blockRank = block->getRank(); - if (blockRank == rank) - { - blockVector.push_back(b.second); - } - } + for (Block3DMap::value_type b : levelSet[level]) { + SPtr<Block3D> block = b.second; + int blockRank = block->getRank(); + if (blockRank == rank) { + blockVector.push_back(b.second); + } + } } ////////////////////////////////////////////////////////////////////////// -void Grid3D::getBlocks(int level, int rank, bool active, std::vector<SPtr<Block3D>>& blockVector) +void Grid3D::getBlocks(int level, int rank, bool active, std::vector<SPtr<Block3D>> &blockVector) { - for (Block3DMap::value_type b : levelSet[level]) - { - SPtr<Block3D> block = b.second; - int blockRank = block->getRank(); + for (Block3DMap::value_type b : levelSet[level]) { + SPtr<Block3D> block = b.second; + int blockRank = block->getRank(); - if (blockRank == rank && active ? block->isActive() : block->isNotActive()) - { - blockVector.push_back(b.second); - } - } + if (blockRank == rank && active ? block->isActive() : block->isNotActive()) { + blockVector.push_back(b.second); + } + } } ////////////////////////////////////////////////////////////////////////// int Grid3D::getFinestInitializedLevel() { - for (int i = Grid3DSystem::MAXLEVEL; i >= 0; i--) if (this->levelSet[i].size() > 0) return(i); - return(-1); + for (int i = Grid3DSystem::MAXLEVEL; i >= 0; i--) + if (this->levelSet[i].size() > 0) + return (i); + return (-1); } ////////////////////////////////////////////////////////////////////////// int Grid3D::getCoarsestInitializedLevel() { - for (int i = 0; i <= Grid3DSystem::MAXLEVEL; i++) if (this->levelSet[i].size() > 0) return(i); - return(-1); + for (int i = 0; i <= Grid3DSystem::MAXLEVEL; i++) + if (this->levelSet[i].size() > 0) + return (i); + return (-1); } ////////////////////////////////////////////////////////////////////////// -void Grid3D::setNX1(int nx1) -{ - this->nx1 = nx1; -} +void Grid3D::setNX1(int nx1) { this->nx1 = nx1; } ////////////////////////////////////////////////////////////////////////// -void Grid3D::setNX2(int nx2) -{ - this->nx2 = nx2; -} +void Grid3D::setNX2(int nx2) { this->nx2 = nx2; } ////////////////////////////////////////////////////////////////////////// -void Grid3D::setNX3(int nx3) -{ - this->nx3 = nx3; -} +void Grid3D::setNX3(int nx3) { this->nx3 = nx3; } ////////////////////////////////////////////////////////////////////////// -int Grid3D::getNX1() const -{ - return this->nx1; -} +int Grid3D::getNX1() const { return this->nx1; } ////////////////////////////////////////////////////////////////////////// -int Grid3D::getNX2() const -{ - return this->nx2; -} +int Grid3D::getNX2() const { return this->nx2; } ////////////////////////////////////////////////////////////////////////// -int Grid3D::getNX3() const -{ - return this->nx3; -} +int Grid3D::getNX3() const { return this->nx3; } ////////////////////////////////////////////////////////////////////////// -void Grid3D::deleteBlocks(const std::vector<int>& ids) +void Grid3D::deleteBlocks(const std::vector<int> &ids) { - for (int i : ids) - { - SPtr<Block3D> block = getBlock(i); - if (block) this->deleteBlock(block); - } + for (int i : ids) { + SPtr<Block3D> block = getBlock(i); + if (block) + this->deleteBlock(block); + } } ////////////////////////////////////////////////////////////////////////// int Grid3D::getNumberOfBlocks() { - int c = 0; - for (Block3DMap l : levelSet) - { - c += (int)l.size(); - } - return c; -} -////////////////////////////////////////////////////////////////////////// -int Grid3D::getNumberOfBlocks(int level) -{ - return (int)levelSet[level].size(); -} -////////////////////////////////////////////////////////////////////////// -void Grid3D::getBlocksByCuboid(double minX1, double minX2, double minX3, double maxX1, double maxX2, double maxX3, std::vector<SPtr<Block3D>>& blocks) -{ - int coarsestLevel = this->getCoarsestInitializedLevel(); - int finestLevel = this->getFinestInitializedLevel(); - - ////////////////////////////////////////////////////////////////////////// - //MINIMALE BLOCK-INDIZES BESTIMMEN - // - //min: - double dMinX1 = trafo->transformForwardToX1Coordinate(minX1, minX2, minX3) * (1 << finestLevel); - double dMinX2 = trafo->transformForwardToX2Coordinate(minX1, minX2, minX3) * (1 << finestLevel); - double dMinX3 = trafo->transformForwardToX3Coordinate(minX1, minX2, minX3) * (1 << finestLevel); - - //Achtung, wenn minX1 genau auf grenze zwischen zwei bloecken -> der "kleinere" muss genommen werden, - //da beim Transformieren der "groessere" Index rauskommt - int iMinX1 = (int)dMinX1; if (UbMath::zero(dMinX1 - iMinX1)) iMinX1 -= 1; - int iMinX2 = (int)dMinX2; if (UbMath::zero(dMinX2 - iMinX2)) iMinX2 -= 1; - int iMinX3 = (int)dMinX3; if (UbMath::zero(dMinX3 - iMinX3)) iMinX3 -= 1; - - //max (hier kann die Zusatzabfrage vernachlaessigt werden): - int iMaxX1 = (int)(trafo->transformForwardToX1Coordinate(maxX1, maxX2, maxX3) * (1 << finestLevel)); - int iMaxX2 = (int)(trafo->transformForwardToX2Coordinate(maxX1, maxX2, maxX3) * (1 << finestLevel)); - int iMaxX3 = (int)(trafo->transformForwardToX3Coordinate(maxX1, maxX2, maxX3) * (1 << finestLevel)); - - SPtr<Block3D> block; - - //set, um doppelte bloecke zu vermeiden, die u.U. bei periodic auftreten koennen - std::set<SPtr<Block3D>> blockset; - for (int level = coarsestLevel; level <= finestLevel; level++) - { - //damit bei negativen werten auch der "kleinere" genommen wird -> floor! - int minx1 = (int)std::floor((double)iMinX1 / (1 << (finestLevel - level))); - int minx2 = (int)std::floor((double)iMinX2 / (1 << (finestLevel - level))); - int minx3 = (int)std::floor((double)iMinX3 / (1 << (finestLevel - level))); - - int maxx1 = iMaxX1 / (1 << (finestLevel - level)); - int maxx2 = iMaxX2 / (1 << (finestLevel - level)); - int maxx3 = iMaxX3 / (1 << (finestLevel - level)); - - for (int ix1 = minx1; ix1 <= maxx1; ix1++) - for (int ix2 = minx2; ix2 <= maxx2; ix2++) - for (int ix3 = minx3; ix3 <= maxx3; ix3++) - if ((block = this->getBlock(ix1, ix2, ix3, level))) - { - if (block->getRank() == rank) - { - blockset.insert(block); - } - } - } - - blocks.resize(blockset.size()); - std::copy(blockset.begin(), blockset.end(), blocks.begin()); -} -////////////////////////////////////////////////////////////////////////// -void Grid3D::getBlocksByCuboid(int level, double minX1, double minX2, double minX3, double maxX1, double maxX2, double maxX3, std::vector<SPtr<Block3D>>& blocks) -{ - ////////////////////////////////////////////////////////////////////////// - //MINIMALE BLOCK-INDIZES BESTIMMEN - // - //min: - double dMinX1 = trafo->transformForwardToX1Coordinate(minX1, minX2, minX3) * (1 << level); - double dMinX2 = trafo->transformForwardToX2Coordinate(minX1, minX2, minX3) * (1 << level); - double dMinX3 = trafo->transformForwardToX3Coordinate(minX1, minX2, minX3) * (1 << level); - - //Achtung, wenn minX1 genau auf grenze zwischen zwei bloecken -> der "kleinere" muss genommen werden: - int iMinX1 = (int)dMinX1; if (UbMath::zero(dMinX1 - iMinX1)) iMinX1 -= 1; - int iMinX2 = (int)dMinX2; if (UbMath::zero(dMinX2 - iMinX2)) iMinX2 -= 1; - int iMinX3 = (int)dMinX3; if (UbMath::zero(dMinX3 - iMinX3)) iMinX3 -= 1; - - //max: - int iMaxX1 = (int)(trafo->transformForwardToX1Coordinate(maxX1, maxX2, maxX3) * (1 << level)); - int iMaxX2 = (int)(trafo->transformForwardToX2Coordinate(maxX1, maxX2, maxX3) * (1 << level)); - int iMaxX3 = (int)(trafo->transformForwardToX3Coordinate(maxX1, maxX2, maxX3) * (1 << level)); - - - //set, um doppelte bloecke zu vermeiden, die u.U. bei periodic auftreten koennen - std::set<SPtr<Block3D>> blockset; - SPtr<Block3D> block; - - for (int ix1 = iMinX1; ix1 <= iMaxX1; ix1++) - for (int ix2 = iMinX2; ix2 <= iMaxX2; ix2++) - for (int ix3 = iMinX3; ix3 <= iMaxX3; ix3++) - if ((block = this->getBlock(ix1, ix2, ix3, level))) - { - if (block->getRank() == rank) - { - blockset.insert(block); - } - } - - blocks.resize(blockset.size()); - std::copy(blockset.begin(), blockset.end(), blocks.begin()); -} -////////////////////////////////////////////////////////////////////////// -void Grid3D::getAllBlocksByCuboid(double minX1, double minX2, double minX3, double maxX1, double maxX2, double maxX3, std::vector<SPtr<Block3D>>& blocks) -{ - int coarsestLevel = this->getCoarsestInitializedLevel(); - int finestLevel = this->getFinestInitializedLevel(); - - ////////////////////////////////////////////////////////////////////////// - //MINIMALE BLOCK-INDIZES BESTIMMEN - // - //min: - double dMinX1 = trafo->transformForwardToX1Coordinate(minX1, minX2, minX3) * (1 << finestLevel); - double dMinX2 = trafo->transformForwardToX2Coordinate(minX1, minX2, minX3) * (1 << finestLevel); - double dMinX3 = trafo->transformForwardToX3Coordinate(minX1, minX2, minX3) * (1 << finestLevel); - - //Achtung, wenn minX1 genau auf grenze zwischen zwei bloecken -> der "kleinere" muss genommen werden, - //da beim Transformieren der "groessere" Index rauskommt - int iMinX1 = (int)dMinX1; if (UbMath::zero(dMinX1 - iMinX1)) iMinX1 -= 1; - int iMinX2 = (int)dMinX2; if (UbMath::zero(dMinX2 - iMinX2)) iMinX2 -= 1; - int iMinX3 = (int)dMinX3; if (UbMath::zero(dMinX3 - iMinX3)) iMinX3 -= 1; - - //max (hier kann die Zusatzabfrage vernachlaessigt werden): - int iMaxX1 = (int)(trafo->transformForwardToX1Coordinate(maxX1, maxX2, maxX3) * (1 << finestLevel)); - int iMaxX2 = (int)(trafo->transformForwardToX2Coordinate(maxX1, maxX2, maxX3) * (1 << finestLevel)); - int iMaxX3 = (int)(trafo->transformForwardToX3Coordinate(maxX1, maxX2, maxX3) * (1 << finestLevel)); - - SPtr<Block3D> block; - - //set, um doppelte bloecke zu vermeiden, die u.U. bei periodic auftreten koennen - std::set<SPtr<Block3D>> blockset; - for (int level = coarsestLevel; level <= finestLevel; level++) - { - //damit bei negativen werten auch der "kleinere" genommen wird -> floor! - int minx1 = (int)std::floor((double)iMinX1 / (1 << (finestLevel - level))); - int minx2 = (int)std::floor((double)iMinX2 / (1 << (finestLevel - level))); - int minx3 = (int)std::floor((double)iMinX3 / (1 << (finestLevel - level))); - - int maxx1 = iMaxX1 / (1 << (finestLevel - level)); - int maxx2 = iMaxX2 / (1 << (finestLevel - level)); - int maxx3 = iMaxX3 / (1 << (finestLevel - level)); - - for (int ix1 = minx1; ix1 <= maxx1; ix1++) - for (int ix2 = minx2; ix2 <= maxx2; ix2++) - for (int ix3 = minx3; ix3 <= maxx3; ix3++) - if ((block = this->getBlock(ix1, ix2, ix3, level))) - { - if (block) - { - blockset.insert(block); - } - } - } - - blocks.resize(blockset.size()); - std::copy(blockset.begin(), blockset.end(), blocks.begin()); -} -////////////////////////////////////////////////////////////////////////// -void Grid3D::calcStartCoordinatesAndDelta(SPtr<Block3D> block, double& worldX1, double& worldX2, double& worldX3, double& deltaX) -{ - int blocklevel = block->getLevel(); - worldX1 = block->getX1() / (float)(1 << blocklevel); - worldX2 = block->getX2() / (float)(1 << blocklevel); - worldX3 = block->getX3() / (float)(1 << blocklevel); - deltaX = (double)1.0 / (double)(this->blockNx1 * (double)(1 << blocklevel)); - - if (this->trafo) - { - double x1tmp = worldX1, x2tmp = worldX2, x3tmp = worldX3; - worldX1 = this->trafo->transformBackwardToX1Coordinate(x1tmp, x2tmp, x3tmp); - worldX2 = this->trafo->transformBackwardToX2Coordinate(x1tmp, x2tmp, x3tmp); - worldX3 = this->trafo->transformBackwardToX3Coordinate(x1tmp, x2tmp, x3tmp); - deltaX = this->trafo->getX1CoordinateScaling() / (double)(this->blockNx1 * (double)(1 << blocklevel)); - } -} -////////////////////////////////////////////////////////////////////////// -void Grid3D::calcStartCoordinatesWithOutOverlap(SPtr<Block3D> block, double& worldX1, double& worldX2, double& worldX3) -{ - int blocklevel = block->getLevel(); - worldX1 = block->getX1() / (float)(1 << blocklevel); - worldX2 = block->getX2() / (float)(1 << blocklevel); - worldX3 = block->getX3() / (float)(1 << blocklevel); - - if (this->trafo) - { - double x1tmp = worldX1, x2tmp = worldX2, x3tmp = worldX3; - worldX1 = this->trafo->transformBackwardToX1Coordinate(x1tmp, x2tmp, x3tmp); - worldX2 = this->trafo->transformBackwardToX2Coordinate(x1tmp, x2tmp, x3tmp); - worldX3 = this->trafo->transformBackwardToX3Coordinate(x1tmp, x2tmp, x3tmp); - } -} -////////////////////////////////////////////////////////////////////////// -void Grid3D::setTimeStep(double step) -{ - timeStep = step; -} -////////////////////////////////////////////////////////////////////////// -double Grid3D::getTimeStep() const -{ - return timeStep; -} + int c = 0; + for (Block3DMap l : levelSet) { + c += (int)l.size(); + } + return c; +} +////////////////////////////////////////////////////////////////////////// +int Grid3D::getNumberOfBlocks(int level) { return (int)levelSet[level].size(); } +////////////////////////////////////////////////////////////////////////// +void Grid3D::getBlocksByCuboid(double minX1, double minX2, double minX3, double maxX1, double maxX2, double maxX3, + std::vector<SPtr<Block3D>> &blocks) +{ + int coarsestLevel = this->getCoarsestInitializedLevel(); + int finestLevel = this->getFinestInitializedLevel(); + + ////////////////////////////////////////////////////////////////////////// + // MINIMALE BLOCK-INDIZES BESTIMMEN + // + // min: + double dMinX1 = trafo->transformForwardToX1Coordinate(minX1, minX2, minX3) * (1 << finestLevel); + double dMinX2 = trafo->transformForwardToX2Coordinate(minX1, minX2, minX3) * (1 << finestLevel); + double dMinX3 = trafo->transformForwardToX3Coordinate(minX1, minX2, minX3) * (1 << finestLevel); + + // Achtung, wenn minX1 genau auf grenze zwischen zwei bloecken -> der "kleinere" muss genommen werden, + // da beim Transformieren der "groessere" Index rauskommt + int iMinX1 = (int)dMinX1; + if (UbMath::zero(dMinX1 - iMinX1)) + iMinX1 -= 1; + int iMinX2 = (int)dMinX2; + if (UbMath::zero(dMinX2 - iMinX2)) + iMinX2 -= 1; + int iMinX3 = (int)dMinX3; + if (UbMath::zero(dMinX3 - iMinX3)) + iMinX3 -= 1; + + // max (hier kann die Zusatzabfrage vernachlaessigt werden): + int iMaxX1 = (int)(trafo->transformForwardToX1Coordinate(maxX1, maxX2, maxX3) * (1 << finestLevel)); + int iMaxX2 = (int)(trafo->transformForwardToX2Coordinate(maxX1, maxX2, maxX3) * (1 << finestLevel)); + int iMaxX3 = (int)(trafo->transformForwardToX3Coordinate(maxX1, maxX2, maxX3) * (1 << finestLevel)); + + SPtr<Block3D> block; + + // set, um doppelte bloecke zu vermeiden, die u.U. bei periodic auftreten koennen + std::set<SPtr<Block3D>> blockset; + for (int level = coarsestLevel; level <= finestLevel; level++) { + // damit bei negativen werten auch der "kleinere" genommen wird -> floor! + int minx1 = (int)std::floor((double)iMinX1 / (1 << (finestLevel - level))); + int minx2 = (int)std::floor((double)iMinX2 / (1 << (finestLevel - level))); + int minx3 = (int)std::floor((double)iMinX3 / (1 << (finestLevel - level))); + + int maxx1 = iMaxX1 / (1 << (finestLevel - level)); + int maxx2 = iMaxX2 / (1 << (finestLevel - level)); + int maxx3 = iMaxX3 / (1 << (finestLevel - level)); + + for (int ix1 = minx1; ix1 <= maxx1; ix1++) + for (int ix2 = minx2; ix2 <= maxx2; ix2++) + for (int ix3 = minx3; ix3 <= maxx3; ix3++) + if ((block = this->getBlock(ix1, ix2, ix3, level))) { + if (block->getRank() == rank) { + blockset.insert(block); + } + } + } + + blocks.resize(blockset.size()); + std::copy(blockset.begin(), blockset.end(), blocks.begin()); +} +////////////////////////////////////////////////////////////////////////// +void Grid3D::getBlocksByCuboid(int level, double minX1, double minX2, double minX3, double maxX1, double maxX2, + double maxX3, std::vector<SPtr<Block3D>> &blocks) +{ + ////////////////////////////////////////////////////////////////////////// + // MINIMALE BLOCK-INDIZES BESTIMMEN + // + // min: + double dMinX1 = trafo->transformForwardToX1Coordinate(minX1, minX2, minX3) * (1 << level); + double dMinX2 = trafo->transformForwardToX2Coordinate(minX1, minX2, minX3) * (1 << level); + double dMinX3 = trafo->transformForwardToX3Coordinate(minX1, minX2, minX3) * (1 << level); + + // Achtung, wenn minX1 genau auf grenze zwischen zwei bloecken -> der "kleinere" muss genommen werden: + int iMinX1 = (int)dMinX1; + if (UbMath::zero(dMinX1 - iMinX1)) + iMinX1 -= 1; + int iMinX2 = (int)dMinX2; + if (UbMath::zero(dMinX2 - iMinX2)) + iMinX2 -= 1; + int iMinX3 = (int)dMinX3; + if (UbMath::zero(dMinX3 - iMinX3)) + iMinX3 -= 1; + + // max: + int iMaxX1 = (int)(trafo->transformForwardToX1Coordinate(maxX1, maxX2, maxX3) * (1 << level)); + int iMaxX2 = (int)(trafo->transformForwardToX2Coordinate(maxX1, maxX2, maxX3) * (1 << level)); + int iMaxX3 = (int)(trafo->transformForwardToX3Coordinate(maxX1, maxX2, maxX3) * (1 << level)); + + // set, um doppelte bloecke zu vermeiden, die u.U. bei periodic auftreten koennen + std::set<SPtr<Block3D>> blockset; + SPtr<Block3D> block; + + for (int ix1 = iMinX1; ix1 <= iMaxX1; ix1++) + for (int ix2 = iMinX2; ix2 <= iMaxX2; ix2++) + for (int ix3 = iMinX3; ix3 <= iMaxX3; ix3++) + if ((block = this->getBlock(ix1, ix2, ix3, level))) { + if (block->getRank() == rank) { + blockset.insert(block); + } + } + + blocks.resize(blockset.size()); + std::copy(blockset.begin(), blockset.end(), blocks.begin()); +} +////////////////////////////////////////////////////////////////////////// +void Grid3D::getAllBlocksByCuboid(double minX1, double minX2, double minX3, double maxX1, double maxX2, double maxX3, + std::vector<SPtr<Block3D>> &blocks) +{ + int coarsestLevel = this->getCoarsestInitializedLevel(); + int finestLevel = this->getFinestInitializedLevel(); + + ////////////////////////////////////////////////////////////////////////// + // MINIMALE BLOCK-INDIZES BESTIMMEN + // + // min: + double dMinX1 = trafo->transformForwardToX1Coordinate(minX1, minX2, minX3) * (1 << finestLevel); + double dMinX2 = trafo->transformForwardToX2Coordinate(minX1, minX2, minX3) * (1 << finestLevel); + double dMinX3 = trafo->transformForwardToX3Coordinate(minX1, minX2, minX3) * (1 << finestLevel); + + // Achtung, wenn minX1 genau auf grenze zwischen zwei bloecken -> der "kleinere" muss genommen werden, + // da beim Transformieren der "groessere" Index rauskommt + int iMinX1 = (int)dMinX1; + if (UbMath::zero(dMinX1 - iMinX1)) + iMinX1 -= 1; + int iMinX2 = (int)dMinX2; + if (UbMath::zero(dMinX2 - iMinX2)) + iMinX2 -= 1; + int iMinX3 = (int)dMinX3; + if (UbMath::zero(dMinX3 - iMinX3)) + iMinX3 -= 1; + + // max (hier kann die Zusatzabfrage vernachlaessigt werden): + int iMaxX1 = (int)(trafo->transformForwardToX1Coordinate(maxX1, maxX2, maxX3) * (1 << finestLevel)); + int iMaxX2 = (int)(trafo->transformForwardToX2Coordinate(maxX1, maxX2, maxX3) * (1 << finestLevel)); + int iMaxX3 = (int)(trafo->transformForwardToX3Coordinate(maxX1, maxX2, maxX3) * (1 << finestLevel)); + + SPtr<Block3D> block; + + // set, um doppelte bloecke zu vermeiden, die u.U. bei periodic auftreten koennen + std::set<SPtr<Block3D>> blockset; + for (int level = coarsestLevel; level <= finestLevel; level++) { + // damit bei negativen werten auch der "kleinere" genommen wird -> floor! + int minx1 = (int)std::floor((double)iMinX1 / (1 << (finestLevel - level))); + int minx2 = (int)std::floor((double)iMinX2 / (1 << (finestLevel - level))); + int minx3 = (int)std::floor((double)iMinX3 / (1 << (finestLevel - level))); + + int maxx1 = iMaxX1 / (1 << (finestLevel - level)); + int maxx2 = iMaxX2 / (1 << (finestLevel - level)); + int maxx3 = iMaxX3 / (1 << (finestLevel - level)); + + for (int ix1 = minx1; ix1 <= maxx1; ix1++) + for (int ix2 = minx2; ix2 <= maxx2; ix2++) + for (int ix3 = minx3; ix3 <= maxx3; ix3++) + if ((block = this->getBlock(ix1, ix2, ix3, level))) { + if (block) { + blockset.insert(block); + } + } + } + + blocks.resize(blockset.size()); + std::copy(blockset.begin(), blockset.end(), blocks.begin()); +} +////////////////////////////////////////////////////////////////////////// +void Grid3D::calcStartCoordinatesAndDelta(SPtr<Block3D> block, double &worldX1, double &worldX2, double &worldX3, + double &deltaX) +{ + int blocklevel = block->getLevel(); + worldX1 = block->getX1() / (float)(1 << blocklevel); + worldX2 = block->getX2() / (float)(1 << blocklevel); + worldX3 = block->getX3() / (float)(1 << blocklevel); + deltaX = (double)1.0 / (double)(this->blockNx1 * (double)(1 << blocklevel)); + + if (this->trafo) { + double x1tmp = worldX1, x2tmp = worldX2, x3tmp = worldX3; + worldX1 = this->trafo->transformBackwardToX1Coordinate(x1tmp, x2tmp, x3tmp); + worldX2 = this->trafo->transformBackwardToX2Coordinate(x1tmp, x2tmp, x3tmp); + worldX3 = this->trafo->transformBackwardToX3Coordinate(x1tmp, x2tmp, x3tmp); + deltaX = this->trafo->getX1CoordinateScaling() / (double)(this->blockNx1 * (double)(1 << blocklevel)); + } +} +////////////////////////////////////////////////////////////////////////// +void Grid3D::calcStartCoordinatesWithOutOverlap(SPtr<Block3D> block, double &worldX1, double &worldX2, double &worldX3) +{ + int blocklevel = block->getLevel(); + worldX1 = block->getX1() / (float)(1 << blocklevel); + worldX2 = block->getX2() / (float)(1 << blocklevel); + worldX3 = block->getX3() / (float)(1 << blocklevel); + + if (this->trafo) { + double x1tmp = worldX1, x2tmp = worldX2, x3tmp = worldX3; + worldX1 = this->trafo->transformBackwardToX1Coordinate(x1tmp, x2tmp, x3tmp); + worldX2 = this->trafo->transformBackwardToX2Coordinate(x1tmp, x2tmp, x3tmp); + worldX3 = this->trafo->transformBackwardToX3Coordinate(x1tmp, x2tmp, x3tmp); + } +} +////////////////////////////////////////////////////////////////////////// +void Grid3D::setTimeStep(double step) { timeStep = step; } +////////////////////////////////////////////////////////////////////////// +double Grid3D::getTimeStep() const { return timeStep; } ////////////////////////////////////////////////////////////////////////// void Grid3D::fillExtentWithBlocks(UbTupleInt3 minInd, UbTupleInt3 maxInd) { - for (int x3 = val<3>(minInd); x3 < val<3>(maxInd); x3++) - { - for (int x2 = val<2>(minInd); x2 < val<2>(maxInd); x2++) - { - for (int x1 = val<1>(minInd); x1 < val<1>(maxInd); x1++) - { - SPtr<Block3D> block(new Block3D(x1, x2, x3, 0)); - this->addBlock(block); - } - } - } + for (int x3 = val<3>(minInd); x3 < val<3>(maxInd); x3++) { + for (int x2 = val<2>(minInd); x2 < val<2>(maxInd); x2++) { + for (int x1 = val<1>(minInd); x1 < val<1>(maxInd); x1++) { + SPtr<Block3D> block(new Block3D(x1, x2, x3, 0)); + this->addBlock(block); + } + } + } } ////////////////////////////////////////////////////////////////////////// -//void Grid3D::notifyObservers( double step ) +// void Grid3D::notifyObservers( double step ) //{ // for(ObserverPtr o, observers) // { @@ -1988,98 +2271,84 @@ void Grid3D::fillExtentWithBlocks(UbTupleInt3 minInd, UbTupleInt3 maxInd) // //} ////////////////////////////////////////////////////////////////////////// -//void Grid3D::addObserver( ObserverPtr observer ) +// void Grid3D::addObserver( ObserverPtr observer ) //{ // observers.insert(observer); // //observers.push_back(observer); //} //////////////////////////////////////////////////////////////////////////// -//void Grid3D::removeObserver( ObserverPtr observer ) +// void Grid3D::removeObserver( ObserverPtr observer ) //{ // observers.erase(observer); // //observers.remove(observer); //} ////////////////////////////////////////////////////////////////////////// -void Grid3D::deleteBlockIDs() -{ - this->blockIdMap.clear(); -} +void Grid3D::deleteBlockIDs() { this->blockIdMap.clear(); } ////////////////////////////////////////////////////////////////////////// void Grid3D::renumberBlockIDs() { - deleteBlockIDs(); + deleteBlockIDs(); - int startLevel = getCoarsestInitializedLevel(); - int stopLevel = getFinestInitializedLevel(); - int counter = 0; + int startLevel = getCoarsestInitializedLevel(); + int stopLevel = getFinestInitializedLevel(); + int counter = 0; - for (int l = startLevel; l <= stopLevel; l++) - { - std::vector<SPtr<Block3D>> blockVector; - getBlocks(l, blockVector); - for (SPtr<Block3D> block : blockVector) - { - block->setGlobalID(counter); - blockIdMap.insert(std::make_pair(counter, block)); - //Block3D::setMaxGlobalID(counter); - counter++; - } - } + for (int l = startLevel; l <= stopLevel; l++) { + std::vector<SPtr<Block3D>> blockVector; + getBlocks(l, blockVector); + for (SPtr<Block3D> block : blockVector) { + block->setGlobalID(counter); + blockIdMap.insert(std::make_pair(counter, block)); + // Block3D::setMaxGlobalID(counter); + counter++; + } + } } - ////////////////////////////////////////////////////////////////////////// void Grid3D::updateDistributedBlocks(SPtr<Communicator> comm) { - std::vector<int> blocks; - - if (comm->isRoot()) - { - int startLevel = getCoarsestInitializedLevel(); - int stopLevel = getFinestInitializedLevel(); - - for (int l = startLevel; l <= stopLevel; l++) - { - std::vector<SPtr<Block3D>> blockVector; - getBlocks(l, blockVector); - for (SPtr<Block3D> block : blockVector) - { - blocks.push_back(block->getX1()); - blocks.push_back(block->getX2()); - blocks.push_back(block->getX3()); - blocks.push_back(l); - blocks.push_back(block->getGlobalID()); - } - } - } - - comm->broadcast(blocks); - - if (!comm->isRoot()) - { - int startLevel = getCoarsestInitializedLevel(); - int stopLevel = getFinestInitializedLevel(); - - blockIdMap.clear(); - - for (int l = startLevel; l <= stopLevel; l++) - { - levelSet[l].clear(); - } - this->levelSet.clear(); - levelSet.resize(Grid3DSystem::MAXLEVEL + 1); - - int rsize = (int)blocks.size(); - for (int i = 0; i < rsize; i += 5) - { - SPtr<Block3D> block(new Block3D(blocks[i], blocks[i + 1], blocks[i + 2], blocks[i + 3])); - block->setGlobalID(blocks[i + 4]); - this->addBlock(block); - } - - } + std::vector<int> blocks; + + if (comm->isRoot()) { + int startLevel = getCoarsestInitializedLevel(); + int stopLevel = getFinestInitializedLevel(); + + for (int l = startLevel; l <= stopLevel; l++) { + std::vector<SPtr<Block3D>> blockVector; + getBlocks(l, blockVector); + for (SPtr<Block3D> block : blockVector) { + blocks.push_back(block->getX1()); + blocks.push_back(block->getX2()); + blocks.push_back(block->getX3()); + blocks.push_back(l); + blocks.push_back(block->getGlobalID()); + } + } + } + + comm->broadcast(blocks); + if (!comm->isRoot()) { + int startLevel = getCoarsestInitializedLevel(); + int stopLevel = getFinestInitializedLevel(); + + blockIdMap.clear(); + + for (int l = startLevel; l <= stopLevel; l++) { + levelSet[l].clear(); + } + this->levelSet.clear(); + levelSet.resize(Grid3DSystem::MAXLEVEL + 1); + + int rsize = (int)blocks.size(); + for (int i = 0; i < rsize; i += 5) { + SPtr<Block3D> block(new Block3D(blocks[i], blocks[i + 1], blocks[i + 2], blocks[i + 3])); + block->setGlobalID(blocks[i + 4]); + this->addBlock(block); + } + } } ////////////////////////////////////////////////////////////////////////// diff --git a/src/cpu/VirtualFluidsCore/Grid/Grid3D.h b/src/cpu/VirtualFluidsCore/Grid/Grid3D.h index c91dca4a0410cf2cffaeebfd2ce8cf46173860de..b954a4361df5b97b91d111e80c30b413a0b9ed05 100644 --- a/src/cpu/VirtualFluidsCore/Grid/Grid3D.h +++ b/src/cpu/VirtualFluidsCore/Grid/Grid3D.h @@ -1,28 +1,28 @@ //======================================================================================= -// ____ ____ __ ______ __________ __ __ __ __ -// \ \ | | | | | _ \ |___ ___| | | | | / \ | | -// \ \ | | | | | |_) | | | | | | | / \ | | -// \ \ | | | | | _ / | | | | | | / /\ \ | | -// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ -// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| -// \ \ | | ________________________________________________________________ -// \ \ | | | ______________________________________________________________| -// \ \| | | | __ __ __ __ ______ _______ -// \ | | |_____ | | | | | | | | | _ \ / _____) -// \ | | _____| | | | | | | | | | | \ \ \_______ +// ____ ____ __ ______ __________ __ __ __ __ +// \ \ | | | | | _ \ |___ ___| | | | | / \ | | +// \ \ | | | | | |_) | | | | | | | / \ | | +// \ \ | | | | | _ / | | | | | | / /\ \ | | +// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ +// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| +// \ \ | | ________________________________________________________________ +// \ \ | | | ______________________________________________________________| +// \ \| | | | __ __ __ __ ______ _______ +// \ | | |_____ | | | | | | | | | _ \ / _____) +// \ | | _____| | | | | | | | | | | \ \ \_______ // \ | | | | |_____ | \_/ | | | | |_/ / _____ | -// \ _____| |__| |________| \_______/ |__| |______/ (_______/ +// \ _____| |__| |________| \_______/ |__| |______/ (_______/ // -// This file is part of VirtualFluids. VirtualFluids is free software: you can +// This file is part of VirtualFluids. VirtualFluids is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of +// License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. -// -// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// +// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License along // with VirtualFluids (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>. // @@ -34,14 +34,13 @@ #ifndef GRID3D_H #define GRID3D_H - -#include <vector> -#include <map> #include <PointerDefinitions.h> +#include <map> +#include <vector> -#include <basics/utilities/Vector3D.h> -#include <basics/utilities/UbTuple.h> #include <basics/utilities/UbKeys.h> +#include <basics/utilities/UbTuple.h> +#include <basics/utilities/Vector3D.h> class CoordinateTransformation3D; @@ -51,7 +50,7 @@ class CoordinateTransformation3D; class Communicator; class Block3D; class Interactor3D; -//class Grid3DVisitor; +// class Grid3DVisitor; #define OFFSET 0.5 @@ -59,219 +58,262 @@ class Interactor3D; class Grid3D : public enableSharedFromThis<Grid3D> { public: - using Block3DKey = UbKeys::Key3<int>; - using Block3DMap = std::map<Block3DKey, SPtr<Block3D> >; - using BlockIDMap = std::map<int, SPtr<Block3D> >; - using LevelSet = std::vector<Block3DMap>; - using Interactor3DSet = std::vector<SPtr<Interactor3D> >; + using Block3DKey = UbKeys::Key3<int>; + using Block3DMap = std::map<Block3DKey, SPtr<Block3D>>; + using BlockIDMap = std::map<int, SPtr<Block3D>>; + using LevelSet = std::vector<Block3DMap>; + using Interactor3DSet = std::vector<SPtr<Interactor3D>>; public: - Grid3D(); - Grid3D(SPtr<Communicator> comm); - Grid3D(SPtr<Communicator> comm, int blockNx1, int blockNx2, int blockNx3, int gridNx1, int gridNx2, int gridNx3); - virtual ~Grid3D() = default; - ////////////////////////////////////////////////////////////////////////// - //blocks control - void addBlock(SPtr<Block3D> block); - bool deleteBlock(SPtr<Block3D> block); - bool deleteBlock(int ix1, int ix2, int ix3, int level); - void deleteBlocks(); - void deleteBlocks(const std::vector<int>& ids); - void replaceBlock(SPtr<Block3D> block); - SPtr<Block3D> getBlock(int ix1, int ix2, int ix3, int level) const; - SPtr<Block3D> getBlock(int id) const; - void getBlocksByCuboid(double minX1, double minX2, double minX3, - double maxX1, double maxX2, double maxX3, - std::vector<SPtr<Block3D>>& blocks); - void getBlocksByCuboid(int level, double minX1, double minX2, double minX3, - double maxX1, double maxX2, double maxX3, - std::vector<SPtr<Block3D>>& blocks); - void getAllBlocksByCuboid(double minX1, double minX2, double minX3, double maxX1, double maxX2, double maxX3, std::vector<SPtr<Block3D>>& blocks); - //!get blocks for level - void getBlocks(int level, std::vector<SPtr<Block3D>>& blockVector); - //!get blocks for level with current rank - void getBlocks(int level, int rank, std::vector<SPtr<Block3D>>& blockVector); - //!get only active or not active blocks - void getBlocks(int level, int rank, bool active, std::vector<SPtr<Block3D>>& blockVector); - int getNumberOfBlocks(); - int getNumberOfBlocks(int level); - //const Block3DMap& getBlocks(int level); - BlockIDMap& getBlockIDs(); - void deleteBlockIDs(); - void renumberBlockIDs(); - void updateDistributedBlocks(SPtr<Communicator> comm); - SPtr<Block3D> getSuperBlock(SPtr<Block3D> block); - SPtr<Block3D> getSuperBlock(int ix1, int ix2, int ix3, int level); - void getSubBlocks(SPtr<Block3D> block, int levelDepth, std::vector<SPtr<Block3D>>& blocks); - void getSubBlocks(int ix1, int ix2, int ix3, int level, int levelDepth, std::vector<SPtr<Block3D>>& blockVector); - SPtr<Block3D> getNeighborBlock(int dir, int ix1, int ix2, int ix3, int level) const; - SPtr<Block3D> getNeighborBlock(int dir, SPtr<Block3D> block) const; - bool expandBlock(int ix1, int ix2, int ix3, int level); - SPtr<Block3D> collapseBlock(int fix1, int fix2, int fix3, int flevel, int levelDepth); - void getAllNeighbors(int ix1, int ix2, int ix3, int level, int levelDepth, std::vector<SPtr<Block3D>>& blocks); - void getAllNeighbors(SPtr<Block3D> block, int level, int levelDepth, std::vector<SPtr<Block3D>>& blocks); - void getNeighborBlocksForDirection(int dir, int ix1, int ix2, int ix3, int level, int levelDepth, std::vector<SPtr<Block3D>>& blocks); - void getNeighborBlocksForDirectionWithDirZero(int dir, int ix1, int ix2, int ix3, int level, int levelDepth, std::vector<SPtr<Block3D>>& blocks); + Grid3D(); + Grid3D(SPtr<Communicator> comm); + Grid3D(SPtr<Communicator> comm, int blockNx1, int blockNx2, int blockNx3, int gridNx1, int gridNx2, int gridNx3); + virtual ~Grid3D() = default; + ////////////////////////////////////////////////////////////////////////// + // blocks control + void addBlock(SPtr<Block3D> block); + bool deleteBlock(SPtr<Block3D> block); + bool deleteBlock(int ix1, int ix2, int ix3, int level); + void deleteBlocks(); + void deleteBlocks(const std::vector<int> &ids); + void replaceBlock(SPtr<Block3D> block); + SPtr<Block3D> getBlock(int ix1, int ix2, int ix3, int level) const; + SPtr<Block3D> getBlock(int id) const; + void getBlocksByCuboid(double minX1, double minX2, double minX3, double maxX1, double maxX2, double maxX3, + std::vector<SPtr<Block3D>> &blocks); + void getBlocksByCuboid(int level, double minX1, double minX2, double minX3, double maxX1, double maxX2, + double maxX3, std::vector<SPtr<Block3D>> &blocks); + void getAllBlocksByCuboid(double minX1, double minX2, double minX3, double maxX1, double maxX2, double maxX3, + std::vector<SPtr<Block3D>> &blocks); + //! get blocks for level + void getBlocks(int level, std::vector<SPtr<Block3D>> &blockVector); + //! get blocks for level with current rank + void getBlocks(int level, int rank, std::vector<SPtr<Block3D>> &blockVector); + //! get only active or not active blocks + void getBlocks(int level, int rank, bool active, std::vector<SPtr<Block3D>> &blockVector); + int getNumberOfBlocks(); + int getNumberOfBlocks(int level); + // const Block3DMap& getBlocks(int level); + BlockIDMap &getBlockIDs(); + void deleteBlockIDs(); + void renumberBlockIDs(); + void updateDistributedBlocks(SPtr<Communicator> comm); + SPtr<Block3D> getSuperBlock(SPtr<Block3D> block); + SPtr<Block3D> getSuperBlock(int ix1, int ix2, int ix3, int level); + void getSubBlocks(SPtr<Block3D> block, int levelDepth, std::vector<SPtr<Block3D>> &blocks); + void getSubBlocks(int ix1, int ix2, int ix3, int level, int levelDepth, std::vector<SPtr<Block3D>> &blockVector); + SPtr<Block3D> getNeighborBlock(int dir, int ix1, int ix2, int ix3, int level) const; + SPtr<Block3D> getNeighborBlock(int dir, SPtr<Block3D> block) const; + bool expandBlock(int ix1, int ix2, int ix3, int level); + SPtr<Block3D> collapseBlock(int fix1, int fix2, int fix3, int flevel, int levelDepth); + void getAllNeighbors(int ix1, int ix2, int ix3, int level, int levelDepth, std::vector<SPtr<Block3D>> &blocks); + void getAllNeighbors(SPtr<Block3D> block, int level, int levelDepth, std::vector<SPtr<Block3D>> &blocks); + void getNeighborBlocksForDirection(int dir, int ix1, int ix2, int ix3, int level, int levelDepth, + std::vector<SPtr<Block3D>> &blocks); + void getNeighborBlocksForDirectionWithDirZero(int dir, int ix1, int ix2, int ix3, int level, int levelDepth, + std::vector<SPtr<Block3D>> &blocks); - void getNeighborsZero(int ix1, int ix2, int ix3, int level, int levelDepth, std::vector<SPtr<Block3D>>& blocks); - void getNeighborsNorth(int ix1, int ix2, int ix3, int level, int levelDepth, std::vector<SPtr<Block3D>>& blocks); - void getNeighborsSouth(int ix1, int ix2, int ix3, int level, int levelDepth, std::vector<SPtr<Block3D>>& blocks); - void getNeighborsEast(int ix1, int ix2, int ix3, int level, int levelDepth, std::vector<SPtr<Block3D>>& blocks); - void getNeighborsWest(int ix1, int ix2, int ix3, int level, int levelDepth, std::vector<SPtr<Block3D>>& blocks); - void getNeighborsTop(int ix1, int ix2, int ix3, int level, int levelDepth, std::vector<SPtr<Block3D>>& blocks); - void getNeighborsBottom(int ix1, int ix2, int ix3, int level, int levelDepth, std::vector<SPtr<Block3D>>& blocks); + void getNeighborsZero(int ix1, int ix2, int ix3, int level, int levelDepth, std::vector<SPtr<Block3D>> &blocks); + void getNeighborsNorth(int ix1, int ix2, int ix3, int level, int levelDepth, std::vector<SPtr<Block3D>> &blocks); + void getNeighborsSouth(int ix1, int ix2, int ix3, int level, int levelDepth, std::vector<SPtr<Block3D>> &blocks); + void getNeighborsEast(int ix1, int ix2, int ix3, int level, int levelDepth, std::vector<SPtr<Block3D>> &blocks); + void getNeighborsWest(int ix1, int ix2, int ix3, int level, int levelDepth, std::vector<SPtr<Block3D>> &blocks); + void getNeighborsTop(int ix1, int ix2, int ix3, int level, int levelDepth, std::vector<SPtr<Block3D>> &blocks); + void getNeighborsBottom(int ix1, int ix2, int ix3, int level, int levelDepth, std::vector<SPtr<Block3D>> &blocks); - void getNeighborsNorthWest(int ix1, int ix2, int ix3, int level, int levelDepth, std::vector<SPtr<Block3D>>& blocks); - void getNeighborsNorthEast(int ix1, int ix2, int ix3, int level, int levelDepth, std::vector<SPtr<Block3D>>& blocks); - void getNeighborsSouthWest(int ix1, int ix2, int ix3, int level, int levelDepth, std::vector<SPtr<Block3D>>& blocks); - void getNeighborsSouthEast(int ix1, int ix2, int ix3, int level, int levelDepth, std::vector<SPtr<Block3D>>& blocks); + void getNeighborsNorthWest(int ix1, int ix2, int ix3, int level, int levelDepth, + std::vector<SPtr<Block3D>> &blocks); + void getNeighborsNorthEast(int ix1, int ix2, int ix3, int level, int levelDepth, + std::vector<SPtr<Block3D>> &blocks); + void getNeighborsSouthWest(int ix1, int ix2, int ix3, int level, int levelDepth, + std::vector<SPtr<Block3D>> &blocks); + void getNeighborsSouthEast(int ix1, int ix2, int ix3, int level, int levelDepth, + std::vector<SPtr<Block3D>> &blocks); - void getNeighborsTopNorth(int ix1, int ix2, int ix3, int level, int levelDepth, std::vector<SPtr<Block3D>>& blocks); - void getNeighborsTopSouth(int ix1, int ix2, int ix3, int level, int levelDepth, std::vector<SPtr<Block3D>>& blocks); - void getNeighborsTopEast(int ix1, int ix2, int ix3, int level, int levelDepth, std::vector<SPtr<Block3D>>& blocks); - void getNeighborsTopWest(int ix1, int ix2, int ix3, int level, int levelDepth, std::vector<SPtr<Block3D>>& blocks); + void getNeighborsTopNorth(int ix1, int ix2, int ix3, int level, int levelDepth, std::vector<SPtr<Block3D>> &blocks); + void getNeighborsTopSouth(int ix1, int ix2, int ix3, int level, int levelDepth, std::vector<SPtr<Block3D>> &blocks); + void getNeighborsTopEast(int ix1, int ix2, int ix3, int level, int levelDepth, std::vector<SPtr<Block3D>> &blocks); + void getNeighborsTopWest(int ix1, int ix2, int ix3, int level, int levelDepth, std::vector<SPtr<Block3D>> &blocks); - void getNeighborsBottomNorth(int ix1, int ix2, int ix3, int level, int levelDepth, std::vector<SPtr<Block3D>>& blocks); - void getNeighborsBottomSouth(int ix1, int ix2, int ix3, int level, int levelDepth, std::vector<SPtr<Block3D>>& blocks); - void getNeighborsBottomEast(int ix1, int ix2, int ix3, int level, int levelDepth, std::vector<SPtr<Block3D>>& blocks); - void getNeighborsBottomWest(int ix1, int ix2, int ix3, int level, int levelDepth, std::vector<SPtr<Block3D>>& blocks); + void getNeighborsBottomNorth(int ix1, int ix2, int ix3, int level, int levelDepth, + std::vector<SPtr<Block3D>> &blocks); + void getNeighborsBottomSouth(int ix1, int ix2, int ix3, int level, int levelDepth, + std::vector<SPtr<Block3D>> &blocks); + void getNeighborsBottomEast(int ix1, int ix2, int ix3, int level, int levelDepth, + std::vector<SPtr<Block3D>> &blocks); + void getNeighborsBottomWest(int ix1, int ix2, int ix3, int level, int levelDepth, + std::vector<SPtr<Block3D>> &blocks); - void getNeighborsTopNorthEast(int ix1, int ix2, int ix3, int level, int levelDepth, std::vector<SPtr<Block3D>>& blocks); - void getNeighborsTopNorthWest(int ix1, int ix2, int ix3, int level, int levelDepth, std::vector<SPtr<Block3D>>& blocks); - void getNeighborsTopSouthEast(int ix1, int ix2, int ix3, int level, int levelDepth, std::vector<SPtr<Block3D>>& blocks); - void getNeighborsTopSouthWest(int ix1, int ix2, int ix3, int level, int levelDepth, std::vector<SPtr<Block3D>>& blocks); - void getNeighborsBottomNorthEast(int ix1, int ix2, int ix3, int level, int levelDepth, std::vector<SPtr<Block3D>>& blocks); - void getNeighborsBottomNorthWest(int ix1, int ix2, int ix3, int level, int levelDepth, std::vector<SPtr<Block3D>>& blocks); - void getNeighborsBottomSouthEast(int ix1, int ix2, int ix3, int level, int levelDepth, std::vector<SPtr<Block3D>>& blocks); - void getNeighborsBottomSouthWest(int ix1, int ix2, int ix3, int level, int levelDepth, std::vector<SPtr<Block3D>>& blocks); - ////////////////////////////////////////////////////////////////////////// - //level control - int getFinestInitializedLevel(); - int getCoarsestInitializedLevel(); - ////////////////////////////////////////////////////////////////////////// - void deleteConnectors(); - ////////////////////////////////////////////////////////////////////////// - //interactors control - void addInteractor(SPtr<Interactor3D> interactor); - void addAndInitInteractor(SPtr<Interactor3D> interactor, double timestep=0); - Interactor3DSet getInteractors(); - ////////////////////////////////////////////////////////////////////////// - //visitors - void accept(Block3DVisitor& blockVisitor); - void accept(Grid3DVisitor& gridVisitor); - void accept(SPtr<Grid3DVisitor> gridVisitor); - ////////////////////////////////////////////////////////////////////////// - //bundle and rank for distributed memory - void setBundle(int bundle); - int getBundle() const; - int getRank() const; - void setRank(int rank); - ////////////////////////////////////////////////////////////////////////// - //periodic boundary - bool isPeriodicX1() const; - bool isPeriodicX2() const; - bool isPeriodicX3() const; - void setPeriodicX1(bool value); - void setPeriodicX2(bool value); - void setPeriodicX3(bool value); - ////////////////////////////////////////////////////////////////////////// - //Topology - UbTupleInt3 getBlockIndexes(double blockX1Coord, double blockX2Coord, double blockX3Coord) const; - UbTupleInt3 getBlockIndexes(double blockX1Coord, double blockX2Coord, double blockX3Coord, int level) const; - UbTupleDouble3 getBlockLengths(SPtr<Block3D> block) const; - UbTupleDouble6 getBlockOversize() const ; - void setCoordinateTransformator(SPtr<CoordinateTransformation3D> trafo); - const SPtr<CoordinateTransformation3D> getCoordinateTransformator() const ; - void setDeltaX(double dx); - void setDeltaX(double worldUnit, double gridUnit); - double getDeltaX(int level) const; - double getDeltaX(SPtr<Block3D> block) const; - UbTupleDouble3 getNodeOffset(SPtr<Block3D> block) const ; - Vector3D getNodeCoordinates(SPtr<Block3D> block, int ix1, int ix2, int ix3) const; - UbTupleInt3 getNodeIndexes(SPtr<Block3D> block, double nodeX1Coord, double nodeX2Coord, double nodeX3Coord) const; - void setBlockNX(int nx1, int nx2, int nx3); - UbTupleInt3 getBlockNX() const; - UbTupleDouble3 getBlockWorldCoordinates(SPtr<Block3D> block) const; - UbTupleDouble3 getBlockWorldCoordinates(int blockX1Index, int blockX2Index, int blockX3Index, int level) const; - void setNX1(int nx1); - void setNX2(int nx2); - void setNX3(int nx3); - int getNX1() const; - int getNX2() const; - int getNX3() const; - void calcStartCoordinatesAndDelta(SPtr<Block3D> block, double& worldX1, double& worldX2, double& worldX3, double& deltaX); - void calcStartCoordinatesWithOutOverlap(SPtr<Block3D> block, double& worldX1, double& worldX2, double& worldX3); - ////////////////////////////////////////////////////////////////////////// - //LBM - //double getDeltaT(SPtr<Block3D>) const; - ////////////////////////////////////////////////////////////////////////// - void setTimeStep(double step); - double getTimeStep() const; + void getNeighborsTopNorthEast(int ix1, int ix2, int ix3, int level, int levelDepth, + std::vector<SPtr<Block3D>> &blocks); + void getNeighborsTopNorthWest(int ix1, int ix2, int ix3, int level, int levelDepth, + std::vector<SPtr<Block3D>> &blocks); + void getNeighborsTopSouthEast(int ix1, int ix2, int ix3, int level, int levelDepth, + std::vector<SPtr<Block3D>> &blocks); + void getNeighborsTopSouthWest(int ix1, int ix2, int ix3, int level, int levelDepth, + std::vector<SPtr<Block3D>> &blocks); + void getNeighborsBottomNorthEast(int ix1, int ix2, int ix3, int level, int levelDepth, + std::vector<SPtr<Block3D>> &blocks); + void getNeighborsBottomNorthWest(int ix1, int ix2, int ix3, int level, int levelDepth, + std::vector<SPtr<Block3D>> &blocks); + void getNeighborsBottomSouthEast(int ix1, int ix2, int ix3, int level, int levelDepth, + std::vector<SPtr<Block3D>> &blocks); + void getNeighborsBottomSouthWest(int ix1, int ix2, int ix3, int level, int levelDepth, + std::vector<SPtr<Block3D>> &blocks); + ////////////////////////////////////////////////////////////////////////// + // level control + int getFinestInitializedLevel(); + int getCoarsestInitializedLevel(); + ////////////////////////////////////////////////////////////////////////// + void deleteConnectors(); + ////////////////////////////////////////////////////////////////////////// + // interactors control + void addInteractor(SPtr<Interactor3D> interactor); + void addAndInitInteractor(SPtr<Interactor3D> interactor, double timestep = 0); + Interactor3DSet getInteractors(); + ////////////////////////////////////////////////////////////////////////// + // visitors + void accept(Block3DVisitor &blockVisitor); + void accept(Grid3DVisitor &gridVisitor); + void accept(SPtr<Grid3DVisitor> gridVisitor); + ////////////////////////////////////////////////////////////////////////// + // bundle and rank for distributed memory + void setBundle(int bundle); + int getBundle() const; + int getRank() const; + void setRank(int rank); + ////////////////////////////////////////////////////////////////////////// + // periodic boundary + bool isPeriodicX1() const; + bool isPeriodicX2() const; + bool isPeriodicX3() const; + void setPeriodicX1(bool value); + void setPeriodicX2(bool value); + void setPeriodicX3(bool value); + ////////////////////////////////////////////////////////////////////////// + // Topology + UbTupleInt3 getBlockIndexes(double blockX1Coord, double blockX2Coord, double blockX3Coord) const; + UbTupleInt3 getBlockIndexes(double blockX1Coord, double blockX2Coord, double blockX3Coord, int level) const; + UbTupleDouble3 getBlockLengths(SPtr<Block3D> block) const; + UbTupleDouble6 getBlockOversize() const; + void setCoordinateTransformator(SPtr<CoordinateTransformation3D> trafo); + const SPtr<CoordinateTransformation3D> getCoordinateTransformator() const; + void setDeltaX(double dx); + void setDeltaX(double worldUnit, double gridUnit); + double getDeltaX(int level) const; + double getDeltaX(SPtr<Block3D> block) const; + UbTupleDouble3 getNodeOffset(SPtr<Block3D> block) const; + Vector3D getNodeCoordinates(SPtr<Block3D> block, int ix1, int ix2, int ix3) const; + UbTupleInt3 getNodeIndexes(SPtr<Block3D> block, double nodeX1Coord, double nodeX2Coord, double nodeX3Coord) const; + void setBlockNX(int nx1, int nx2, int nx3); + UbTupleInt3 getBlockNX() const; + UbTupleDouble3 getBlockWorldCoordinates(SPtr<Block3D> block) const; + UbTupleDouble3 getBlockWorldCoordinates(int blockX1Index, int blockX2Index, int blockX3Index, int level) const; + void setNX1(int nx1); + void setNX2(int nx2); + void setNX3(int nx3); + int getNX1() const; + int getNX2() const; + int getNX3() const; + void calcStartCoordinatesAndDelta(SPtr<Block3D> block, double &worldX1, double &worldX2, double &worldX3, + double &deltaX); + void calcStartCoordinatesWithOutOverlap(SPtr<Block3D> block, double &worldX1, double &worldX2, double &worldX3); + ////////////////////////////////////////////////////////////////////////// + // LBM + // double getDeltaT(SPtr<Block3D>) const; + ////////////////////////////////////////////////////////////////////////// + void setTimeStep(double step); + double getTimeStep() const; protected: - void checkLevel(int level); - bool hasLevel(int level) const; + void checkLevel(int level); + bool hasLevel(int level) const; - void fillExtentWithBlocks( UbTupleInt3 minInd, UbTupleInt3 maxInd ); + void fillExtentWithBlocks(UbTupleInt3 minInd, UbTupleInt3 maxInd); - void getSubBlocksZero(int ix1, int ix2, int ix3, int level,std::vector<SPtr<Block3D>>& blockVector, int levelDepth); + void getSubBlocksZero(int ix1, int ix2, int ix3, int level, std::vector<SPtr<Block3D>> &blockVector, + int levelDepth); - void getSubBlocksEast(int ix1, int ix2, int ix3, int level, std::vector<SPtr<Block3D>>& blockVector, int levelDepth); - void getSubBlocksWest(int ix1, int ix2, int ix3, int level, std::vector<SPtr<Block3D>>& blockVector, int levelDepth); - void getSubBlocksNorth(int ix1, int ix2, int ix3, int level, std::vector<SPtr<Block3D>>& blockVector, int levelDepth); - void getSubBlocksSouth(int ix1, int ix2, int ix3, int level, std::vector<SPtr<Block3D>>& blockVector, int levelDepth); - void getSubBlocksTop(int ix1, int ix2, int ix3, int level, std::vector<SPtr<Block3D>>& blockVector, int levelDepth); - void getSubBlocksBottom(int ix1, int ix2, int ix3, int level, std::vector<SPtr<Block3D>>& blockVector, int levelDepth); + void getSubBlocksEast(int ix1, int ix2, int ix3, int level, std::vector<SPtr<Block3D>> &blockVector, + int levelDepth); + void getSubBlocksWest(int ix1, int ix2, int ix3, int level, std::vector<SPtr<Block3D>> &blockVector, + int levelDepth); + void getSubBlocksNorth(int ix1, int ix2, int ix3, int level, std::vector<SPtr<Block3D>> &blockVector, + int levelDepth); + void getSubBlocksSouth(int ix1, int ix2, int ix3, int level, std::vector<SPtr<Block3D>> &blockVector, + int levelDepth); + void getSubBlocksTop(int ix1, int ix2, int ix3, int level, std::vector<SPtr<Block3D>> &blockVector, int levelDepth); + void getSubBlocksBottom(int ix1, int ix2, int ix3, int level, std::vector<SPtr<Block3D>> &blockVector, + int levelDepth); - void getSubBlocksSouthEast(int ix1, int ix2, int ix3, int level, std::vector<SPtr<Block3D>>& blockVector, int levelDepth); - void getSubBlocksSouthWest(int ix1, int ix2, int ix3, int level, std::vector<SPtr<Block3D>>& blockVector, int levelDepth); - void getSubBlocksNorthEast(int ix1, int ix2, int ix3, int level, std::vector<SPtr<Block3D>>& blockVector, int levelDepth); - void getSubBlocksNorthWest(int ix1, int ix2, int ix3, int level, std::vector<SPtr<Block3D>>& blockVector, int levelDepth); + void getSubBlocksSouthEast(int ix1, int ix2, int ix3, int level, std::vector<SPtr<Block3D>> &blockVector, + int levelDepth); + void getSubBlocksSouthWest(int ix1, int ix2, int ix3, int level, std::vector<SPtr<Block3D>> &blockVector, + int levelDepth); + void getSubBlocksNorthEast(int ix1, int ix2, int ix3, int level, std::vector<SPtr<Block3D>> &blockVector, + int levelDepth); + void getSubBlocksNorthWest(int ix1, int ix2, int ix3, int level, std::vector<SPtr<Block3D>> &blockVector, + int levelDepth); - void getSubBlocksTopEast(int ix1, int ix2, int ix3, int level, std::vector<SPtr<Block3D>>& blockVector, int levelDepth); - void getSubBlocksTopWest(int ix1, int ix2, int ix3, int level, std::vector<SPtr<Block3D>>& blockVector, int levelDepth); - void getSubBlocksTopNorth(int ix1, int ix2, int ix3, int level, std::vector<SPtr<Block3D>>& blockVector, int levelDepth); - void getSubBlocksTopSouth(int ix1, int ix2, int ix3, int level, std::vector<SPtr<Block3D>>& blockVector, int levelDepth); + void getSubBlocksTopEast(int ix1, int ix2, int ix3, int level, std::vector<SPtr<Block3D>> &blockVector, + int levelDepth); + void getSubBlocksTopWest(int ix1, int ix2, int ix3, int level, std::vector<SPtr<Block3D>> &blockVector, + int levelDepth); + void getSubBlocksTopNorth(int ix1, int ix2, int ix3, int level, std::vector<SPtr<Block3D>> &blockVector, + int levelDepth); + void getSubBlocksTopSouth(int ix1, int ix2, int ix3, int level, std::vector<SPtr<Block3D>> &blockVector, + int levelDepth); - void getSubBlocksBottomEast(int ix1, int ix2, int ix3, int level, std::vector<SPtr<Block3D>>& blockVector, int levelDepth); - void getSubBlocksBottomWest(int ix1, int ix2, int ix3, int level, std::vector<SPtr<Block3D>>& blockVector, int levelDepth); - void getSubBlocksBottomNorth(int ix1, int ix2, int ix3, int level, std::vector<SPtr<Block3D>>& blockVector, int levelDepth); - void getSubBlocksBottomSouth(int ix1, int ix2, int ix3, int level, std::vector<SPtr<Block3D>>& blockVector, int levelDepth); + void getSubBlocksBottomEast(int ix1, int ix2, int ix3, int level, std::vector<SPtr<Block3D>> &blockVector, + int levelDepth); + void getSubBlocksBottomWest(int ix1, int ix2, int ix3, int level, std::vector<SPtr<Block3D>> &blockVector, + int levelDepth); + void getSubBlocksBottomNorth(int ix1, int ix2, int ix3, int level, std::vector<SPtr<Block3D>> &blockVector, + int levelDepth); + void getSubBlocksBottomSouth(int ix1, int ix2, int ix3, int level, std::vector<SPtr<Block3D>> &blockVector, + int levelDepth); - void getSubBlocksTopNorthEast(int ix1, int ix2, int ix3, int level, std::vector<SPtr<Block3D>>& blockVector, int levelDepth); - void getSubBlocksTopNorthWest(int ix1, int ix2, int ix3, int level, std::vector<SPtr<Block3D>>& blockVector, int levelDepth); - void getSubBlocksTopSouthEast(int ix1, int ix2, int ix3, int level, std::vector<SPtr<Block3D>>& blockVector, int levelDepth); - void getSubBlocksTopSouthWest(int ix1, int ix2, int ix3, int level, std::vector<SPtr<Block3D>>& blockVector, int levelDepth); - void getSubBlocksBottomNorthEast(int ix1, int ix2, int ix3, int level, std::vector<SPtr<Block3D>>& blockVector, int levelDepth); - void getSubBlocksBottomNorthWest(int ix1, int ix2, int ix3, int level, std::vector<SPtr<Block3D>>& blockVector, int levelDepth); - void getSubBlocksBottomSouthEast(int ix1, int ix2, int ix3, int level, std::vector<SPtr<Block3D>>& blockVector, int levelDepth); - void getSubBlocksBottomSouthWest(int ix1, int ix2, int ix3, int level, std::vector<SPtr<Block3D>>& blockVector, int levelDepth); + void getSubBlocksTopNorthEast(int ix1, int ix2, int ix3, int level, std::vector<SPtr<Block3D>> &blockVector, + int levelDepth); + void getSubBlocksTopNorthWest(int ix1, int ix2, int ix3, int level, std::vector<SPtr<Block3D>> &blockVector, + int levelDepth); + void getSubBlocksTopSouthEast(int ix1, int ix2, int ix3, int level, std::vector<SPtr<Block3D>> &blockVector, + int levelDepth); + void getSubBlocksTopSouthWest(int ix1, int ix2, int ix3, int level, std::vector<SPtr<Block3D>> &blockVector, + int levelDepth); + void getSubBlocksBottomNorthEast(int ix1, int ix2, int ix3, int level, std::vector<SPtr<Block3D>> &blockVector, + int levelDepth); + void getSubBlocksBottomNorthWest(int ix1, int ix2, int ix3, int level, std::vector<SPtr<Block3D>> &blockVector, + int levelDepth); + void getSubBlocksBottomSouthEast(int ix1, int ix2, int ix3, int level, std::vector<SPtr<Block3D>> &blockVector, + int levelDepth); + void getSubBlocksBottomSouthWest(int ix1, int ix2, int ix3, int level, std::vector<SPtr<Block3D>> &blockVector, + int levelDepth); private: - LevelSet levelSet; - BlockIDMap blockIdMap; - Interactor3DSet interactors; + LevelSet levelSet; + BlockIDMap blockIdMap; + Interactor3DSet interactors; + + int rank{ 0 }; + int bundle{ 0 }; - int rank{0}; - int bundle{0}; - - bool periodicX1{false}; - bool periodicX2{false}; - bool periodicX3{false}; + bool periodicX1{ false }; + bool periodicX2{ false }; + bool periodicX3{ false }; - int blockNx1{0}; - int blockNx2{0}; - int blockNx3{0}; + int blockNx1{ 0 }; + int blockNx2{ 0 }; + int blockNx3{ 0 }; - int nx1{0}; - int nx2{0}; - int nx3{0}; + int nx1{ 0 }; + int nx2{ 0 }; + int nx3{ 0 }; - SPtr<CoordinateTransformation3D> trafo; - double orgDeltaX{1.0}; + SPtr<CoordinateTransformation3D> trafo; + double orgDeltaX{ 1.0 }; - double timeStep{0.0}; - + double timeStep{ 0.0 }; }; -#endif +#endif diff --git a/src/cpu/VirtualFluidsCore/Grid/Grid3DSystem.cpp b/src/cpu/VirtualFluidsCore/Grid/Grid3DSystem.cpp index b3c711a73b5f99a922a04e05e95289cd83d5ba5f..33db1b0cf0fd07e5ac1db313ace368a3da0c7aed 100644 --- a/src/cpu/VirtualFluidsCore/Grid/Grid3DSystem.cpp +++ b/src/cpu/VirtualFluidsCore/Grid/Grid3DSystem.cpp @@ -1,28 +1,28 @@ //======================================================================================= -// ____ ____ __ ______ __________ __ __ __ __ -// \ \ | | | | | _ \ |___ ___| | | | | / \ | | -// \ \ | | | | | |_) | | | | | | | / \ | | -// \ \ | | | | | _ / | | | | | | / /\ \ | | -// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ -// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| -// \ \ | | ________________________________________________________________ -// \ \ | | | ______________________________________________________________| -// \ \| | | | __ __ __ __ ______ _______ -// \ | | |_____ | | | | | | | | | _ \ / _____) -// \ | | _____| | | | | | | | | | | \ \ \_______ +// ____ ____ __ ______ __________ __ __ __ __ +// \ \ | | | | | _ \ |___ ___| | | | | / \ | | +// \ \ | | | | | |_) | | | | | | | / \ | | +// \ \ | | | | | _ / | | | | | | / /\ \ | | +// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ +// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| +// \ \ | | ________________________________________________________________ +// \ \ | | | ______________________________________________________________| +// \ \| | | | __ __ __ __ ______ _______ +// \ | | |_____ | | | | | | | | | _ \ / _____) +// \ | | _____| | | | | | | | | | | \ \ \_______ // \ | | | | |_____ | \_/ | | | | |_/ / _____ | -// \ _____| |__| |________| \_______/ |__| |______/ (_______/ +// \ _____| |__| |________| \_______/ |__| |______/ (_______/ // -// This file is part of VirtualFluids. VirtualFluids is free software: you can +// This file is part of VirtualFluids. VirtualFluids is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of +// License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. -// -// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// +// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License along // with VirtualFluids (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>. // @@ -35,47 +35,24 @@ namespace Grid3DSystem { - const int INVDIR[] = { INV_E , - INV_W , - INV_N , - INV_S , - INV_T , - INV_B , - INV_NE , - INV_NW , - INV_SE , - INV_SW , - INV_TE , - INV_TW , - INV_BE , - INV_BW , - INV_TN , - INV_TS , - INV_BN , - INV_BS , - INV_TNE, - INV_TNW, - INV_TSE, - INV_TSW, - INV_BNE, - INV_BNW, - INV_BSE, - INV_BSW }; +const int INVDIR[] = { INV_E, INV_W, INV_N, INV_S, INV_T, INV_B, INV_NE, INV_NW, INV_SE, + INV_SW, INV_TE, INV_TW, INV_BE, INV_BW, INV_TN, INV_TS, INV_BN, INV_BS, + INV_TNE, INV_TNW, INV_TSE, INV_TSW, INV_BNE, INV_BNW, INV_BSE, INV_BSW }; - //index 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 - //direction: E, W, N, S, T, B, NE, SW, SE, NW, TE, BW, BE, TW, TN, BS, BN, TS, TNE TNW TSE TSW BNE BNW BSE BSW - const int EX1[] = { 1, -1, 0, 0, 0, 0, 1, -1, 1, -1, 1, -1, 1, -1, 0, 0, 0, 0, 1, -1, 1, -1, 1, -1, 1, -1 }; - const int EX2[] = { 0, 0, 1, -1, 0, 0, 1, -1, -1, 1, 0, 0, 0, 0, 1, -1, 1, -1, 1, 1, -1, -1, 1, 1, -1, -1 }; - const int EX3[] = { 0, 0, 0, 0, 1, -1, 0, 0, 0, 0, 1, -1, -1, 1, 1, -1, -1, 1, 1, 1, 1, 1, -1, -1, -1, -1 }; -} +// index 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 +// direction: E, W, N, S, T, B, NE, SW, SE, NW, TE, BW, BE, TW, TN, BS, BN, TS, TNE TNW TSE TSW BNE BNW BSE +// BSW +const int EX1[] = { 1, -1, 0, 0, 0, 0, 1, -1, 1, -1, 1, -1, 1, -1, 0, 0, 0, 0, 1, -1, 1, -1, 1, -1, 1, -1 }; +const int EX2[] = { 0, 0, 1, -1, 0, 0, 1, -1, -1, 1, 0, 0, 0, 0, 1, -1, 1, -1, 1, 1, -1, -1, 1, 1, -1, -1 }; +const int EX3[] = { 0, 0, 0, 0, 1, -1, 0, 0, 0, 0, 1, -1, -1, 1, 1, -1, -1, 1, 1, 1, 1, 1, -1, -1, -1, -1 }; +} // namespace Grid3DSystem ////////////////////////////////////////////////////////////////////////// -const int& Grid3DSystem::getInvertDirection(const int& direction) -{ +const int &Grid3DSystem::getInvertDirection(const int &direction) +{ #ifdef _DEBUG - if(direction<STARTDIR || direction>ENDDIR) - throw UbException(UB_EXARGS,"unknown direction"); + if (direction < STARTDIR || direction > ENDDIR) + throw UbException(UB_EXARGS, "unknown direction"); #endif - return INVDIR[direction]; + return INVDIR[direction]; } - diff --git a/src/cpu/VirtualFluidsCore/Grid/Grid3DSystem.h b/src/cpu/VirtualFluidsCore/Grid/Grid3DSystem.h index 49fb973f566389194f7ef59a3383219baa777311..ee61b8f7327e76a9393d4d3caa13c3a796470c08 100644 --- a/src/cpu/VirtualFluidsCore/Grid/Grid3DSystem.h +++ b/src/cpu/VirtualFluidsCore/Grid/Grid3DSystem.h @@ -1,28 +1,28 @@ //======================================================================================= -// ____ ____ __ ______ __________ __ __ __ __ -// \ \ | | | | | _ \ |___ ___| | | | | / \ | | -// \ \ | | | | | |_) | | | | | | | / \ | | -// \ \ | | | | | _ / | | | | | | / /\ \ | | -// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ -// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| -// \ \ | | ________________________________________________________________ -// \ \ | | | ______________________________________________________________| -// \ \| | | | __ __ __ __ ______ _______ -// \ | | |_____ | | | | | | | | | _ \ / _____) -// \ | | _____| | | | | | | | | | | \ \ \_______ +// ____ ____ __ ______ __________ __ __ __ __ +// \ \ | | | | | _ \ |___ ___| | | | | / \ | | +// \ \ | | | | | |_) | | | | | | | / \ | | +// \ \ | | | | | _ / | | | | | | / /\ \ | | +// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ +// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| +// \ \ | | ________________________________________________________________ +// \ \ | | | ______________________________________________________________| +// \ \| | | | __ __ __ __ ______ _______ +// \ | | |_____ | | | | | | | | | _ \ / _____) +// \ | | _____| | | | | | | | | | | \ \ \_______ // \ | | | | |_____ | \_/ | | | | |_/ / _____ | -// \ _____| |__| |________| \_______/ |__| |______/ (_______/ +// \ _____| |__| |________| \_______/ |__| |______/ (_______/ // -// This file is part of VirtualFluids. VirtualFluids is free software: you can +// This file is part of VirtualFluids. VirtualFluids is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of +// License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. -// -// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// +// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License along // with VirtualFluids (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>. // @@ -38,149 +38,254 @@ #include <iostream> #include <string> -#include <basics/utilities/UbMath.h> #include <basics/utilities/UbException.h> - +#include <basics/utilities/UbMath.h> namespace Grid3DSystem { - static const int STARTDIR = 0; +static const int STARTDIR = 0; - static const int E /*f1 */ = 0; - static const int W /*f2 */ = 1; - static const int N /*f3 */ = 2; - static const int S /*f4 */ = 3; - static const int T /*f5 */ = 4; - static const int B /*f6 */ = 5; - static const int NE /*f7 */ = 6; - static const int SW /*f8 */ = 7; - static const int SE /*f9 */ = 8; - static const int NW /*f10*/ = 9; - static const int TE /*f11*/ = 10; - static const int BW /*f12*/ = 11; - static const int BE /*f13*/ = 12; - static const int TW /*f14*/ = 13; - static const int TN /*f15*/ = 14; - static const int BS /*f16*/ = 15; - static const int BN /*f17*/ = 16; - static const int TS /*f18*/ = 17; - static const int TNE = 18; - static const int TNW = 19; - static const int TSE = 20; - static const int TSW = 21; - static const int BNE = 22; - static const int BNW = 23; - static const int BSE = 24; - static const int BSW = 25; - static const int ZERO /*f0 */ = 26; +static const int E /*f1 */ = 0; +static const int W /*f2 */ = 1; +static const int N /*f3 */ = 2; +static const int S /*f4 */ = 3; +static const int T /*f5 */ = 4; +static const int B /*f6 */ = 5; +static const int NE /*f7 */ = 6; +static const int SW /*f8 */ = 7; +static const int SE /*f9 */ = 8; +static const int NW /*f10*/ = 9; +static const int TE /*f11*/ = 10; +static const int BW /*f12*/ = 11; +static const int BE /*f13*/ = 12; +static const int TW /*f14*/ = 13; +static const int TN /*f15*/ = 14; +static const int BS /*f16*/ = 15; +static const int BN /*f17*/ = 16; +static const int TS /*f18*/ = 17; +static const int TNE = 18; +static const int TNW = 19; +static const int TSE = 20; +static const int TSW = 21; +static const int BNE = 22; +static const int BNW = 23; +static const int BSE = 24; +static const int BSW = 25; +static const int ZERO /*f0 */ = 26; - static const int ENDDIR = 25; +static const int ENDDIR = 25; - static const int INV_E = W; - static const int INV_W = E; - static const int INV_N = S; - static const int INV_S = N; - static const int INV_T = B; - static const int INV_B = T; - static const int INV_NE = SW; - static const int INV_NW = SE; - static const int INV_SE = NW; - static const int INV_SW = NE; - static const int INV_TE = BW; - static const int INV_TW = BE; - static const int INV_BE = TW; - static const int INV_BW = TE; - static const int INV_TN = BS; - static const int INV_TS = BN; - static const int INV_BN = TS; - static const int INV_BS = TN; - static const int INV_TNE = BSW; - static const int INV_TNW = BSE; - static const int INV_TSE = BNW; - static const int INV_TSW = BNE; - static const int INV_BNE = TSW; - static const int INV_BNW = TSE; - static const int INV_BSE = TNW; - static const int INV_BSW = TNE; +static const int INV_E = W; +static const int INV_W = E; +static const int INV_N = S; +static const int INV_S = N; +static const int INV_T = B; +static const int INV_B = T; +static const int INV_NE = SW; +static const int INV_NW = SE; +static const int INV_SE = NW; +static const int INV_SW = NE; +static const int INV_TE = BW; +static const int INV_TW = BE; +static const int INV_BE = TW; +static const int INV_BW = TE; +static const int INV_TN = BS; +static const int INV_TS = BN; +static const int INV_BN = TS; +static const int INV_BS = TN; +static const int INV_TNE = BSW; +static const int INV_TNW = BSE; +static const int INV_TSE = BNW; +static const int INV_TSW = BNE; +static const int INV_BNE = TSW; +static const int INV_BNW = TSE; +static const int INV_BSE = TNW; +static const int INV_BSW = TNE; - extern const int INVDIR[ENDDIR+1]; +extern const int INVDIR[ENDDIR + 1]; - static const int MINLEVEL = 0; - static const int MAXLEVEL = 25; +static const int MINLEVEL = 0; +static const int MAXLEVEL = 25; - extern const int EX1[ENDDIR+1]; - extern const int EX2[ENDDIR+1]; - extern const int EX3[ENDDIR+1]; +extern const int EX1[ENDDIR + 1]; +extern const int EX2[ENDDIR + 1]; +extern const int EX3[ENDDIR + 1]; - inline std::string getDirectionString(int direction) - { - switch(direction) - { - case E : return "E"; - case W : return "W"; - case N : return "N"; - case S : return "S"; - case T : return "T"; - case B : return "B"; - case NE : return "NE"; - case NW : return "NW"; - case SE : return "SE"; - case SW : return "SW"; - case TE : return "TE"; - case TW : return "TW"; - case BE : return "BE"; - case BW : return "BW"; - case TN : return "TN"; - case TS : return "TS"; - case BN : return "BN"; - case BS : return "BS"; - case TNE : return "TNE"; - case TNW : return "TNW"; - case TSE : return "TSE"; - case TSW : return "TSW"; - case BNE : return "BNE"; - case BNW : return "BNW"; - case BSE : return "BSE"; - case BSW : return "BSW"; - default : return "Cell3DSystem::getDrectionString(...) - unknown dir"; - } - } - static const int& getInvertDirection(const int& direction); +inline std::string getDirectionString(int direction) +{ + switch (direction) { + case E: + return "E"; + case W: + return "W"; + case N: + return "N"; + case S: + return "S"; + case T: + return "T"; + case B: + return "B"; + case NE: + return "NE"; + case NW: + return "NW"; + case SE: + return "SE"; + case SW: + return "SW"; + case TE: + return "TE"; + case TW: + return "TW"; + case BE: + return "BE"; + case BW: + return "BW"; + case TN: + return "TN"; + case TS: + return "TS"; + case BN: + return "BN"; + case BS: + return "BS"; + case TNE: + return "TNE"; + case TNW: + return "TNW"; + case TSE: + return "TSE"; + case TSW: + return "TSW"; + case BNE: + return "BNE"; + case BNW: + return "BNW"; + case BSE: + return "BSE"; + case BSW: + return "BSW"; + default: + return "Cell3DSystem::getDrectionString(...) - unknown dir"; + } +} +static const int &getInvertDirection(const int &direction); ////////////////////////////////////////////////////////////////////////// - static inline void setNeighborCoordinatesForDirection(int &x1, int &x2,int &x3, const int& direction) - { - switch(direction) - { - case Grid3DSystem::E : x1++; break; - case Grid3DSystem::N : x2++; break; - case Grid3DSystem::T : x3++; break; - case Grid3DSystem::W : x1--; break; - case Grid3DSystem::S : x2--; break; - case Grid3DSystem::B : x3--; break; - case Grid3DSystem::NE : x1++; x2++; break; - case Grid3DSystem::NW : x1--; x2++; break; - case Grid3DSystem::SW : x1--; x2--; break; - case Grid3DSystem::SE : x1++; x2--; break; - case Grid3DSystem::TE : x1++; x3++; break; - case Grid3DSystem::BW : x1--; x3--; break; - case Grid3DSystem::BE : x1++; x3--; break; - case Grid3DSystem::TW : x1--; x3++; break; - case Grid3DSystem::TN : x2++; x3++; break; - case Grid3DSystem::BS : x2--; x3--; break; - case Grid3DSystem::BN : x2++; x3--; break; - case Grid3DSystem::TS : x2--; x3++; break; - case Grid3DSystem::TNE: x1++; x2++; x3++; break; - case Grid3DSystem::TNW: x1--; x2++; x3++; break; - case Grid3DSystem::TSE: x1++; x2--; x3++; break; - case Grid3DSystem::TSW: x1--; x2--; x3++; break; - case Grid3DSystem::BNE: x1++; x2++; x3--; break; - case Grid3DSystem::BNW: x1--; x2++; x3--; break; - case Grid3DSystem::BSE: x1++; x2--; x3--; break; - case Grid3DSystem::BSW: x1--; x2--; x3--; break; - default: throw UbException(UB_EXARGS,"no direction ..."); - } - } +static inline void setNeighborCoordinatesForDirection(int &x1, int &x2, int &x3, const int &direction) +{ + switch (direction) { + case Grid3DSystem::E: + x1++; + break; + case Grid3DSystem::N: + x2++; + break; + case Grid3DSystem::T: + x3++; + break; + case Grid3DSystem::W: + x1--; + break; + case Grid3DSystem::S: + x2--; + break; + case Grid3DSystem::B: + x3--; + break; + case Grid3DSystem::NE: + x1++; + x2++; + break; + case Grid3DSystem::NW: + x1--; + x2++; + break; + case Grid3DSystem::SW: + x1--; + x2--; + break; + case Grid3DSystem::SE: + x1++; + x2--; + break; + case Grid3DSystem::TE: + x1++; + x3++; + break; + case Grid3DSystem::BW: + x1--; + x3--; + break; + case Grid3DSystem::BE: + x1++; + x3--; + break; + case Grid3DSystem::TW: + x1--; + x3++; + break; + case Grid3DSystem::TN: + x2++; + x3++; + break; + case Grid3DSystem::BS: + x2--; + x3--; + break; + case Grid3DSystem::BN: + x2++; + x3--; + break; + case Grid3DSystem::TS: + x2--; + x3++; + break; + case Grid3DSystem::TNE: + x1++; + x2++; + x3++; + break; + case Grid3DSystem::TNW: + x1--; + x2++; + x3++; + break; + case Grid3DSystem::TSE: + x1++; + x2--; + x3++; + break; + case Grid3DSystem::TSW: + x1--; + x2--; + x3++; + break; + case Grid3DSystem::BNE: + x1++; + x2++; + x3--; + break; + case Grid3DSystem::BNW: + x1--; + x2++; + x3--; + break; + case Grid3DSystem::BSE: + x1++; + x2--; + x3--; + break; + case Grid3DSystem::BSW: + x1--; + x2--; + x3--; + break; + default: + throw UbException(UB_EXARGS, "no direction ..."); + } } +} // namespace Grid3DSystem -#endif +#endif diff --git a/src/cpu/VirtualFluidsCore/Interactors/D3Q27Interactor.cpp b/src/cpu/VirtualFluidsCore/Interactors/D3Q27Interactor.cpp index bc77cedde86a4aa83bb1328cad15a3e72f71af31..55ce8d1dd332c51d1acd8e1285ea0e81ec9ab00f 100644 --- a/src/cpu/VirtualFluidsCore/Interactors/D3Q27Interactor.cpp +++ b/src/cpu/VirtualFluidsCore/Interactors/D3Q27Interactor.cpp @@ -1,28 +1,28 @@ //======================================================================================= -// ____ ____ __ ______ __________ __ __ __ __ -// \ \ | | | | | _ \ |___ ___| | | | | / \ | | -// \ \ | | | | | |_) | | | | | | | / \ | | -// \ \ | | | | | _ / | | | | | | / /\ \ | | -// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ -// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| -// \ \ | | ________________________________________________________________ -// \ \ | | | ______________________________________________________________| -// \ \| | | | __ __ __ __ ______ _______ -// \ | | |_____ | | | | | | | | | _ \ / _____) -// \ | | _____| | | | | | | | | | | \ \ \_______ +// ____ ____ __ ______ __________ __ __ __ __ +// \ \ | | | | | _ \ |___ ___| | | | | / \ | | +// \ \ | | | | | |_) | | | | | | | / \ | | +// \ \ | | | | | _ / | | | | | | / /\ \ | | +// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ +// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| +// \ \ | | ________________________________________________________________ +// \ \ | | | ______________________________________________________________| +// \ \| | | | __ __ __ __ ______ _______ +// \ | | |_____ | | | | | | | | | _ \ / _____) +// \ | | _____| | | | | | | | | | | \ \ \_______ // \ | | | | |_____ | \_/ | | | | |_/ / _____ | -// \ _____| |__| |________| \_______/ |__| |______/ (_______/ +// \ _____| |__| |________| \_______/ |__| |______/ (_______/ // -// This file is part of VirtualFluids. VirtualFluids is free software: you can +// This file is part of VirtualFluids. VirtualFluids is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of +// License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. -// -// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// +// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License along // with VirtualFluids (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>. // @@ -34,21 +34,20 @@ //======================================================================================= #include "D3Q27Interactor.h" -#include <basics/utilities/UbMath.h> #include <basics/utilities/UbLogger.h> +#include <basics/utilities/UbMath.h> #include <basics/writer/WbWriterVtkXmlBinary.h> -#include <GbCuboid3D.h> -#include <GbLine3D.h> -#include "Block3D.h" -#include "Grid3D.h" +#include "BCAdapter.h" #include "BCArray3D.h" +#include "BCProcessor.h" +#include "Block3D.h" #include "BoundaryConditions.h" +#include "Grid3D.h" #include "LBMKernel.h" -#include "BCProcessor.h" -#include "BCAdapter.h" - +#include <GbCuboid3D.h> +#include <GbLine3D.h> using namespace std; @@ -56,139 +55,225 @@ using namespace std; ////////////////////////////////////////////////////////////////////////// D3Q27Interactor::D3Q27Interactor() : Interactor3D() { - this->reinitWithStoredQsFlag = false; - this->initRayVectors(); + this->reinitWithStoredQsFlag = false; + this->initRayVectors(); } ////////////////////////////////////////////////////////////////////////// D3Q27Interactor::D3Q27Interactor(SPtr<GbObject3D> geoObject3D, SPtr<Grid3D> grid, int type) -: Interactor3D(geoObject3D, grid, type), relevantForForces(false) + : Interactor3D(geoObject3D, grid, type), relevantForForces(false) { - this->reinitWithStoredQsFlag = false; - this->initRayVectors(); + this->reinitWithStoredQsFlag = false; + this->initRayVectors(); } ////////////////////////////////////////////////////////////////////////// -D3Q27Interactor::D3Q27Interactor(SPtr<GbObject3D> geoObject3D, SPtr<Grid3D> grid, SPtr<BCAdapter> bcAdapter, int type) - : Interactor3D(geoObject3D, grid, type), relevantForForces(false) +D3Q27Interactor::D3Q27Interactor(SPtr<GbObject3D> geoObject3D, SPtr<Grid3D> grid, SPtr<BCAdapter> bcAdapter, int type) + : Interactor3D(geoObject3D, grid, type), relevantForForces(false) { - this->reinitWithStoredQsFlag = false; - this->addBCAdapter(bcAdapter); - this->initRayVectors(); + this->reinitWithStoredQsFlag = false; + this->addBCAdapter(bcAdapter); + this->initRayVectors(); } ////////////////////////////////////////////////////////////////////////// -D3Q27Interactor::D3Q27Interactor(SPtr<GbObject3D> geoObject3D, SPtr<Grid3D> grid, SPtr<BCAdapter> bcAdapter, int type, Interactor3D::Accuracy a) - : Interactor3D(geoObject3D, grid, type, a), relevantForForces(false) +D3Q27Interactor::D3Q27Interactor(SPtr<GbObject3D> geoObject3D, SPtr<Grid3D> grid, SPtr<BCAdapter> bcAdapter, int type, + Interactor3D::Accuracy a) + : Interactor3D(geoObject3D, grid, type, a), relevantForForces(false) { - this->reinitWithStoredQsFlag = false; - this->addBCAdapter(bcAdapter); - this->initRayVectors(); + this->reinitWithStoredQsFlag = false; + this->addBCAdapter(bcAdapter); + this->initRayVectors(); } ////////////////////////////////////////////////////////////////////////// -D3Q27Interactor::~D3Q27Interactor() -= default; +D3Q27Interactor::~D3Q27Interactor() = default; ////////////////////////////////////////////////////////////////////////// void D3Q27Interactor::initRayVectors() { - int fdir; - double c1oS2 = UbMath::one_over_sqrt2; - double c1oS3 = UbMath::one_over_sqrt3; - fdir = D3Q27System::E; rayX1[fdir] = 1.0; rayX2[fdir] = 0.0; rayX3[fdir] = 0.0; - fdir = D3Q27System::W; rayX1[fdir] = -1.0; rayX2[fdir] = 0.0; rayX3[fdir] = 0.0; - fdir = D3Q27System::N; rayX1[fdir] = 0.0; rayX2[fdir] = 1.0; rayX3[fdir] = 0.0; - fdir = D3Q27System::S; rayX1[fdir] = 0.0; rayX2[fdir] = -1.0; rayX3[fdir] = 0.0; - fdir = D3Q27System::T; rayX1[fdir] = 0.0; rayX2[fdir] = 0.0; rayX3[fdir] = 1.0; - fdir = D3Q27System::B; rayX1[fdir] = 0.0; rayX2[fdir] = 0.0; rayX3[fdir] = -1.0; - fdir = D3Q27System::NE; rayX1[fdir] = c1oS2; rayX2[fdir] = c1oS2; rayX3[fdir] = 0.0; - fdir = D3Q27System::SW; rayX1[fdir] = -c1oS2; rayX2[fdir] = -c1oS2; rayX3[fdir] = 0.0; - fdir = D3Q27System::SE; rayX1[fdir] = c1oS2; rayX2[fdir] = -c1oS2; rayX3[fdir] = 0.0; - fdir = D3Q27System::NW; rayX1[fdir] = -c1oS2; rayX2[fdir] = c1oS2; rayX3[fdir] = 0.0; - fdir = D3Q27System::TE; rayX1[fdir] = c1oS2; rayX2[fdir] = 0.0; rayX3[fdir] = c1oS2; - fdir = D3Q27System::BW; rayX1[fdir] = -c1oS2; rayX2[fdir] = 0.0; rayX3[fdir] = -c1oS2; - fdir = D3Q27System::BE; rayX1[fdir] = c1oS2; rayX2[fdir] = 0.0; rayX3[fdir] = -c1oS2; - fdir = D3Q27System::TW; rayX1[fdir] = -c1oS2; rayX2[fdir] = 0.0; rayX3[fdir] = c1oS2; - fdir = D3Q27System::TN; rayX1[fdir] = 0.0; rayX2[fdir] = c1oS2; rayX3[fdir] = c1oS2; - fdir = D3Q27System::BS; rayX1[fdir] = 0.0; rayX2[fdir] =-c1oS2; rayX3[fdir] = -c1oS2; - fdir = D3Q27System::BN; rayX1[fdir] = 0.0; rayX2[fdir] = c1oS2; rayX3[fdir] = -c1oS2; - fdir = D3Q27System::TS; rayX1[fdir] = 0.0; rayX2[fdir] =-c1oS2; rayX3[fdir] = c1oS2; - - fdir = D3Q27System::TNW; rayX1[fdir] = -c1oS3; rayX2[fdir] = c1oS3; rayX3[fdir] = c1oS3; - fdir = D3Q27System::TNE; rayX1[fdir] = c1oS3; rayX2[fdir] = c1oS3; rayX3[fdir] = c1oS3; - fdir = D3Q27System::TSW; rayX1[fdir] = -c1oS3; rayX2[fdir] =-c1oS3; rayX3[fdir] = c1oS3; - fdir = D3Q27System::TSE; rayX1[fdir] = c1oS3; rayX2[fdir] =-c1oS3; rayX3[fdir] = c1oS3; - fdir = D3Q27System::BNW; rayX1[fdir] = -c1oS3; rayX2[fdir] = c1oS3; rayX3[fdir] = -c1oS3; - fdir = D3Q27System::BNE; rayX1[fdir] = c1oS3; rayX2[fdir] = c1oS3; rayX3[fdir] = -c1oS3; - fdir = D3Q27System::BSW; rayX1[fdir] = -c1oS3; rayX2[fdir] =-c1oS3; rayX3[fdir] = -c1oS3; - fdir = D3Q27System::BSE; rayX1[fdir] = c1oS3; rayX2[fdir] =-c1oS3; rayX3[fdir] = -c1oS3; + int fdir; + double c1oS2 = UbMath::one_over_sqrt2; + double c1oS3 = UbMath::one_over_sqrt3; + fdir = D3Q27System::E; + rayX1[fdir] = 1.0; + rayX2[fdir] = 0.0; + rayX3[fdir] = 0.0; + fdir = D3Q27System::W; + rayX1[fdir] = -1.0; + rayX2[fdir] = 0.0; + rayX3[fdir] = 0.0; + fdir = D3Q27System::N; + rayX1[fdir] = 0.0; + rayX2[fdir] = 1.0; + rayX3[fdir] = 0.0; + fdir = D3Q27System::S; + rayX1[fdir] = 0.0; + rayX2[fdir] = -1.0; + rayX3[fdir] = 0.0; + fdir = D3Q27System::T; + rayX1[fdir] = 0.0; + rayX2[fdir] = 0.0; + rayX3[fdir] = 1.0; + fdir = D3Q27System::B; + rayX1[fdir] = 0.0; + rayX2[fdir] = 0.0; + rayX3[fdir] = -1.0; + fdir = D3Q27System::NE; + rayX1[fdir] = c1oS2; + rayX2[fdir] = c1oS2; + rayX3[fdir] = 0.0; + fdir = D3Q27System::SW; + rayX1[fdir] = -c1oS2; + rayX2[fdir] = -c1oS2; + rayX3[fdir] = 0.0; + fdir = D3Q27System::SE; + rayX1[fdir] = c1oS2; + rayX2[fdir] = -c1oS2; + rayX3[fdir] = 0.0; + fdir = D3Q27System::NW; + rayX1[fdir] = -c1oS2; + rayX2[fdir] = c1oS2; + rayX3[fdir] = 0.0; + fdir = D3Q27System::TE; + rayX1[fdir] = c1oS2; + rayX2[fdir] = 0.0; + rayX3[fdir] = c1oS2; + fdir = D3Q27System::BW; + rayX1[fdir] = -c1oS2; + rayX2[fdir] = 0.0; + rayX3[fdir] = -c1oS2; + fdir = D3Q27System::BE; + rayX1[fdir] = c1oS2; + rayX2[fdir] = 0.0; + rayX3[fdir] = -c1oS2; + fdir = D3Q27System::TW; + rayX1[fdir] = -c1oS2; + rayX2[fdir] = 0.0; + rayX3[fdir] = c1oS2; + fdir = D3Q27System::TN; + rayX1[fdir] = 0.0; + rayX2[fdir] = c1oS2; + rayX3[fdir] = c1oS2; + fdir = D3Q27System::BS; + rayX1[fdir] = 0.0; + rayX2[fdir] = -c1oS2; + rayX3[fdir] = -c1oS2; + fdir = D3Q27System::BN; + rayX1[fdir] = 0.0; + rayX2[fdir] = c1oS2; + rayX3[fdir] = -c1oS2; + fdir = D3Q27System::TS; + rayX1[fdir] = 0.0; + rayX2[fdir] = -c1oS2; + rayX3[fdir] = c1oS2; + + fdir = D3Q27System::TNW; + rayX1[fdir] = -c1oS3; + rayX2[fdir] = c1oS3; + rayX3[fdir] = c1oS3; + fdir = D3Q27System::TNE; + rayX1[fdir] = c1oS3; + rayX2[fdir] = c1oS3; + rayX3[fdir] = c1oS3; + fdir = D3Q27System::TSW; + rayX1[fdir] = -c1oS3; + rayX2[fdir] = -c1oS3; + rayX3[fdir] = c1oS3; + fdir = D3Q27System::TSE; + rayX1[fdir] = c1oS3; + rayX2[fdir] = -c1oS3; + rayX3[fdir] = c1oS3; + fdir = D3Q27System::BNW; + rayX1[fdir] = -c1oS3; + rayX2[fdir] = c1oS3; + rayX3[fdir] = -c1oS3; + fdir = D3Q27System::BNE; + rayX1[fdir] = c1oS3; + rayX2[fdir] = c1oS3; + rayX3[fdir] = -c1oS3; + fdir = D3Q27System::BSW; + rayX1[fdir] = -c1oS3; + rayX2[fdir] = -c1oS3; + rayX3[fdir] = -c1oS3; + fdir = D3Q27System::BSE; + rayX1[fdir] = c1oS3; + rayX2[fdir] = -c1oS3; + rayX3[fdir] = -c1oS3; } ////////////////////////////////////////////////////////////////////////// -void D3Q27Interactor::initInteractor(const double& timeStep) +void D3Q27Interactor::initInteractor(const double &timeStep) { - UBLOG(logDEBUG5,"D3Q27Interactor::initInteractor - "<<" for timestep = "<<timeStep); - - ////////////////////////////////////////////////////////////////////////// - //init bcs - int nofAdapter = (int)bcAdapters.size(); - if(nofAdapter==0) { UBLOG(logWARNING,"WARNING - D3Q27Interactor::initInteractor Warning - no nodeAdapter available"); } - bool needTimeDependence = false; - for(int pos=0; pos<nofAdapter; ++pos) - { - bcAdapters[pos]->init(this,timeStep); - if(bcAdapters[pos]->isTimeDependent()) needTimeDependence = true; - } - if(needTimeDependence) this->setTimeDependent(); - else this->unsetTimeDependent(); - - Interactor3D::initInteractor(timeStep); + UBLOG(logDEBUG5, "D3Q27Interactor::initInteractor - " + << " for timestep = " << timeStep); + + ////////////////////////////////////////////////////////////////////////// + // init bcs + int nofAdapter = (int)bcAdapters.size(); + if (nofAdapter == 0) { + UBLOG(logWARNING, "WARNING - D3Q27Interactor::initInteractor Warning - no nodeAdapter available"); + } + bool needTimeDependence = false; + for (int pos = 0; pos < nofAdapter; ++pos) { + bcAdapters[pos]->init(this, timeStep); + if (bcAdapters[pos]->isTimeDependent()) + needTimeDependence = true; + } + if (needTimeDependence) + this->setTimeDependent(); + else + this->unsetTimeDependent(); + + Interactor3D::initInteractor(timeStep); } ////////////////////////////////////////////////////////////////////////// -void D3Q27Interactor::updateInteractor(const double& timestep) +void D3Q27Interactor::updateInteractor(const double ×tep) { - UBLOG(logDEBUG5,"D3Q27Interactor::updateInteractor - for timestep = "<<timestep); - - ////////////////////////////////////////////////////////////////////////// - //update bcs - int nofAdapter = (int)bcAdapters.size(); - if(nofAdapter==0) { UBLOG(logERROR,"WARNING - D3Q27Interactor::updateInteractor Warning - no nodeAdapter available for "); } - - bool needTimeDependence = false; - - for(int pos=0; pos<nofAdapter; ++pos) - { - bcAdapters[pos]->update(this,timestep); - if(bcAdapters[pos]->isTimeDependent()) needTimeDependence = true; - } - if(needTimeDependence) this->setTimeDependent(); - else this->unsetTimeDependent(); - - for(BcNodeIndicesMap::value_type t : bcNodeIndicesMap) - { - SPtr<Block3D> block = t.first; - std::set< std::vector<int> >& transNodeIndicesSet = t.second; - - if(block->isNotActive() || !block) continue; - - SPtr<ILBMKernel> kernel = block->getKernel(); - SPtr<BCArray3D> bcArray = kernel->getBCProcessor()->getBCArray(); - - set< std::vector<int> >::iterator setPos; - - for(setPos=transNodeIndicesSet.begin(); setPos!=transNodeIndicesSet.end(); ++setPos) - { - int x1 = (*setPos)[0]; - int x2 = (*setPos)[1]; - int x3 = (*setPos)[2]; - Vector3D coords = grid.lock()->getNodeCoordinates(block, x1, x2, x3); - double worldX1 = coords[0]; - double worldX2 = coords[1]; - double worldX3 = coords[2]; - - SPtr<BoundaryConditions> bc = bcArray->getBC(x1,x2,x3); - if(bc) //may be that the BC has been deleted by the solid setting of another interactor - { - for(size_t i=0; i<bcAdapters.size(); i++) - bcAdapters[i]->adaptBC(*this,bc,worldX1,worldX2,worldX3,timestep); - } - } - } + UBLOG(logDEBUG5, "D3Q27Interactor::updateInteractor - for timestep = " << timestep); + + ////////////////////////////////////////////////////////////////////////// + // update bcs + int nofAdapter = (int)bcAdapters.size(); + if (nofAdapter == 0) { + UBLOG(logERROR, "WARNING - D3Q27Interactor::updateInteractor Warning - no nodeAdapter available for "); + } + + bool needTimeDependence = false; + + for (int pos = 0; pos < nofAdapter; ++pos) { + bcAdapters[pos]->update(this, timestep); + if (bcAdapters[pos]->isTimeDependent()) + needTimeDependence = true; + } + if (needTimeDependence) + this->setTimeDependent(); + else + this->unsetTimeDependent(); + + for (BcNodeIndicesMap::value_type t : bcNodeIndicesMap) { + SPtr<Block3D> block = t.first; + std::set<std::vector<int>> &transNodeIndicesSet = t.second; + + if (block->isNotActive() || !block) + continue; + + SPtr<ILBMKernel> kernel = block->getKernel(); + SPtr<BCArray3D> bcArray = kernel->getBCProcessor()->getBCArray(); + + set<std::vector<int>>::iterator setPos; + + for (setPos = transNodeIndicesSet.begin(); setPos != transNodeIndicesSet.end(); ++setPos) { + int x1 = (*setPos)[0]; + int x2 = (*setPos)[1]; + int x3 = (*setPos)[2]; + Vector3D coords = grid.lock()->getNodeCoordinates(block, x1, x2, x3); + double worldX1 = coords[0]; + double worldX2 = coords[1]; + double worldX3 = coords[2]; + + SPtr<BoundaryConditions> bc = bcArray->getBC(x1, x2, x3); + if (bc) // may be that the BC has been deleted by the solid setting of another interactor + { + for (size_t i = 0; i < bcAdapters.size(); i++) + bcAdapters[i]->adaptBC(*this, bc, worldX1, worldX2, worldX3, timestep); + } + } + } } ////////////////////////////////////////////////////////////////////////// // calculation takes place in the real coordinate system !!! @@ -197,542 +282,730 @@ void D3Q27Interactor::updateInteractor(const double& timestep) // extendedBoundingGeoOfGeoObject MUST already have been magnified by delta_x_level in each direction for SOLID bool D3Q27Interactor::setDifferencesToGbObject3D(const SPtr<Block3D> block) { - if(!block) return false; - - if(block->isNotActive()) return false;//continue; - - bcNodeIndicesMap[block] = set< std::vector<int> >(); - set< std::vector<int> >& transNodeIndices = bcNodeIndicesMap[block]; - solidNodeIndicesMap[block] = set< UbTupleInt3 >(); - set< UbTupleInt3 >& solidNodeIndices = solidNodeIndicesMap[block]; - - - double timestep = 0; - bool oneEntryGotBC = false; - bool gotQs = false; - SPtr<BoundaryConditions> bc; - - SPtr<ILBMKernel> kernel = block->getKernel(); - SPtr<BCArray3D> bcArray = kernel->getBCProcessor()->getBCArray(); - - double internX1,internX2,internX3; - - - int startIX1 = 0; - int startIX2 = 0; - int startIX3 = 0; - int stopIX1 = (int)bcArray->getNX1(); - int stopIX2 = (int)bcArray->getNX2(); - int stopIX3 = (int)bcArray->getNX3(); - - double dx = grid.lock()->getDeltaX(block); - - //other boundingRect than in init, because here the boundrect has to be increased by one dx - GbCuboid3D extendedBoundingGeoOfGeoObject( geoObject3D->getX1Minimum()-1.02*dx - , geoObject3D->getX2Minimum()-1.02*dx - , geoObject3D->getX3Minimum()-1.02*dx - , geoObject3D->getX1Maximum()+1.02*dx - , geoObject3D->getX2Maximum()+1.02*dx - , geoObject3D->getX3Maximum()+1.02*dx ); - - double deltaX1=dx, deltaX2 =dx, deltaX3=dx; - - if( geoObject3D->hasRaytracing() - || (this->isInverseSolid() && geoObject3D->raytracingSupportsPointsInside() ) ) - { - //if deltaX1==deltaX2==deltaX3 (must for LB!!) - if(!UbMath::zero( deltaX1-deltaX2 + deltaX1-deltaX3 + deltaX2-deltaX3 ) ) - throw UbException(UB_EXARGS,"fuer den bei LB nicht vorkommenden Fall deltaX1!=deltaX2!=deltaX3 nicht implementiert "); - - vector<double> distNeigh(D3Q27System::FENDDIR+1, UbMath::sqrt2*deltaX1); - distNeigh[D3Q27System::E] = distNeigh[D3Q27System::W] = distNeigh[D3Q27System::N] = deltaX1; - distNeigh[D3Q27System::S] = distNeigh[D3Q27System::T] = distNeigh[D3Q27System::B] = deltaX1; - distNeigh[D3Q27System::NE] = distNeigh[D3Q27System::NW] = distNeigh[D3Q27System::SW] = distNeigh[D3Q27System::SE] = UbMath::sqrt2*deltaX1; - distNeigh[D3Q27System::TE] = distNeigh[D3Q27System::TN] = distNeigh[D3Q27System::TW] = distNeigh[D3Q27System::TS] = UbMath::sqrt2*deltaX1; - distNeigh[D3Q27System::BE] = distNeigh[D3Q27System::BN] = distNeigh[D3Q27System::BW] = distNeigh[D3Q27System::BS] = UbMath::sqrt2*deltaX1; - distNeigh[D3Q27System::TNE] = distNeigh[D3Q27System::TNW] = distNeigh[D3Q27System::TSE] = distNeigh[D3Q27System::TSW] = UbMath::sqrt3*deltaX1; - distNeigh[D3Q27System::BNE] = distNeigh[D3Q27System::BNW] = distNeigh[D3Q27System::BSE] = distNeigh[D3Q27System::BSW] = UbMath::sqrt3*deltaX1; - double q; - bool pointOnBoundary = false; - -//#ifdef _OPENMP -// #pragma omp parallel for private(internX1,internX2,internX3,gotQs,bc,q ) -//#endif - for(int ix3=startIX3; ix3<stopIX3; ix3++) - { - for(int ix2=startIX2; ix2<stopIX2; ix2++) - { - for(int ix1=startIX1; ix1<stopIX1; ix1++) - { - //TODO: further, investigate if this is not a mistake - if(bcArray->isUndefined(ix1, ix2, ix3)) continue; - - Vector3D coords = grid.lock()->getNodeCoordinates(block, ix1, ix2, ix3); - internX1 = coords[0]; - internX2 = coords[1]; - internX3 = coords[2]; - - // Point in the object test is superfluous, since the start and stop indices already exist - // are determined -> only point-in-cube indexes are considered - if(extendedBoundingGeoOfGeoObject.isPointInGbObject3D(internX1,internX2,internX3)) - { - if(this->isSolid() ) - { - if(this->geoObject3D->isPointInGbObject3D(internX1, internX2, internX3)) - { - { - solidNodeIndices.insert(UbTupleInt3(ix1, ix2, ix3)); - bcArray->setSolid(ix1,ix2,ix3); - } + if (!block) + return false; + + if (block->isNotActive()) + return false; // continue; + + bcNodeIndicesMap[block] = set<std::vector<int>>(); + set<std::vector<int>> &transNodeIndices = bcNodeIndicesMap[block]; + solidNodeIndicesMap[block] = set<UbTupleInt3>(); + set<UbTupleInt3> &solidNodeIndices = solidNodeIndicesMap[block]; + + double timestep = 0; + bool oneEntryGotBC = false; + bool gotQs = false; + SPtr<BoundaryConditions> bc; + + SPtr<ILBMKernel> kernel = block->getKernel(); + SPtr<BCArray3D> bcArray = kernel->getBCProcessor()->getBCArray(); + + double internX1, internX2, internX3; + + int startIX1 = 0; + int startIX2 = 0; + int startIX3 = 0; + int stopIX1 = (int)bcArray->getNX1(); + int stopIX2 = (int)bcArray->getNX2(); + int stopIX3 = (int)bcArray->getNX3(); + + double dx = grid.lock()->getDeltaX(block); + + // other boundingRect than in init, because here the boundrect has to be increased by one dx + GbCuboid3D extendedBoundingGeoOfGeoObject( + geoObject3D->getX1Minimum() - 1.02 * dx, geoObject3D->getX2Minimum() - 1.02 * dx, + geoObject3D->getX3Minimum() - 1.02 * dx, geoObject3D->getX1Maximum() + 1.02 * dx, + geoObject3D->getX2Maximum() + 1.02 * dx, geoObject3D->getX3Maximum() + 1.02 * dx); + + double deltaX1 = dx, deltaX2 = dx, deltaX3 = dx; + + if (geoObject3D->hasRaytracing() || (this->isInverseSolid() && geoObject3D->raytracingSupportsPointsInside())) { + // if deltaX1==deltaX2==deltaX3 (must for LB!!) + if (!UbMath::zero(deltaX1 - deltaX2 + deltaX1 - deltaX3 + deltaX2 - deltaX3)) + throw UbException( + UB_EXARGS, "fuer den bei LB nicht vorkommenden Fall deltaX1!=deltaX2!=deltaX3 nicht implementiert "); + + vector<double> distNeigh(D3Q27System::FENDDIR + 1, UbMath::sqrt2 * deltaX1); + distNeigh[D3Q27System::E] = distNeigh[D3Q27System::W] = distNeigh[D3Q27System::N] = deltaX1; + distNeigh[D3Q27System::S] = distNeigh[D3Q27System::T] = distNeigh[D3Q27System::B] = deltaX1; + distNeigh[D3Q27System::NE] = distNeigh[D3Q27System::NW] = distNeigh[D3Q27System::SW] = + distNeigh[D3Q27System::SE] = UbMath::sqrt2 * deltaX1; + distNeigh[D3Q27System::TE] = distNeigh[D3Q27System::TN] = distNeigh[D3Q27System::TW] = + distNeigh[D3Q27System::TS] = UbMath::sqrt2 * deltaX1; + distNeigh[D3Q27System::BE] = distNeigh[D3Q27System::BN] = distNeigh[D3Q27System::BW] = + distNeigh[D3Q27System::BS] = UbMath::sqrt2 * deltaX1; + distNeigh[D3Q27System::TNE] = distNeigh[D3Q27System::TNW] = distNeigh[D3Q27System::TSE] = + distNeigh[D3Q27System::TSW] = UbMath::sqrt3 * deltaX1; + distNeigh[D3Q27System::BNE] = distNeigh[D3Q27System::BNW] = distNeigh[D3Q27System::BSE] = + distNeigh[D3Q27System::BSW] = UbMath::sqrt3 * deltaX1; + double q; + bool pointOnBoundary = false; + + //#ifdef _OPENMP + // #pragma omp parallel for private(internX1,internX2,internX3,gotQs,bc,q ) + //#endif + for (int ix3 = startIX3; ix3 < stopIX3; ix3++) { + for (int ix2 = startIX2; ix2 < stopIX2; ix2++) { + for (int ix1 = startIX1; ix1 < stopIX1; ix1++) { + // TODO: further, investigate if this is not a mistake + if (bcArray->isUndefined(ix1, ix2, ix3)) continue; - } - } - else if( this->isInverseSolid() ) - { - //in inverse solid all nodes are OUTSIDE and on the boundary SOLID - if( !this->geoObject3D->isPointInGbObject3D(internX1, internX2, internX3, pointOnBoundary) - || pointOnBoundary == true ) - { - - { - solidNodeIndices.insert(UbTupleInt3(ix1, ix2, ix3)); - bcArray->setSolid(ix1,ix2,ix3); + + Vector3D coords = grid.lock()->getNodeCoordinates(block, ix1, ix2, ix3); + internX1 = coords[0]; + internX2 = coords[1]; + internX3 = coords[2]; + + // Point in the object test is superfluous, since the start and stop indices already exist + // are determined -> only point-in-cube indexes are considered + if (extendedBoundingGeoOfGeoObject.isPointInGbObject3D(internX1, internX2, internX3)) { + if (this->isSolid()) { + if (this->geoObject3D->isPointInGbObject3D(internX1, internX2, internX3)) { + { + solidNodeIndices.insert(UbTupleInt3(ix1, ix2, ix3)); + bcArray->setSolid(ix1, ix2, ix3); + } + continue; + } + } else if (this->isInverseSolid()) { + // in inverse solid all nodes are OUTSIDE and on the boundary SOLID + if (!this->geoObject3D->isPointInGbObject3D(internX1, internX2, internX3, + pointOnBoundary) || + pointOnBoundary == true) { + + { + solidNodeIndices.insert(UbTupleInt3(ix1, ix2, ix3)); + bcArray->setSolid(ix1, ix2, ix3); + } + continue; + } } - continue; - } - } - - if(bcArray->isSolid(ix1,ix2,ix3)) - continue; - - gotQs = false; - - for(int fdir=D3Q27System::FSTARTDIR; fdir<=D3Q27System::FENDDIR; fdir++) - { - q = geoObject3D->getIntersectionRaytraceFactor(internX1,internX2,internX3,rayX1[fdir],rayX2[fdir],rayX3[fdir]); - q /= distNeigh[fdir]; - - //assert(UbMath::lessEqual(q, 1.0)); - - if( UbMath::inClosedInterval(q, 1.0, 1.0) ) q = 1.0; - if( UbMath::greater(q, 0.0) && UbMath::lessEqual(q, 1.0) ) - { - //#pragma omp critical (BC_CHANGE) - { - bc = bcArray->getBC(ix1,ix2,ix3); - if(!bc) - { - bc = std::make_shared<BoundaryConditions>(); - bcArray->setBC(ix1,ix2,ix3,bc); - } - - if(bc->hasNoSlipBoundary()) - { - bc->setBoundaryVelocityX1(0.0); - bc->setBoundaryVelocityX2(0.0); - bc->setBoundaryVelocityX3(0.0); - } - - for(int index=(int)bcAdapters.size()-1; index>=0; --index) - bcAdapters[index]->adaptBCForDirection(*this,bc,internX1,internX2,internX3,q,fdir, timestep); + + if (bcArray->isSolid(ix1, ix2, ix3)) + continue; + + gotQs = false; + + for (int fdir = D3Q27System::FSTARTDIR; fdir <= D3Q27System::FENDDIR; fdir++) { + q = geoObject3D->getIntersectionRaytraceFactor(internX1, internX2, internX3, rayX1[fdir], + rayX2[fdir], rayX3[fdir]); + q /= distNeigh[fdir]; + + // assert(UbMath::lessEqual(q, 1.0)); + + if (UbMath::inClosedInterval(q, 1.0, 1.0)) + q = 1.0; + if (UbMath::greater(q, 0.0) && UbMath::lessEqual(q, 1.0)) { + //#pragma omp critical (BC_CHANGE) + { + bc = bcArray->getBC(ix1, ix2, ix3); + if (!bc) { + bc = std::make_shared<BoundaryConditions>(); + bcArray->setBC(ix1, ix2, ix3, bc); + } + + if (bc->hasNoSlipBoundary()) { + bc->setBoundaryVelocityX1(0.0); + bc->setBoundaryVelocityX2(0.0); + bc->setBoundaryVelocityX3(0.0); + } + + for (int index = (int)bcAdapters.size() - 1; index >= 0; --index) + bcAdapters[index]->adaptBCForDirection(*this, bc, internX1, internX2, internX3, + q, fdir, timestep); + } + + gotQs = true; + } } - gotQs=true; - } - } - - if(gotQs) - { - { - oneEntryGotBC = true; - - std::vector<int> p(3); - p[0]=ix1; p[1]=ix2; p[2]=ix3; - transNodeIndices.insert(p); - - for(int index=(int)bcAdapters.size()-1; index>=0; --index) - bcAdapters[index]->adaptBC(*this,bc,internX1,internX2,internX3, timestep); - } - } - } - else if( this->isInverseSolid() ) - { - //bei inverse solid sind alle Knoten AUSSERHALB und auf der boundary SOLID - if( !this->geoObject3D->isPointInGbObject3D(internX1, internX2, internX3, pointOnBoundary) - || pointOnBoundary == true ) - { - { - solidNodeIndices.insert(UbTupleInt3(ix1, ix2, ix3)); - bcArray->setSolid(ix1,ix2,ix3); - } - continue; - } - } - } - } - } - } - else //clipping -> slower (currently also used for all inverse Solid objects whose raytracing does not work for nodes INSIDE the geo) - { - bool pointOnBoundary = false; - for(int ix1=startIX1; ix1<stopIX1; ix1++) - { - for(int ix2=startIX2; ix2<stopIX2; ix2++) - { - for(int ix3=startIX3; ix3<stopIX3; ix3++) - { - if(bcArray->isSolid(ix1,ix2,ix3) || bcArray->isUndefined(ix1, ix2, ix3)) continue; - - Vector3D coords = grid.lock()->getNodeCoordinates(block, ix1, ix2, ix3); - internX1 = coords[0]; - internX2 = coords[1]; - internX3 = coords[2]; - - if(extendedBoundingGeoOfGeoObject.isPointInGbObject3D(internX1,internX2,internX3)) - { - if( this->isSolid() && this->geoObject3D->isPointInGbObject3D(internX1, internX2, internX3) ) - { - { - solidNodeIndices.insert(UbTupleInt3(ix1, ix2, ix3)); - bcArray->setSolid(ix1,ix2,ix3); - } - continue; - } - else if( this->isInverseSolid() ) - { - //bei inverse solid sind alle Knoten AUSSERHALB und auf der boundary SOLID - if( !this->geoObject3D->isPointInGbObject3D(internX1, internX2, internX3, pointOnBoundary) - || pointOnBoundary == true ) - { - { - solidNodeIndices.insert(UbTupleInt3(ix1, ix2, ix3)); - bcArray->setSolid(ix1,ix2,ix3); + if (gotQs) { + { + oneEntryGotBC = true; + + std::vector<int> p(3); + p[0] = ix1; + p[1] = ix2; + p[2] = ix3; + transNodeIndices.insert(p); + + for (int index = (int)bcAdapters.size() - 1; index >= 0; --index) + bcAdapters[index]->adaptBC(*this, bc, internX1, internX2, internX3, timestep); + } } - continue; - } - } - - gotQs = false; - - GbPoint3D pointA(internX1,internX2,internX3); - for(int fdir=D3Q27System::FSTARTDIR; fdir<=D3Q27System::FENDDIR; fdir++) - { - double x1B = internX1+D3Q27System::DX1[fdir]*deltaX1; - double x2B = internX2+D3Q27System::DX2[fdir]*deltaX2; - double x3B = internX3+D3Q27System::DX3[fdir]*deltaX3; - - GbPoint3D pointB(x1B,x2B,x3B); - GbLine3D* clippedLine = this->geoObject3D->createClippedLine3D(pointA, pointB); - - if(clippedLine) - { - double q=0.0; - if( !this->isInverseSolid() ) //A is outside - { - double distanceAB = pointA.getDistance(&pointB); //pointA to B - double distanceAP = UbMath::min(pointA.getDistance(clippedLine->getPoint1()), - pointA.getDistance(clippedLine->getPoint2()) ); - q = distanceAP/distanceAB; + } else if (this->isInverseSolid()) { + // bei inverse solid sind alle Knoten AUSSERHALB und auf der boundary SOLID + if (!this->geoObject3D->isPointInGbObject3D(internX1, internX2, internX3, pointOnBoundary) || + pointOnBoundary == true) { + { + solidNodeIndices.insert(UbTupleInt3(ix1, ix2, ix3)); + bcArray->setSolid(ix1, ix2, ix3); + } + continue; } - else - { - bool pointIsOnBoundary = false; - if( !clippedLine->getPoint1()->equals(&pointB) - && !clippedLine->getPoint2()->equals(&pointB) ) - { - //A is inside, a clipped line must not contain B - double distanceAB = pointA.getDistance(&pointB); //pointA to B - double distanceAP = clippedLine->getLength(); - q = distanceAP/distanceAB; - } - else if( this->geoObject3D->isPointInGbObject3D( pointB.getX1Coordinate() - ,pointB.getX2Coordinate() - ,pointB.getX3Coordinate() - ,pointIsOnBoundary ) - && pointIsOnBoundary ) - { - //A is definitely inside, B is exactly on ObjectBoundary => q = 1.0 - q=1.0; - } - else - { - q = 0.0; - } + } + } + } + } + } else // clipping -> slower (currently also used for all inverse Solid objects whose raytracing does not work for + // nodes INSIDE the geo) + { + bool pointOnBoundary = false; + for (int ix1 = startIX1; ix1 < stopIX1; ix1++) { + for (int ix2 = startIX2; ix2 < stopIX2; ix2++) { + for (int ix3 = startIX3; ix3 < stopIX3; ix3++) { + if (bcArray->isSolid(ix1, ix2, ix3) || bcArray->isUndefined(ix1, ix2, ix3)) + continue; + + Vector3D coords = grid.lock()->getNodeCoordinates(block, ix1, ix2, ix3); + internX1 = coords[0]; + internX2 = coords[1]; + internX3 = coords[2]; + + if (extendedBoundingGeoOfGeoObject.isPointInGbObject3D(internX1, internX2, internX3)) { + if (this->isSolid() && this->geoObject3D->isPointInGbObject3D(internX1, internX2, internX3)) { + { + solidNodeIndices.insert(UbTupleInt3(ix1, ix2, ix3)); + bcArray->setSolid(ix1, ix2, ix3); + } + continue; + } else if (this->isInverseSolid()) { + // bei inverse solid sind alle Knoten AUSSERHALB und auf der boundary SOLID + if (!this->geoObject3D->isPointInGbObject3D(internX1, internX2, internX3, + pointOnBoundary) || + pointOnBoundary == true) { + { + solidNodeIndices.insert(UbTupleInt3(ix1, ix2, ix3)); + bcArray->setSolid(ix1, ix2, ix3); + } + continue; + } } - if(UbMath::inClosedInterval(q, 1.0, 1.0)) q = 1.0; - if(UbMath::lessEqual(q, 1.0) && UbMath::greater(q, 0.0)) - { - { - bc = bcArray->getBC(ix1,ix2,ix3); - if(!bc) - { - bc = std::make_shared<BoundaryConditions>(); - bcArray->setBC(ix1,ix2,ix3,bc); - } - for(int index=(int)bcAdapters.size()-1; index>=0; --index) - bcAdapters[index]->adaptBCForDirection(*this,bc,internX1,internX2,internX3,q,fdir,timestep); - } - - gotQs=true; + gotQs = false; + + GbPoint3D pointA(internX1, internX2, internX3); + for (int fdir = D3Q27System::FSTARTDIR; fdir <= D3Q27System::FENDDIR; fdir++) { + double x1B = internX1 + D3Q27System::DX1[fdir] * deltaX1; + double x2B = internX2 + D3Q27System::DX2[fdir] * deltaX2; + double x3B = internX3 + D3Q27System::DX3[fdir] * deltaX3; + + GbPoint3D pointB(x1B, x2B, x3B); + GbLine3D *clippedLine = this->geoObject3D->createClippedLine3D(pointA, pointB); + + if (clippedLine) { + double q = 0.0; + if (!this->isInverseSolid()) // A is outside + { + double distanceAB = pointA.getDistance(&pointB); // pointA to B + double distanceAP = UbMath::min(pointA.getDistance(clippedLine->getPoint1()), + pointA.getDistance(clippedLine->getPoint2())); + q = distanceAP / distanceAB; + } else { + bool pointIsOnBoundary = false; + if (!clippedLine->getPoint1()->equals(&pointB) && + !clippedLine->getPoint2()->equals(&pointB)) { + // A is inside, a clipped line must not contain B + double distanceAB = pointA.getDistance(&pointB); // pointA to B + double distanceAP = clippedLine->getLength(); + q = distanceAP / distanceAB; + } else if (this->geoObject3D->isPointInGbObject3D( + pointB.getX1Coordinate(), pointB.getX2Coordinate(), + pointB.getX3Coordinate(), pointIsOnBoundary) && + pointIsOnBoundary) { + // A is definitely inside, B is exactly on ObjectBoundary => q = 1.0 + q = 1.0; + } else { + q = 0.0; + } + } + + if (UbMath::inClosedInterval(q, 1.0, 1.0)) + q = 1.0; + if (UbMath::lessEqual(q, 1.0) && UbMath::greater(q, 0.0)) { + { + bc = bcArray->getBC(ix1, ix2, ix3); + if (!bc) { + bc = std::make_shared<BoundaryConditions>(); + bcArray->setBC(ix1, ix2, ix3, bc); + } + for (int index = (int)bcAdapters.size() - 1; index >= 0; --index) + bcAdapters[index]->adaptBCForDirection(*this, bc, internX1, internX2, + internX3, q, fdir, timestep); + } + + gotQs = true; + } + + clippedLine->deletePoint1(); + clippedLine->deletePoint2(); + delete clippedLine; + } } - clippedLine->deletePoint1(); - clippedLine->deletePoint2(); - delete clippedLine; - } - } - - if(gotQs) - { - { - oneEntryGotBC = true; - - std::vector<int> p(3); - p[0]=ix1; p[1]=ix2; p[2]=ix3; - transNodeIndices.insert(p); - - for(int index=(int)bcAdapters.size()-1; index>=0; --index) - bcAdapters[index]->adaptBC(*this,bc,internX1,internX2,internX3,timestep); - } - } - } + if (gotQs) { + { + oneEntryGotBC = true; + + std::vector<int> p(3); + p[0] = ix1; + p[1] = ix2; + p[2] = ix3; + transNodeIndices.insert(p); + + for (int index = (int)bcAdapters.size() - 1; index >= 0; --index) + bcAdapters[index]->adaptBC(*this, bc, internX1, internX2, internX3, timestep); + } + } + } + } } - } - } - } + } + } - return oneEntryGotBC; + return oneEntryGotBC; } ////////////////////////////////////////////////////////////////////////// -void D3Q27Interactor::addQsLineSet(std::vector<UbTupleFloat3 >& nodes, std::vector<UbTupleInt2 >& lines) +void D3Q27Interactor::addQsLineSet(std::vector<UbTupleFloat3> &nodes, std::vector<UbTupleInt2> &lines) { - for(SPtr<Block3D> block : bcBlocks) - { - if(!block) continue; + for (SPtr<Block3D> block : bcBlocks) { + if (!block) + continue; - double dx = grid.lock()->getDeltaX(block); - UbTupleDouble3 orgDelta = grid.lock()->getNodeOffset(block); + double dx = grid.lock()->getDeltaX(block); + UbTupleDouble3 orgDelta = grid.lock()->getNodeOffset(block); - SPtr<ILBMKernel> kernel = block->getKernel(); - SPtr<BCArray3D> bcArray = kernel->getBCProcessor()->getBCArray(); + SPtr<ILBMKernel> kernel = block->getKernel(); + SPtr<BCArray3D> bcArray = kernel->getBCProcessor()->getBCArray(); - map<SPtr<Block3D>, set< std::vector<int> > >::iterator pos = bcNodeIndicesMap.find(block); - if(pos==bcNodeIndicesMap.end()) - { - UB_THROW( UbException(UB_EXARGS,"block nicht in indizes map!!!") ); - } - set< std::vector<int> >& transNodeIndicesSet = pos->second; - set< std::vector<int> >::iterator setPos; + map<SPtr<Block3D>, set<std::vector<int>>>::iterator pos = bcNodeIndicesMap.find(block); + if (pos == bcNodeIndicesMap.end()) { + UB_THROW(UbException(UB_EXARGS, "block nicht in indizes map!!!")); + } + set<std::vector<int>> &transNodeIndicesSet = pos->second; + set<std::vector<int>>::iterator setPos; - std::size_t node1Index, node2Index; + std::size_t node1Index, node2Index; - UbTupleDouble3 blockOrg = grid.lock()->getBlockWorldCoordinates(block); + UbTupleDouble3 blockOrg = grid.lock()->getBlockWorldCoordinates(block); - for(setPos=transNodeIndicesSet.begin(); setPos!=transNodeIndicesSet.end(); ++setPos) - { + for (setPos = transNodeIndicesSet.begin(); setPos != transNodeIndicesSet.end(); ++setPos) { int ix1 = (*setPos)[0]; int ix2 = (*setPos)[1]; int ix3 = (*setPos)[2]; - if(bcArray->isFluid(ix1,ix2,ix3)) //it may be that the node is replaced by another interactor e.g. was marked as solid !!! + if (bcArray->isFluid( + ix1, ix2, + ix3)) // it may be that the node is replaced by another interactor e.g. was marked as solid !!! { - if( !bcArray->hasBC(ix1,ix2,ix3) ) continue; - SPtr<BoundaryConditions> bc = bcArray->getBC(ix1,ix2,ix3); - - double x1a = val<1>(blockOrg) - val<1>(orgDelta) + ix1 * dx; - double x2a = val<2>(blockOrg) - val<2>(orgDelta) + ix2 * dx; - double x3a = val<3>(blockOrg) - val<3>(orgDelta) + ix3 * dx; - nodes.push_back( makeUbTuple( (float)x1a, (float)x2a, (float)x3a ) ); - node1Index = nodes.size()-1; - - for(int dir = D3Q27System::FSTARTDIR; dir<=D3Q27System::FENDDIR; dir++) - { - if (bc->hasBoundaryConditionFlag(D3Q27System::INVDIR[dir])) - { - double x1b, x2b, x3b, q = bc->getQ(dir); - switch(dir) - { - case D3Q27System::E : x1b = x1a+q*dx; x2b = x2a ; x3b = x3a ; break; - case D3Q27System::N : x1b = x1a ; x2b = x2a+q*dx; x3b = x3a ; break; - case D3Q27System::W : x1b = x1a-q*dx; x2b = x2a ; x3b = x3a ; break; - case D3Q27System::S : x1b = x1a ; x2b = x2a-q*dx; x3b = x3a ; break; - case D3Q27System::NE: x1b = x1a+q*dx; x2b = x2a+q*dx; x3b = x3a ; break; - case D3Q27System::NW: x1b = x1a-q*dx; x2b = x2a+q*dx; x3b = x3a ; break; - case D3Q27System::SW: x1b = x1a-q*dx; x2b = x2a-q*dx; x3b = x3a ; break; - case D3Q27System::SE: x1b = x1a+q*dx; x2b = x2a-q*dx; x3b = x3a ; break; - case D3Q27System::T : x1b = x1a ; x2b = x2a ; x3b = x3a+q*dx; break; - case D3Q27System::TE: x1b = x1a+q*dx; x2b = x2a ; x3b = x3a+q*dx; break; - case D3Q27System::TN: x1b = x1a ; x2b = x2a+q*dx; x3b = x3a+q*dx; break; - case D3Q27System::TW: x1b = x1a-q*dx; x2b = x2a ; x3b = x3a+q*dx; break; - case D3Q27System::TS: x1b = x1a ; x2b = x2a-q*dx; x3b = x3a+q*dx; break; - case D3Q27System::B : x1b = x1a ; x2b = x2a ; x3b = x3a-q*dx; break; - case D3Q27System::BE: x1b = x1a+q*dx; x2b = x2a ; x3b = x3a-q*dx; break; - case D3Q27System::BN: x1b = x1a ; x2b = x2a+q*dx; x3b = x3a-q*dx; break; - case D3Q27System::BW: x1b = x1a-q*dx; x2b = x2a ; x3b = x3a-q*dx; break; - case D3Q27System::BS: x1b = x1a ; x2b = x2a-q*dx; x3b = x3a-q*dx; break; - case D3Q27System::TNE : x1b = x1a+q*dx ; x2b = x2a+q*dx; x3b = x3a+q*dx; break; - case D3Q27System::BSW : x1b = x1a-q*dx ; x2b = x2a-q*dx; x3b = x3a-q*dx; break; - case D3Q27System::BNE : x1b = x1a+q*dx ; x2b = x2a+q*dx; x3b = x3a-q*dx; break; - case D3Q27System::TSW : x1b = x1a-q*dx ; x2b = x2a-q*dx; x3b = x3a+q*dx; break; - case D3Q27System::TSE : x1b = x1a+q*dx ; x2b = x2a-q*dx; x3b = x3a+q*dx; break; - case D3Q27System::BNW : x1b = x1a-q*dx ; x2b = x2a+q*dx; x3b = x3a-q*dx; break; - case D3Q27System::BSE : x1b = x1a+q*dx ; x2b = x2a-q*dx; x3b = x3a-q*dx; break; - case D3Q27System::TNW : x1b = x1a-q*dx ; x2b = x2a+q*dx; x3b = x3a+q*dx; break; - default: throw UbException(UB_EXARGS,"unknown direction"); - } - - nodes.push_back( makeUbTuple( (float)x1b, (float)x2b, (float)x3b ) ); - node2Index = nodes.size()-1; - - lines.push_back( makeUbTuple( (int)node1Index, (int)node2Index) ); - } - } + if (!bcArray->hasBC(ix1, ix2, ix3)) + continue; + SPtr<BoundaryConditions> bc = bcArray->getBC(ix1, ix2, ix3); + + double x1a = val<1>(blockOrg) - val<1>(orgDelta) + ix1 * dx; + double x2a = val<2>(blockOrg) - val<2>(orgDelta) + ix2 * dx; + double x3a = val<3>(blockOrg) - val<3>(orgDelta) + ix3 * dx; + nodes.push_back(makeUbTuple((float)x1a, (float)x2a, (float)x3a)); + node1Index = nodes.size() - 1; + + for (int dir = D3Q27System::FSTARTDIR; dir <= D3Q27System::FENDDIR; dir++) { + if (bc->hasBoundaryConditionFlag(D3Q27System::INVDIR[dir])) { + double x1b, x2b, x3b, q = bc->getQ(dir); + switch (dir) { + case D3Q27System::E: + x1b = x1a + q * dx; + x2b = x2a; + x3b = x3a; + break; + case D3Q27System::N: + x1b = x1a; + x2b = x2a + q * dx; + x3b = x3a; + break; + case D3Q27System::W: + x1b = x1a - q * dx; + x2b = x2a; + x3b = x3a; + break; + case D3Q27System::S: + x1b = x1a; + x2b = x2a - q * dx; + x3b = x3a; + break; + case D3Q27System::NE: + x1b = x1a + q * dx; + x2b = x2a + q * dx; + x3b = x3a; + break; + case D3Q27System::NW: + x1b = x1a - q * dx; + x2b = x2a + q * dx; + x3b = x3a; + break; + case D3Q27System::SW: + x1b = x1a - q * dx; + x2b = x2a - q * dx; + x3b = x3a; + break; + case D3Q27System::SE: + x1b = x1a + q * dx; + x2b = x2a - q * dx; + x3b = x3a; + break; + case D3Q27System::T: + x1b = x1a; + x2b = x2a; + x3b = x3a + q * dx; + break; + case D3Q27System::TE: + x1b = x1a + q * dx; + x2b = x2a; + x3b = x3a + q * dx; + break; + case D3Q27System::TN: + x1b = x1a; + x2b = x2a + q * dx; + x3b = x3a + q * dx; + break; + case D3Q27System::TW: + x1b = x1a - q * dx; + x2b = x2a; + x3b = x3a + q * dx; + break; + case D3Q27System::TS: + x1b = x1a; + x2b = x2a - q * dx; + x3b = x3a + q * dx; + break; + case D3Q27System::B: + x1b = x1a; + x2b = x2a; + x3b = x3a - q * dx; + break; + case D3Q27System::BE: + x1b = x1a + q * dx; + x2b = x2a; + x3b = x3a - q * dx; + break; + case D3Q27System::BN: + x1b = x1a; + x2b = x2a + q * dx; + x3b = x3a - q * dx; + break; + case D3Q27System::BW: + x1b = x1a - q * dx; + x2b = x2a; + x3b = x3a - q * dx; + break; + case D3Q27System::BS: + x1b = x1a; + x2b = x2a - q * dx; + x3b = x3a - q * dx; + break; + case D3Q27System::TNE: + x1b = x1a + q * dx; + x2b = x2a + q * dx; + x3b = x3a + q * dx; + break; + case D3Q27System::BSW: + x1b = x1a - q * dx; + x2b = x2a - q * dx; + x3b = x3a - q * dx; + break; + case D3Q27System::BNE: + x1b = x1a + q * dx; + x2b = x2a + q * dx; + x3b = x3a - q * dx; + break; + case D3Q27System::TSW: + x1b = x1a - q * dx; + x2b = x2a - q * dx; + x3b = x3a + q * dx; + break; + case D3Q27System::TSE: + x1b = x1a + q * dx; + x2b = x2a - q * dx; + x3b = x3a + q * dx; + break; + case D3Q27System::BNW: + x1b = x1a - q * dx; + x2b = x2a + q * dx; + x3b = x3a - q * dx; + break; + case D3Q27System::BSE: + x1b = x1a + q * dx; + x2b = x2a - q * dx; + x3b = x3a - q * dx; + break; + case D3Q27System::TNW: + x1b = x1a - q * dx; + x2b = x2a + q * dx; + x3b = x3a + q * dx; + break; + default: + throw UbException(UB_EXARGS, "unknown direction"); + } + + nodes.push_back(makeUbTuple((float)x1b, (float)x2b, (float)x3b)); + node2Index = nodes.size() - 1; + + lines.push_back(makeUbTuple((int)node1Index, (int)node2Index)); + } + } } - } - } + } + } } //////////////////////////////////////////////////////////////////////////// -vector< pair<GbPoint3D,GbPoint3D> > D3Q27Interactor::getQsLineSet() +vector<pair<GbPoint3D, GbPoint3D>> D3Q27Interactor::getQsLineSet() { - vector< pair<GbPoint3D,GbPoint3D> > QsLineSet; - pair<GbPoint3D,GbPoint3D> pointpair; - - UbTupleInt3 blocknx = grid.lock()->getBlockNX(); - - int blocknx1 = val<1>(blocknx); - int blocknx2 = val<2>(blocknx); - int blocknx3 = val<3>(blocknx); - - for(SPtr<Block3D> block : bcBlocks) - { - SPtr<ILBMKernel> kernel = block->getKernel(); - SPtr<BCArray3D> bcMatrix = kernel->getBCProcessor()->getBCArray(); - UbTupleDouble3 nodeOffset = grid.lock()->getNodeOffset(block); - - //Check whether top row is double in the system or not - bool include_N_Face = false; //x1=[0..blocknx1[ && x3=[0..blocknx3[ - bool include_E_Face = false; //x2=[0..blocknx2[ && x3=[0..blocknx3[ - bool include_T_Face = false; //x1=[0..blocknx1[ && x2=[0..blocknx2[ - bool include_NE_Edge = false; //(x1/x2/x3)=(blocknx1/blocknx2/[0..blocknx3[) - bool include_TN_Edge = false; //(x1/x2/x3)=([0..blocknx1[/blocknx2/blocknx1) - bool include_TE_Edge = false; //(x1/x2/x3)=(blocknx1/[0..blocknx2[/blocknx2) - if(block) - { - if( !block->getConnector(D3Q27System::N ) ) include_N_Face = true; - if( !block->getConnector(D3Q27System::E ) ) include_E_Face = true; - if( !block->getConnector(D3Q27System::T ) ) include_T_Face = true; - if( !block->getConnector(D3Q27System::NE) && include_N_Face && include_E_Face ) include_NE_Edge = true; - if( !block->getConnector(D3Q27System::TN) && include_T_Face && include_N_Face ) include_TN_Edge = true; - if( !block->getConnector(D3Q27System::TE) && include_T_Face && include_E_Face ) include_TE_Edge = true; - } - - map<SPtr<Block3D>, set< std::vector<int> > >::iterator pos = bcNodeIndicesMap.find(block); - if(pos==bcNodeIndicesMap.end()) throw UbException(UB_EXARGS,"block nicht in indizes map!!!"+block->toString()); - set< std::vector<int> >& transNodeIndicesSet = pos->second; - set< std::vector<int> >::iterator setPos; - - double x1,x2,x3,dx; - grid.lock()->calcStartCoordinatesAndDelta(block,x1,x2,x3,dx); - - for(setPos=transNodeIndicesSet.begin(); setPos!=transNodeIndicesSet.end(); ++setPos) - { - int ix1 = (*setPos)[0]; - int ix2 = (*setPos)[1]; - int ix3 = (*setPos)[2]; - - if( ( ix1<blocknx1 && ix2<blocknx2 && ix3<blocknx3 ) - || ( include_E_Face && ix1==blocknx1 && ix2<blocknx2 && ix3<blocknx3 ) - || ( include_N_Face && ix2==blocknx2 && ix1<blocknx1 && ix3<blocknx3 ) - || ( include_T_Face && ix3==blocknx3 && ix1<blocknx1 && ix2<blocknx2 ) - || ( include_NE_Edge && ix1==blocknx1 && ix2==blocknx2 ) - || ( include_TN_Edge && ix2==blocknx2 && ix3==blocknx3 ) - || ( include_TE_Edge && ix1==blocknx1 && ix3==blocknx3 ) ) - { - if(bcMatrix->isFluid(ix1,ix2,ix3)) //it may be that the node is replaced by another interactor e.g. was marked as solid !!! - { - if( !bcMatrix->hasBC(ix1,ix2,ix3) ) continue; - SPtr<BoundaryConditions> bc = bcMatrix->getBC(ix1,ix2,ix3); - double x1a = x1-val<1>(nodeOffset)+dx * ix1; - double x2a = x2-val<2>(nodeOffset)+dx * ix2; - double x3a = x3-val<3>(nodeOffset)+dx * ix3; - pointpair.first.setX1(x1a); - pointpair.first.setX2(x2a); - pointpair.first.setX3(x3a); - for(int dir = D3Q27System::FSTARTDIR; dir<=D3Q27System::FENDDIR; dir++) - { - if (bc->hasBoundaryConditionFlag(D3Q27System::INVDIR[dir])) - { - double x1b, x2b, x3b, q = bc->getQ(dir); - switch(dir) - { - case D3Q27System::E : x1b = x1a+q*dx; x2b = x2a ; x3b = x3a ; break; - case D3Q27System::N : x1b = x1a ; x2b = x2a+q*dx; x3b = x3a ; break; - case D3Q27System::W : x1b = x1a-q*dx; x2b = x2a ; x3b = x3a ; break; - case D3Q27System::S : x1b = x1a ; x2b = x2a-q*dx; x3b = x3a ; break; - case D3Q27System::NE: x1b = x1a+q*dx; x2b = x2a+q*dx; x3b = x3a ; break; - case D3Q27System::NW: x1b = x1a-q*dx; x2b = x2a+q*dx; x3b = x3a ; break; - case D3Q27System::SW: x1b = x1a-q*dx; x2b = x2a-q*dx; x3b = x3a ; break; - case D3Q27System::SE: x1b = x1a+q*dx; x2b = x2a-q*dx; x3b = x3a ; break; - case D3Q27System::T : x1b = x1a ; x2b = x2a ; x3b = x3a+q*dx; break; - case D3Q27System::TE: x1b = x1a+q*dx; x2b = x2a ; x3b = x3a+q*dx; break; - case D3Q27System::TN: x1b = x1a ; x2b = x2a+q*dx; x3b = x3a+q*dx; break; - case D3Q27System::TW: x1b = x1a-q*dx; x2b = x2a ; x3b = x3a+q*dx; break; - case D3Q27System::TS: x1b = x1a ; x2b = x2a-q*dx; x3b = x3a+q*dx; break; - case D3Q27System::B : x1b = x1a ; x2b = x2a ; x3b = x3a-q*dx; break; - case D3Q27System::BE: x1b = x1a+q*dx; x2b = x2a ; x3b = x3a-q*dx; break; - case D3Q27System::BN: x1b = x1a ; x2b = x2a+q*dx; x3b = x3a-q*dx; break; - case D3Q27System::BW: x1b = x1a-q*dx; x2b = x2a ; x3b = x3a-q*dx; break; - case D3Q27System::BS: x1b = x1a ; x2b = x2a-q*dx; x3b = x3a-q*dx; break; - case D3Q27System::TNE : x1b = x1a+q*dx ; x2b = x2a+q*dx; x3b = x3a+q*dx; break; - case D3Q27System::BSW : x1b = x1a-q*dx ; x2b = x2a-q*dx; x3b = x3a-q*dx; break; - case D3Q27System::BNE : x1b = x1a+q*dx ; x2b = x2a+q*dx; x3b = x3a-q*dx; break; - case D3Q27System::TSW : x1b = x1a-q*dx ; x2b = x2a-q*dx; x3b = x3a+q*dx; break; - case D3Q27System::TSE : x1b = x1a+q*dx ; x2b = x2a-q*dx; x3b = x3a+q*dx; break; - case D3Q27System::BNW : x1b = x1a-q*dx ; x2b = x2a+q*dx; x3b = x3a-q*dx; break; - case D3Q27System::BSE : x1b = x1a+q*dx ; x2b = x2a-q*dx; x3b = x3a-q*dx; break; - case D3Q27System::TNW : x1b = x1a-q*dx ; x2b = x2a+q*dx; x3b = x3a+q*dx; break; - default: throw UbException(UB_EXARGS,"unknown direction"); - } - pointpair.second.setX1(x1b); - pointpair.second.setX2(x2b); - pointpair.second.setX3(x3b); - QsLineSet.push_back(pointpair); - } - } + vector<pair<GbPoint3D, GbPoint3D>> QsLineSet; + pair<GbPoint3D, GbPoint3D> pointpair; + + UbTupleInt3 blocknx = grid.lock()->getBlockNX(); + + int blocknx1 = val<1>(blocknx); + int blocknx2 = val<2>(blocknx); + int blocknx3 = val<3>(blocknx); + + for (SPtr<Block3D> block : bcBlocks) { + SPtr<ILBMKernel> kernel = block->getKernel(); + SPtr<BCArray3D> bcMatrix = kernel->getBCProcessor()->getBCArray(); + UbTupleDouble3 nodeOffset = grid.lock()->getNodeOffset(block); + + // Check whether top row is double in the system or not + bool include_N_Face = false; // x1=[0..blocknx1[ && x3=[0..blocknx3[ + bool include_E_Face = false; // x2=[0..blocknx2[ && x3=[0..blocknx3[ + bool include_T_Face = false; // x1=[0..blocknx1[ && x2=[0..blocknx2[ + bool include_NE_Edge = false; //(x1/x2/x3)=(blocknx1/blocknx2/[0..blocknx3[) + bool include_TN_Edge = false; //(x1/x2/x3)=([0..blocknx1[/blocknx2/blocknx1) + bool include_TE_Edge = false; //(x1/x2/x3)=(blocknx1/[0..blocknx2[/blocknx2) + if (block) { + if (!block->getConnector(D3Q27System::N)) + include_N_Face = true; + if (!block->getConnector(D3Q27System::E)) + include_E_Face = true; + if (!block->getConnector(D3Q27System::T)) + include_T_Face = true; + if (!block->getConnector(D3Q27System::NE) && include_N_Face && include_E_Face) + include_NE_Edge = true; + if (!block->getConnector(D3Q27System::TN) && include_T_Face && include_N_Face) + include_TN_Edge = true; + if (!block->getConnector(D3Q27System::TE) && include_T_Face && include_E_Face) + include_TE_Edge = true; + } + + map<SPtr<Block3D>, set<std::vector<int>>>::iterator pos = bcNodeIndicesMap.find(block); + if (pos == bcNodeIndicesMap.end()) + throw UbException(UB_EXARGS, "block nicht in indizes map!!!" + block->toString()); + set<std::vector<int>> &transNodeIndicesSet = pos->second; + set<std::vector<int>>::iterator setPos; + + double x1, x2, x3, dx; + grid.lock()->calcStartCoordinatesAndDelta(block, x1, x2, x3, dx); + + for (setPos = transNodeIndicesSet.begin(); setPos != transNodeIndicesSet.end(); ++setPos) { + int ix1 = (*setPos)[0]; + int ix2 = (*setPos)[1]; + int ix3 = (*setPos)[2]; + if ((ix1 < blocknx1 && ix2 < blocknx2 && ix3 < blocknx3) || + (include_E_Face && ix1 == blocknx1 && ix2 < blocknx2 && ix3 < blocknx3) || + (include_N_Face && ix2 == blocknx2 && ix1 < blocknx1 && ix3 < blocknx3) || + (include_T_Face && ix3 == blocknx3 && ix1 < blocknx1 && ix2 < blocknx2) || + (include_NE_Edge && ix1 == blocknx1 && ix2 == blocknx2) || + (include_TN_Edge && ix2 == blocknx2 && ix3 == blocknx3) || + (include_TE_Edge && ix1 == blocknx1 && ix3 == blocknx3)) { + if (bcMatrix->isFluid( + ix1, ix2, + ix3)) // it may be that the node is replaced by another interactor e.g. was marked as solid !!! + { + if (!bcMatrix->hasBC(ix1, ix2, ix3)) + continue; + SPtr<BoundaryConditions> bc = bcMatrix->getBC(ix1, ix2, ix3); + double x1a = x1 - val<1>(nodeOffset) + dx * ix1; + double x2a = x2 - val<2>(nodeOffset) + dx * ix2; + double x3a = x3 - val<3>(nodeOffset) + dx * ix3; + pointpair.first.setX1(x1a); + pointpair.first.setX2(x2a); + pointpair.first.setX3(x3a); + for (int dir = D3Q27System::FSTARTDIR; dir <= D3Q27System::FENDDIR; dir++) { + if (bc->hasBoundaryConditionFlag(D3Q27System::INVDIR[dir])) { + double x1b, x2b, x3b, q = bc->getQ(dir); + switch (dir) { + case D3Q27System::E: + x1b = x1a + q * dx; + x2b = x2a; + x3b = x3a; + break; + case D3Q27System::N: + x1b = x1a; + x2b = x2a + q * dx; + x3b = x3a; + break; + case D3Q27System::W: + x1b = x1a - q * dx; + x2b = x2a; + x3b = x3a; + break; + case D3Q27System::S: + x1b = x1a; + x2b = x2a - q * dx; + x3b = x3a; + break; + case D3Q27System::NE: + x1b = x1a + q * dx; + x2b = x2a + q * dx; + x3b = x3a; + break; + case D3Q27System::NW: + x1b = x1a - q * dx; + x2b = x2a + q * dx; + x3b = x3a; + break; + case D3Q27System::SW: + x1b = x1a - q * dx; + x2b = x2a - q * dx; + x3b = x3a; + break; + case D3Q27System::SE: + x1b = x1a + q * dx; + x2b = x2a - q * dx; + x3b = x3a; + break; + case D3Q27System::T: + x1b = x1a; + x2b = x2a; + x3b = x3a + q * dx; + break; + case D3Q27System::TE: + x1b = x1a + q * dx; + x2b = x2a; + x3b = x3a + q * dx; + break; + case D3Q27System::TN: + x1b = x1a; + x2b = x2a + q * dx; + x3b = x3a + q * dx; + break; + case D3Q27System::TW: + x1b = x1a - q * dx; + x2b = x2a; + x3b = x3a + q * dx; + break; + case D3Q27System::TS: + x1b = x1a; + x2b = x2a - q * dx; + x3b = x3a + q * dx; + break; + case D3Q27System::B: + x1b = x1a; + x2b = x2a; + x3b = x3a - q * dx; + break; + case D3Q27System::BE: + x1b = x1a + q * dx; + x2b = x2a; + x3b = x3a - q * dx; + break; + case D3Q27System::BN: + x1b = x1a; + x2b = x2a + q * dx; + x3b = x3a - q * dx; + break; + case D3Q27System::BW: + x1b = x1a - q * dx; + x2b = x2a; + x3b = x3a - q * dx; + break; + case D3Q27System::BS: + x1b = x1a; + x2b = x2a - q * dx; + x3b = x3a - q * dx; + break; + case D3Q27System::TNE: + x1b = x1a + q * dx; + x2b = x2a + q * dx; + x3b = x3a + q * dx; + break; + case D3Q27System::BSW: + x1b = x1a - q * dx; + x2b = x2a - q * dx; + x3b = x3a - q * dx; + break; + case D3Q27System::BNE: + x1b = x1a + q * dx; + x2b = x2a + q * dx; + x3b = x3a - q * dx; + break; + case D3Q27System::TSW: + x1b = x1a - q * dx; + x2b = x2a - q * dx; + x3b = x3a + q * dx; + break; + case D3Q27System::TSE: + x1b = x1a + q * dx; + x2b = x2a - q * dx; + x3b = x3a + q * dx; + break; + case D3Q27System::BNW: + x1b = x1a - q * dx; + x2b = x2a + q * dx; + x3b = x3a - q * dx; + break; + case D3Q27System::BSE: + x1b = x1a + q * dx; + x2b = x2a - q * dx; + x3b = x3a - q * dx; + break; + case D3Q27System::TNW: + x1b = x1a - q * dx; + x2b = x2a + q * dx; + x3b = x3a + q * dx; + break; + default: + throw UbException(UB_EXARGS, "unknown direction"); + } + pointpair.second.setX1(x1b); + pointpair.second.setX2(x2b); + pointpair.second.setX3(x3b); + QsLineSet.push_back(pointpair); + } + } + } } - } - } - } - return QsLineSet; + } + } + return QsLineSet; } void D3Q27Interactor::writeValidationAVSFile(string filename) { - UBLOG(logINFO,"D3Q27Interactor::writeValidationAVSFile("<<filename<<") - start "); - ofstream out(filename.c_str(),ios::out); - if(!out) throw UbException(UB_EXARGS,"couldn't open file "+filename); - - int numpoints, numlines; - vector< pair<GbPoint3D,GbPoint3D> > qsLineSet = this->getQsLineSet(); - numlines = (unsigned)qsLineSet.size(); - numpoints = numlines*2; - - out<<"# UCD-File created by D3Q27Interactor\n"; - out<<numpoints<<" "<<numlines<<" 0 0 0 "<<endl; - int nr=1; - for (int i=0; i<numlines; i++) - { - out<<nr++<<" "<<qsLineSet[i].first.getX1Coordinate() <<" " <<qsLineSet[i].first.getX2Coordinate() <<" " <<qsLineSet[i].first.getX3Coordinate() <<" \n"; - out<<nr++<<" "<<qsLineSet[i].second.getX1Coordinate()<<" " <<qsLineSet[i].second.getX2Coordinate()<<" " <<qsLineSet[i].second.getX3Coordinate() <<" \n"; - } - nr = 1; - for (int i=0; i<numlines; i++) - { - int el = nr+1; - out<<i+1<<" "<<2<<" line "<<nr<<" "<<el<<" "<<endl; - nr=el+1; - } - UBLOG(logINFO,"D3Q27Interactor::writeValidationAVSFile("<<filename<<") - end"); + UBLOG(logINFO, "D3Q27Interactor::writeValidationAVSFile(" << filename << ") - start "); + ofstream out(filename.c_str(), ios::out); + if (!out) + throw UbException(UB_EXARGS, "couldn't open file " + filename); + + int numpoints, numlines; + vector<pair<GbPoint3D, GbPoint3D>> qsLineSet = this->getQsLineSet(); + numlines = (unsigned)qsLineSet.size(); + numpoints = numlines * 2; + + out << "# UCD-File created by D3Q27Interactor\n"; + out << numpoints << " " << numlines << " 0 0 0 " << endl; + int nr = 1; + for (int i = 0; i < numlines; i++) { + out << nr++ << " " << qsLineSet[i].first.getX1Coordinate() << " " << qsLineSet[i].first.getX2Coordinate() << " " + << qsLineSet[i].first.getX3Coordinate() << " \n"; + out << nr++ << " " << qsLineSet[i].second.getX1Coordinate() << " " << qsLineSet[i].second.getX2Coordinate() + << " " << qsLineSet[i].second.getX3Coordinate() << " \n"; + } + nr = 1; + for (int i = 0; i < numlines; i++) { + int el = nr + 1; + out << i + 1 << " " << 2 << " line " << nr << " " << el << " " << endl; + nr = el + 1; + } + UBLOG(logINFO, "D3Q27Interactor::writeValidationAVSFile(" << filename << ") - end"); } diff --git a/src/cpu/VirtualFluidsCore/Interactors/D3Q27Interactor.h b/src/cpu/VirtualFluidsCore/Interactors/D3Q27Interactor.h index d0c16b2a5799dab42788b1ec3f11c2cd3549a8ed..4e588e96adbd42102a38cf3ee8ec27cd49e87dbf 100644 --- a/src/cpu/VirtualFluidsCore/Interactors/D3Q27Interactor.h +++ b/src/cpu/VirtualFluidsCore/Interactors/D3Q27Interactor.h @@ -1,28 +1,28 @@ //======================================================================================= -// ____ ____ __ ______ __________ __ __ __ __ -// \ \ | | | | | _ \ |___ ___| | | | | / \ | | -// \ \ | | | | | |_) | | | | | | | / \ | | -// \ \ | | | | | _ / | | | | | | / /\ \ | | -// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ -// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| -// \ \ | | ________________________________________________________________ -// \ \ | | | ______________________________________________________________| -// \ \| | | | __ __ __ __ ______ _______ -// \ | | |_____ | | | | | | | | | _ \ / _____) -// \ | | _____| | | | | | | | | | | \ \ \_______ +// ____ ____ __ ______ __________ __ __ __ __ +// \ \ | | | | | _ \ |___ ___| | | | | / \ | | +// \ \ | | | | | |_) | | | | | | | / \ | | +// \ \ | | | | | _ / | | | | | | / /\ \ | | +// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ +// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| +// \ \ | | ________________________________________________________________ +// \ \ | | | ______________________________________________________________| +// \ \| | | | __ __ __ __ ______ _______ +// \ | | |_____ | | | | | | | | | _ \ / _____) +// \ | | _____| | | | | | | | | | | \ \ \_______ // \ | | | | |_____ | \_/ | | | | |_/ / _____ | -// \ _____| |__| |________| \_______/ |__| |______/ (_______/ +// \ _____| |__| |________| \_______/ |__| |______/ (_______/ // -// This file is part of VirtualFluids. VirtualFluids is free software: you can +// This file is part of VirtualFluids. VirtualFluids is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of +// License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. -// -// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// +// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License along // with VirtualFluids (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>. // @@ -36,79 +36,85 @@ #ifndef D3Q27INTERACTOR_H #define D3Q27INTERACTOR_H -#include <string> -#include <vector> +#include <PointerDefinitions.h> #include <map> #include <set> -#include <PointerDefinitions.h> +#include <string> +#include <vector> -#include "UbException.h" -#include "UbTuple.h" +#include "D3Q27System.h" #include "GbPoint3D.h" #include "Interactor3D.h" -#include "D3Q27System.h" +#include "UbException.h" +#include "UbTuple.h" class BCAdapter; class Block3D; class Grid3D; class GbObject3D; -using BcNodeIndicesMap = std::map<SPtr<Block3D>, std::set< std::vector<int> > >; -using SolidNodeIndicesMap = std::map<SPtr<Block3D>, std::set<UbTupleInt3> >; +using BcNodeIndicesMap = std::map<SPtr<Block3D>, std::set<std::vector<int>>>; +using SolidNodeIndicesMap = std::map<SPtr<Block3D>, std::set<UbTupleInt3>>; //! \brief A specialized class for grid generation. //! \details Support standard geometric primitives. -class D3Q27Interactor : public Interactor3D +class D3Q27Interactor : public Interactor3D { public: - D3Q27Interactor(); - D3Q27Interactor(SPtr<GbObject3D> geoObject3D, SPtr<Grid3D> grid, int type); - D3Q27Interactor(SPtr<GbObject3D> geoObject3D, SPtr<Grid3D> grid, SPtr<BCAdapter> bcAdapter, int type); - D3Q27Interactor(SPtr<GbObject3D> geoObject3D, SPtr<Grid3D> grid, SPtr<BCAdapter> bcAdapter, int type, Interactor3D::Accuracy a); + D3Q27Interactor(); + D3Q27Interactor(SPtr<GbObject3D> geoObject3D, SPtr<Grid3D> grid, int type); + D3Q27Interactor(SPtr<GbObject3D> geoObject3D, SPtr<Grid3D> grid, SPtr<BCAdapter> bcAdapter, int type); + D3Q27Interactor(SPtr<GbObject3D> geoObject3D, SPtr<Grid3D> grid, SPtr<BCAdapter> bcAdapter, int type, + Interactor3D::Accuracy a); - ~D3Q27Interactor() override; + ~D3Q27Interactor() override; - void setRelevantForForces(const bool& value) { this->relevantForForces = value; } - bool isRelevantForForces() { return this->relevantForForces; } + void setRelevantForForces(const bool &value) { this->relevantForForces = value; } + bool isRelevantForForces() { return this->relevantForForces; } - virtual void addBCAdapter(const SPtr<BCAdapter> bcAdapter) { bcAdapters.push_back(bcAdapter); } - void deleteBCAdapter() { bcAdapters.clear(); } + virtual void addBCAdapter(const SPtr<BCAdapter> bcAdapter) { bcAdapters.push_back(bcAdapter); } + void deleteBCAdapter() { bcAdapters.clear(); } - - void initInteractor(const double& timeStep=0) override; - void updateInteractor(const double& timestep=0) override; + void initInteractor(const double &timeStep = 0) override; + void updateInteractor(const double ×tep = 0) override; - void setReinitWithStoredQs(bool reinitWithStoredQsFlag) { this->reinitWithStoredQsFlag = reinitWithStoredQsFlag; } - - void removeSolidBlocks() override { Interactor3D::removeSolidBlocks(); solidNodeIndicesMap.clear(); } - void removeBcBlocks() override { Interactor3D::removeBcBlocks(); bcNodeIndicesMap.clear(); } + void setReinitWithStoredQs(bool reinitWithStoredQsFlag) { this->reinitWithStoredQsFlag = reinitWithStoredQsFlag; } - bool setDifferencesToGbObject3D(const SPtr<Block3D> block) override; + void removeSolidBlocks() override + { + Interactor3D::removeSolidBlocks(); + solidNodeIndicesMap.clear(); + } + void removeBcBlocks() override + { + Interactor3D::removeBcBlocks(); + bcNodeIndicesMap.clear(); + } - ObObject* clone() { throw UbException(UB_EXARGS,"not implemented"); } + bool setDifferencesToGbObject3D(const SPtr<Block3D> block) override; - void writeValidationAVSFile(std::string filename); - virtual std::vector< std::pair<GbPoint3D,GbPoint3D> > getQsLineSet(); + ObObject *clone() { throw UbException(UB_EXARGS, "not implemented"); } - void addQsLineSet(std::vector<UbTupleFloat3 >& nodes, std::vector<UbTupleInt2 >& lines); + void writeValidationAVSFile(std::string filename); + virtual std::vector<std::pair<GbPoint3D, GbPoint3D>> getQsLineSet(); - const BcNodeIndicesMap& getBcNodeIndicesMap() const { return bcNodeIndicesMap; } + void addQsLineSet(std::vector<UbTupleFloat3> &nodes, std::vector<UbTupleInt2> &lines); + + const BcNodeIndicesMap &getBcNodeIndicesMap() const { return bcNodeIndicesMap; } protected: - bool relevantForForces; - bool reinitWithStoredQsFlag; + bool relevantForForces; + bool reinitWithStoredQsFlag; - std::vector<SPtr<BCAdapter> > bcAdapters; + std::vector<SPtr<BCAdapter>> bcAdapters; - SolidNodeIndicesMap solidNodeIndicesMap; - BcNodeIndicesMap bcNodeIndicesMap; - - void initRayVectors(); - double rayX1[D3Q27System::FENDDIR+1]; - double rayX2[D3Q27System::FENDDIR+1]; - double rayX3[D3Q27System::FENDDIR+1]; + SolidNodeIndicesMap solidNodeIndicesMap; + BcNodeIndicesMap bcNodeIndicesMap; + void initRayVectors(); + double rayX1[D3Q27System::FENDDIR + 1]; + double rayX2[D3Q27System::FENDDIR + 1]; + double rayX3[D3Q27System::FENDDIR + 1]; }; - #endif diff --git a/src/cpu/VirtualFluidsCore/Interactors/D3Q27TriFaceMeshInteractor.cpp b/src/cpu/VirtualFluidsCore/Interactors/D3Q27TriFaceMeshInteractor.cpp index 9bdf07ccee2b55bdbbd66507735f6137c601728d..fba35290871b92e1b4bdd2f3307ee9a8db76d45b 100644 --- a/src/cpu/VirtualFluidsCore/Interactors/D3Q27TriFaceMeshInteractor.cpp +++ b/src/cpu/VirtualFluidsCore/Interactors/D3Q27TriFaceMeshInteractor.cpp @@ -1,562 +1,583 @@ #include "D3Q27TriFaceMeshInteractor.h" -#include <basics/utilities/UbMath.h> #include <basics/utilities/UbLogger.h> +#include <basics/utilities/UbMath.h> +#include "basics/writer/WbWriterVtkXmlASCII.h" +#include <basics/writer/WbWriterVtkASCII.h> #include <basics/writer/WbWriterVtkBinary.h> #include <basics/writer/WbWriterVtkXmlBinary.h> -#include <basics/writer/WbWriterVtkASCII.h> -#include "basics/writer/WbWriterVtkXmlASCII.h" -#include <geometry3d/GbSystem3D.h> -#include <geometry3d/GbCuboid3D.h> -#include <geometry3d/GbHalfSpace3D.h> -#include <geometry3d/GbMeshTools3D.h> -#include "Block3D.h" -#include "Grid3D.h" #include "BCArray3D.h" +#include "BCProcessor.h" +#include "Block3D.h" #include "BoundaryConditions.h" -#include "VelocityBCAdapter.h" +#include "Grid3D.h" #include "LBMKernel.h" -#include "BCProcessor.h" +#include "VelocityBCAdapter.h" #include "basics/utilities/UbTiming.h" +#include <geometry3d/GbCuboid3D.h> +#include <geometry3d/GbHalfSpace3D.h> +#include <geometry3d/GbMeshTools3D.h> +#include <geometry3d/GbSystem3D.h> #include <geometry3d/GbTriFaceMesh3D.h> //#include <omp.h> -#include <stack> #include "CoordinateTransformation3D.h" +#include <stack> using namespace std; -D3Q27TriFaceMeshInteractor::D3Q27TriFaceMeshInteractor() -: D3Q27Interactor() -{ - this->stressMode = STRESSNORMAL; -} +D3Q27TriFaceMeshInteractor::D3Q27TriFaceMeshInteractor() : D3Q27Interactor() { this->stressMode = STRESSNORMAL; } ////////////////////////////////////////////////////////////////////////// -D3Q27TriFaceMeshInteractor::D3Q27TriFaceMeshInteractor(SPtr<Grid3D> /*grid*/, std::string /*name*/) +D3Q27TriFaceMeshInteractor::D3Q27TriFaceMeshInteractor(SPtr<Grid3D> /*grid*/, std::string /*name*/) { - this->stressMode = STRESSNORMAL; + this->stressMode = STRESSNORMAL; } ////////////////////////////////////////////////////////////////////////// -D3Q27TriFaceMeshInteractor::D3Q27TriFaceMeshInteractor(SPtr<GbTriFaceMesh3D> triFaceMesh, SPtr<Grid3D> grid, SPtr<BCAdapter> bcAdapter, int type) -: D3Q27Interactor(triFaceMesh, grid, bcAdapter, type) +D3Q27TriFaceMeshInteractor::D3Q27TriFaceMeshInteractor(SPtr<GbTriFaceMesh3D> triFaceMesh, SPtr<Grid3D> grid, + SPtr<BCAdapter> bcAdapter, int type) + : D3Q27Interactor(triFaceMesh, grid, bcAdapter, type) { - this->stressMode = STRESSNORMAL; + this->stressMode = STRESSNORMAL; } ////////////////////////////////////////////////////////////////////////// -D3Q27TriFaceMeshInteractor::D3Q27TriFaceMeshInteractor(SPtr<GbTriFaceMesh3D> triFaceMesh, SPtr<Grid3D> grid, SPtr<BCAdapter> bcAdapter, int type, Interactor3D::Accuracy a) - : D3Q27Interactor(triFaceMesh, grid, bcAdapter, type, a) +D3Q27TriFaceMeshInteractor::D3Q27TriFaceMeshInteractor(SPtr<GbTriFaceMesh3D> triFaceMesh, SPtr<Grid3D> grid, + SPtr<BCAdapter> bcAdapter, int type, Interactor3D::Accuracy a) + : D3Q27Interactor(triFaceMesh, grid, bcAdapter, type, a) { - this->stressMode = STRESSNORMAL; + this->stressMode = STRESSNORMAL; } ////////////////////////////////////////////////////////////////////////// -D3Q27TriFaceMeshInteractor::~D3Q27TriFaceMeshInteractor() -= default; +D3Q27TriFaceMeshInteractor::~D3Q27TriFaceMeshInteractor() = default; ////////////////////////////////////////////////////////////////////////// -void D3Q27TriFaceMeshInteractor::initInteractor(const double& timeStep) +void D3Q27TriFaceMeshInteractor::initInteractor(const double &timeStep) { - Interactor3D::initInteractor(timeStep); // FIXME: refers to a member overridden in subclass - setQs(timeStep); + Interactor3D::initInteractor(timeStep); // FIXME: refers to a member overridden in subclass + setQs(timeStep); } ////////////////////////////////////////////////////////////////////////// bool D3Q27TriFaceMeshInteractor::setDifferencesToGbObject3D(const SPtr<Block3D> block/*,const double& orgX1,const double& orgX2,const double& orgX3,const double& blockLengthX1,const double& blockLengthX2,const double& blockLengthX3, const double& timestep*/) { - if(!block) return false; - - //UBLOG(logINFO, "D3Q27TriFaceMeshInteractor::setDifferencesToGbObject3D()"); - - bcNodeIndicesMap[block] = set< std::vector<int> >(); -// set< std::vector<int> >& transNodeIndices = bcNodeIndicesMap[block]; - solidNodeIndicesMap[block] = set< UbTupleInt3 >(); - set< UbTupleInt3 >& solidNodeIndices = solidNodeIndicesMap[block]; - - - bool oneEntryGotBC = false; //ob ueberhaupt ein eintrag ein BC zugewiesen wurde -// bool gotQs = false; //true, wenn "difference" gesetzt wurde - SPtr<BoundaryConditions> bc; - - SPtr<ILBMKernel> kernel = block->getKernel(); - SPtr<BCArray3D> bcArray = kernel->getBCProcessor()->getBCArray(); - - double internX1,internX2,internX3; - - int startIX1 = 0, startIX2 = 0, startIX3 = 0; - int stopIX1 = (int)bcArray->getNX1(), stopIX2 = (int)bcArray->getNX2(), stopIX3 = (int)bcArray->getNX3(); - -// double dx = grid.lock()->getDeltaX(block); -// UbTupleDouble3 orgDelta = grid.lock()->getNodeOffset(block); - - bool pointOnBoundary = false; - - for(int ix3=startIX3; ix3<stopIX3; ix3++) - { - for(int ix2=startIX2; ix2<stopIX2; ix2++) - { - for(int ix1=startIX1; ix1<stopIX1; ix1++) - { - Vector3D coords = grid.lock()->getNodeCoordinates(block, ix1, ix2, ix3); - internX1 = coords[0]; - internX2 = coords[1]; - internX3 = coords[2]; - - if(this->isSolid() ) - { - if(this->geoObject3D->isPointInGbObject3D(internX1, internX2, internX3)) - { - if(bcArray->isFluid(ix1,ix2,ix3)) - { - solidNodeIndices.insert(UbTupleInt3(ix1, ix2, ix3)); - bcArray->setSolid(ix1,ix2,ix3); - } - } - } - else if( this->isInverseSolid() ) - { - //bei inverse solid sind alle Knoten AUSSERHALB und auf der boundary SOLID - if( !this->geoObject3D->isPointInGbObject3D(internX1, internX2, internX3, pointOnBoundary) || pointOnBoundary == true ) - { - if(bcArray->isFluid(ix1,ix2,ix3)) - { - solidNodeIndices.insert(UbTupleInt3(ix1, ix2, ix3)); - bcArray->setSolid(ix1,ix2,ix3); - } - } - } - } - } - } + if (!block) + return false; - return oneEntryGotBC; -} -////////////////////////////////////////////////////////////////////////// -//E.F. /4/16/2013 -void D3Q27TriFaceMeshInteractor::setQs(const double& timeStep) -{ - UBLOGML(logDEBUG1,"\nLBMTriFaceMeshInteractor - setQs start "); - if( !this->grid.lock() ) throw UbException(UB_EXARGS,"ups, no grid.lock()!!"); - - if( this->reinitWithStoredQsFlag && !bcNodeIndicesAndQsMap.empty() ) - { - this->reinitWithStoredQs(timeStep); - return; - } - - GbTriFaceMesh3D* mesh = dynamic_cast<GbTriFaceMesh3D*>(this->geoObject3D.get()); - - ////////////////////////////////////////////////////////////////////////// - //init bcs - ////////////////////////////////////////////////////////////////////////// - int nofAdapter = (int)this->bcAdapters.size(); - if(nofAdapter==0) std::cout<<"WARNING - D3Q27TriFaceMeshInteractor::initInteractor Warning - no nodeAdapter available for "/*<<this->getName()*/<<std::endl; - bool needTimeDependence = false; - for(int pos=0; pos<nofAdapter; ++pos) - { - this->bcAdapters[pos]->init(this,timeStep); - if(this->bcAdapters[pos]->isTimeDependent()) needTimeDependence = true; - } - if(needTimeDependence) this->setTimeDependent(); - else this->unsetTimeDependent(); - - ////////////////////////////////////////////////////////////////////////// - //grid.lock() info - ////////////////////////////////////////////////////////////////////////// - int coarsestInitLevel = grid.lock()->getCoarsestInitializedLevel(); - int finestInitLevel = grid.lock()->getFinestInitializedLevel(); - - UbTupleInt3 blocknx = grid.lock()->getBlockNX(); - int blocknx1 = val<1>(blocknx); //gilt fuer alle Level - int blocknx2 = val<2>(blocknx); //gilt fuer alle Level - int blocknx3 = val<3>(blocknx); //gilt fuer alle Level - - //grobe Blocklaengen - SPtr<CoordinateTransformation3D> trafo = grid.lock()->getCoordinateTransformator(); - double cblockDeltaX1,cblockDeltaX2,cblockDeltaX3, delta ; - cblockDeltaX1 = cblockDeltaX2 = cblockDeltaX3 = delta = 1.0/(double)(1<<coarsestInitLevel); - if(trafo) - { - cblockDeltaX1 = trafo->getX1CoordinateScaling()*delta; - cblockDeltaX2 = trafo->getX2CoordinateScaling()*delta; - cblockDeltaX3 = trafo->getX3CoordinateScaling()*delta; - } - //levelspezifische blocklaengen und knotenabstaende - std::vector< std::vector<double> > nodeDeltaToNeigh(finestInitLevel+1); - std::vector<float> deltaMinX1(finestInitLevel+1),deltaMinX2(finestInitLevel+1),deltaMinX3(finestInitLevel+1); - std::vector<float> deltaMaxX1(finestInitLevel+1),deltaMaxX2(finestInitLevel+1),deltaMaxX3(finestInitLevel+1); - - //Im Boltzmankontext muss dx1==dx2==dx3 sein!! - assert( UbMath::equal(cblockDeltaX1/(double)blocknx1, cblockDeltaX2/(double)blocknx2 ) ); - assert( UbMath::equal(cblockDeltaX1/(double)blocknx1, cblockDeltaX3/(double)blocknx3 ) ); - - for(int level = coarsestInitLevel; level<=finestInitLevel; level++) - { - double nodeDeltaX1 = cblockDeltaX1/(double)(blocknx1*(1<<(level-coarsestInitLevel))); - double nodeDeltaX2 = cblockDeltaX2/(double)(blocknx2*(1<<(level-coarsestInitLevel))); - double nodeDeltaX3 = cblockDeltaX3/(double)(blocknx3*(1<<(level-coarsestInitLevel))); - - std::vector<double> distNeigh(D3Q27System::FENDDIR+1, 0.0); - D3Q27System::calcDistanceToNeighbors(distNeigh, nodeDeltaX1,nodeDeltaX2,nodeDeltaX3); - //D3Q27System::calcDistanceToNeighbors(distNeigh, nodeDeltaX1); - - - nodeDeltaToNeigh[level].resize(D3Q27System::ENDDIR+1,0.0); - for(int fdir=D3Q27System::FSTARTDIR; fdir<=D3Q27System::FENDDIR; fdir++) - { - nodeDeltaToNeigh[level][fdir] = distNeigh[fdir]; - } - - //im gegensatz zum allg. Cell3DInteractor kann man hier auf max(0.02*blockDeltaX1[level],fabs(...)) verzichten - //da dies nur für blockDeltaCalculator->getMinX1Delta(level)==0.0 benötigt wird. ist im D3Q19... aber nie so - //Geller: kann man nicht diesen befuckten DeltaCalculator weglassen und hier einfach die Formel zum Delta rechnen reinpacken - //SirAnn: klar, mann kann auch weißwuerste am Alex verkaufen... aber zum einen ist das Ding dazu da - // und zum anderen sollt eman mal überlegen: "Formel zum Delta rechnen"->man muss rechnen - // blockDeltaCalculator->getMinX1Delta(level) -> ein geinlinter wert wird geholt - - //TODO: set 5.0 as variable parameter in constructor, default 2.0 - deltaMinX1[level] = (float)( 5.0*nodeDeltaX1); //kein minus da unten -deltaMin - deltaMinX2[level] = (float)( 5.0*nodeDeltaX2); - deltaMinX3[level] = (float)( 5.0*nodeDeltaX3); - deltaMaxX1[level] = (float)( 5.0*nodeDeltaX1); - deltaMaxX2[level] = (float)( 5.0*nodeDeltaX2); - deltaMaxX3[level] = (float)( 5.0*nodeDeltaX3); - } - - ////////////////////////////////////////////////////////////////////////// - //bounding cubes des TriFaceMesh ermitteln (pro level) - ////////////////////////////////////////////////////////////////////////// - //min/max Werte des Dreiecksnetzes holen -// double geoMinX1(0.0), geoMinX2(0.0), geoMinX3(0.0), geoMaxX1(0.0), geoMaxX2(0.0), geoMaxX3(0.0); - -// geoMinX1 = this->geoObject3D->getX1Minimum(); geoMaxX1 = this->geoObject3D->getX1Maximum(); -// geoMinX2 = this->geoObject3D->getX2Minimum(); geoMaxX2 = this->geoObject3D->getX2Maximum(); -// geoMinX3 = this->geoObject3D->getX3Minimum(); geoMaxX3 = this->geoObject3D->getX3Maximum(); - - - ////////////////////////////////////////////////////////////////////////// - //DREIECKE: q-Bestimmung - ////////////////////////////////////////////////////////////////////////// - - //notwendige variablen initialisieren (u.a. blockDeltas des groben levels) - float triPoints[3][3]; - float vx1=0.0, vx2=0.0, vx3=0.0; - unsigned counterTriBoxOverlap=0, counterAABBTriFace=0, counterHalfspace=0, counterBilligOBB=0; - std::vector<GbTriFaceMesh3D::TriFace>& triangles = *mesh->getTriangles(); - std::vector<GbTriFaceMesh3D::Vertex>& nodes = *mesh->getNodes(); - std::map< SPtr<Block3D>, std::set< UbTupleInt3 > > tmpSolidNodesFromOtherInteractors; - - int onePercent = UbMath::integerRounding(triangles.size()*0.01); - if(onePercent==0) onePercent=1; - UbTimer setQTimer; setQTimer.start(); - UBLOG(logDEBUG3, " - setQs for "<<(int)triangles.size()<<" triangles"); - -// bool solidFromOtherInteractor = false; - float blockMinX[3],blockMaxX[3],boxCenter[3],halfBoxSize[3]; - - for(size_t t=0; t<triangles.size(); t++) - { - ////////////////////////////////////////////////////////////////////////// - // Halfspace zum Dreieck generieren und min/max des Dreiecks ermitteln - ////////////////////////////////////////////////////////////////////////// - GbTriFaceMesh3D::TriFace& triangle = triangles[t]; - - GbTriFaceMesh3D::Vertex& v1 = nodes[triangle.v1]; - GbTriFaceMesh3D::Vertex& v2 = nodes[triangle.v2]; - GbTriFaceMesh3D::Vertex& v3 = nodes[triangle.v3]; - - if(this->isInverseSolid() ) - { - triangle.nx*=(-1); - triangle.ny*=(-1); - triangle.nz*=(-1); - } - GbHalfSpace3D halfSpace( v1.x,v1.y,v1.z,triangle.nx,triangle.ny,triangle.nz ); - - ////////////////////////////////////////////////////////////////////////// - //fuer GbMeshTools3D::triBoxOverlap - ////////////////////////////////////////////////////////////////////////// - triPoints[0][0] = v1.x; triPoints[0][1] = v1.y; triPoints[0][2] = v1.z; - triPoints[1][0] = v2.x; triPoints[1][1] = v2.y; triPoints[1][2] = v2.z; - triPoints[2][0] = v3.x; triPoints[2][1] = v3.y; triPoints[2][2] = v3.z; - - double minX1 = triangle.getMinX(nodes); double maxX1 = triangle.getMaxX(nodes); - double minX2 = triangle.getMinY(nodes); double maxX2 = triangle.getMaxY(nodes); - double minX3 = triangle.getMinZ(nodes); double maxX3 = triangle.getMaxZ(nodes); - - ////////////////////////////////////////////////////////////////////////// - // Schleife ueber alle Level - ////////////////////////////////////////////////////////////////////////// - double e1x1,e1x2,e1x3,e2x1,e2x2,e2x3,px1,px2,px3,a,f,sx1,sx2,sx3,u,qx1,qx2,qx3,v; - bool gotQs = false; - SPtr<BoundaryConditions> bc; - - for(int level=coarsestInitLevel; level<=finestInitLevel; level++) - { - ////////////////////////////////////////////////////////////////////////// - // levelspezifisches BoundCube des Dreicks ermitteln und zugehörige Bloecke beziehen - ////////////////////////////////////////////////////////////////////////// - double boundCubeTriangleMinX1 = minX1-deltaMinX1[level]; double boundCubeTriangleMaxX1 = maxX1+deltaMaxX1[level]; - double boundCubeTriangleMinX2 = minX2-deltaMinX2[level]; double boundCubeTriangleMaxX2 = maxX2+deltaMaxX2[level]; - double boundCubeTriangleMinX3 = minX3-deltaMinX3[level]; double boundCubeTriangleMaxX3 = maxX3+deltaMaxX3[level]; - - GbCuboid3D boundingCubeTriangle( boundCubeTriangleMinX1, boundCubeTriangleMinX2, boundCubeTriangleMinX3 - , boundCubeTriangleMaxX1, boundCubeTriangleMaxX2, boundCubeTriangleMaxX3 ); - - std::vector<SPtr<Block3D>> triBlocks; - grid.lock()->getBlocksByCuboid(level, boundCubeTriangleMinX1, boundCubeTriangleMinX2, boundCubeTriangleMinX3 - , boundCubeTriangleMaxX1, boundCubeTriangleMaxX2, boundCubeTriangleMaxX3, triBlocks ); - - ////////////////////////////////////////////////////////////////////////// - // Schleife ueber bloecke des level, die das dreieck beinhalten - ////////////////////////////////////////////////////////////////////////// - for(std::size_t b=0; b<triBlocks.size(); b++) - { - SPtr<Block3D> block = triBlocks[b]; - - //////////////////////////////////////////////////////////////////////////// - //// Block Dreieck-/test - //////////////////////////////////////////////////////////////////////////// - UbTupleDouble3 coords = grid.lock()->getBlockWorldCoordinates(block); - UbTupleDouble3 deltas = grid.lock()->getBlockLengths(block); + // UBLOG(logINFO, "D3Q27TriFaceMeshInteractor::setDifferencesToGbObject3D()"); + + bcNodeIndicesMap[block] = set<std::vector<int>>(); + // set< std::vector<int> >& transNodeIndices = bcNodeIndicesMap[block]; + solidNodeIndicesMap[block] = set<UbTupleInt3>(); + set<UbTupleInt3> &solidNodeIndices = solidNodeIndicesMap[block]; + + bool oneEntryGotBC = false; // ob ueberhaupt ein eintrag ein BC zugewiesen wurde + // bool gotQs = false; //true, wenn "difference" gesetzt wurde + SPtr<BoundaryConditions> bc; - blockMinX[0] = (float)(val<1>(coords)-deltaMinX1[level]); - blockMinX[1] = (float)(val<2>(coords)-deltaMinX2[level]); - blockMinX[2] = (float)(val<3>(coords)-deltaMinX3[level]); + SPtr<ILBMKernel> kernel = block->getKernel(); + SPtr<BCArray3D> bcArray = kernel->getBCProcessor()->getBCArray(); - blockMaxX[0] = (float)(val<1>(coords)+val<1>(deltas)+deltaMaxX1[level]); - blockMaxX[1] = (float)(val<2>(coords)+val<2>(deltas)+deltaMaxX2[level]); - blockMaxX[2] = (float)(val<3>(coords)+val<3>(deltas)+deltaMaxX3[level]); + double internX1, internX2, internX3; - boxCenter[0] = (float)(0.5*(blockMaxX[0]+blockMinX[0])); - boxCenter[1] = (float)(0.5*(blockMaxX[1]+blockMinX[1])); - boxCenter[2] = (float)(0.5*(blockMaxX[2]+blockMinX[2])); + int startIX1 = 0, startIX2 = 0, startIX3 = 0; + int stopIX1 = (int)bcArray->getNX1(), stopIX2 = (int)bcArray->getNX2(), stopIX3 = (int)bcArray->getNX3(); - halfBoxSize[0] = (float)(0.5*(blockMaxX[0]-blockMinX[0])); - halfBoxSize[1] = (float)(0.5*(blockMaxX[1]-blockMinX[1])); - halfBoxSize[2] = (float)(0.5*(blockMaxX[2]-blockMinX[2])); + // double dx = grid.lock()->getDeltaX(block); + // UbTupleDouble3 orgDelta = grid.lock()->getNodeOffset(block); - //wenn dreieck "vergroesserten cube" nicht schneidet/beruehrt -> keine BC moeglich -> continue - if( !GbMeshTools3D::triBoxOverlap(boxCenter,halfBoxSize,triPoints) ) - { - counterTriBoxOverlap++; - continue; + bool pointOnBoundary = false; + + for (int ix3 = startIX3; ix3 < stopIX3; ix3++) { + for (int ix2 = startIX2; ix2 < stopIX2; ix2++) { + for (int ix1 = startIX1; ix1 < stopIX1; ix1++) { + Vector3D coords = grid.lock()->getNodeCoordinates(block, ix1, ix2, ix3); + internX1 = coords[0]; + internX2 = coords[1]; + internX3 = coords[2]; + + if (this->isSolid()) { + if (this->geoObject3D->isPointInGbObject3D(internX1, internX2, internX3)) { + if (bcArray->isFluid(ix1, ix2, ix3)) { + solidNodeIndices.insert(UbTupleInt3(ix1, ix2, ix3)); + bcArray->setSolid(ix1, ix2, ix3); + } + } + } else if (this->isInverseSolid()) { + // bei inverse solid sind alle Knoten AUSSERHALB und auf der boundary SOLID + if (!this->geoObject3D->isPointInGbObject3D(internX1, internX2, internX3, pointOnBoundary) || + pointOnBoundary == true) { + if (bcArray->isFluid(ix1, ix2, ix3)) { + solidNodeIndices.insert(UbTupleInt3(ix1, ix2, ix3)); + bcArray->setSolid(ix1, ix2, ix3); + } + } + } } + } + } + return oneEntryGotBC; +} +////////////////////////////////////////////////////////////////////////// +// E.F. /4/16/2013 +void D3Q27TriFaceMeshInteractor::setQs(const double &timeStep) +{ + UBLOGML(logDEBUG1, "\nLBMTriFaceMeshInteractor - setQs start "); + if (!this->grid.lock()) + throw UbException(UB_EXARGS, "ups, no grid.lock()!!"); + + if (this->reinitWithStoredQsFlag && !bcNodeIndicesAndQsMap.empty()) { + this->reinitWithStoredQs(timeStep); + return; + } + + GbTriFaceMesh3D *mesh = dynamic_cast<GbTriFaceMesh3D *>(this->geoObject3D.get()); + + ////////////////////////////////////////////////////////////////////////// + // init bcs + ////////////////////////////////////////////////////////////////////////// + int nofAdapter = (int)this->bcAdapters.size(); + if (nofAdapter == 0) + std::cout + << "WARNING - D3Q27TriFaceMeshInteractor::initInteractor Warning - no nodeAdapter available for " /*<<this->getName()*/ + << std::endl; + bool needTimeDependence = false; + for (int pos = 0; pos < nofAdapter; ++pos) { + this->bcAdapters[pos]->init(this, timeStep); + if (this->bcAdapters[pos]->isTimeDependent()) + needTimeDependence = true; + } + if (needTimeDependence) + this->setTimeDependent(); + else + this->unsetTimeDependent(); + + ////////////////////////////////////////////////////////////////////////// + // grid.lock() info + ////////////////////////////////////////////////////////////////////////// + int coarsestInitLevel = grid.lock()->getCoarsestInitializedLevel(); + int finestInitLevel = grid.lock()->getFinestInitializedLevel(); + + UbTupleInt3 blocknx = grid.lock()->getBlockNX(); + int blocknx1 = val<1>(blocknx); // gilt fuer alle Level + int blocknx2 = val<2>(blocknx); // gilt fuer alle Level + int blocknx3 = val<3>(blocknx); // gilt fuer alle Level + + // grobe Blocklaengen + SPtr<CoordinateTransformation3D> trafo = grid.lock()->getCoordinateTransformator(); + double cblockDeltaX1, cblockDeltaX2, cblockDeltaX3, delta; + cblockDeltaX1 = cblockDeltaX2 = cblockDeltaX3 = delta = 1.0 / (double)(1 << coarsestInitLevel); + if (trafo) { + cblockDeltaX1 = trafo->getX1CoordinateScaling() * delta; + cblockDeltaX2 = trafo->getX2CoordinateScaling() * delta; + cblockDeltaX3 = trafo->getX3CoordinateScaling() * delta; + } + // levelspezifische blocklaengen und knotenabstaende + std::vector<std::vector<double>> nodeDeltaToNeigh(finestInitLevel + 1); + std::vector<float> deltaMinX1(finestInitLevel + 1), deltaMinX2(finestInitLevel + 1), + deltaMinX3(finestInitLevel + 1); + std::vector<float> deltaMaxX1(finestInitLevel + 1), deltaMaxX2(finestInitLevel + 1), + deltaMaxX3(finestInitLevel + 1); + + // Im Boltzmankontext muss dx1==dx2==dx3 sein!! + assert(UbMath::equal(cblockDeltaX1 / (double)blocknx1, cblockDeltaX2 / (double)blocknx2)); + assert(UbMath::equal(cblockDeltaX1 / (double)blocknx1, cblockDeltaX3 / (double)blocknx3)); + + for (int level = coarsestInitLevel; level <= finestInitLevel; level++) { + double nodeDeltaX1 = cblockDeltaX1 / (double)(blocknx1 * (1 << (level - coarsestInitLevel))); + double nodeDeltaX2 = cblockDeltaX2 / (double)(blocknx2 * (1 << (level - coarsestInitLevel))); + double nodeDeltaX3 = cblockDeltaX3 / (double)(blocknx3 * (1 << (level - coarsestInitLevel))); + + std::vector<double> distNeigh(D3Q27System::FENDDIR + 1, 0.0); + D3Q27System::calcDistanceToNeighbors(distNeigh, nodeDeltaX1, nodeDeltaX2, nodeDeltaX3); + // D3Q27System::calcDistanceToNeighbors(distNeigh, nodeDeltaX1); + + nodeDeltaToNeigh[level].resize(D3Q27System::ENDDIR + 1, 0.0); + for (int fdir = D3Q27System::FSTARTDIR; fdir <= D3Q27System::FENDDIR; fdir++) { + nodeDeltaToNeigh[level][fdir] = distNeigh[fdir]; + } + + // im gegensatz zum allg. Cell3DInteractor kann man hier auf max(0.02*blockDeltaX1[level],fabs(...)) verzichten + // da dies nur für blockDeltaCalculator->getMinX1Delta(level)==0.0 benötigt wird. ist im D3Q19... aber nie so + // Geller: kann man nicht diesen befuckten DeltaCalculator weglassen und hier einfach die Formel zum Delta + // rechnen reinpacken SirAnn: klar, mann kann auch weißwuerste am Alex verkaufen... aber zum einen ist das Ding + // dazu da + // und zum anderen sollt eman mal überlegen: "Formel zum Delta rechnen"->man muss rechnen + // blockDeltaCalculator->getMinX1Delta(level) -> ein geinlinter wert wird geholt + + // TODO: set 5.0 as variable parameter in constructor, default 2.0 + deltaMinX1[level] = (float)(5.0 * nodeDeltaX1); // kein minus da unten -deltaMin + deltaMinX2[level] = (float)(5.0 * nodeDeltaX2); + deltaMinX3[level] = (float)(5.0 * nodeDeltaX3); + deltaMaxX1[level] = (float)(5.0 * nodeDeltaX1); + deltaMaxX2[level] = (float)(5.0 * nodeDeltaX2); + deltaMaxX3[level] = (float)(5.0 * nodeDeltaX3); + } + + ////////////////////////////////////////////////////////////////////////// + // bounding cubes des TriFaceMesh ermitteln (pro level) + ////////////////////////////////////////////////////////////////////////// + // min/max Werte des Dreiecksnetzes holen + // double geoMinX1(0.0), geoMinX2(0.0), geoMinX3(0.0), geoMaxX1(0.0), geoMaxX2(0.0), geoMaxX3(0.0); + + // geoMinX1 = this->geoObject3D->getX1Minimum(); geoMaxX1 = this->geoObject3D->getX1Maximum(); + // geoMinX2 = this->geoObject3D->getX2Minimum(); geoMaxX2 = this->geoObject3D->getX2Maximum(); + // geoMinX3 = this->geoObject3D->getX3Minimum(); geoMaxX3 = this->geoObject3D->getX3Maximum(); + + ////////////////////////////////////////////////////////////////////////// + // DREIECKE: q-Bestimmung + ////////////////////////////////////////////////////////////////////////// + + // notwendige variablen initialisieren (u.a. blockDeltas des groben levels) + float triPoints[3][3]; + float vx1 = 0.0, vx2 = 0.0, vx3 = 0.0; + unsigned counterTriBoxOverlap = 0, counterAABBTriFace = 0, counterHalfspace = 0, counterBilligOBB = 0; + std::vector<GbTriFaceMesh3D::TriFace> &triangles = *mesh->getTriangles(); + std::vector<GbTriFaceMesh3D::Vertex> &nodes = *mesh->getNodes(); + std::map<SPtr<Block3D>, std::set<UbTupleInt3>> tmpSolidNodesFromOtherInteractors; + + int onePercent = UbMath::integerRounding(triangles.size() * 0.01); + if (onePercent == 0) + onePercent = 1; + UbTimer setQTimer; + setQTimer.start(); + UBLOG(logDEBUG3, " - setQs for " << (int)triangles.size() << " triangles"); + + // bool solidFromOtherInteractor = false; + float blockMinX[3], blockMaxX[3], boxCenter[3], halfBoxSize[3]; + + for (size_t t = 0; t < triangles.size(); t++) { + ////////////////////////////////////////////////////////////////////////// + // Halfspace zum Dreieck generieren und min/max des Dreiecks ermitteln + ////////////////////////////////////////////////////////////////////////// + GbTriFaceMesh3D::TriFace &triangle = triangles[t]; + + GbTriFaceMesh3D::Vertex &v1 = nodes[triangle.v1]; + GbTriFaceMesh3D::Vertex &v2 = nodes[triangle.v2]; + GbTriFaceMesh3D::Vertex &v3 = nodes[triangle.v3]; + + if (this->isInverseSolid()) { + triangle.nx *= (-1); + triangle.ny *= (-1); + triangle.nz *= (-1); + } + GbHalfSpace3D halfSpace(v1.x, v1.y, v1.z, triangle.nx, triangle.ny, triangle.nz); + + ////////////////////////////////////////////////////////////////////////// + // fuer GbMeshTools3D::triBoxOverlap + ////////////////////////////////////////////////////////////////////////// + triPoints[0][0] = v1.x; + triPoints[0][1] = v1.y; + triPoints[0][2] = v1.z; + triPoints[1][0] = v2.x; + triPoints[1][1] = v2.y; + triPoints[1][2] = v2.z; + triPoints[2][0] = v3.x; + triPoints[2][1] = v3.y; + triPoints[2][2] = v3.z; + + double minX1 = triangle.getMinX(nodes); + double maxX1 = triangle.getMaxX(nodes); + double minX2 = triangle.getMinY(nodes); + double maxX2 = triangle.getMaxY(nodes); + double minX3 = triangle.getMinZ(nodes); + double maxX3 = triangle.getMaxZ(nodes); + + ////////////////////////////////////////////////////////////////////////// + // Schleife ueber alle Level + ////////////////////////////////////////////////////////////////////////// + double e1x1, e1x2, e1x3, e2x1, e2x2, e2x3, px1, px2, px3, a, f, sx1, sx2, sx3, u, qx1, qx2, qx3, v; + bool gotQs = false; + SPtr<BoundaryConditions> bc; + + for (int level = coarsestInitLevel; level <= finestInitLevel; level++) { ////////////////////////////////////////////////////////////////////////// - //Untersuchung der einzelnen nodes + // levelspezifisches BoundCube des Dreicks ermitteln und zugehörige Bloecke beziehen ////////////////////////////////////////////////////////////////////////// - bool blockGotBCs = false; - - SPtr<ILBMKernel> kernel = block->getKernel(); - SPtr<BCArray3D> bcMatrix = kernel->getBCProcessor()->getBCArray(); - - int indexMinX1 = 0; - int indexMinX2 = 0; - int indexMinX3 = 0; - - int indexMaxX1 = (int)bcMatrix->getNX1(); - int indexMaxX2 = (int)bcMatrix->getNX2(); - int indexMaxX3 = (int)bcMatrix->getNX3(); - - std::set< std::vector<int> >& bcNodeIndices = this->bcNodeIndicesMap[block]; -// std::set< UbTupleInt3 >& solidsFromOtherInteractors = tmpSolidNodesFromOtherInteractors[block]; - double q, distance; - - double& nodeDx1 = nodeDeltaToNeigh[level][D3Q27System::E]; - double& nodeDx2 = nodeDeltaToNeigh[level][D3Q27System::N]; - double& nodeDx3 = nodeDeltaToNeigh[level][D3Q27System::T]; - - //fuer OBB-Test - double qEinflussDelta = 1.1 * sqrt( nodeDx1*nodeDx1 + nodeDx2*nodeDx2 + nodeDx3*nodeDx3); - - for(int ix3=indexMinX3; ix3<indexMaxX3; ix3++) - { - for(int ix2=indexMinX2; ix2<indexMaxX2; ix2++) - { - for(int ix1=indexMinX1; ix1<indexMaxX1; ix1++) - { - Vector3D pointplane1 = grid.lock()->getNodeCoordinates(block, ix1,ix2,ix3); - double internX1 = pointplane1[0]; - double internX2 = pointplane1[1]; - double internX3 = pointplane1[2]; - -// int blx1 = block->getX1(); -// int blx2 = block->getX2(); -// int blx3 = block->getX3(); - - if(bcMatrix->isSolid(ix1,ix2,ix3) || bcMatrix->isUndefined(ix1,ix2,ix3)) - { - continue; - } - - ////////////////////////////////////////////////////////////////////////// - //Punkt in AABB von Dreieck? - ////////////////////////////////////////////////////////////////////////// - //ehsan changed - bool pointIsOnBoundary = true; - if( !boundingCubeTriangle.isPointInGbObject3D(internX1, internX2, internX3,pointIsOnBoundary) ) - { - counterAABBTriFace++; - continue; - } - //std::cout<<"internX3 "<<internX3<<" internX2"<<internX2<<" internX1 "<<internX1<<"\n"; - ////////////////////////////////////////////////////////////////////////// - // Halbebenentests - ////////////////////////////////////////////////////////////////////////// - distance = halfSpace.getDistance( internX1, internX2, internX3 ); - //Punkt in Halbebene? (nein, wenn distance<0) - if(useHalfSpace && UbMath::less(distance, 0.0) )//== !halfSpace.ptInside(internX1,internX2,internX3) ) - { - counterHalfspace++; - continue; - } - - //BilligOBB-Test: wenn distance > qEinflussDelta -> kein q - if( UbMath::greater( fabs(distance), qEinflussDelta ) ) - { - counterBilligOBB++; - continue; - } - - ///////////////////////////////////////////////////////////////////////////// - //Raytracingfür diskrete Boltzmannrichtungen - ///////////////////////////////////////////////////////////////////////////// - gotQs = false; - bc = SPtr<BoundaryConditions>(); - - //RAYTRACING - diskrete LB-dir zu Dreick - //e1 = v1 - v0 - e1x1 = v2.x-v1.x; - e1x2 = v2.y-v1.y; - e1x3 = v2.z-v1.z; - - //e2 = v2 - v0 - e2x1 = v3.x-v1.x; - e2x2 = v3.y-v1.y; - e2x3 = v3.z-v1.z; - - //s = o - v0 - sx1 = internX1 - v1.x; - sx2 = internX2 - v1.y; - sx3 = internX3 - v1.z; - - for(int fdir=D3Q27System::FSTARTDIR; fdir<=D3Q27System::FENDDIR; fdir++) - { - //p = d x e2 - px1 = this->rayX2[fdir]*e2x3 - this->rayX3[fdir]*e2x2; - px2 = this->rayX3[fdir]*e2x1 - this->rayX1[fdir]*e2x3; - px3 = this->rayX1[fdir]*e2x2 - this->rayX2[fdir]*e2x1; - - //a = e1 dot p - a = e1x1*px1 + e1x2*px2 + e1x3*px3; - if(fabs(a)<1.E-10) continue; - f = 1.0/a; - - //u = f * ( s dot p) - u = f * ( sx1*px1 + sx2*px2 + sx3*px3 ); - if(u<-1.E-10 || u>1.0+1.E-10) continue; - - //q = s x e1 - qx1 = sx2*e1x3 - sx3*e1x2; - qx2 = sx3*e1x1 - sx1*e1x3; - qx3 = sx1*e1x2 - sx2*e1x1; - - //v = f*(e2 dot q) - v = f * (this->rayX1[fdir]*qx1 + this->rayX2[fdir]*qx2 + this->rayX3[fdir]*qx3); - if(v<-1.E-10 || (u+v)>1.0+1.E-10) continue; - - //t = f * (e2 dot q) - q = f * (e2x1*qx1 + e2x2*qx2 + e2x3*qx3); - q /= nodeDeltaToNeigh[level][fdir]; - /////ehsan q///////////////////////////////////////////////////////////////////// - double det=triangle.nx * this->rayX1[fdir]+ triangle.ny * this->rayX2[fdir]+ triangle.nz * this->rayX3[fdir]; - - if(det>-1.E-10) continue; - double d=triangle.nx*v1.x+triangle.ny*v1.y+triangle.nz*v1.z; - double x1= -((-d* this->rayX1[fdir] - triangle.ny *this->rayX2[fdir]* internX1 - triangle.nz *this->rayX3[fdir]* internX1 + triangle.ny *this->rayX1[fdir]* internX2 + triangle.nz* this->rayX1[fdir]* internX3))/det; - double y1= -((-d* this->rayX2[fdir] + triangle.nx* this->rayX2[fdir]* internX1 - triangle.nx* this->rayX1[fdir]* internX2 - triangle.nz* this->rayX3[fdir] *internX2 + triangle.nz* this->rayX2[fdir]* internX3))/det; - double z1= -((-d* this->rayX3[fdir] + triangle.nx* this->rayX3[fdir]* internX1 + triangle.ny* this->rayX3[fdir]* internX2 - triangle.nx* this->rayX1[fdir]* internX3 - triangle.ny* this->rayX2[fdir]* internX3))/det; - double q_ehsan=sqrt((x1-internX1)*(x1-internX1)+(y1-internX2)*(y1-internX2)+(z1-internX3)*(z1-internX3)); - q_ehsan /= nodeDeltaToNeigh[level][fdir]; - q=q_ehsan; - if( UbMath::greater(q, 1.0) || UbMath::lessEqual(q, 0.0) )continue; - - //gefundenes q auf gueltigkeit pruefen - if( UbMath::zero(q) ) - { - //neu (18.05.2010) - //es kann vorkommen, dass bei dünnwandigen geos punkte, die auf einem dreieck liegen, qs bekommen, die durch die geo - //durchgehen. diese punkte werden später jedoch nicht mehr auf solid getestet, da sie ja ne BC bekommen haben - //--> da mind ein q==0.0 für eines der dreiecke -> dort solid setzen - this->solidNodeIndicesMap[block].insert( UbTupleInt3(ix1,ix2,ix3) ); - bcMatrix->setSolid( ix1, ix2, ix3 ); - continue; - } + double boundCubeTriangleMinX1 = minX1 - deltaMinX1[level]; + double boundCubeTriangleMaxX1 = maxX1 + deltaMaxX1[level]; + double boundCubeTriangleMinX2 = minX2 - deltaMinX2[level]; + double boundCubeTriangleMaxX2 = maxX2 + deltaMaxX2[level]; + double boundCubeTriangleMinX3 = minX3 - deltaMinX3[level]; + double boundCubeTriangleMaxX3 = maxX3 + deltaMaxX3[level]; + + GbCuboid3D boundingCubeTriangle(boundCubeTriangleMinX1, boundCubeTriangleMinX2, boundCubeTriangleMinX3, + boundCubeTriangleMaxX1, boundCubeTriangleMaxX2, boundCubeTriangleMaxX3); - if( UbMath::inClosedInterval(q, 1.0, 1.0) ) q = 1.0; - if( UbMath::greater(q, 0.0) && UbMath::lessEqual(q, 1.0) ) - { - gotQs=blockGotBCs=true; - - bc = bcMatrix->getBC(ix1,ix2,ix3); - - //SG 26.08.2010 if(!bc && !bcMatrix->isSolid()) - if(!bc) - { - bc = SPtr<BoundaryConditions>(new BoundaryConditions);; - bcMatrix->setBC(ix1,ix2,ix3,bc); - } - else if( UbMath::less( bc->getQ(fdir), q ) ) //schon ein kuerzeres q voehanden? - { - //neu:: 18.05.2010 - //um falsche qs die evtl durch die "wand" gehen zu vermeiden - //q nur dann neu setzen, wenn neues q kleiner als vorhandenes! - //Zudem: insbesondere an ecken mit zwei BC geos ist nur das - //naehere gueltig - continue; - } - - bc->setBoundaryVelocityX1(vx1); - bc->setBoundaryVelocityX2(vx2); - bc->setBoundaryVelocityX3(vx3); - - for(int index=(int)this->bcAdapters.size()-1; index>=0; --index) - this->bcAdapters[index]->adaptBCForDirection(*this,bc,internX1,internX2,internX3,q,fdir); - - //fuer beschleunigtes wiedereinlesen - if(this->reinitWithStoredQsFlag) - { - bcNodeIndicesAndQsMap[block][ UbTupleInt3(ix1, ix2, ix3) ].resize(D3Q27System::FENDDIR+1+3, -1.0f); - bcNodeIndicesAndQsMap[block][ UbTupleInt3(ix1, ix2, ix3) ][fdir ] = float(q); - bcNodeIndicesAndQsMap[block][ UbTupleInt3(ix1, ix2, ix3) ][D3Q27System::FENDDIR+1+0] = float(internX1); - bcNodeIndicesAndQsMap[block][ UbTupleInt3(ix1, ix2, ix3) ][D3Q27System::FENDDIR+1+1] = float(internX2); - bcNodeIndicesAndQsMap[block][ UbTupleInt3(ix1, ix2, ix3) ][D3Q27System::FENDDIR+1+2] = float(internX3); - } + std::vector<SPtr<Block3D>> triBlocks; + grid.lock()->getBlocksByCuboid(level, boundCubeTriangleMinX1, boundCubeTriangleMinX2, + boundCubeTriangleMinX3, boundCubeTriangleMaxX1, boundCubeTriangleMaxX2, + boundCubeTriangleMaxX3, triBlocks); + + ////////////////////////////////////////////////////////////////////////// + // Schleife ueber bloecke des level, die das dreieck beinhalten + ////////////////////////////////////////////////////////////////////////// + for (std::size_t b = 0; b < triBlocks.size(); b++) { + SPtr<Block3D> block = triBlocks[b]; + + //////////////////////////////////////////////////////////////////////////// + //// Block Dreieck-/test + //////////////////////////////////////////////////////////////////////////// + UbTupleDouble3 coords = grid.lock()->getBlockWorldCoordinates(block); + UbTupleDouble3 deltas = grid.lock()->getBlockLengths(block); + + blockMinX[0] = (float)(val<1>(coords) - deltaMinX1[level]); + blockMinX[1] = (float)(val<2>(coords) - deltaMinX2[level]); + blockMinX[2] = (float)(val<3>(coords) - deltaMinX3[level]); + + blockMaxX[0] = (float)(val<1>(coords) + val<1>(deltas) + deltaMaxX1[level]); + blockMaxX[1] = (float)(val<2>(coords) + val<2>(deltas) + deltaMaxX2[level]); + blockMaxX[2] = (float)(val<3>(coords) + val<3>(deltas) + deltaMaxX3[level]); + + boxCenter[0] = (float)(0.5 * (blockMaxX[0] + blockMinX[0])); + boxCenter[1] = (float)(0.5 * (blockMaxX[1] + blockMinX[1])); + boxCenter[2] = (float)(0.5 * (blockMaxX[2] + blockMinX[2])); + + halfBoxSize[0] = (float)(0.5 * (blockMaxX[0] - blockMinX[0])); + halfBoxSize[1] = (float)(0.5 * (blockMaxX[1] - blockMinX[1])); + halfBoxSize[2] = (float)(0.5 * (blockMaxX[2] - blockMinX[2])); + + // wenn dreieck "vergroesserten cube" nicht schneidet/beruehrt -> keine BC moeglich -> continue + if (!GbMeshTools3D::triBoxOverlap(boxCenter, halfBoxSize, triPoints)) { + counterTriBoxOverlap++; + continue; + } + + ////////////////////////////////////////////////////////////////////////// + // Untersuchung der einzelnen nodes + ////////////////////////////////////////////////////////////////////////// + bool blockGotBCs = false; + + SPtr<ILBMKernel> kernel = block->getKernel(); + SPtr<BCArray3D> bcMatrix = kernel->getBCProcessor()->getBCArray(); + + int indexMinX1 = 0; + int indexMinX2 = 0; + int indexMinX3 = 0; + + int indexMaxX1 = (int)bcMatrix->getNX1(); + int indexMaxX2 = (int)bcMatrix->getNX2(); + int indexMaxX3 = (int)bcMatrix->getNX3(); + + std::set<std::vector<int>> &bcNodeIndices = this->bcNodeIndicesMap[block]; + // std::set< UbTupleInt3 >& solidsFromOtherInteractors = + // tmpSolidNodesFromOtherInteractors[block]; + double q, distance; + + double &nodeDx1 = nodeDeltaToNeigh[level][D3Q27System::E]; + double &nodeDx2 = nodeDeltaToNeigh[level][D3Q27System::N]; + double &nodeDx3 = nodeDeltaToNeigh[level][D3Q27System::T]; + + // fuer OBB-Test + double qEinflussDelta = 1.1 * sqrt(nodeDx1 * nodeDx1 + nodeDx2 * nodeDx2 + nodeDx3 * nodeDx3); + + for (int ix3 = indexMinX3; ix3 < indexMaxX3; ix3++) { + for (int ix2 = indexMinX2; ix2 < indexMaxX2; ix2++) { + for (int ix1 = indexMinX1; ix1 < indexMaxX1; ix1++) { + Vector3D pointplane1 = grid.lock()->getNodeCoordinates(block, ix1, ix2, ix3); + double internX1 = pointplane1[0]; + double internX2 = pointplane1[1]; + double internX3 = pointplane1[2]; + + // int blx1 = block->getX1(); + // int blx2 = block->getX2(); + // int blx3 = block->getX3(); + + if (bcMatrix->isSolid(ix1, ix2, ix3) || bcMatrix->isUndefined(ix1, ix2, ix3)) { + continue; + } + + ////////////////////////////////////////////////////////////////////////// + // Punkt in AABB von Dreieck? + ////////////////////////////////////////////////////////////////////////// + // ehsan changed + bool pointIsOnBoundary = true; + if (!boundingCubeTriangle.isPointInGbObject3D(internX1, internX2, internX3, + pointIsOnBoundary)) { + counterAABBTriFace++; + continue; + } + // std::cout<<"internX3 "<<internX3<<" internX2"<<internX2<<" internX1 "<<internX1<<"\n"; + ////////////////////////////////////////////////////////////////////////// + // Halbebenentests + ////////////////////////////////////////////////////////////////////////// + distance = halfSpace.getDistance(internX1, internX2, internX3); + // Punkt in Halbebene? (nein, wenn distance<0) + if (useHalfSpace && + UbMath::less(distance, 0.0)) //== !halfSpace.ptInside(internX1,internX2,internX3) ) + { + counterHalfspace++; + continue; + } + + // BilligOBB-Test: wenn distance > qEinflussDelta -> kein q + if (UbMath::greater(fabs(distance), qEinflussDelta)) { + counterBilligOBB++; + continue; + } + + ///////////////////////////////////////////////////////////////////////////// + // Raytracingfür diskrete Boltzmannrichtungen + ///////////////////////////////////////////////////////////////////////////// + gotQs = false; + bc = SPtr<BoundaryConditions>(); + + // RAYTRACING - diskrete LB-dir zu Dreick + // e1 = v1 - v0 + e1x1 = v2.x - v1.x; + e1x2 = v2.y - v1.y; + e1x3 = v2.z - v1.z; + + // e2 = v2 - v0 + e2x1 = v3.x - v1.x; + e2x2 = v3.y - v1.y; + e2x3 = v3.z - v1.z; + + // s = o - v0 + sx1 = internX1 - v1.x; + sx2 = internX2 - v1.y; + sx3 = internX3 - v1.z; + + for (int fdir = D3Q27System::FSTARTDIR; fdir <= D3Q27System::FENDDIR; fdir++) { + // p = d x e2 + px1 = this->rayX2[fdir] * e2x3 - this->rayX3[fdir] * e2x2; + px2 = this->rayX3[fdir] * e2x1 - this->rayX1[fdir] * e2x3; + px3 = this->rayX1[fdir] * e2x2 - this->rayX2[fdir] * e2x1; + + // a = e1 dot p + a = e1x1 * px1 + e1x2 * px2 + e1x3 * px3; + if (fabs(a) < 1.E-10) + continue; + f = 1.0 / a; + + // u = f * ( s dot p) + u = f * (sx1 * px1 + sx2 * px2 + sx3 * px3); + if (u < -1.E-10 || u > 1.0 + 1.E-10) + continue; + + // q = s x e1 + qx1 = sx2 * e1x3 - sx3 * e1x2; + qx2 = sx3 * e1x1 - sx1 * e1x3; + qx3 = sx1 * e1x2 - sx2 * e1x1; + + // v = f*(e2 dot q) + v = f * (this->rayX1[fdir] * qx1 + this->rayX2[fdir] * qx2 + this->rayX3[fdir] * qx3); + if (v < -1.E-10 || (u + v) > 1.0 + 1.E-10) + continue; + + // t = f * (e2 dot q) + q = f * (e2x1 * qx1 + e2x2 * qx2 + e2x3 * qx3); + q /= nodeDeltaToNeigh[level][fdir]; + /////ehsan q///////////////////////////////////////////////////////////////////// + double det = triangle.nx * this->rayX1[fdir] + triangle.ny * this->rayX2[fdir] + + triangle.nz * this->rayX3[fdir]; + + if (det > -1.E-10) + continue; + double d = triangle.nx * v1.x + triangle.ny * v1.y + triangle.nz * v1.z; + double x1 = -((-d * this->rayX1[fdir] - triangle.ny * this->rayX2[fdir] * internX1 - + triangle.nz * this->rayX3[fdir] * internX1 + + triangle.ny * this->rayX1[fdir] * internX2 + + triangle.nz * this->rayX1[fdir] * internX3)) / + det; + double y1 = -((-d * this->rayX2[fdir] + triangle.nx * this->rayX2[fdir] * internX1 - + triangle.nx * this->rayX1[fdir] * internX2 - + triangle.nz * this->rayX3[fdir] * internX2 + + triangle.nz * this->rayX2[fdir] * internX3)) / + det; + double z1 = -((-d * this->rayX3[fdir] + triangle.nx * this->rayX3[fdir] * internX1 + + triangle.ny * this->rayX3[fdir] * internX2 - + triangle.nx * this->rayX1[fdir] * internX3 - + triangle.ny * this->rayX2[fdir] * internX3)) / + det; + double q_ehsan = + sqrt((x1 - internX1) * (x1 - internX1) + (y1 - internX2) * (y1 - internX2) + + (z1 - internX3) * (z1 - internX3)); + q_ehsan /= nodeDeltaToNeigh[level][fdir]; + q = q_ehsan; + if (UbMath::greater(q, 1.0) || UbMath::lessEqual(q, 0.0)) + continue; + + // gefundenes q auf gueltigkeit pruefen + if (UbMath::zero(q)) { + // neu (18.05.2010) + // es kann vorkommen, dass bei dünnwandigen geos punkte, die auf einem dreieck + // liegen, qs bekommen, die durch die geo durchgehen. diese punkte werden später + // jedoch nicht mehr auf solid getestet, da sie ja ne BC bekommen haben + //--> da mind ein q==0.0 für eines der dreiecke -> dort solid setzen + this->solidNodeIndicesMap[block].insert(UbTupleInt3(ix1, ix2, ix3)); + bcMatrix->setSolid(ix1, ix2, ix3); + continue; + } + + if (UbMath::inClosedInterval(q, 1.0, 1.0)) + q = 1.0; + if (UbMath::greater(q, 0.0) && UbMath::lessEqual(q, 1.0)) { + gotQs = blockGotBCs = true; + + bc = bcMatrix->getBC(ix1, ix2, ix3); + + // SG 26.08.2010 if(!bc && !bcMatrix->isSolid()) + if (!bc) { + bc = SPtr<BoundaryConditions>(new BoundaryConditions); + ; + bcMatrix->setBC(ix1, ix2, ix3, bc); + } else if (UbMath::less(bc->getQ(fdir), q)) // schon ein kuerzeres q voehanden? + { + // neu:: 18.05.2010 + // um falsche qs die evtl durch die "wand" gehen zu vermeiden + // q nur dann neu setzen, wenn neues q kleiner als vorhandenes! + // Zudem: insbesondere an ecken mit zwei BC geos ist nur das + // naehere gueltig + continue; + } + + bc->setBoundaryVelocityX1(vx1); + bc->setBoundaryVelocityX2(vx2); + bc->setBoundaryVelocityX3(vx3); + + for (int index = (int)this->bcAdapters.size() - 1; index >= 0; --index) + this->bcAdapters[index]->adaptBCForDirection(*this, bc, internX1, internX2, + internX3, q, fdir); + + // fuer beschleunigtes wiedereinlesen + if (this->reinitWithStoredQsFlag) { + bcNodeIndicesAndQsMap[block][UbTupleInt3(ix1, ix2, ix3)].resize( + D3Q27System::FENDDIR + 1 + 3, -1.0f); + bcNodeIndicesAndQsMap[block][UbTupleInt3(ix1, ix2, ix3)][fdir] = float(q); + bcNodeIndicesAndQsMap[block][UbTupleInt3(ix1, ix2, ix3)] + [D3Q27System::FENDDIR + 1 + 0] = float(internX1); + bcNodeIndicesAndQsMap[block][UbTupleInt3(ix1, ix2, ix3)] + [D3Q27System::FENDDIR + 1 + 1] = float(internX2); + bcNodeIndicesAndQsMap[block][UbTupleInt3(ix1, ix2, ix3)] + [D3Q27System::FENDDIR + 1 + 2] = float(internX3); + } + } + } + + if (gotQs) { + std::vector<int> p(3); + p[0] = ix1; + p[1] = ix2; + p[2] = ix3; + bcNodeIndices.insert(p); + + for (int index = (int)this->bcAdapters.size() - 1; index >= 0; --index) + this->bcAdapters[index]->adaptBC(*this, bc, internX1, internX2, internX3); + } } - } - - if(gotQs) - { - std::vector<int> p(3); - p[0]=ix1; p[1]=ix2; p[2]=ix3; - bcNodeIndices.insert(p); - - for(int index=(int)this->bcAdapters.size()-1; index>=0; --index) - this->bcAdapters[index]->adaptBC(*this,bc,internX1,internX2,internX3); - } - } - } + } + } } - } - //dynamische Punkte des GbCuboids muessen leider per "Hand" geloescht werden :-( - boundingCubeTriangle.finalize(); - } - } - UBLOGML(logDEBUG1,"\nLBMTriFaceMeshInteractor - setQs end "); + // dynamische Punkte des GbCuboids muessen leider per "Hand" geloescht werden :-( + boundingCubeTriangle.finalize(); + } + } + UBLOGML(logDEBUG1, "\nLBMTriFaceMeshInteractor - setQs end "); } ////////////////////////////////////////////////////////////////////////// -//Vorgehesnweise -//A – Bestimmung der q's +// Vorgehesnweise +// A – Bestimmung der q's // 1. fuer jeden Bounding cube eines Dreiecks des netzes werden die Bloecke des Blockgitter ermittelt // 2. mittels eines Dreieck/Block Verschneidungstest werden weitere nicht relevante Bloecke aussortiert // (fuer lange „schief“ im Raum stehende Dreicke, bei denen das Bounding Cube suboptimal ist) @@ -564,1272 +585,1323 @@ void D3Q27TriFaceMeshInteractor::setQs(const double& timeStep) // 4. Knoten die innerhalb des Cubes aber „innerhalb“ des Netzes liegen werden mittels Halbebenentest aussoriert // 5. fuer die restliche Knoten erfolgt die q bestimmung mittels effizienter raytracing algorithmen // fuer die diskreten Boltzmannrichtungen -//B – Setzen der nicht aktiven Bloecke und Solid Nodes +// B – Setzen der nicht aktiven Bloecke und Solid Nodes // alle Bloecke des Bounding Cube des Netzes, die mind eine BC erhielten, wurden in A markiert -// 1. fuer nicht markierte Bloecke genuegt EIN pointInObject(Dreicksnetz)-Test um den gesamten Block bei Erfolg als „not active“ zu markieren +// 1. fuer nicht markierte Bloecke genuegt EIN pointInObject(Dreicksnetz)-Test um den gesamten Block bei Erfolg als +// „not active“ zu markieren // 2. fuer markiertre Bloecke wird ein rekursiver Fuellalgorithmus durchgefuehrt -void D3Q27TriFaceMeshInteractor::initInteractor2(const double& timeStep) +void D3Q27TriFaceMeshInteractor::initInteractor2(const double &timeStep) { - UBLOGML(logDEBUG1,"\nLBMTriFaceMeshInteractor - initInteractor start "); - if( !this->grid.lock() ) throw UbException(UB_EXARGS,"ups, no grid.lock()!!"); - - if( this->reinitWithStoredQsFlag && !bcNodeIndicesAndQsMap.empty() ) - { - this->reinitWithStoredQs(timeStep); - return; - } - - GbTriFaceMesh3D* mesh = dynamic_cast<GbTriFaceMesh3D*>(this->geoObject3D.get()); - - UBLOGML(logDEBUG1,"\nLBMTriFaceMeshInteractor - initInteractor for \""<<mesh->getName()<<" \" t="<<timeStep); - //cout<<" - init basics ..."; - - this->removeBcBlocks(); //hier wird auch die nodeIndicesMap geloescht! - this->removeSolidBlocks(); - - ////////////////////////////////////////////////////////////////////////// - //init bcs - ////////////////////////////////////////////////////////////////////////// - int nofAdapter = (int)this->bcAdapters.size(); - if(nofAdapter==0) std::cout<<"WARNING - D3Q27TriFaceMeshInteractor::initInteractor Warning - no nodeAdapter available for "/*<<this->getName()*/<<std::endl; - bool needTimeDependence = false; - for(int pos=0; pos<nofAdapter; ++pos) - { - this->bcAdapters[pos]->init(this,timeStep); - if(this->bcAdapters[pos]->isTimeDependent()) needTimeDependence = true; - } - if(needTimeDependence) this->setTimeDependent(); - else this->unsetTimeDependent(); - - ////////////////////////////////////////////////////////////////////////// - //grid.lock() info - ////////////////////////////////////////////////////////////////////////// - int coarsestInitLevel = grid.lock()->getCoarsestInitializedLevel(); - int finestInitLevel = grid.lock()->getFinestInitializedLevel(); - - UbTupleInt3 blocknx = grid.lock()->getBlockNX(); - int blocknx1 = val<1>(blocknx); //gilt fuer alle Level - int blocknx2 = val<2>(blocknx); //gilt fuer alle Level - int blocknx3 = val<3>(blocknx); //gilt fuer alle Level - - //grobe Blocklaengen - SPtr<CoordinateTransformation3D> trafo = grid.lock()->getCoordinateTransformator(); - double cblockDeltaX1,cblockDeltaX2,cblockDeltaX3, delta ; - cblockDeltaX1 = cblockDeltaX2 = cblockDeltaX3 = delta = 1.0/(double)(1<<coarsestInitLevel); - if(trafo) - { - cblockDeltaX1 = trafo->getX1CoordinateScaling()*delta; - cblockDeltaX2 = trafo->getX2CoordinateScaling()*delta; - cblockDeltaX3 = trafo->getX3CoordinateScaling()*delta; - } - //levelspezifische blocklaengen und knotenabstaende - std::vector< std::vector<double> > nodeDeltaToNeigh(finestInitLevel+1); - //vector<double> blockDeltaX1(finestInitLevel+1), blockDeltaX2(finestInitLevel+1), blockDeltaX3(finestInitLevel+1); - std::vector<float> deltaMinX1(finestInitLevel+1),deltaMinX2(finestInitLevel+1),deltaMinX3(finestInitLevel+1); - std::vector<float> deltaMaxX1(finestInitLevel+1),deltaMaxX2(finestInitLevel+1),deltaMaxX3(finestInitLevel+1); - - //Im Boltzmankontext muss dx1==dx2==dx3 sein!! - assert( UbMath::equal(cblockDeltaX1/(double)blocknx1, cblockDeltaX2/(double)blocknx2 ) ); - assert( UbMath::equal(cblockDeltaX1/(double)blocknx1, cblockDeltaX3/(double)blocknx3 ) ); - - for(int level = coarsestInitLevel; level<=finestInitLevel; level++) - { - double nodeDelta = cblockDeltaX1/(double)(blocknx1*(1<<(level-coarsestInitLevel))); - - std::vector<double> distNeigh(D3Q27System::FENDDIR+1, 0.0); - D3Q27System::calcDistanceToNeighbors(distNeigh, nodeDelta); - - nodeDeltaToNeigh[level].resize(D3Q27System::ENDDIR+1,0.0); - for(int fdir=D3Q27System::FSTARTDIR; fdir<=D3Q27System::FENDDIR; fdir++) - { - nodeDeltaToNeigh[level][fdir] = distNeigh[fdir]; - } - - //im gegensatz zum allg. Cell3DInteractor kann man hier auf max(0.02*blockDeltaX1[level],fabs(...)) verzichten - //da dies nur für blockDeltaCalculator->getMinX1Delta(level)==0.0 benötigt wird. ist im D3Q19... aber nie so - //Geller: kann man nicht diesen befuckten DeltaCalculator weglassen und hier einfach die Formel zum Delta rechnen reinpacken - //SirAnn: klar, mann kann auch weißwuerste am Alex verkaufen... aber zum einen ist das Ding dazu da - // und zum anderen sollt eman mal überlegen: "Formel zum Delta rechnen"->man muss rechnen - // blockDeltaCalculator->getMinX1Delta(level) -> ein geinlinter wert wird geholt - - deltaMinX1[level] = (float)( 1.2*nodeDelta); //kein minus da unten -deltaMin - deltaMinX2[level] = (float)( 1.2*nodeDelta); - deltaMinX3[level] = (float)( 1.2*nodeDelta); - deltaMaxX1[level] = (float)( 1.2*nodeDelta); - deltaMaxX2[level] = (float)( 1.2*nodeDelta); - deltaMaxX3[level] = (float)( 1.2*nodeDelta); - } - - ////////////////////////////////////////////////////////////////////////// - //bounding cubes des TriFaceMesh ermitteln (pro level) - ////////////////////////////////////////////////////////////////////////// - //min/max Werte des Dreiecksnetzes holen - double geoMinX1(0.0), geoMinX2(0.0), geoMinX3(0.0), geoMaxX1(0.0), geoMaxX2(0.0), geoMaxX3(0.0); - if(this->isSolid() || this->isMoveable()) - { - geoMinX1 = this->geoObject3D->getX1Minimum(); geoMaxX1 = this->geoObject3D->getX1Maximum(); - geoMinX2 = this->geoObject3D->getX2Minimum(); geoMaxX2 = this->geoObject3D->getX2Maximum(); - geoMinX3 = this->geoObject3D->getX3Minimum(); geoMaxX3 = this->geoObject3D->getX3Maximum(); - } - else throw UbException(UB_EXARGS,"only TYPE==SOLID is implemented" ); - - std::map<SPtr<Block3D>,SolidCheckMethod> blocksForSolidCheck; - - for(int level = coarsestInitLevel; level<=finestInitLevel; level++) - { - if(this->isSolid() || this->isMoveable()) - { - //bloecke fuer "bounding cube gesamt" - std::vector<SPtr<Block3D>> tmpblocks; - grid.lock()->getBlocksByCuboid(level,geoMinX1-deltaMinX1[level], geoMinX2-deltaMinX2[level], geoMinX3-deltaMinX3[level], - geoMaxX1+deltaMaxX1[level], geoMaxX2+deltaMaxX2[level], geoMaxX3+deltaMaxX3[level],tmpblocks ); - - for( size_t i=0; i<tmpblocks.size(); i++ ) - blocksForSolidCheck[tmpblocks[i]] = PointInObject; - } - } - - ////////////////////////////////////////////////////////////////////////// - //FE-specific - ////////////////////////////////////////////////////////////////////////// - //bool calcVelocities = false; - //FeTriFaceMesh3D* feMesh = dynamic_cast<FeTriFaceMesh3D*>(mesh); - //std::vector<FeTriFaceMesh3D::VertexAttributes>* attributes = NULL; - //if(feMesh) - //{ - // calcVelocities = true; - // attributes = feMesh->getAttributes(); - //} - - ////////////////////////////////////////////////////////////////////////// - //DREIECKE: q-Bestimmung - ////////////////////////////////////////////////////////////////////////// - - //notwendige variablen initialisieren (u.a. blockDeltas des groben levels) - float triPoints[3][3]; - float vx1=0.0, vx2=0.0, vx3=0.0; - unsigned counterTriBoxOverlap=0, counterAABBTriFace=0, counterHalfspace=0, counterBilligOBB=0; - std::vector<GbTriFaceMesh3D::TriFace>& triangles = *mesh->getTriangles(); - std::vector<GbTriFaceMesh3D::Vertex>& nodes = *mesh->getNodes(); - std::map< SPtr<Block3D>, std::set< std::vector<int> > > tmpSolidNodesFromOtherInteractors; - - int onePercent = UbMath::integerRounding(triangles.size()*0.01); - if(onePercent==0) onePercent=1; - UbTimer setQTimer; setQTimer.start(); - UBLOG(logDEBUG3, " - setQs for "<<(int)triangles.size()<<" triangles"); - -// bool solidFromOtherInteractor = false; - float blockMinX[3],blockMaxX[3],boxCenter[3],halfBoxSize[3]; - - for(size_t t=0; t<triangles.size(); t++) - { - //if (t==10577) - //{ - // int ehsan=0; - //} - ////////////////////////////////////////////////////////////////////////// - // Halfspace zum Dreieck generieren und min/max des Dreiecks ermitteln - ////////////////////////////////////////////////////////////////////////// - GbTriFaceMesh3D::TriFace& triangle = triangles[t]; - - GbTriFaceMesh3D::Vertex& v1 = nodes[triangle.v1]; - GbTriFaceMesh3D::Vertex& v2 = nodes[triangle.v2]; - GbTriFaceMesh3D::Vertex& v3 = nodes[triangle.v3]; - - GbHalfSpace3D halfSpace( v1.x,v1.y,v1.z,v2.x,v2.y,v2.z,v3.x,v3.y,v3.z ); - - //if(calcVelocities) - //{ - // FeTriFaceMesh3D::VertexAttributes& vAttribut1 = (*attributes)[triangle.v1]; - // FeTriFaceMesh3D::VertexAttributes& vAttribut2 = (*attributes)[triangle.v2]; - // FeTriFaceMesh3D::VertexAttributes& vAttribut3 = (*attributes)[triangle.v3]; - // vx1 = (float)(UbMath::c1o3*(vAttribut1.getVelocityX()+vAttribut2.getVelocityX()+vAttribut3.getVelocityX())); - // vx2 = (float)(UbMath::c1o3*(vAttribut1.getVelocityY()+vAttribut2.getVelocityY()+vAttribut3.getVelocityY())); - // vx3 = (float)(UbMath::c1o3*(vAttribut1.getVelocityZ()+vAttribut2.getVelocityZ()+vAttribut3.getVelocityZ())); - //} - - ////////////////////////////////////////////////////////////////////////// - //fuer GbMeshTools3D::triBoxOverlap - ////////////////////////////////////////////////////////////////////////// - triPoints[0][0] = v1.x; triPoints[0][1] = v1.y; triPoints[0][2] = v1.z; - triPoints[1][0] = v2.x; triPoints[1][1] = v2.y; triPoints[1][2] = v2.z; - triPoints[2][0] = v3.x; triPoints[2][1] = v3.y; triPoints[2][2] = v3.z; - - double minX1 = triangle.getMinX(nodes); double maxX1 = triangle.getMaxX(nodes); - double minX2 = triangle.getMinY(nodes); double maxX2 = triangle.getMaxY(nodes); - double minX3 = triangle.getMinZ(nodes); double maxX3 = triangle.getMaxZ(nodes); - - ////////////////////////////////////////////////////////////////////////// - // Schleife ueber alle Level - ////////////////////////////////////////////////////////////////////////// - double e1x1,e1x2,e1x3,e2x1,e2x2,e2x3,px1,px2,px3,a,f,sx1,sx2,sx3,u,qx1,qx2,qx3,v; - bool gotQs = false; - SPtr<BoundaryConditions> bc; - - for(int level=coarsestInitLevel; level<=finestInitLevel; level++) - { - ////////////////////////////////////////////////////////////////////////// - // levelspezifisches BoundCube des Dreicks ermitteln und zugehörige Bloecke beziehen - ////////////////////////////////////////////////////////////////////////// - double boundCubeTriangleMinX1 = minX1-deltaMinX1[level]; double boundCubeTriangleMaxX1 = maxX1+deltaMaxX1[level]; - double boundCubeTriangleMinX2 = minX2-deltaMinX2[level]; double boundCubeTriangleMaxX2 = maxX2+deltaMaxX2[level]; - double boundCubeTriangleMinX3 = minX3-deltaMinX3[level]; double boundCubeTriangleMaxX3 = maxX3+deltaMaxX3[level]; - - GbCuboid3D boundingCubeTriangle( boundCubeTriangleMinX1, boundCubeTriangleMinX2, boundCubeTriangleMinX3 - , boundCubeTriangleMaxX1, boundCubeTriangleMaxX2, boundCubeTriangleMaxX3 ); - - std::vector<SPtr<Block3D>> triBlocks; - grid.lock()->getBlocksByCuboid(level, boundCubeTriangleMinX1, boundCubeTriangleMinX2, boundCubeTriangleMinX3 - , boundCubeTriangleMaxX1, boundCubeTriangleMaxX2, boundCubeTriangleMaxX3, triBlocks ); - - ////////////////////////////////////////////////////////////////////////// - // Schleife ueber bloecke des level, die das dreieck beinhalten - ////////////////////////////////////////////////////////////////////////// - for(std::size_t b=0; b<triBlocks.size(); b++) - { - SPtr<Block3D> block = triBlocks[b]; - - //////////////////////////////////////////////////////////////////////////// - //// Block Dreieck-/test - //////////////////////////////////////////////////////////////////////////// - UbTupleDouble3 coords = grid.lock()->getBlockWorldCoordinates(block); - UbTupleDouble3 deltas = grid.lock()->getBlockLengths(block); - - blockMinX[0] = (float)(val<1>(coords)-deltaMinX1[level]); - blockMinX[1] = (float)(val<2>(coords)-deltaMinX2[level]); - blockMinX[2] = (float)(val<3>(coords)-deltaMinX3[level]); - - blockMaxX[0] = (float)(val<1>(coords)+val<1>(deltas)+deltaMaxX1[level]); - blockMaxX[1] = (float)(val<2>(coords)+val<2>(deltas)+deltaMaxX2[level]); - blockMaxX[2] = (float)(val<3>(coords)+val<3>(deltas)+deltaMaxX3[level]); - - boxCenter[0] = (float)(0.5*(blockMaxX[0]+blockMinX[0])); - boxCenter[1] = (float)(0.5*(blockMaxX[1]+blockMinX[1])); - boxCenter[2] = (float)(0.5*(blockMaxX[2]+blockMinX[2])); + UBLOGML(logDEBUG1, "\nLBMTriFaceMeshInteractor - initInteractor start "); + if (!this->grid.lock()) + throw UbException(UB_EXARGS, "ups, no grid.lock()!!"); + + if (this->reinitWithStoredQsFlag && !bcNodeIndicesAndQsMap.empty()) { + this->reinitWithStoredQs(timeStep); + return; + } + + GbTriFaceMesh3D *mesh = dynamic_cast<GbTriFaceMesh3D *>(this->geoObject3D.get()); + + UBLOGML(logDEBUG1, "\nLBMTriFaceMeshInteractor - initInteractor for \"" << mesh->getName() << " \" t=" << timeStep); + // cout<<" - init basics ..."; + + this->removeBcBlocks(); // hier wird auch die nodeIndicesMap geloescht! + this->removeSolidBlocks(); + + ////////////////////////////////////////////////////////////////////////// + // init bcs + ////////////////////////////////////////////////////////////////////////// + int nofAdapter = (int)this->bcAdapters.size(); + if (nofAdapter == 0) + std::cout + << "WARNING - D3Q27TriFaceMeshInteractor::initInteractor Warning - no nodeAdapter available for " /*<<this->getName()*/ + << std::endl; + bool needTimeDependence = false; + for (int pos = 0; pos < nofAdapter; ++pos) { + this->bcAdapters[pos]->init(this, timeStep); + if (this->bcAdapters[pos]->isTimeDependent()) + needTimeDependence = true; + } + if (needTimeDependence) + this->setTimeDependent(); + else + this->unsetTimeDependent(); + + ////////////////////////////////////////////////////////////////////////// + // grid.lock() info + ////////////////////////////////////////////////////////////////////////// + int coarsestInitLevel = grid.lock()->getCoarsestInitializedLevel(); + int finestInitLevel = grid.lock()->getFinestInitializedLevel(); + + UbTupleInt3 blocknx = grid.lock()->getBlockNX(); + int blocknx1 = val<1>(blocknx); // gilt fuer alle Level + int blocknx2 = val<2>(blocknx); // gilt fuer alle Level + int blocknx3 = val<3>(blocknx); // gilt fuer alle Level + + // grobe Blocklaengen + SPtr<CoordinateTransformation3D> trafo = grid.lock()->getCoordinateTransformator(); + double cblockDeltaX1, cblockDeltaX2, cblockDeltaX3, delta; + cblockDeltaX1 = cblockDeltaX2 = cblockDeltaX3 = delta = 1.0 / (double)(1 << coarsestInitLevel); + if (trafo) { + cblockDeltaX1 = trafo->getX1CoordinateScaling() * delta; + cblockDeltaX2 = trafo->getX2CoordinateScaling() * delta; + cblockDeltaX3 = trafo->getX3CoordinateScaling() * delta; + } + // levelspezifische blocklaengen und knotenabstaende + std::vector<std::vector<double>> nodeDeltaToNeigh(finestInitLevel + 1); + // vector<double> blockDeltaX1(finestInitLevel+1), blockDeltaX2(finestInitLevel+1), blockDeltaX3(finestInitLevel+1); + std::vector<float> deltaMinX1(finestInitLevel + 1), deltaMinX2(finestInitLevel + 1), + deltaMinX3(finestInitLevel + 1); + std::vector<float> deltaMaxX1(finestInitLevel + 1), deltaMaxX2(finestInitLevel + 1), + deltaMaxX3(finestInitLevel + 1); + + // Im Boltzmankontext muss dx1==dx2==dx3 sein!! + assert(UbMath::equal(cblockDeltaX1 / (double)blocknx1, cblockDeltaX2 / (double)blocknx2)); + assert(UbMath::equal(cblockDeltaX1 / (double)blocknx1, cblockDeltaX3 / (double)blocknx3)); + + for (int level = coarsestInitLevel; level <= finestInitLevel; level++) { + double nodeDelta = cblockDeltaX1 / (double)(blocknx1 * (1 << (level - coarsestInitLevel))); + + std::vector<double> distNeigh(D3Q27System::FENDDIR + 1, 0.0); + D3Q27System::calcDistanceToNeighbors(distNeigh, nodeDelta); + + nodeDeltaToNeigh[level].resize(D3Q27System::ENDDIR + 1, 0.0); + for (int fdir = D3Q27System::FSTARTDIR; fdir <= D3Q27System::FENDDIR; fdir++) { + nodeDeltaToNeigh[level][fdir] = distNeigh[fdir]; + } + + // im gegensatz zum allg. Cell3DInteractor kann man hier auf max(0.02*blockDeltaX1[level],fabs(...)) verzichten + // da dies nur für blockDeltaCalculator->getMinX1Delta(level)==0.0 benötigt wird. ist im D3Q19... aber nie so + // Geller: kann man nicht diesen befuckten DeltaCalculator weglassen und hier einfach die Formel zum Delta + // rechnen reinpacken SirAnn: klar, mann kann auch weißwuerste am Alex verkaufen... aber zum einen ist das Ding + // dazu da + // und zum anderen sollt eman mal überlegen: "Formel zum Delta rechnen"->man muss rechnen + // blockDeltaCalculator->getMinX1Delta(level) -> ein geinlinter wert wird geholt + + deltaMinX1[level] = (float)(1.2 * nodeDelta); // kein minus da unten -deltaMin + deltaMinX2[level] = (float)(1.2 * nodeDelta); + deltaMinX3[level] = (float)(1.2 * nodeDelta); + deltaMaxX1[level] = (float)(1.2 * nodeDelta); + deltaMaxX2[level] = (float)(1.2 * nodeDelta); + deltaMaxX3[level] = (float)(1.2 * nodeDelta); + } + + ////////////////////////////////////////////////////////////////////////// + // bounding cubes des TriFaceMesh ermitteln (pro level) + ////////////////////////////////////////////////////////////////////////// + // min/max Werte des Dreiecksnetzes holen + double geoMinX1(0.0), geoMinX2(0.0), geoMinX3(0.0), geoMaxX1(0.0), geoMaxX2(0.0), geoMaxX3(0.0); + if (this->isSolid() || this->isMoveable()) { + geoMinX1 = this->geoObject3D->getX1Minimum(); + geoMaxX1 = this->geoObject3D->getX1Maximum(); + geoMinX2 = this->geoObject3D->getX2Minimum(); + geoMaxX2 = this->geoObject3D->getX2Maximum(); + geoMinX3 = this->geoObject3D->getX3Minimum(); + geoMaxX3 = this->geoObject3D->getX3Maximum(); + } else + throw UbException(UB_EXARGS, "only TYPE==SOLID is implemented"); + + std::map<SPtr<Block3D>, SolidCheckMethod> blocksForSolidCheck; + + for (int level = coarsestInitLevel; level <= finestInitLevel; level++) { + if (this->isSolid() || this->isMoveable()) { + // bloecke fuer "bounding cube gesamt" + std::vector<SPtr<Block3D>> tmpblocks; + grid.lock()->getBlocksByCuboid(level, geoMinX1 - deltaMinX1[level], geoMinX2 - deltaMinX2[level], + geoMinX3 - deltaMinX3[level], geoMaxX1 + deltaMaxX1[level], + geoMaxX2 + deltaMaxX2[level], geoMaxX3 + deltaMaxX3[level], tmpblocks); + + for (size_t i = 0; i < tmpblocks.size(); i++) + blocksForSolidCheck[tmpblocks[i]] = PointInObject; + } + } + + ////////////////////////////////////////////////////////////////////////// + // FE-specific + ////////////////////////////////////////////////////////////////////////// + // bool calcVelocities = false; + // FeTriFaceMesh3D* feMesh = dynamic_cast<FeTriFaceMesh3D*>(mesh); + // std::vector<FeTriFaceMesh3D::VertexAttributes>* attributes = NULL; + // if(feMesh) + //{ + // calcVelocities = true; + // attributes = feMesh->getAttributes(); + //} + + ////////////////////////////////////////////////////////////////////////// + // DREIECKE: q-Bestimmung + ////////////////////////////////////////////////////////////////////////// + + // notwendige variablen initialisieren (u.a. blockDeltas des groben levels) + float triPoints[3][3]; + float vx1 = 0.0, vx2 = 0.0, vx3 = 0.0; + unsigned counterTriBoxOverlap = 0, counterAABBTriFace = 0, counterHalfspace = 0, counterBilligOBB = 0; + std::vector<GbTriFaceMesh3D::TriFace> &triangles = *mesh->getTriangles(); + std::vector<GbTriFaceMesh3D::Vertex> &nodes = *mesh->getNodes(); + std::map<SPtr<Block3D>, std::set<std::vector<int>>> tmpSolidNodesFromOtherInteractors; + + int onePercent = UbMath::integerRounding(triangles.size() * 0.01); + if (onePercent == 0) + onePercent = 1; + UbTimer setQTimer; + setQTimer.start(); + UBLOG(logDEBUG3, " - setQs for " << (int)triangles.size() << " triangles"); + + // bool solidFromOtherInteractor = false; + float blockMinX[3], blockMaxX[3], boxCenter[3], halfBoxSize[3]; + + for (size_t t = 0; t < triangles.size(); t++) { + // if (t==10577) + //{ + // int ehsan=0; + //} + ////////////////////////////////////////////////////////////////////////// + // Halfspace zum Dreieck generieren und min/max des Dreiecks ermitteln + ////////////////////////////////////////////////////////////////////////// + GbTriFaceMesh3D::TriFace &triangle = triangles[t]; + + GbTriFaceMesh3D::Vertex &v1 = nodes[triangle.v1]; + GbTriFaceMesh3D::Vertex &v2 = nodes[triangle.v2]; + GbTriFaceMesh3D::Vertex &v3 = nodes[triangle.v3]; + + GbHalfSpace3D halfSpace(v1.x, v1.y, v1.z, v2.x, v2.y, v2.z, v3.x, v3.y, v3.z); + + // if(calcVelocities) + //{ + // FeTriFaceMesh3D::VertexAttributes& vAttribut1 = (*attributes)[triangle.v1]; + // FeTriFaceMesh3D::VertexAttributes& vAttribut2 = (*attributes)[triangle.v2]; + // FeTriFaceMesh3D::VertexAttributes& vAttribut3 = (*attributes)[triangle.v3]; + // vx1 = + // (float)(UbMath::c1o3*(vAttribut1.getVelocityX()+vAttribut2.getVelocityX()+vAttribut3.getVelocityX())); vx2 + // = (float)(UbMath::c1o3*(vAttribut1.getVelocityY()+vAttribut2.getVelocityY()+vAttribut3.getVelocityY())); + // vx3 = + // (float)(UbMath::c1o3*(vAttribut1.getVelocityZ()+vAttribut2.getVelocityZ()+vAttribut3.getVelocityZ())); + //} + + ////////////////////////////////////////////////////////////////////////// + // fuer GbMeshTools3D::triBoxOverlap + ////////////////////////////////////////////////////////////////////////// + triPoints[0][0] = v1.x; + triPoints[0][1] = v1.y; + triPoints[0][2] = v1.z; + triPoints[1][0] = v2.x; + triPoints[1][1] = v2.y; + triPoints[1][2] = v2.z; + triPoints[2][0] = v3.x; + triPoints[2][1] = v3.y; + triPoints[2][2] = v3.z; + + double minX1 = triangle.getMinX(nodes); + double maxX1 = triangle.getMaxX(nodes); + double minX2 = triangle.getMinY(nodes); + double maxX2 = triangle.getMaxY(nodes); + double minX3 = triangle.getMinZ(nodes); + double maxX3 = triangle.getMaxZ(nodes); + + ////////////////////////////////////////////////////////////////////////// + // Schleife ueber alle Level + ////////////////////////////////////////////////////////////////////////// + double e1x1, e1x2, e1x3, e2x1, e2x2, e2x3, px1, px2, px3, a, f, sx1, sx2, sx3, u, qx1, qx2, qx3, v; + bool gotQs = false; + SPtr<BoundaryConditions> bc; + + for (int level = coarsestInitLevel; level <= finestInitLevel; level++) { + ////////////////////////////////////////////////////////////////////////// + // levelspezifisches BoundCube des Dreicks ermitteln und zugehörige Bloecke beziehen + ////////////////////////////////////////////////////////////////////////// + double boundCubeTriangleMinX1 = minX1 - deltaMinX1[level]; + double boundCubeTriangleMaxX1 = maxX1 + deltaMaxX1[level]; + double boundCubeTriangleMinX2 = minX2 - deltaMinX2[level]; + double boundCubeTriangleMaxX2 = maxX2 + deltaMaxX2[level]; + double boundCubeTriangleMinX3 = minX3 - deltaMinX3[level]; + double boundCubeTriangleMaxX3 = maxX3 + deltaMaxX3[level]; - halfBoxSize[0] = (float)(0.5*(blockMaxX[0]-blockMinX[0])); - halfBoxSize[1] = (float)(0.5*(blockMaxX[1]-blockMinX[1])); - halfBoxSize[2] = (float)(0.5*(blockMaxX[2]-blockMinX[2])); + GbCuboid3D boundingCubeTriangle(boundCubeTriangleMinX1, boundCubeTriangleMinX2, boundCubeTriangleMinX3, + boundCubeTriangleMaxX1, boundCubeTriangleMaxX2, boundCubeTriangleMaxX3); - //wenn dreieck "vergroesserten cube" nicht schneidet/beruehrt -> keine BC moeglich -> continue - if( !GbMeshTools3D::triBoxOverlap(boxCenter,halfBoxSize,triPoints) ) - { - counterTriBoxOverlap++; - continue; - } + std::vector<SPtr<Block3D>> triBlocks; + grid.lock()->getBlocksByCuboid(level, boundCubeTriangleMinX1, boundCubeTriangleMinX2, + boundCubeTriangleMinX3, boundCubeTriangleMaxX1, boundCubeTriangleMaxX2, + boundCubeTriangleMaxX3, triBlocks); ////////////////////////////////////////////////////////////////////////// - //Untersuchung der einzelnen nodes + // Schleife ueber bloecke des level, die das dreieck beinhalten ////////////////////////////////////////////////////////////////////////// - bool blockGotBCs = false; - - SPtr<ILBMKernel> kernel = block->getKernel(); - SPtr<BCArray3D> bcMatrix = kernel->getBCProcessor()->getBCArray(); - - int indexMinX1 = 0; - int indexMinX2 = 0; - int indexMinX3 = 0; - - int indexMaxX1 = (int)bcMatrix->getNX1(); - int indexMaxX2 = (int)bcMatrix->getNX2(); - int indexMaxX3 = (int)bcMatrix->getNX3(); - - std::set< std::vector<int> >& bcNodeIndices = this->bcNodeIndicesMap[block]; - std::set< std::vector<int> >& solidsFromOtherInteractors = tmpSolidNodesFromOtherInteractors[block]; - double q, internX1, internX2, internX3,distance; - - double& nodeDx1 = nodeDeltaToNeigh[level][D3Q27System::E]; - double& nodeDx2 = nodeDeltaToNeigh[level][D3Q27System::N]; - double& nodeDx3 = nodeDeltaToNeigh[level][D3Q27System::T]; - - //fuer OBB-Test - double qEinflussDelta = 1.1 * sqrt( nodeDx1*nodeDx1 + nodeDx2*nodeDx2 + nodeDx3*nodeDx3); - - for(int ix3=indexMinX3; ix3<indexMaxX3; ix3++) - { - internX3 = val<3>(coords)+nodeDx3*ix3-0.5*nodeDx3; - for(int ix2=indexMinX2; ix2<indexMaxX2; ix2++) - { - internX2 = val<2>(coords)+nodeDx2*ix2-0.5*nodeDx2; - for(int ix1=indexMinX1; ix1<indexMaxX1; ix1++) - { - -// int blx1 =block->getX1(); -// int blx2 = block->getX2(); -// int blx3 = block->getX3(); - -// if (blx1==0&&blx2==1&&blx3==0) -// { -// //if (ix2==39&&ix3==4) -// if (ix2==39&&ix3==4) -// { -// int seb=0; -// } -// } - //Problem: wenn voher der punkt durch eine andere geo not active gesetzt wird und - //dieser nun uebersprungen wird, dann hat man spaeter beim fuellalgorithmus luecken - //in der front und der block wird u.U. faelschlicher weise komplett solid markiert - //Lsg: positionen merken und erst Nach dem fuellarlgo wieder auf not active setzen :-) -// solidFromOtherInteractor = false; - if(bcMatrix->isSolid(ix1,ix2,ix3)) - { - if(this->reinitWithStoredQsFlag) - { - //solidFromOtherInteractor = true; //hier muss man weitermachen - //SG //oje - std::vector<int> p(3); - p[0]=ix1; p[1]=ix2; p[2]=ix3; - solidsFromOtherInteractors.insert( p ); - } - else - { - //SG //oje - std::vector<int> p(3); - p[0]=ix1; p[1]=ix2; p[2]=ix3; - solidsFromOtherInteractors.insert(p); - //SG continue; - //solidFromOtherInteractor = true; - } - } - - internX1 = val<1>(coords)+nodeDx1*ix1-0.5*nodeDx1; - - ////////////////////////////////////////////////////////////////////////// - //Punkt in AABB von Dreieck? - ////////////////////////////////////////////////////////////////////////// - //ehsan changedâ—˜ - bool pointIsOnBoundary = false; - if( !boundingCubeTriangle.isPointInGbObject3D(internX1, internX2, internX3,pointIsOnBoundary) ) - // if( !boundingCubeTriangle.isPointInGbObject3D(internX1, internX2, internX3) ) - { - counterAABBTriFace++; - continue; - } - - ////////////////////////////////////////////////////////////////////////// - // Halbebenentests - ////////////////////////////////////////////////////////////////////////// - distance = halfSpace.getDistance( internX1, internX2, internX3 ); - - //Punkt in Halbebene? (nein, wenn distance<0) - if(useHalfSpace && UbMath::less(distance, 0.0) )//== !halfSpace.ptInside(internX1,internX2,internX3) ) - { - counterHalfspace++; - continue; - } - - //BilligOBB-Test: wenn distance > qEinflussDelta -> kein q - if( UbMath::greater( fabs(distance), qEinflussDelta ) ) - { - counterBilligOBB++; - continue; - } - - ///////////////////////////////////////////////////////////////////////////// - //Raytracingfür diskrete Boltzmannrichtungen - ///////////////////////////////////////////////////////////////////////////// - gotQs = false; - bc = SPtr<BoundaryConditions>(); - - //RAYTRACING - diskrete LB-dir zu Dreick - //e1 = v1 - v0 - e1x1 = v2.x-v1.x; - e1x2 = v2.y-v1.y; - e1x3 = v2.z-v1.z; - - //e2 = v2 - v0 - e2x1 = v3.x-v1.x; - e2x2 = v3.y-v1.y; - e2x3 = v3.z-v1.z; - - //s = o - v0 - sx1 = internX1 - v1.x; - sx2 = internX2 - v1.y; - sx3 = internX3 - v1.z; - - for(int fdir=D3Q27System::FSTARTDIR; fdir<=D3Q27System::FENDDIR; fdir++) - { - //p = d x e2 - px1 = this->rayX2[fdir]*e2x3 - this->rayX3[fdir]*e2x2; - px2 = this->rayX3[fdir]*e2x1 - this->rayX1[fdir]*e2x3; - px3 = this->rayX1[fdir]*e2x2 - this->rayX2[fdir]*e2x1; - - //a = e1 dot p - a = e1x1*px1 + e1x2*px2 + e1x3*px3; - if(fabs(a)<1.E-10) continue; - f = 1.0/a; - - //u = f * ( s dot p) - u = f * ( sx1*px1 + sx2*px2 + sx3*px3 ); - if(u<-1.E-10 || u>1.0+1.E-10) continue; - - //q = s x e1 - qx1 = sx2*e1x3 - sx3*e1x2; - qx2 = sx3*e1x1 - sx1*e1x3; - qx3 = sx1*e1x2 - sx2*e1x1; - - //v = f*(e2 dot q) - v = f * (this->rayX1[fdir]*qx1 + this->rayX2[fdir]*qx2 + this->rayX3[fdir]*qx3); - if(v<-1.E-10 || (u+v)>1.0+1.E-10) continue; - - //t = f * (e2 dot q) - q = f * (e2x1*qx1 + e2x2*qx2 + e2x3*qx3); - q /= nodeDeltaToNeigh[level][fdir]; - - //gefundenes q auf gueltigkeit pruefen - if( UbMath::zero(q) ) - { - //neu (18.05.2010) - //es kann vorkommen, dass bei dünnwandigen geos punkte, die auf einem dreieck liegen, qs bekommen, die durch die geo - //durchgehen. diese punkte werden später jedoch nicht mehr auf solid getestet, da sie ja ne BC bekommen haben - //--> da mind ein q==0.0 für eines der dreiecke -> dort solid setzen - this->solidNodeIndicesMap[block].insert( UbTupleInt3(ix1,ix2,ix3) ); - bcMatrix->setSolid( ix1, ix2, ix3 ); - continue; - } - - if( UbMath::inClosedInterval(q, 1.0, 1.0) ) q = 1.0; - if( UbMath::greater(q, 0.0) && UbMath::lessEqual(q, 1.0) ) - { - //if( !solidFromOtherInteractor ) //--> Knoten schon solid-->BC setzen ueberfluessig - //SG changed to - //if( solidFromOtherInteractor ) //--> Knoten schon solid-->BC setzen ueberfluessig - { - //SG 26.08.2010 muss bereits hierhin, da das continue sonst den Knoten nicht als transNode fürs - //markiert - gotQs=blockGotBCs=true; - - bc = bcMatrix->getBC(ix1,ix2,ix3); - - //SG 26.08.2010 if(!bc && !bcMatrix->isSolid()) - if(!bc) - { - bc = SPtr<BoundaryConditions>(new BoundaryConditions);; - bcMatrix->setBC(ix1,ix2,ix3,bc); - } - else if( UbMath::less( bc->getQ(fdir), q ) ) //schon ein kuerzeres q voehanden? - { - //neu:: 18.05.2010 - //um falsche qs die evtl durch die "wand" gehen zu vermeiden - //q nur dann neu setzen, wenn neues q kleiner als vorhandenes! - //Zudem: insbesondere an ecken mit zwei BC geos ist nur das - //naehere gueltig - continue; - } - - bc->setBoundaryVelocityX1(vx1); - bc->setBoundaryVelocityX2(vx2); - bc->setBoundaryVelocityX3(vx3); - - for(int index=(int)this->bcAdapters.size()-1; index>=0; --index) - this->bcAdapters[index]->adaptBCForDirection(*this,bc,internX1,internX2,internX3,q,fdir); - - //SG 26.08.2010 gotQs=blockGotBCs=true; - } - //fuer beschleunigtes wiedereinlesen - if(this->reinitWithStoredQsFlag) - { - bcNodeIndicesAndQsMap[block][ UbTupleInt3(ix1, ix2, ix3) ].resize(D3Q27System::FENDDIR+1+3, -1.0f); - bcNodeIndicesAndQsMap[block][ UbTupleInt3(ix1, ix2, ix3) ][fdir ] = float(q); - bcNodeIndicesAndQsMap[block][ UbTupleInt3(ix1, ix2, ix3) ][D3Q27System::FENDDIR+1+0] = float(internX1); - bcNodeIndicesAndQsMap[block][ UbTupleInt3(ix1, ix2, ix3) ][D3Q27System::FENDDIR+1+1] = float(internX2); - bcNodeIndicesAndQsMap[block][ UbTupleInt3(ix1, ix2, ix3) ][D3Q27System::FENDDIR+1+2] = float(internX3); - } + for (std::size_t b = 0; b < triBlocks.size(); b++) { + SPtr<Block3D> block = triBlocks[b]; + + //////////////////////////////////////////////////////////////////////////// + //// Block Dreieck-/test + //////////////////////////////////////////////////////////////////////////// + UbTupleDouble3 coords = grid.lock()->getBlockWorldCoordinates(block); + UbTupleDouble3 deltas = grid.lock()->getBlockLengths(block); + + blockMinX[0] = (float)(val<1>(coords) - deltaMinX1[level]); + blockMinX[1] = (float)(val<2>(coords) - deltaMinX2[level]); + blockMinX[2] = (float)(val<3>(coords) - deltaMinX3[level]); + + blockMaxX[0] = (float)(val<1>(coords) + val<1>(deltas) + deltaMaxX1[level]); + blockMaxX[1] = (float)(val<2>(coords) + val<2>(deltas) + deltaMaxX2[level]); + blockMaxX[2] = (float)(val<3>(coords) + val<3>(deltas) + deltaMaxX3[level]); + + boxCenter[0] = (float)(0.5 * (blockMaxX[0] + blockMinX[0])); + boxCenter[1] = (float)(0.5 * (blockMaxX[1] + blockMinX[1])); + boxCenter[2] = (float)(0.5 * (blockMaxX[2] + blockMinX[2])); + + halfBoxSize[0] = (float)(0.5 * (blockMaxX[0] - blockMinX[0])); + halfBoxSize[1] = (float)(0.5 * (blockMaxX[1] - blockMinX[1])); + halfBoxSize[2] = (float)(0.5 * (blockMaxX[2] - blockMinX[2])); + + // wenn dreieck "vergroesserten cube" nicht schneidet/beruehrt -> keine BC moeglich -> continue + if (!GbMeshTools3D::triBoxOverlap(boxCenter, halfBoxSize, triPoints)) { + counterTriBoxOverlap++; + continue; + } + + ////////////////////////////////////////////////////////////////////////// + // Untersuchung der einzelnen nodes + ////////////////////////////////////////////////////////////////////////// + bool blockGotBCs = false; + + SPtr<ILBMKernel> kernel = block->getKernel(); + SPtr<BCArray3D> bcMatrix = kernel->getBCProcessor()->getBCArray(); + + int indexMinX1 = 0; + int indexMinX2 = 0; + int indexMinX3 = 0; + + int indexMaxX1 = (int)bcMatrix->getNX1(); + int indexMaxX2 = (int)bcMatrix->getNX2(); + int indexMaxX3 = (int)bcMatrix->getNX3(); + + std::set<std::vector<int>> &bcNodeIndices = this->bcNodeIndicesMap[block]; + std::set<std::vector<int>> &solidsFromOtherInteractors = tmpSolidNodesFromOtherInteractors[block]; + double q, internX1, internX2, internX3, distance; + + double &nodeDx1 = nodeDeltaToNeigh[level][D3Q27System::E]; + double &nodeDx2 = nodeDeltaToNeigh[level][D3Q27System::N]; + double &nodeDx3 = nodeDeltaToNeigh[level][D3Q27System::T]; + + // fuer OBB-Test + double qEinflussDelta = 1.1 * sqrt(nodeDx1 * nodeDx1 + nodeDx2 * nodeDx2 + nodeDx3 * nodeDx3); + + for (int ix3 = indexMinX3; ix3 < indexMaxX3; ix3++) { + internX3 = val<3>(coords) + nodeDx3 * ix3 - 0.5 * nodeDx3; + for (int ix2 = indexMinX2; ix2 < indexMaxX2; ix2++) { + internX2 = val<2>(coords) + nodeDx2 * ix2 - 0.5 * nodeDx2; + for (int ix1 = indexMinX1; ix1 < indexMaxX1; ix1++) { + + // int blx1 =block->getX1(); + // int blx2 = block->getX2(); + // int blx3 = block->getX3(); + + // if (blx1==0&&blx2==1&&blx3==0) + // { + // //if (ix2==39&&ix3==4) + // if (ix2==39&&ix3==4) + // { + // int seb=0; + // } + // } + // Problem: wenn voher der punkt durch eine andere geo not active gesetzt wird und + // dieser nun uebersprungen wird, dann hat man spaeter beim fuellalgorithmus luecken + // in der front und der block wird u.U. faelschlicher weise komplett solid markiert + // Lsg: positionen merken und erst Nach dem fuellarlgo wieder auf not active setzen :-) + // solidFromOtherInteractor = false; + if (bcMatrix->isSolid(ix1, ix2, ix3)) { + if (this->reinitWithStoredQsFlag) { + // solidFromOtherInteractor = true; //hier muss man weitermachen + // SG //oje + std::vector<int> p(3); + p[0] = ix1; + p[1] = ix2; + p[2] = ix3; + solidsFromOtherInteractors.insert(p); + } else { + // SG //oje + std::vector<int> p(3); + p[0] = ix1; + p[1] = ix2; + p[2] = ix3; + solidsFromOtherInteractors.insert(p); + // SG continue; + // solidFromOtherInteractor = true; + } + } + + internX1 = val<1>(coords) + nodeDx1 * ix1 - 0.5 * nodeDx1; + + ////////////////////////////////////////////////////////////////////////// + // Punkt in AABB von Dreieck? + ////////////////////////////////////////////////////////////////////////// + // ehsan changedâ—˜ + bool pointIsOnBoundary = false; + if (!boundingCubeTriangle.isPointInGbObject3D(internX1, internX2, internX3, + pointIsOnBoundary)) + // if( !boundingCubeTriangle.isPointInGbObject3D(internX1, internX2, internX3) ) + { + counterAABBTriFace++; + continue; + } + + ////////////////////////////////////////////////////////////////////////// + // Halbebenentests + ////////////////////////////////////////////////////////////////////////// + distance = halfSpace.getDistance(internX1, internX2, internX3); + + // Punkt in Halbebene? (nein, wenn distance<0) + if (useHalfSpace && + UbMath::less(distance, 0.0)) //== !halfSpace.ptInside(internX1,internX2,internX3) ) + { + counterHalfspace++; + continue; + } + + // BilligOBB-Test: wenn distance > qEinflussDelta -> kein q + if (UbMath::greater(fabs(distance), qEinflussDelta)) { + counterBilligOBB++; + continue; + } + + ///////////////////////////////////////////////////////////////////////////// + // Raytracingfür diskrete Boltzmannrichtungen + ///////////////////////////////////////////////////////////////////////////// + gotQs = false; + bc = SPtr<BoundaryConditions>(); + + // RAYTRACING - diskrete LB-dir zu Dreick + // e1 = v1 - v0 + e1x1 = v2.x - v1.x; + e1x2 = v2.y - v1.y; + e1x3 = v2.z - v1.z; + + // e2 = v2 - v0 + e2x1 = v3.x - v1.x; + e2x2 = v3.y - v1.y; + e2x3 = v3.z - v1.z; + + // s = o - v0 + sx1 = internX1 - v1.x; + sx2 = internX2 - v1.y; + sx3 = internX3 - v1.z; + + for (int fdir = D3Q27System::FSTARTDIR; fdir <= D3Q27System::FENDDIR; fdir++) { + // p = d x e2 + px1 = this->rayX2[fdir] * e2x3 - this->rayX3[fdir] * e2x2; + px2 = this->rayX3[fdir] * e2x1 - this->rayX1[fdir] * e2x3; + px3 = this->rayX1[fdir] * e2x2 - this->rayX2[fdir] * e2x1; + + // a = e1 dot p + a = e1x1 * px1 + e1x2 * px2 + e1x3 * px3; + if (fabs(a) < 1.E-10) + continue; + f = 1.0 / a; + + // u = f * ( s dot p) + u = f * (sx1 * px1 + sx2 * px2 + sx3 * px3); + if (u < -1.E-10 || u > 1.0 + 1.E-10) + continue; + + // q = s x e1 + qx1 = sx2 * e1x3 - sx3 * e1x2; + qx2 = sx3 * e1x1 - sx1 * e1x3; + qx3 = sx1 * e1x2 - sx2 * e1x1; + + // v = f*(e2 dot q) + v = f * (this->rayX1[fdir] * qx1 + this->rayX2[fdir] * qx2 + this->rayX3[fdir] * qx3); + if (v < -1.E-10 || (u + v) > 1.0 + 1.E-10) + continue; + + // t = f * (e2 dot q) + q = f * (e2x1 * qx1 + e2x2 * qx2 + e2x3 * qx3); + q /= nodeDeltaToNeigh[level][fdir]; + + // gefundenes q auf gueltigkeit pruefen + if (UbMath::zero(q)) { + // neu (18.05.2010) + // es kann vorkommen, dass bei dünnwandigen geos punkte, die auf einem dreieck + // liegen, qs bekommen, die durch die geo durchgehen. diese punkte werden später + // jedoch nicht mehr auf solid getestet, da sie ja ne BC bekommen haben + //--> da mind ein q==0.0 für eines der dreiecke -> dort solid setzen + this->solidNodeIndicesMap[block].insert(UbTupleInt3(ix1, ix2, ix3)); + bcMatrix->setSolid(ix1, ix2, ix3); + continue; + } + + if (UbMath::inClosedInterval(q, 1.0, 1.0)) + q = 1.0; + if (UbMath::greater(q, 0.0) && UbMath::lessEqual(q, 1.0)) { + // if( !solidFromOtherInteractor ) //--> Knoten schon solid-->BC setzen + // ueberfluessig SG changed to if( solidFromOtherInteractor ) //--> Knoten schon + // solid-->BC setzen ueberfluessig + { + // SG 26.08.2010 muss bereits hierhin, da das continue sonst den Knoten nicht + // als transNode fürs markiert + gotQs = blockGotBCs = true; + + bc = bcMatrix->getBC(ix1, ix2, ix3); + + // SG 26.08.2010 if(!bc && !bcMatrix->isSolid()) + if (!bc) { + bc = SPtr<BoundaryConditions>(new BoundaryConditions); + ; + bcMatrix->setBC(ix1, ix2, ix3, bc); + } else if (UbMath::less(bc->getQ(fdir), q)) // schon ein kuerzeres q voehanden? + { + // neu:: 18.05.2010 + // um falsche qs die evtl durch die "wand" gehen zu vermeiden + // q nur dann neu setzen, wenn neues q kleiner als vorhandenes! + // Zudem: insbesondere an ecken mit zwei BC geos ist nur das + // naehere gueltig + continue; + } + + bc->setBoundaryVelocityX1(vx1); + bc->setBoundaryVelocityX2(vx2); + bc->setBoundaryVelocityX3(vx3); + + for (int index = (int)this->bcAdapters.size() - 1; index >= 0; --index) + this->bcAdapters[index]->adaptBCForDirection(*this, bc, internX1, internX2, + internX3, q, fdir); + + // SG 26.08.2010 gotQs=blockGotBCs=true; + } + // fuer beschleunigtes wiedereinlesen + if (this->reinitWithStoredQsFlag) { + bcNodeIndicesAndQsMap[block][UbTupleInt3(ix1, ix2, ix3)].resize( + D3Q27System::FENDDIR + 1 + 3, -1.0f); + bcNodeIndicesAndQsMap[block][UbTupleInt3(ix1, ix2, ix3)][fdir] = float(q); + bcNodeIndicesAndQsMap[block][UbTupleInt3(ix1, ix2, ix3)] + [D3Q27System::FENDDIR + 1 + 0] = float(internX1); + bcNodeIndicesAndQsMap[block][UbTupleInt3(ix1, ix2, ix3)] + [D3Q27System::FENDDIR + 1 + 1] = float(internX2); + bcNodeIndicesAndQsMap[block][UbTupleInt3(ix1, ix2, ix3)] + [D3Q27System::FENDDIR + 1 + 2] = float(internX3); + } + } + } + + if (gotQs) { + std::vector<int> p(3); + p[0] = ix1; + p[1] = ix2; + p[2] = ix3; + bcNodeIndices.insert(p); + + for (int index = (int)this->bcAdapters.size() - 1; index >= 0; --index) + this->bcAdapters[index]->adaptBC(*this, bc, internX1, internX2, internX3); + } } - } - - if(gotQs) - { - std::vector<int> p(3); - p[0]=ix1; p[1]=ix2; p[2]=ix3; - bcNodeIndices.insert(p); - - for(int index=(int)this->bcAdapters.size()-1; index>=0; --index) - this->bcAdapters[index]->adaptBC(*this,bc,internX1,internX2,internX3); - } - } - } + } + } + // Block wird für scanline-check "anmelden", dieser wird dann spaeter zu "transBlocks" hinzugefuegt + if (blockGotBCs) { + blocksForSolidCheck[block] = ScanLine; + } + // bvd->getTimer().stop(); } - //Block wird für scanline-check "anmelden", dieser wird dann spaeter zu "transBlocks" hinzugefuegt - if(blockGotBCs) - { - blocksForSolidCheck[block] = ScanLine; - } - // bvd->getTimer().stop(); - } - //dynamische Punkte des GbCuboids muessen leider per "Hand" geloescht werden :-( - boundingCubeTriangle.finalize(); - } - } - setQTimer.stop(); - - UBLOG(logDEBUG1," - setQs for "/*<< this->getName()*/ << " - " <<(int)triangles.size()<<" triangles: 100% done in "<<setQTimer.getTotalTime()<<"sec"); - UBLOG(logDEBUG1," * rejected blocks with tribox overlap test : " << counterTriBoxOverlap); - UBLOG(logDEBUG1," * rejected nodes with AABB test : " << counterAABBTriFace); - UBLOG(logDEBUG1," * rejected nodes with halfspace test : " << counterHalfspace); - UBLOG(logDEBUG1," * rejected nodes with OBB test : " << counterBilligOBB); - - typedef std::map<SPtr<Block3D>,SolidCheckMethod>::iterator BlockSolidCheckMethodIterator; - - ////////////////////////////////////////////////////////////////////////// - // SOLID checks - ////////////////////////////////////////////////////////////////////////// - if( regardPIOTest ) - { - int pointInObjectCounter = 0; - int scanlineCounter = 0; -// int counter = 0; - - //sollte die matrix groesse zu gross sein und der rekursive floodFill mehr speicher - //benoetigen als der Stack hergibt -> keinen floodFill verwenden! - void (D3Q27TriFaceMeshInteractor::*gridFill)(CbArray3D<FLAGS>&, const short&, const short&, const short&, const FLAGS&) = NULL; - /*if(blocknx1*blocknx2*blocknx3 < 200000 ) gridFill = &D3Q27TriFaceMeshInteractor::recursiveGridFill;*/ - /*else */ gridFill = &D3Q27TriFaceMeshInteractor::iterativeGridFill; - - UBLOG(logDEBUG1," - setSolids for "<< blocksForSolidCheck.size() << " blocks"); - - UbTimer scanLineTimer; - UbTimer solidTimer; - solidTimer.start(); - - for(BlockSolidCheckMethodIterator pos=blocksForSolidCheck.begin(); pos!=blocksForSolidCheck.end(); ++pos) - { - SPtr<Block3D> const& block = pos->first; - int level = block->getLevel(); - - UbTupleDouble3 coords = grid.lock()->getBlockWorldCoordinates(block); - - //Bloecke, die keinerlei Verschneidung mit Dreicken bzw. deren BoundCubes hatten - //hier: durch inside/outside Tests EINES knotens gilt fuer ALLE Knoten des blockes - if( pos->second == PointInObject ) - { - pointInObjectCounter++; - if(mesh->isPointInGbObject3D(val<1>(coords),val<2>(coords),val<3>(coords)) ) - { - //block->setActive(false); - //this->solidBlocks.push_back(block); + // dynamische Punkte des GbCuboids muessen leider per "Hand" geloescht werden :-( + boundingCubeTriangle.finalize(); + } + } + setQTimer.stop(); + + UBLOG(logDEBUG1, " - setQs for " /*<< this->getName()*/ << " - " << (int)triangles.size() + << " triangles: 100% done in " << setQTimer.getTotalTime() + << "sec"); + UBLOG(logDEBUG1, " * rejected blocks with tribox overlap test : " << counterTriBoxOverlap); + UBLOG(logDEBUG1, " * rejected nodes with AABB test : " << counterAABBTriFace); + UBLOG(logDEBUG1, " * rejected nodes with halfspace test : " << counterHalfspace); + UBLOG(logDEBUG1, " * rejected nodes with OBB test : " << counterBilligOBB); + + typedef std::map<SPtr<Block3D>, SolidCheckMethod>::iterator BlockSolidCheckMethodIterator; + + ////////////////////////////////////////////////////////////////////////// + // SOLID checks + ////////////////////////////////////////////////////////////////////////// + if (regardPIOTest) { + int pointInObjectCounter = 0; + int scanlineCounter = 0; + // int counter = 0; + + // sollte die matrix groesse zu gross sein und der rekursive floodFill mehr speicher + // benoetigen als der Stack hergibt -> keinen floodFill verwenden! + void (D3Q27TriFaceMeshInteractor::*gridFill)(CbArray3D<FLAGS> &, const short &, const short &, const short &, + const FLAGS &) = NULL; + /*if(blocknx1*blocknx2*blocknx3 < 200000 ) gridFill = &D3Q27TriFaceMeshInteractor::recursiveGridFill;*/ + /*else */ gridFill = &D3Q27TriFaceMeshInteractor::iterativeGridFill; + + UBLOG(logDEBUG1, " - setSolids for " << blocksForSolidCheck.size() << " blocks"); + + UbTimer scanLineTimer; + UbTimer solidTimer; + solidTimer.start(); + + for (BlockSolidCheckMethodIterator pos = blocksForSolidCheck.begin(); pos != blocksForSolidCheck.end(); ++pos) { + SPtr<Block3D> const &block = pos->first; + int level = block->getLevel(); + + UbTupleDouble3 coords = grid.lock()->getBlockWorldCoordinates(block); + + // Bloecke, die keinerlei Verschneidung mit Dreicken bzw. deren BoundCubes hatten + // hier: durch inside/outside Tests EINES knotens gilt fuer ALLE Knoten des blockes + if (pos->second == PointInObject) { + pointInObjectCounter++; + if (mesh->isPointInGbObject3D(val<1>(coords), val<2>(coords), val<3>(coords))) { + // block->setActive(false); + // this->solidBlocks.push_back(block); + } } - } - //Bloecke, die Verschneidung mit Dreicken bzw. deren BoundCubes hatten - //scanline algortihmus. dieser berücksichtigt durch weitere tests, dass innerhalb evtl schon andere - //geos bcs gesetzt haben. es werden ausschließelich solids gesetzt (also keine FLUIDS oder neuen BCs) - else if( pos->second == ScanLine ) - { - scanlineCounter++; - scanLineTimer.start(); - - SPtr<ILBMKernel> kernel = block->getKernel(); - if(!kernel) throw UbException(UB_EXARGS,"na sowas kein kernel bzw. kernel=NULL (2)"); - SPtr<BCArray3D> bcMatrix = kernel->getBCProcessor()->getBCArray(); - - // bvd->getTimer().start(); -// int indexMinX1 = 0; -// int indexMinX2 = 0; -// int indexMinX3 = 0; - int indexMaxX1 = (int)bcMatrix->getNX1(); - int indexMaxX2 = (int)bcMatrix->getNX2(); - int indexMaxX3 = (int)bcMatrix->getNX3(); - - //quick and dirty - blocknx1 = indexMaxX1; - blocknx2 = indexMaxX2; - blocknx3 = indexMaxX3; - - std::set< UbTupleInt3 >& solidNodeIndices = this->solidNodeIndicesMap[block]; - - float nodeDeltaX1 = (float)nodeDeltaToNeigh[level][D3Q27System::E]; - float nodeDeltaX2 = (float)nodeDeltaToNeigh[level][D3Q27System::N]; - float nodeDeltaX3 = (float)nodeDeltaToNeigh[level][D3Q27System::T]; - - //flagfield matrix initialisieren - CbArray3D<FLAGS> flagField(blocknx1,blocknx2,blocknx3,UNDEF_FLAG); - - //hier gesetzte bcs markieren - std::set< std::vector<int> >& transNodeIndices = this->bcNodeIndicesMap[block]; - std::set< std::vector<int> >::iterator setPos; - for(setPos=transNodeIndices.begin(); setPos!=transNodeIndices.end(); ++setPos) - flagField( (*setPos)[0], (*setPos)[1], (*setPos)[2] ) = BC_FLAG; - - //solids die bereits durch andere interaktoren gesetzt wurden (wurden oben gespeichert) - //ist EMPTY bei reinitWithStoredQsFlag == true - //SG 28.08.2010 std::set< UbTupleInt3 >& tmpSolidNodeIndices = tmpSolidNodesFromOtherInteractors[block]; - //SG 28.08.2010 if(reinitWithStoredQsFlag && !tmpSolidNodeIndices.empty() ) throw UbException(UB_EXARGS, "tmpSolidNodeIndices darf bei reinitWithStoredQsFlag==true keine Knoten enthalten"); - //SG 28.08.2010 for(setPos=tmpSolidNodeIndices.begin(); setPos!=tmpSolidNodeIndices.end(); ++setPos) - //SG 28.08.2010 flagField( val<1>(*setPos), val<2>(*setPos), val<3>(*setPos) ) = OLDSOLID_FLAG; - - //flagfield matrix belegen - for(int bx3=0; bx3<blocknx3; ++bx3) - { - for(int bx2=0; bx2<blocknx2; ++bx2) - { - for(int bx1=0; bx1<blocknx1; ++bx1) - { - -// if (bx2==9&&bx3==29) -// { -// int ride=0; -// } - if( flagField(bx1,bx2,bx3)==UNDEF_FLAG ) - { - if( mesh->isPointInGbObject3D( val<1>(coords) + bx1*nodeDeltaX1 - 0.5*nodeDeltaX1 - , val<2>(coords) + bx2*nodeDeltaX2 - 0.5*nodeDeltaX2 - , val<3>(coords) + bx3*nodeDeltaX3 - 0.5*nodeDeltaX3) ) - { - (this->*gridFill)(flagField,bx1,bx2,bx3,SOLID_FLAG); - } - else - { - (this->*gridFill)(flagField,bx1,bx2,bx3,FLUID_FLAG); + // Bloecke, die Verschneidung mit Dreicken bzw. deren BoundCubes hatten + // scanline algortihmus. dieser berücksichtigt durch weitere tests, dass innerhalb evtl schon andere + // geos bcs gesetzt haben. es werden ausschließelich solids gesetzt (also keine FLUIDS oder neuen BCs) + else if (pos->second == ScanLine) { + scanlineCounter++; + scanLineTimer.start(); + + SPtr<ILBMKernel> kernel = block->getKernel(); + if (!kernel) + throw UbException(UB_EXARGS, "na sowas kein kernel bzw. kernel=NULL (2)"); + SPtr<BCArray3D> bcMatrix = kernel->getBCProcessor()->getBCArray(); + + // bvd->getTimer().start(); + // int indexMinX1 = 0; + // int indexMinX2 = 0; + // int indexMinX3 = 0; + int indexMaxX1 = (int)bcMatrix->getNX1(); + int indexMaxX2 = (int)bcMatrix->getNX2(); + int indexMaxX3 = (int)bcMatrix->getNX3(); + + // quick and dirty + blocknx1 = indexMaxX1; + blocknx2 = indexMaxX2; + blocknx3 = indexMaxX3; + + std::set<UbTupleInt3> &solidNodeIndices = this->solidNodeIndicesMap[block]; + + float nodeDeltaX1 = (float)nodeDeltaToNeigh[level][D3Q27System::E]; + float nodeDeltaX2 = (float)nodeDeltaToNeigh[level][D3Q27System::N]; + float nodeDeltaX3 = (float)nodeDeltaToNeigh[level][D3Q27System::T]; + + // flagfield matrix initialisieren + CbArray3D<FLAGS> flagField(blocknx1, blocknx2, blocknx3, UNDEF_FLAG); + + // hier gesetzte bcs markieren + std::set<std::vector<int>> &transNodeIndices = this->bcNodeIndicesMap[block]; + std::set<std::vector<int>>::iterator setPos; + for (setPos = transNodeIndices.begin(); setPos != transNodeIndices.end(); ++setPos) + flagField((*setPos)[0], (*setPos)[1], (*setPos)[2]) = BC_FLAG; + + // solids die bereits durch andere interaktoren gesetzt wurden (wurden oben gespeichert) + // ist EMPTY bei reinitWithStoredQsFlag == true + // SG 28.08.2010 std::set< UbTupleInt3 >& tmpSolidNodeIndices = + // tmpSolidNodesFromOtherInteractors[block]; SG 28.08.2010 if(reinitWithStoredQsFlag && + // !tmpSolidNodeIndices.empty() ) throw UbException(UB_EXARGS, "tmpSolidNodeIndices darf bei + // reinitWithStoredQsFlag==true keine Knoten enthalten"); SG 28.08.2010 + // for(setPos=tmpSolidNodeIndices.begin(); setPos!=tmpSolidNodeIndices.end(); ++setPos) SG 28.08.2010 + // flagField( val<1>(*setPos), val<2>(*setPos), val<3>(*setPos) ) = OLDSOLID_FLAG; + + // flagfield matrix belegen + for (int bx3 = 0; bx3 < blocknx3; ++bx3) { + for (int bx2 = 0; bx2 < blocknx2; ++bx2) { + for (int bx1 = 0; bx1 < blocknx1; ++bx1) { + + // if (bx2==9&&bx3==29) + // { + // int ride=0; + // } + if (flagField(bx1, bx2, bx3) == UNDEF_FLAG) { + if (mesh->isPointInGbObject3D(val<1>(coords) + bx1 * nodeDeltaX1 - 0.5 * nodeDeltaX1, + val<2>(coords) + bx2 * nodeDeltaX2 - 0.5 * nodeDeltaX2, + val<3>(coords) + bx3 * nodeDeltaX3 - 0.5 * nodeDeltaX3)) { + (this->*gridFill)(flagField, bx1, bx2, bx3, SOLID_FLAG); + } else { + (this->*gridFill)(flagField, bx1, bx2, bx3, FLUID_FLAG); + } + } + + if (flagField(bx1, bx2, bx3) == SOLID_FLAG) { + // hier ist noch das Problem, das "alle" solid in die solidNodeIndices kommen + // evtl. Abhilfe durch einführen eines anderen Flags bei tmpSolidNodeIndices .. + solidNodeIndices.insert(UbTupleInt3(bx1, bx2, bx3)); + bcMatrix->setSolid(bx1, bx2, bx3); + } + // SG 28.08.2010 else if( flagField(bx1,bx2,bx3)==OLDSOLID_FLAG ) + // SG 28.08.2010 { + // SG 28.08.2010 bcMatrix->setSolid(bx1,bx2,bx3); + // SG 28.08.2010 } } - } - - if( flagField(bx1,bx2,bx3)==SOLID_FLAG ) - { - //hier ist noch das Problem, das "alle" solid in die solidNodeIndices kommen - //evtl. Abhilfe durch einführen eines anderen Flags bei tmpSolidNodeIndices .. - solidNodeIndices.insert(UbTupleInt3(bx1,bx2,bx3)); - bcMatrix->setSolid(bx1,bx2,bx3); - } - //SG 28.08.2010 else if( flagField(bx1,bx2,bx3)==OLDSOLID_FLAG ) - //SG 28.08.2010 { - //SG 28.08.2010 bcMatrix->setSolid(bx1,bx2,bx3); - //SG 28.08.2010 } - } - } - } - - //SG 28.08.2010 halt danach setzen, damit die BCs die fälschlicherweise gesetzt wurden korrigiert werden - std::set< std::vector<int> >& tmpSolidNodeIndices = tmpSolidNodesFromOtherInteractors[block]; - for(setPos=tmpSolidNodeIndices.begin(); setPos!=tmpSolidNodeIndices.end(); ++setPos) - bcMatrix->setSolid((*setPos)[0], (*setPos)[1], (*setPos)[2] ); - - //block hat in initInteractor mind eine BC erhalten -> transBlock - this->bcBlocks.push_back(block); - scanLineTimer.stop(); - - // bvd->getTimer().stop(); - } - else throw UbException(UB_EXARGS,"unknown option for in object test"); - } - - solidTimer.stop(); - - UBLOG(logDEBUG1, " - setSolids for "<<blocksForSolidCheck.size()<<" blocks: 100% done in "<<solidTimer.getTotalTime()<<"s"); - UBLOG(logDEBUG1, " * pointInObject for "<<pointInObjectCounter<<" blocks in "<<solidTimer.getTotalTime()-scanLineTimer.getTotalTime()<<"s"); - UBLOG(logDEBUG1, " * flood fill for "<<scanlineCounter <<" blocks in "<<scanLineTimer.getTotalTime()<<" secs"); - UBLOG(logDEBUG1, "LBMTriFaceMeshInteractor::initInteractor for \""<<mesh->getName()<<"\" done in "<<setQTimer.getTotalTime()+solidTimer.getTotalTime()<<"s"); - } - - //calcForces arbeitet nicht korrekt, wenn Geo mit Bloecken - //unterschiedlicher Leveltiefe diskretisiert -> exception - //abfrage steht hier, weil es theoretisch sein kann, dass bei parallelen rechnungen - //genau der block mit dem anderen level auf einem anderen prozess liegt... - //Update: es kann u.U. passieren, dass Blöcke in der Liste nicht aktiv sin - //(falls diese z.B. duch andere Interactoren solid gesetzt wurden) - //diese werden nicht berücksichtigt (auch nicht beid er kraftauswertung später) - //if( this->isRelevantForForces() ) - //{ - // int level = -1; - // for( std::vector<SPtr<Block3D>>::const_iterator pos = this->transBlocks.begin(); pos!=this->transBlocks.end(); ++pos) - // if( (*pos)->isActive() ) - // { - // level = (*pos)->getLevel(); - // break; - // } - - // bool check = false; - // for( std::vector<SPtr<Block3D>>::const_iterator pos = this->transBlocks.begin(); pos!=this->transBlocks.end(); ++pos) - // if( (*pos)->isActive() && (*pos)->getLevel()!=level) - // { - // (*pos)->setRank(1000); - // check = true; - // UbTupleDouble3 coords = grid.lock()->getBlockWorldCoordinates((*pos)); - // std::cout<<(*pos)->getLevel()<<","<<(*pos)->getX1()<<","<<(*pos)->getX2()<<","<<(*pos)->getX3()<<std::endl; - // std::cout<<std::setprecision(15)<<val<1>(coords)<<","<<val<2>(coords)<<","<<val<3>(coords)<<std::endl<<std::endl; - - // } - // if(check) - // { - // //this->grid.lock()->writeBlocks(UbStaticPathMap::getPath(UbStaticPathMap::GLOBAL)+"/error_grid",0, WbWriterVtkXmlASCII::getInstance(), false); - - // throw UbException(UB_EXARGS,"interactor is relevant for forces," - // +(std::string)" but has transblocks with different levels (wrote error_grid)" - // +(std::string)" -> not supportet by LBMInteractor::getForces()" - // +(std::string)" -> increase refineWidth"); - - // } - //} + } + } + + // SG 28.08.2010 halt danach setzen, damit die BCs die fälschlicherweise gesetzt wurden korrigiert + // werden + std::set<std::vector<int>> &tmpSolidNodeIndices = tmpSolidNodesFromOtherInteractors[block]; + for (setPos = tmpSolidNodeIndices.begin(); setPos != tmpSolidNodeIndices.end(); ++setPos) + bcMatrix->setSolid((*setPos)[0], (*setPos)[1], (*setPos)[2]); + + // block hat in initInteractor mind eine BC erhalten -> transBlock + this->bcBlocks.push_back(block); + scanLineTimer.stop(); + + // bvd->getTimer().stop(); + } else + throw UbException(UB_EXARGS, "unknown option for in object test"); + } + + solidTimer.stop(); + + UBLOG(logDEBUG1, " - setSolids for " << blocksForSolidCheck.size() << " blocks: 100% done in " + << solidTimer.getTotalTime() << "s"); + UBLOG(logDEBUG1, " * pointInObject for " << pointInObjectCounter << " blocks in " + << solidTimer.getTotalTime() - scanLineTimer.getTotalTime() + << "s"); + UBLOG(logDEBUG1, " * flood fill for " << scanlineCounter << " blocks in " + << scanLineTimer.getTotalTime() << " secs"); + UBLOG(logDEBUG1, "LBMTriFaceMeshInteractor::initInteractor for \"" + << mesh->getName() << "\" done in " << setQTimer.getTotalTime() + solidTimer.getTotalTime() + << "s"); + } + + // calcForces arbeitet nicht korrekt, wenn Geo mit Bloecken + // unterschiedlicher Leveltiefe diskretisiert -> exception + // abfrage steht hier, weil es theoretisch sein kann, dass bei parallelen rechnungen + // genau der block mit dem anderen level auf einem anderen prozess liegt... + // Update: es kann u.U. passieren, dass Blöcke in der Liste nicht aktiv sin + //(falls diese z.B. duch andere Interactoren solid gesetzt wurden) + // diese werden nicht berücksichtigt (auch nicht beid er kraftauswertung später) + // if( this->isRelevantForForces() ) + //{ + // int level = -1; + // for( std::vector<SPtr<Block3D>>::const_iterator pos = this->transBlocks.begin(); pos!=this->transBlocks.end(); + // ++pos) + // if( (*pos)->isActive() ) + // { + // level = (*pos)->getLevel(); + // break; + // } + + // bool check = false; + // for( std::vector<SPtr<Block3D>>::const_iterator pos = this->transBlocks.begin(); + // pos!=this->transBlocks.end(); ++pos) + // if( (*pos)->isActive() && (*pos)->getLevel()!=level) + // { + // (*pos)->setRank(1000); + // check = true; + // UbTupleDouble3 coords = grid.lock()->getBlockWorldCoordinates((*pos)); + // std::cout<<(*pos)->getLevel()<<","<<(*pos)->getX1()<<","<<(*pos)->getX2()<<","<<(*pos)->getX3()<<std::endl; + // std::cout<<std::setprecision(15)<<val<1>(coords)<<","<<val<2>(coords)<<","<<val<3>(coords)<<std::endl<<std::endl; + + // } + // if(check) + // { + // //this->grid.lock()->writeBlocks(UbStaticPathMap::getPath(UbStaticPathMap::GLOBAL)+"/error_grid",0, + // WbWriterVtkXmlASCII::getInstance(), false); + + // throw UbException(UB_EXARGS,"interactor is relevant for forces," + // +(std::string)" but has transblocks with different levels (wrote error_grid)" + // +(std::string)" -> not supportet by LBMInteractor::getForces()" + // +(std::string)" -> increase refineWidth"); + + // } + //} } ////////////////////////////////////////////////////////////////////////// void D3Q27TriFaceMeshInteractor::refineBlockGridToLevel(int level, double startDistance, double stopDistance) { - UBLOG(logDEBUG1, "D3Q27TriFaceMeshInteractor::refineBlockGridToLevel - start"); - - //ToDo: evtl checken, ob man noch einen HalbraumCheck für StopDistance einbaut - // oder ob man schneller ist, wenn man gar keinen halbraum test macht... - if(!grid.lock()) - throw UbException(UB_EXARGS,"Grid isn't exist!"); - if( UbMath::greater(startDistance,0.0) ) - throw UbException(UB_EXARGS,"startDistance>0.0 not supported by this interactor"); - if( UbMath::less(stopDistance,0.0) ) - throw UbException(UB_EXARGS,"stopDistance<0.0 not supported by this interactor"); - - SPtr<Grid3D> bgrid = this->grid.lock(); - GbTriFaceMesh3D& mesh = dynamic_cast<GbTriFaceMesh3D&>(*this->geoObject3D.get()); - - int coarsestLevel = bgrid->getCoarsestInitializedLevel(); - - std::vector<GbTriFaceMesh3D::TriFace>& triangles = *mesh.getTriangles(); - std::vector<GbTriFaceMesh3D::Vertex>& nodes = *mesh.getNodes(); - - double minX1,minX2,minX3,maxX1,maxX2,maxX3; - float blockMinX[3],blockMaxX[3],boxCenter[3],halfBoxSize[3]; - float triPoints[3][3]; - - size_t nofTriangles = (int)triangles.size(); - -//#pragma omp parallel -//#pragma omp for - for(size_t i=0; i<nofTriangles; i++) - //for(int i=0; i<nofTriangles; i++) - { -//#pragma omp master - //{ - // printf_s("num_threads=%d\n", omp_get_num_threads( )); - //} - - - GbTriFaceMesh3D::TriFace& triangle = triangles[i]; - - GbTriFaceMesh3D::Vertex& v1 = nodes[triangle.v1]; - GbTriFaceMesh3D::Vertex& v2 = nodes[triangle.v2]; - GbTriFaceMesh3D::Vertex& v3 = nodes[triangle.v3]; - - //dreick muss normal besitzen! - assert( !UbMath::zero(triangle.nx) || !UbMath::zero(triangle.ny) || !UbMath::zero(triangle.nz) ); - //Normale muss normiert sein! - assert( (fabs(std::sqrt( triangle.nx*triangle.nx + triangle.ny*triangle.ny + triangle.nz*triangle.nz ))-1.0f)<1.0E-6); - - //Halfspace um startDistance entgegen normale verscheiebn, ansonsten werden spaeter - //zu testende bloecke auf der dreicksrueckseite nicht getestet!!! - GbHalfSpace3D halfSpace( v1.x+startDistance*triangle.nx, v1.y+startDistance*triangle.ny, v1.z+startDistance*triangle.nz - , v2.x+startDistance*triangle.nx, v2.y+startDistance*triangle.ny, v2.z+startDistance*triangle.nz - , v3.x+startDistance*triangle.nx, v3.y+startDistance*triangle.ny, v3.z+startDistance*triangle.nz ); - - //Boundingbox um massgebliches dx erweitern -> zur Bestimmung der zu testenden Bloecke - if( triangle.nx>1.0E-8 ) { minX1 = triangle.getMinX(nodes)+1.05*triangle.nx*startDistance; - maxX1 = triangle.getMaxX(nodes)+1.05*triangle.nx*stopDistance; } - else { minX1 = triangle.getMinX(nodes)+1.05*triangle.nx*stopDistance; - maxX1 = triangle.getMaxX(nodes)+1.05*triangle.nx*startDistance; } - - if( triangle.ny>1.0E-8 ) { minX2 = triangle.getMinY(nodes)+1.05*triangle.ny*startDistance; - maxX2 = triangle.getMaxY(nodes)+1.05*triangle.ny*stopDistance; } - else { minX2 = triangle.getMinY(nodes)+1.05*triangle.ny*stopDistance; - maxX2 = triangle.getMaxY(nodes)+1.05*triangle.ny*startDistance; } - - if( triangle.nz>1.0E-8 ) { minX3 = triangle.getMinZ(nodes)+1.05*triangle.nz*startDistance; - maxX3 = triangle.getMaxZ(nodes)+1.05*triangle.nz*stopDistance; } - else { minX3 = triangle.getMinZ(nodes)+1.05*triangle.nz*stopDistance; - maxX3 = triangle.getMaxZ(nodes)+1.05*triangle.nz*startDistance; } - - - int flag = 0; - //Levelweise alle Bloecke holen, die erweiterte BB schneiden - //und bearbeiten - for(int l=coarsestLevel; l<level; l++) - { - std::vector<SPtr<Block3D>> consideredBlocks; - bgrid->getBlocksByCuboid(l,minX1, minX2, minX3, maxX1, maxX2, maxX3, consideredBlocks); - double x1a,x2a,x3a,x1b,x2b,x3b; - - for(size_t b=0; b<consideredBlocks.size(); b++) - { - SPtr<Block3D> block = consideredBlocks[b]; - if(block->getLevel()>=level) continue; - - //start coordinaten des blocks ermitteln - UbTupleDouble3 coords = bgrid->getBlockWorldCoordinates(block); - UbTupleDouble3 deltas = bgrid->getBlockLengths(block); - - //Check, ob block komplett im Halbraum - x1a = val<1>(coords); x1b = val<1>(coords)+val<1>(deltas); - x2a = val<2>(coords); x2b = val<2>(coords)+val<2>(deltas); - x3a = val<3>(coords); x3b = val<3>(coords)+val<3>(deltas); - - flag = 0; - if( !halfSpace.ptInside(x1a,x2a,x3a) ) flag |= (1<<0); //1 - if( !halfSpace.ptInside(x1b,x2a,x3a) ) flag |= (1<<1); //2 - if( !halfSpace.ptInside(x1b,x2b,x3a) ) flag |= (1<<2); //4 - if( !halfSpace.ptInside(x1a,x2b,x3a) ) flag |= (1<<3); //8 - if( !halfSpace.ptInside(x1a,x2a,x3b) ) flag |= (1<<4); //16 - if( !halfSpace.ptInside(x1b,x2a,x3b) ) flag |= (1<<5); //32 - if( !halfSpace.ptInside(x1b,x2b,x3b) ) flag |= (1<<6); //64 - if( !halfSpace.ptInside(x1a,x2b,x3b) ) flag |= (1<<7); //128 - - - if( true && flag!=255 ) - { - //blockseite ermitteln (skalarprodukt dreiecks-normale, vector (midTri->midCub) ) - //je nachdem muss für den massgeblichen block start oder stopdistance verwendet werden - //liegt block auf pos seite -> stopdistance ansonsten startdistance - double skalarprod = triangle.nx * ( 0.5*(x1a+x1b)-triangle.getX1Centroid(nodes) ) - + triangle.ny * ( 0.5*(x2a+x2b)-triangle.getX2Centroid(nodes) ) - + triangle.nz * ( 0.5*(x3a+x3b)-triangle.getX3Centroid(nodes) ); - - double blockdelta = 1.05*stopDistance; - if (skalarprod<1.E-8 ) blockdelta = -1.05*startDistance; //startDistance<0!! - else if( fabs(skalarprod)<1.E-8) blockdelta = 1.05*UbMath::max(-startDistance,stopDistance); - - //block anpassen - blockMinX[0] = (float)(val<1>(coords)-blockdelta ); - blockMinX[1] = (float)(val<2>(coords)-blockdelta ); - blockMinX[2] = (float)(val<3>(coords)-blockdelta ); - - blockMaxX[0] = (float)(val<1>(coords)+val<1>(deltas)+blockdelta ); - blockMaxX[1] = (float)(val<2>(coords)+val<2>(deltas)+blockdelta ); - blockMaxX[2] = (float)(val<3>(coords)+val<3>(deltas)+blockdelta ); - - boxCenter[0] = (float)(0.5*(blockMaxX[0]+blockMinX[0])); - boxCenter[1] = (float)(0.5*(blockMaxX[1]+blockMinX[1])); - boxCenter[2] = (float)(0.5*(blockMaxX[2]+blockMinX[2])); - - halfBoxSize[0] = (float)(0.5*(blockMaxX[0]-blockMinX[0])); - halfBoxSize[1] = (float)(0.5*(blockMaxX[1]-blockMinX[1])); - halfBoxSize[2] = (float)(0.5*(blockMaxX[2]-blockMinX[2])); - - GbTriFaceMesh3D::Vertex& v1_ = nodes[triangle.v1]; - GbTriFaceMesh3D::Vertex& v2_ = nodes[triangle.v2]; - GbTriFaceMesh3D::Vertex& v3_ = nodes[triangle.v3]; - - triPoints[0][0] = v1_.x; triPoints[0][1] = v1_.y; triPoints[0][2] = v1_.z; - triPoints[1][0] = v2_.x; triPoints[1][1] = v2_.y; triPoints[1][2] = v2_.z; - triPoints[2][0] = v3_.x; triPoints[2][1] = v3_.y; triPoints[2][2] = v3_.z; - - //wenn block dreick schneidet, dann muss er verfeinert werden - if( GbMeshTools3D::triBoxOverlap(boxCenter,halfBoxSize,triPoints) ) - { - bgrid->expandBlock(block->getX1(), block->getX2(),block->getX3(),block->getLevel()); - } + UBLOG(logDEBUG1, "D3Q27TriFaceMeshInteractor::refineBlockGridToLevel - start"); + + // ToDo: evtl checken, ob man noch einen HalbraumCheck für StopDistance einbaut + // oder ob man schneller ist, wenn man gar keinen halbraum test macht... + if (!grid.lock()) + throw UbException(UB_EXARGS, "Grid isn't exist!"); + if (UbMath::greater(startDistance, 0.0)) + throw UbException(UB_EXARGS, "startDistance>0.0 not supported by this interactor"); + if (UbMath::less(stopDistance, 0.0)) + throw UbException(UB_EXARGS, "stopDistance<0.0 not supported by this interactor"); + + SPtr<Grid3D> bgrid = this->grid.lock(); + GbTriFaceMesh3D &mesh = dynamic_cast<GbTriFaceMesh3D &>(*this->geoObject3D.get()); + + int coarsestLevel = bgrid->getCoarsestInitializedLevel(); + + std::vector<GbTriFaceMesh3D::TriFace> &triangles = *mesh.getTriangles(); + std::vector<GbTriFaceMesh3D::Vertex> &nodes = *mesh.getNodes(); + + double minX1, minX2, minX3, maxX1, maxX2, maxX3; + float blockMinX[3], blockMaxX[3], boxCenter[3], halfBoxSize[3]; + float triPoints[3][3]; + + size_t nofTriangles = (int)triangles.size(); + + //#pragma omp parallel + //#pragma omp for + for (size_t i = 0; i < nofTriangles; i++) + // for(int i=0; i<nofTriangles; i++) + { + //#pragma omp master + //{ + // printf_s("num_threads=%d\n", omp_get_num_threads( )); + //} + + GbTriFaceMesh3D::TriFace &triangle = triangles[i]; + + GbTriFaceMesh3D::Vertex &v1 = nodes[triangle.v1]; + GbTriFaceMesh3D::Vertex &v2 = nodes[triangle.v2]; + GbTriFaceMesh3D::Vertex &v3 = nodes[triangle.v3]; + + // dreick muss normal besitzen! + assert(!UbMath::zero(triangle.nx) || !UbMath::zero(triangle.ny) || !UbMath::zero(triangle.nz)); + // Normale muss normiert sein! + assert((fabs(std::sqrt(triangle.nx * triangle.nx + triangle.ny * triangle.ny + triangle.nz * triangle.nz)) - + 1.0f) < 1.0E-6); + + // Halfspace um startDistance entgegen normale verscheiebn, ansonsten werden spaeter + // zu testende bloecke auf der dreicksrueckseite nicht getestet!!! + GbHalfSpace3D halfSpace( + v1.x + startDistance * triangle.nx, v1.y + startDistance * triangle.ny, v1.z + startDistance * triangle.nz, + v2.x + startDistance * triangle.nx, v2.y + startDistance * triangle.ny, v2.z + startDistance * triangle.nz, + v3.x + startDistance * triangle.nx, v3.y + startDistance * triangle.ny, v3.z + startDistance * triangle.nz); + + // Boundingbox um massgebliches dx erweitern -> zur Bestimmung der zu testenden Bloecke + if (triangle.nx > 1.0E-8) { + minX1 = triangle.getMinX(nodes) + 1.05 * triangle.nx * startDistance; + maxX1 = triangle.getMaxX(nodes) + 1.05 * triangle.nx * stopDistance; + } else { + minX1 = triangle.getMinX(nodes) + 1.05 * triangle.nx * stopDistance; + maxX1 = triangle.getMaxX(nodes) + 1.05 * triangle.nx * startDistance; + } + + if (triangle.ny > 1.0E-8) { + minX2 = triangle.getMinY(nodes) + 1.05 * triangle.ny * startDistance; + maxX2 = triangle.getMaxY(nodes) + 1.05 * triangle.ny * stopDistance; + } else { + minX2 = triangle.getMinY(nodes) + 1.05 * triangle.ny * stopDistance; + maxX2 = triangle.getMaxY(nodes) + 1.05 * triangle.ny * startDistance; + } + + if (triangle.nz > 1.0E-8) { + minX3 = triangle.getMinZ(nodes) + 1.05 * triangle.nz * startDistance; + maxX3 = triangle.getMaxZ(nodes) + 1.05 * triangle.nz * stopDistance; + } else { + minX3 = triangle.getMinZ(nodes) + 1.05 * triangle.nz * stopDistance; + maxX3 = triangle.getMaxZ(nodes) + 1.05 * triangle.nz * startDistance; + } + + int flag = 0; + // Levelweise alle Bloecke holen, die erweiterte BB schneiden + // und bearbeiten + for (int l = coarsestLevel; l < level; l++) { + std::vector<SPtr<Block3D>> consideredBlocks; + bgrid->getBlocksByCuboid(l, minX1, minX2, minX3, maxX1, maxX2, maxX3, consideredBlocks); + double x1a, x2a, x3a, x1b, x2b, x3b; + + for (size_t b = 0; b < consideredBlocks.size(); b++) { + SPtr<Block3D> block = consideredBlocks[b]; + if (block->getLevel() >= level) + continue; + + // start coordinaten des blocks ermitteln + UbTupleDouble3 coords = bgrid->getBlockWorldCoordinates(block); + UbTupleDouble3 deltas = bgrid->getBlockLengths(block); + + // Check, ob block komplett im Halbraum + x1a = val<1>(coords); + x1b = val<1>(coords) + val<1>(deltas); + x2a = val<2>(coords); + x2b = val<2>(coords) + val<2>(deltas); + x3a = val<3>(coords); + x3b = val<3>(coords) + val<3>(deltas); + + flag = 0; + if (!halfSpace.ptInside(x1a, x2a, x3a)) + flag |= (1 << 0); // 1 + if (!halfSpace.ptInside(x1b, x2a, x3a)) + flag |= (1 << 1); // 2 + if (!halfSpace.ptInside(x1b, x2b, x3a)) + flag |= (1 << 2); // 4 + if (!halfSpace.ptInside(x1a, x2b, x3a)) + flag |= (1 << 3); // 8 + if (!halfSpace.ptInside(x1a, x2a, x3b)) + flag |= (1 << 4); // 16 + if (!halfSpace.ptInside(x1b, x2a, x3b)) + flag |= (1 << 5); // 32 + if (!halfSpace.ptInside(x1b, x2b, x3b)) + flag |= (1 << 6); // 64 + if (!halfSpace.ptInside(x1a, x2b, x3b)) + flag |= (1 << 7); // 128 + + if (true && flag != 255) { + // blockseite ermitteln (skalarprodukt dreiecks-normale, vector (midTri->midCub) ) + // je nachdem muss für den massgeblichen block start oder stopdistance verwendet werden + // liegt block auf pos seite -> stopdistance ansonsten startdistance + double skalarprod = triangle.nx * (0.5 * (x1a + x1b) - triangle.getX1Centroid(nodes)) + + triangle.ny * (0.5 * (x2a + x2b) - triangle.getX2Centroid(nodes)) + + triangle.nz * (0.5 * (x3a + x3b) - triangle.getX3Centroid(nodes)); + + double blockdelta = 1.05 * stopDistance; + if (skalarprod < 1.E-8) + blockdelta = -1.05 * startDistance; // startDistance<0!! + else if (fabs(skalarprod) < 1.E-8) + blockdelta = 1.05 * UbMath::max(-startDistance, stopDistance); + + // block anpassen + blockMinX[0] = (float)(val<1>(coords) - blockdelta); + blockMinX[1] = (float)(val<2>(coords) - blockdelta); + blockMinX[2] = (float)(val<3>(coords) - blockdelta); + + blockMaxX[0] = (float)(val<1>(coords) + val<1>(deltas) + blockdelta); + blockMaxX[1] = (float)(val<2>(coords) + val<2>(deltas) + blockdelta); + blockMaxX[2] = (float)(val<3>(coords) + val<3>(deltas) + blockdelta); + + boxCenter[0] = (float)(0.5 * (blockMaxX[0] + blockMinX[0])); + boxCenter[1] = (float)(0.5 * (blockMaxX[1] + blockMinX[1])); + boxCenter[2] = (float)(0.5 * (blockMaxX[2] + blockMinX[2])); + + halfBoxSize[0] = (float)(0.5 * (blockMaxX[0] - blockMinX[0])); + halfBoxSize[1] = (float)(0.5 * (blockMaxX[1] - blockMinX[1])); + halfBoxSize[2] = (float)(0.5 * (blockMaxX[2] - blockMinX[2])); + + GbTriFaceMesh3D::Vertex &v1_ = nodes[triangle.v1]; + GbTriFaceMesh3D::Vertex &v2_ = nodes[triangle.v2]; + GbTriFaceMesh3D::Vertex &v3_ = nodes[triangle.v3]; + + triPoints[0][0] = v1_.x; + triPoints[0][1] = v1_.y; + triPoints[0][2] = v1_.z; + triPoints[1][0] = v2_.x; + triPoints[1][1] = v2_.y; + triPoints[1][2] = v2_.z; + triPoints[2][0] = v3_.x; + triPoints[2][1] = v3_.y; + triPoints[2][2] = v3_.z; + + // wenn block dreick schneidet, dann muss er verfeinert werden + if (GbMeshTools3D::triBoxOverlap(boxCenter, halfBoxSize, triPoints)) { + bgrid->expandBlock(block->getX1(), block->getX2(), block->getX3(), block->getLevel()); + } + } } - } - } - } - UBLOG(logDEBUG1, " - refine done"); + } + } + UBLOG(logDEBUG1, " - refine done"); } ////////////////////////////////////////////////////////////////////////// -void D3Q27TriFaceMeshInteractor::updateMovedGeometry(const double& timeStep) -{ - -} +void D3Q27TriFaceMeshInteractor::updateMovedGeometry(const double &timeStep) {} //////////////////////////////////////////////////////////////////////////// -void D3Q27TriFaceMeshInteractor::recursiveGridFill(CbArray3D<FLAGS>& flagfield, const short& xs, const short& ys, const short& zs, const FLAGS& type) +void D3Q27TriFaceMeshInteractor::recursiveGridFill(CbArray3D<FLAGS> &flagfield, const short &xs, const short &ys, + const short &zs, const FLAGS &type) { - // Algorithmus zum Füllen eines Polyeders, ausgehend vom Saatpunkt xs,ys,zs - - //Saatknoten einfärben - if( flagfield(xs,ys,zs)==UNDEF_FLAG ) - { - flagfield(xs,ys,zs) = type; - - if ( flagfield.indicesInRange( xs+1, ys , zs ) ) this->recursiveGridFill(flagfield,xs+1, ys , zs ,type); - if ( flagfield.indicesInRange( xs , ys+1, zs ) ) this->recursiveGridFill(flagfield,xs , ys+1, zs ,type); - if ( flagfield.indicesInRange( xs , ys , zs+1 ) ) this->recursiveGridFill(flagfield,xs , ys , zs+1,type); - if ( flagfield.indicesInRange( xs-1, ys , zs ) ) this->recursiveGridFill(flagfield,xs-1, ys , zs ,type); - if ( flagfield.indicesInRange( xs , ys-1, zs ) ) this->recursiveGridFill(flagfield,xs , ys-1, zs ,type); - if ( flagfield.indicesInRange( xs , ys , zs-1 ) ) this->recursiveGridFill(flagfield,xs , ys , zs-1,type); - } + // Algorithmus zum Füllen eines Polyeders, ausgehend vom Saatpunkt xs,ys,zs + + // Saatknoten einfärben + if (flagfield(xs, ys, zs) == UNDEF_FLAG) { + flagfield(xs, ys, zs) = type; + + if (flagfield.indicesInRange(xs + 1, ys, zs)) + this->recursiveGridFill(flagfield, xs + 1, ys, zs, type); + if (flagfield.indicesInRange(xs, ys + 1, zs)) + this->recursiveGridFill(flagfield, xs, ys + 1, zs, type); + if (flagfield.indicesInRange(xs, ys, zs + 1)) + this->recursiveGridFill(flagfield, xs, ys, zs + 1, type); + if (flagfield.indicesInRange(xs - 1, ys, zs)) + this->recursiveGridFill(flagfield, xs - 1, ys, zs, type); + if (flagfield.indicesInRange(xs, ys - 1, zs)) + this->recursiveGridFill(flagfield, xs, ys - 1, zs, type); + if (flagfield.indicesInRange(xs, ys, zs - 1)) + this->recursiveGridFill(flagfield, xs, ys, zs - 1, type); + } } ////////////////////////////////////////////////////////////////////////// -void D3Q27TriFaceMeshInteractor::iterativeGridFill(CbArray3D<FLAGS>& flagfield, const short& xs, const short& ys, const short& zs, const FLAGS& type) +void D3Q27TriFaceMeshInteractor::iterativeGridFill(CbArray3D<FLAGS> &flagfield, const short &xs, const short &ys, + const short &zs, const FLAGS &type) { - std::stack< UbTupleInt3 > stck; - stck.push( UbTupleInt3(xs,ys,zs) ); - - int x,y,z; - - while( !stck.empty() ) - { - x = val<1>( stck.top() ); - y = val<2>( stck.top() ); - z = val<3>( stck.top() ); - stck.pop(); - - FLAGS& flagType = flagfield( x, y, z ); - - if( flagType == UNDEF_FLAG ) - { - flagType = type; - - if ( flagfield.indicesInRange( x+1, y , z ) ) stck.push( UbTupleInt3( x+1, y , z ) ); - if ( flagfield.indicesInRange( x , y+1, z ) ) stck.push( UbTupleInt3( x , y+1, z ) ); - if ( flagfield.indicesInRange( x , y , z+1 ) ) stck.push( UbTupleInt3( x , y , z+1 ) ); - if ( flagfield.indicesInRange( x-1, y , z ) ) stck.push( UbTupleInt3( x-1, y , z ) ); - if ( flagfield.indicesInRange( x , y-1, z ) ) stck.push( UbTupleInt3( x , y-1, z ) ); - if ( flagfield.indicesInRange( x , y , z-1 ) ) stck.push( UbTupleInt3( x , y , z-1 ) ); - } - } - return; + std::stack<UbTupleInt3> stck; + stck.push(UbTupleInt3(xs, ys, zs)); + + int x, y, z; + + while (!stck.empty()) { + x = val<1>(stck.top()); + y = val<2>(stck.top()); + z = val<3>(stck.top()); + stck.pop(); + + FLAGS &flagType = flagfield(x, y, z); + + if (flagType == UNDEF_FLAG) { + flagType = type; + + if (flagfield.indicesInRange(x + 1, y, z)) + stck.push(UbTupleInt3(x + 1, y, z)); + if (flagfield.indicesInRange(x, y + 1, z)) + stck.push(UbTupleInt3(x, y + 1, z)); + if (flagfield.indicesInRange(x, y, z + 1)) + stck.push(UbTupleInt3(x, y, z + 1)); + if (flagfield.indicesInRange(x - 1, y, z)) + stck.push(UbTupleInt3(x - 1, y, z)); + if (flagfield.indicesInRange(x, y - 1, z)) + stck.push(UbTupleInt3(x, y - 1, z)); + if (flagfield.indicesInRange(x, y, z - 1)) + stck.push(UbTupleInt3(x, y, z - 1)); + } + } + return; } ////////////////////////////////////////////////////////////////////////// UbTupleDouble3 D3Q27TriFaceMeshInteractor::getForces() { - //FeTriFaceMesh3D* feMesh = dynamic_cast<FeTriFaceMesh3D*>(this->geoObject3D.get()); - //if(!feMesh) - //{ - // return D3Q19AMRInteractor::getForces(); - //} - ////return getForcesTriangle(); - //this->calculateForces(); - - double forceX1=0.0; - double forceX2=0.0; - double forceX3=0.0; - - //double area = 0.0; - - //vector<FeTriFaceMesh3D::VertexAttributes>* attributes = feMesh->getAttributes(); - - //for(size_t i=0; i<attributes->size(); i++) - //{ - // FeTriFaceMesh3D::VertexAttributes& attribut = (*attributes)[i]; - // area = attribut.getArea(); - // forceX1 += attribut.getFX()*area; - // forceX2 += attribut.getFY()*area; - // forceX3 += attribut.getFZ()*area; - //} - return {forceX1,forceX2,forceX3}; + // FeTriFaceMesh3D* feMesh = dynamic_cast<FeTriFaceMesh3D*>(this->geoObject3D.get()); + // if(!feMesh) + //{ + // return D3Q19AMRInteractor::getForces(); + //} + ////return getForcesTriangle(); + // this->calculateForces(); + + double forceX1 = 0.0; + double forceX2 = 0.0; + double forceX3 = 0.0; + + // double area = 0.0; + + // vector<FeTriFaceMesh3D::VertexAttributes>* attributes = feMesh->getAttributes(); + + // for(size_t i=0; i<attributes->size(); i++) + //{ + // FeTriFaceMesh3D::VertexAttributes& attribut = (*attributes)[i]; + // area = attribut.getArea(); + // forceX1 += attribut.getFX()*area; + // forceX2 += attribut.getFY()*area; + // forceX3 += attribut.getFZ()*area; + //} + return { forceX1, forceX2, forceX3 }; } ////////////////////////////////////////////////////////////////////////// UbTupleDouble3 D3Q27TriFaceMeshInteractor::getForcesTriangle() { - double forceX1=0.0; - double forceX2=0.0; - double forceX3=0.0; - - //D3Q19BlockGrid& grid.lock() = dynamic_cast<D3Q19BlockGrid&>(*this->grid.lock()); - //// CoordinateTransformation3D *trafo = this->grid.lock()->getTransformation(); - //// int minLevel = this->grid.lock()->getFinestInitializedLevel(); - //// double scaleX = trafo->getX1CoordinateScaling()/(1<<minLevel); - //// double scaleY = trafo->getX2CoordinateScaling()/(1<<minLevel); - //// double scaleZ = trafo->getX3CoordinateScaling()/(1<<minLevel); - //// int blocknx1 = grid.lock()->getBlockNX1(); - //// int blocknx2 = grid.lock()->getBlockNX2(); - //// int blocknx3 = grid.lock()->getBlockNX3(); - //// double xOffset = trafo->getX1CoordinateOffset(); - //// double yOffset = trafo->getX2CoordinateOffset(); - //// double zOffset = trafo->getX3CoordinateOffset(); - //vector<D3Q19Real> collFactors = ((D3Q19Calculator*)grid.lock()->getCalculator())->getCollisionsFactors(); - - ////for (int i=0;i<(int)gbTriangle3DInteractors.size(); i++) - ////{ - //// GbTriangle3D* tri = (GbTriangle3D*)gbTriangle3DInteractors[i]->getGbObject3D(); - - //// double px0 = tri->getX1Centroid(); - //// double py0 = tri->getX2Centroid(); - //// double pz0 = tri->getX3Centroid(); - //// double px = px0-xOffset; - //// double py = py0-yOffset; - //// double pz = pz0-zOffset; - //// px = px/scaleX; - //// py = py/scaleY; - //// pz = pz/scaleZ; - //// int x1 = (int)px; - //// int y1 = (int)py; - //// int z1 = (int)pz; - //// AMR3DBlock* block = this->grid.lock()->getBlock(x1,y1,z1,minLevel); - //// if(!block) block = this->grid.lock()->getSuperBlock(x1,y1,z1,minLevel); - //// if(!block) throw UbException(__FILE__,__LINE__,"kein Block ..."); - - //// double collFactor = collFactors[block->getLevel()]; - //// double nodeDistance = grid.lock()->getNodeDeltaX(block->getLevel()); - //// double bertX1 = ((px0-xOffset)/(1000.*nodeDistance)); - //// double bertX2 = ((py0-yOffset)/(1000.*nodeDistance)); - //// double bertX3 = ((pz0-zOffset)/(1000.*nodeDistance)); - //// int abstaendeX1 = (int)(bertX1*1000.); - //// int abstaendeX2 = (int)(bertX2*1000.); - //// int abstaendeX3 = (int)(bertX3*1000.); - //// int posW = abstaendeX1 - block->getX1Index()*blocknx1; - //// int posS = abstaendeX2 - block->getX2Index()*blocknx2; - //// int posB = abstaendeX3 - block->getX3Index()*blocknx3; - //// int posE=posW+1; - //// int posN=posS+1; - //// int posT=posB+1; - - //// D3Q19BlockDescriptor *bvd = dynamic_cast<D3Q19BlockDescriptor*>(block->getBlockDescriptor()); - //// if(!bvd) throw UbException(__FILE__,__LINE__,"kein Bvd ..."); - - //// CbUniformMatrix4D<double,IndexerX1X2X3X4>* tempdistributions = bvd->getTempDistributionMatrix(); - //// D3Q19BCMatrix<D3Q19BoundaryCondition> *bcMatrix = bvd->getBcMatrix(); - - //// UbTupleDouble6 stresses; - //// double dX = px0-this->geoObject3D->getX1Centroid(); - //// double dY = py0-this->geoObject3D->getX2Centroid(); - //// double dZ = pz0-this->geoObject3D->getX3Centroid(); - //// if(dX<=0.0 && dY<=0.0 && dZ<=0.0) - //// { - //// double *fWSB = tempdistributions->getStartAdressOfSortedArray(posW,posS,posB,0); - //// if(bcMatrix->isFluid(posW,posS,posB)) stresses = D3Q19System::getIncompStresses(fWSB, collFactor ); - //// else cout<<__LINE__<<" nicht fluid ..."; - //// } - //// else if(dX<=0.0 && dY>0.0 && dZ<=0.0) - //// { - //// double *fWNB = tempdistributions->getStartAdressOfSortedArray(posW,posN,posB,0); - //// if(bcMatrix->isFluid(posW,posN,posB)) stresses = D3Q19System::getIncompStresses(fWNB, collFactor ); - //// else cout<<__LINE__<<" nicht fluid ..."; - //// } - //// else if(dX<=0.0 && dY<=0.0 && dZ>0.0) - //// { - //// double *fWST = tempdistributions->getStartAdressOfSortedArray(posW,posS,posT,0); - //// if(bcMatrix->isFluid(posW,posS,posT)) stresses = D3Q19System::getIncompStresses(fWST, collFactor ); - //// else cout<<__LINE__<<" nicht fluid ..."; - //// } - //// else if(dX<=0.0 && dY>0.0 && dZ>0.0) - //// { - //// double *fWNT = tempdistributions->getStartAdressOfSortedArray(posW,posN,posT,0); - //// if(bcMatrix->isFluid(posW,posN,posT)) stresses = D3Q19System::getIncompStresses(fWNT, collFactor ); - //// else cout<<__LINE__<<" nicht fluid ..."; - //// } - //// else if(dX>0.0 && dY<=0.0 && dZ<=0.0) - //// { - //// double *fESB = tempdistributions->getStartAdressOfSortedArray(posE,posS,posB,0); - //// if(bcMatrix->isFluid(posE,posS,posB)) stresses = D3Q19System::getIncompStresses(fESB, collFactor ); - //// else cout<<__LINE__<<" nicht fluid ..."; - //// } - //// else if(dX>0.0 && dY>0.0 && dZ<=0.0) - //// { - //// double *fENB = tempdistributions->getStartAdressOfSortedArray(posE,posN,posB,0); - //// if(bcMatrix->isFluid(posE,posN,posB)) stresses = D3Q19System::getIncompStresses(fENB, collFactor ); - //// else cout<<__LINE__<<" nicht fluid ..."; - //// } - //// else if(dX>0.0 && dY<=0.0 && dZ>0.0) - //// { - //// double *fEST = tempdistributions->getStartAdressOfSortedArray(posE,posS,posT,0); - //// if(bcMatrix->isFluid(posE,posS,posT)) stresses = D3Q19System::getIncompStresses(fEST, collFactor ); - //// else cout<<__LINE__<<" nicht fluid ..."; - //// } - //// else if(dX>0.0 && dY>0.0 && dZ>0.0) - //// { - //// double *fENT = tempdistributions->getStartAdressOfSortedArray(posE,posN,posT,0); - //// if(bcMatrix->isFluid(posE,posN,posT)) stresses = D3Q19System::getIncompStresses(fENT, collFactor ); - //// else cout<<__LINE__<<" nicht fluid ..."; - //// } - //// else cout<<"punkt mit:"<<dX<<" "<<dY<<" "<<dZ<<" ist nicht bei \n"; - - //// double S11 = val<1>(stresses); - //// double S22 = val<2>(stresses); - //// double S33 = val<3>(stresses); - //// double S12 = val<4>(stresses); - //// double S13 = val<5>(stresses); - //// double S23 = val<6>(stresses); - - //// GbVector3D normal = tri->getNormal(); - //// double nx = normal.X1(); - //// double ny = normal.X2(); - //// double nz = normal.X3(); - //// double area = tri->getArea(); - - //// double Fx1 = area*(S11*nx+S12*ny+S13*nz); - //// double Fy1 = area*(S12*nx+S22*ny+S23*nz); - //// double Fz1 = area*(S13*nx+S23*ny+S33*nz); - //// forceX1 += Fx1; - //// forceX2 += Fy1; - //// forceX3 += Fz1; - ////} - return {forceX1,forceX2,forceX3}; + double forceX1 = 0.0; + double forceX2 = 0.0; + double forceX3 = 0.0; + + // D3Q19BlockGrid& grid.lock() = dynamic_cast<D3Q19BlockGrid&>(*this->grid.lock()); + //// CoordinateTransformation3D *trafo = this->grid.lock()->getTransformation(); + //// int minLevel = this->grid.lock()->getFinestInitializedLevel(); + //// double scaleX = trafo->getX1CoordinateScaling()/(1<<minLevel); + //// double scaleY = trafo->getX2CoordinateScaling()/(1<<minLevel); + //// double scaleZ = trafo->getX3CoordinateScaling()/(1<<minLevel); + //// int blocknx1 = grid.lock()->getBlockNX1(); + //// int blocknx2 = grid.lock()->getBlockNX2(); + //// int blocknx3 = grid.lock()->getBlockNX3(); + //// double xOffset = trafo->getX1CoordinateOffset(); + //// double yOffset = trafo->getX2CoordinateOffset(); + //// double zOffset = trafo->getX3CoordinateOffset(); + // vector<D3Q19Real> collFactors = ((D3Q19Calculator*)grid.lock()->getCalculator())->getCollisionsFactors(); + + ////for (int i=0;i<(int)gbTriangle3DInteractors.size(); i++) + ////{ + //// GbTriangle3D* tri = (GbTriangle3D*)gbTriangle3DInteractors[i]->getGbObject3D(); + + //// double px0 = tri->getX1Centroid(); + //// double py0 = tri->getX2Centroid(); + //// double pz0 = tri->getX3Centroid(); + //// double px = px0-xOffset; + //// double py = py0-yOffset; + //// double pz = pz0-zOffset; + //// px = px/scaleX; + //// py = py/scaleY; + //// pz = pz/scaleZ; + //// int x1 = (int)px; + //// int y1 = (int)py; + //// int z1 = (int)pz; + //// AMR3DBlock* block = this->grid.lock()->getBlock(x1,y1,z1,minLevel); + //// if(!block) block = this->grid.lock()->getSuperBlock(x1,y1,z1,minLevel); + //// if(!block) throw UbException(__FILE__,__LINE__,"kein Block ..."); + + //// double collFactor = collFactors[block->getLevel()]; + //// double nodeDistance = grid.lock()->getNodeDeltaX(block->getLevel()); + //// double bertX1 = ((px0-xOffset)/(1000.*nodeDistance)); + //// double bertX2 = ((py0-yOffset)/(1000.*nodeDistance)); + //// double bertX3 = ((pz0-zOffset)/(1000.*nodeDistance)); + //// int abstaendeX1 = (int)(bertX1*1000.); + //// int abstaendeX2 = (int)(bertX2*1000.); + //// int abstaendeX3 = (int)(bertX3*1000.); + //// int posW = abstaendeX1 - block->getX1Index()*blocknx1; + //// int posS = abstaendeX2 - block->getX2Index()*blocknx2; + //// int posB = abstaendeX3 - block->getX3Index()*blocknx3; + //// int posE=posW+1; + //// int posN=posS+1; + //// int posT=posB+1; + + //// D3Q19BlockDescriptor *bvd = dynamic_cast<D3Q19BlockDescriptor*>(block->getBlockDescriptor()); + //// if(!bvd) throw UbException(__FILE__,__LINE__,"kein Bvd ..."); + + //// CbUniformMatrix4D<double,IndexerX1X2X3X4>* tempdistributions = bvd->getTempDistributionMatrix(); + //// D3Q19BCMatrix<D3Q19BoundaryCondition> *bcMatrix = bvd->getBcMatrix(); + + //// UbTupleDouble6 stresses; + //// double dX = px0-this->geoObject3D->getX1Centroid(); + //// double dY = py0-this->geoObject3D->getX2Centroid(); + //// double dZ = pz0-this->geoObject3D->getX3Centroid(); + //// if(dX<=0.0 && dY<=0.0 && dZ<=0.0) + //// { + //// double *fWSB = tempdistributions->getStartAdressOfSortedArray(posW,posS,posB,0); + //// if(bcMatrix->isFluid(posW,posS,posB)) stresses = D3Q19System::getIncompStresses(fWSB, collFactor ); + //// else cout<<__LINE__<<" nicht fluid ..."; + //// } + //// else if(dX<=0.0 && dY>0.0 && dZ<=0.0) + //// { + //// double *fWNB = tempdistributions->getStartAdressOfSortedArray(posW,posN,posB,0); + //// if(bcMatrix->isFluid(posW,posN,posB)) stresses = D3Q19System::getIncompStresses(fWNB, collFactor ); + //// else cout<<__LINE__<<" nicht fluid ..."; + //// } + //// else if(dX<=0.0 && dY<=0.0 && dZ>0.0) + //// { + //// double *fWST = tempdistributions->getStartAdressOfSortedArray(posW,posS,posT,0); + //// if(bcMatrix->isFluid(posW,posS,posT)) stresses = D3Q19System::getIncompStresses(fWST, collFactor ); + //// else cout<<__LINE__<<" nicht fluid ..."; + //// } + //// else if(dX<=0.0 && dY>0.0 && dZ>0.0) + //// { + //// double *fWNT = tempdistributions->getStartAdressOfSortedArray(posW,posN,posT,0); + //// if(bcMatrix->isFluid(posW,posN,posT)) stresses = D3Q19System::getIncompStresses(fWNT, collFactor ); + //// else cout<<__LINE__<<" nicht fluid ..."; + //// } + //// else if(dX>0.0 && dY<=0.0 && dZ<=0.0) + //// { + //// double *fESB = tempdistributions->getStartAdressOfSortedArray(posE,posS,posB,0); + //// if(bcMatrix->isFluid(posE,posS,posB)) stresses = D3Q19System::getIncompStresses(fESB, collFactor ); + //// else cout<<__LINE__<<" nicht fluid ..."; + //// } + //// else if(dX>0.0 && dY>0.0 && dZ<=0.0) + //// { + //// double *fENB = tempdistributions->getStartAdressOfSortedArray(posE,posN,posB,0); + //// if(bcMatrix->isFluid(posE,posN,posB)) stresses = D3Q19System::getIncompStresses(fENB, collFactor ); + //// else cout<<__LINE__<<" nicht fluid ..."; + //// } + //// else if(dX>0.0 && dY<=0.0 && dZ>0.0) + //// { + //// double *fEST = tempdistributions->getStartAdressOfSortedArray(posE,posS,posT,0); + //// if(bcMatrix->isFluid(posE,posS,posT)) stresses = D3Q19System::getIncompStresses(fEST, collFactor ); + //// else cout<<__LINE__<<" nicht fluid ..."; + //// } + //// else if(dX>0.0 && dY>0.0 && dZ>0.0) + //// { + //// double *fENT = tempdistributions->getStartAdressOfSortedArray(posE,posN,posT,0); + //// if(bcMatrix->isFluid(posE,posN,posT)) stresses = D3Q19System::getIncompStresses(fENT, collFactor ); + //// else cout<<__LINE__<<" nicht fluid ..."; + //// } + //// else cout<<"punkt mit:"<<dX<<" "<<dY<<" "<<dZ<<" ist nicht bei \n"; + + //// double S11 = val<1>(stresses); + //// double S22 = val<2>(stresses); + //// double S33 = val<3>(stresses); + //// double S12 = val<4>(stresses); + //// double S13 = val<5>(stresses); + //// double S23 = val<6>(stresses); + + //// GbVector3D normal = tri->getNormal(); + //// double nx = normal.X1(); + //// double ny = normal.X2(); + //// double nz = normal.X3(); + //// double area = tri->getArea(); + + //// double Fx1 = area*(S11*nx+S12*ny+S13*nz); + //// double Fy1 = area*(S12*nx+S22*ny+S23*nz); + //// double Fz1 = area*(S13*nx+S23*ny+S33*nz); + //// forceX1 += Fx1; + //// forceX2 += Fy1; + //// forceX3 += Fz1; + ////} + return { forceX1, forceX2, forceX3 }; } ////////////////////////////////////////////////////////////////////////// void D3Q27TriFaceMeshInteractor::calculateForces() { - //FeTriFaceMesh3D* feMesh = dynamic_cast<FeTriFaceMesh3D*>(this->geoObject3D.get()); - //if(!feMesh) throw UbException(UB_EXARGS,"geoObject is not a FeTriFaceMesh3D!"); - - //if(this->stressMode == STRESSNORMAL) this->calculateStresses(); - //else if(this->stressMode == STRESSALTERNATIV) this->calculateStressesAlternativ(); - - //vector<FeTriFaceMesh3D::VertexAttributes>* attributes = feMesh->getAttributes(); - - //for (int i=0;i<(int)attributes->size() ;i++) - //{ - // FeTriFaceMesh3D::VertexAttributes& attribut = (*attributes)[i]; - // attribut.setFX(0.0); - // attribut.setFY(0.0); - // attribut.setFZ(0.0); - // attribut.setArea(0.0); - //} - //vector<GbTriFaceMesh3D::TriFace>& triangles = *feMesh->getTriangles(); - //vector<GbTriFaceMesh3D::Vertex>& nodes = *feMesh->getNodes(); - //for (size_t i=0; i<triangles.size(); i++) - //{ - // GbTriFaceMesh3D::TriFace& triangle = triangles[i]; - // FeTriFaceMesh3D::VertexAttributes& vAttribut1 = (*attributes)[triangle.v1]; - // FeTriFaceMesh3D::VertexAttributes& vAttribut2 = (*attributes)[triangle.v2]; - // FeTriFaceMesh3D::VertexAttributes& vAttribut3 = (*attributes)[triangle.v3]; - // UbTupleDouble6& stressesP1 = vAttribut1.getStresses(); - // UbTupleDouble6& stressesP2 = vAttribut2.getStresses(); - // UbTupleDouble6& stressesP3 = vAttribut3.getStresses(); - // double p1S11 = val<1>(stressesP1); double p2S11 = val<1>(stressesP2); double p3S11 = val<1>(stressesP3); - // double p1S22 = val<2>(stressesP1); double p2S22 = val<2>(stressesP2); double p3S22 = val<2>(stressesP3); - // double p1S33 = val<3>(stressesP1); double p2S33 = val<3>(stressesP2); double p3S33 = val<3>(stressesP3); - // double p1S12 = val<4>(stressesP1); double p2S12 = val<4>(stressesP2); double p3S12 = val<4>(stressesP3); - // double p1S13 = val<5>(stressesP1); double p2S13 = val<5>(stressesP2); double p3S13 = val<5>(stressesP3); - // double p1S23 = val<6>(stressesP1); double p2S23 = val<6>(stressesP2); double p3S23 = val<6>(stressesP3); - - // triangle.calculateNormal(nodes); - // double nx = triangle.nx; - // double ny = triangle.ny; - // double nz = triangle.nz; - // double area = 0.3333*triangle.getArea(nodes); - - // if(UbMath::lessEqual(area,0.0)) cout<<__FILE__<<" "<<__LINE__<<" area <= 0 "<<endl; - - // double Fx1 = area*(0.333*(p1S11*nx+p1S12*ny+p1S13*nz)+0.333*(p2S11*nx+p2S12*ny+p2S13*nz)+0.333*(p3S11*nx+p3S12*ny+p3S13*nz)); - // double Fx2 = Fx1; - // double Fx3 = Fx1; - - // double Fy1 = area*(0.333*(p1S12*nx+p1S22*ny+p1S23*nz)+0.333*(p2S12*nx+p2S22*ny+p2S23*nz)+0.333*(p3S12*nx+p3S22*ny+p3S23*nz)); - // double Fy2 = Fy1; - // double Fy3 = Fy1; - - // double Fz1 = area*(0.333*(p1S13*nx+p1S23*ny+p1S33*nz)+0.333*(p2S13*nx+p2S23*ny+p2S33*nz)+0.333*(p3S13*nx+p3S23*ny+p3S33*nz)); - // double Fz2 = Fz1; - // double Fz3 = Fz1; - // // cout<<Fx1<<" "<<Fy1<<" "<<Fz1<<endl; - // vAttribut1.addFX(Fx1); vAttribut2.addFX(Fx2); vAttribut3.addFX(Fx3); - // vAttribut1.addFY(Fy1); vAttribut2.addFY(Fy2); vAttribut3.addFY(Fy3); - // vAttribut1.addFZ(Fz1); vAttribut2.addFZ(Fz2); vAttribut3.addFZ(Fz3); - // vAttribut1.addArea(area); vAttribut2.addArea(area); vAttribut3.addArea(area); - //} - //for (size_t i=0; i<attributes->size(); i++) - //{ - // FeTriFaceMesh3D::VertexAttributes& attribut = (*attributes)[i]; - - // double newFX = attribut.getFX()/attribut.getArea(); - // double newFY = attribut.getFY()/attribut.getArea(); - // double newFZ = attribut.getFZ()/attribut.getArea(); - // //if(i==100) cout<<"F:"<<newFX<<" "<<newFY<<" "<<newFZ<<endl; - // //double oldFX = p->getOldFX(); - // //double oldFY = p->getOldFY(); - // //int alphaSteps = p->getFilteringSteps(); - // //double alpha = 1.0; - // //if(alphaSteps != 0) - // //{ - // // alpha = (1.0-alphaSteps*0.1); - // // // cout<<p->toString()<<" alpha:"<<alpha<<" steps:"<<alphaSteps<<endl; - // // p->reduceFilteringSteps(); - // //} - // //newFX = (1.-alpha)*oldFX+alpha*newFX; - // //newFY = (1.-alpha)*oldFY+alpha*newFY; - - // attribut.setFX(newFX); - // attribut.setFY(newFY); - // attribut.setFZ(newFZ); - // //cout<<i<<" "<<newFX<<" "<<newFY<<" "<<newFZ<<endl; - // //cout<<i<<" "<<p->toString()<<endl; - - //} + // FeTriFaceMesh3D* feMesh = dynamic_cast<FeTriFaceMesh3D*>(this->geoObject3D.get()); + // if(!feMesh) throw UbException(UB_EXARGS,"geoObject is not a FeTriFaceMesh3D!"); + + // if(this->stressMode == STRESSNORMAL) this->calculateStresses(); + // else if(this->stressMode == STRESSALTERNATIV) this->calculateStressesAlternativ(); + + // vector<FeTriFaceMesh3D::VertexAttributes>* attributes = feMesh->getAttributes(); + + // for (int i=0;i<(int)attributes->size() ;i++) + //{ + // FeTriFaceMesh3D::VertexAttributes& attribut = (*attributes)[i]; + // attribut.setFX(0.0); + // attribut.setFY(0.0); + // attribut.setFZ(0.0); + // attribut.setArea(0.0); + //} + // vector<GbTriFaceMesh3D::TriFace>& triangles = *feMesh->getTriangles(); + // vector<GbTriFaceMesh3D::Vertex>& nodes = *feMesh->getNodes(); + // for (size_t i=0; i<triangles.size(); i++) + //{ + // GbTriFaceMesh3D::TriFace& triangle = triangles[i]; + // FeTriFaceMesh3D::VertexAttributes& vAttribut1 = (*attributes)[triangle.v1]; + // FeTriFaceMesh3D::VertexAttributes& vAttribut2 = (*attributes)[triangle.v2]; + // FeTriFaceMesh3D::VertexAttributes& vAttribut3 = (*attributes)[triangle.v3]; + // UbTupleDouble6& stressesP1 = vAttribut1.getStresses(); + // UbTupleDouble6& stressesP2 = vAttribut2.getStresses(); + // UbTupleDouble6& stressesP3 = vAttribut3.getStresses(); + // double p1S11 = val<1>(stressesP1); double p2S11 = val<1>(stressesP2); double p3S11 = val<1>(stressesP3); + // double p1S22 = val<2>(stressesP1); double p2S22 = val<2>(stressesP2); double p3S22 = val<2>(stressesP3); + // double p1S33 = val<3>(stressesP1); double p2S33 = val<3>(stressesP2); double p3S33 = val<3>(stressesP3); + // double p1S12 = val<4>(stressesP1); double p2S12 = val<4>(stressesP2); double p3S12 = val<4>(stressesP3); + // double p1S13 = val<5>(stressesP1); double p2S13 = val<5>(stressesP2); double p3S13 = val<5>(stressesP3); + // double p1S23 = val<6>(stressesP1); double p2S23 = val<6>(stressesP2); double p3S23 = val<6>(stressesP3); + + // triangle.calculateNormal(nodes); + // double nx = triangle.nx; + // double ny = triangle.ny; + // double nz = triangle.nz; + // double area = 0.3333*triangle.getArea(nodes); + + // if(UbMath::lessEqual(area,0.0)) cout<<__FILE__<<" "<<__LINE__<<" area <= 0 "<<endl; + + // double Fx1 = + // area*(0.333*(p1S11*nx+p1S12*ny+p1S13*nz)+0.333*(p2S11*nx+p2S12*ny+p2S13*nz)+0.333*(p3S11*nx+p3S12*ny+p3S13*nz)); + // double Fx2 = Fx1; + // double Fx3 = Fx1; + + // double Fy1 = + // area*(0.333*(p1S12*nx+p1S22*ny+p1S23*nz)+0.333*(p2S12*nx+p2S22*ny+p2S23*nz)+0.333*(p3S12*nx+p3S22*ny+p3S23*nz)); + // double Fy2 = Fy1; + // double Fy3 = Fy1; + + // double Fz1 = + // area*(0.333*(p1S13*nx+p1S23*ny+p1S33*nz)+0.333*(p2S13*nx+p2S23*ny+p2S33*nz)+0.333*(p3S13*nx+p3S23*ny+p3S33*nz)); + // double Fz2 = Fz1; + // double Fz3 = Fz1; + // // cout<<Fx1<<" "<<Fy1<<" "<<Fz1<<endl; + // vAttribut1.addFX(Fx1); vAttribut2.addFX(Fx2); vAttribut3.addFX(Fx3); + // vAttribut1.addFY(Fy1); vAttribut2.addFY(Fy2); vAttribut3.addFY(Fy3); + // vAttribut1.addFZ(Fz1); vAttribut2.addFZ(Fz2); vAttribut3.addFZ(Fz3); + // vAttribut1.addArea(area); vAttribut2.addArea(area); vAttribut3.addArea(area); + //} + // for (size_t i=0; i<attributes->size(); i++) + //{ + // FeTriFaceMesh3D::VertexAttributes& attribut = (*attributes)[i]; + + // double newFX = attribut.getFX()/attribut.getArea(); + // double newFY = attribut.getFY()/attribut.getArea(); + // double newFZ = attribut.getFZ()/attribut.getArea(); + // //if(i==100) cout<<"F:"<<newFX<<" "<<newFY<<" "<<newFZ<<endl; + // //double oldFX = p->getOldFX(); + // //double oldFY = p->getOldFY(); + // //int alphaSteps = p->getFilteringSteps(); + // //double alpha = 1.0; + // //if(alphaSteps != 0) + // //{ + // // alpha = (1.0-alphaSteps*0.1); + // // // cout<<p->toString()<<" alpha:"<<alpha<<" steps:"<<alphaSteps<<endl; + // // p->reduceFilteringSteps(); + // //} + // //newFX = (1.-alpha)*oldFX+alpha*newFX; + // //newFY = (1.-alpha)*oldFY+alpha*newFY; + + // attribut.setFX(newFX); + // attribut.setFY(newFY); + // attribut.setFZ(newFZ); + // //cout<<i<<" "<<newFX<<" "<<newFY<<" "<<newFZ<<endl; + // //cout<<i<<" "<<p->toString()<<endl; + + //} } ////////////////////////////////////////////////////////////////////////// string D3Q27TriFaceMeshInteractor::toString() { - stringstream ss; - ss<< "D3Q27TriFaceMeshInteractor[label=D3Q27TriFaceMeshInteractor"; - if(this->isSolid()) ss<<", solid"; - if(this->isInverseSolid()) ss<<", inversesolid"; - if(this->isTimeDependent()) ss<<", timedependent"; - if(geoObject3D!=NULL) ss<<", AMR3DInteractor: "<<geoObject3D->toString(); - ss<<"]"; - - return ss.str(); + stringstream ss; + ss << "D3Q27TriFaceMeshInteractor[label=D3Q27TriFaceMeshInteractor"; + if (this->isSolid()) + ss << ", solid"; + if (this->isInverseSolid()) + ss << ", inversesolid"; + if (this->isTimeDependent()) + ss << ", timedependent"; + if (geoObject3D != NULL) + ss << ", AMR3DInteractor: " << geoObject3D->toString(); + ss << "]"; + + return ss.str(); } ////////////////////////////////////////////////////////////////////////// -void D3Q27TriFaceMeshInteractor::reinitWithStoredQs( const double& /*timeStep*/ ) +void D3Q27TriFaceMeshInteractor::reinitWithStoredQs(const double & /*timeStep*/) { - //alle solid Bloecke wieder solid setzen - std::vector<SPtr<Block3D>>& solidBlocks = this->getSolidBlockSet(); - for(size_t i=0; i<solidBlocks.size(); i++) - { - solidBlocks[i]->setActive(false); //<- quick n dirty - } - - //alle solid-nodes wieder solid setzen (solids die quasi in den TransBloecken liegen) - std::map<SPtr<Block3D>, std::set< UbTupleInt3 > >::iterator it1; - for( it1=this->solidNodeIndicesMap.begin(); it1!=this->solidNodeIndicesMap.end(); ++it1 ) - { - SPtr<Block3D> block = it1->first; - - SPtr<ILBMKernel> kernel = block->getKernel(); - SPtr<BCArray3D> bcMatrix = kernel->getBCProcessor()->getBCArray(); - std::set< UbTupleInt3 >& indicesSet = it1->second; - - for( std::set< UbTupleInt3 >::iterator setIt=indicesSet.begin(); setIt!=indicesSet.end(); ++setIt ) - { - bcMatrix->setSolid( val<1>(*setIt), val<2>(*setIt), val<3>(*setIt) ); - } - } - - //BCS WIEDERHERSTELLEN - std::map<SPtr<Block3D>, std::map< UbTupleInt3, std::vector<float> > >::iterator it; - for( it=bcNodeIndicesAndQsMap.begin(); it!=bcNodeIndicesAndQsMap.end(); ++it ) - { - SPtr<Block3D> block = it->first; - SPtr<ILBMKernel> kernel = block->getKernel(); - SPtr<BCArray3D> bcMatrix = kernel->getBCProcessor()->getBCArray(); - - std::map< UbTupleInt3, std::vector<float> >::iterator it2; - for( it2=it->second.begin(); it2!=it->second.end(); ++it2 ) - { - const UbTupleInt3& pos = it2->first; - std::vector< float > qs = it2->second; - - //SG_27.08.2010 - if(bcMatrix->isSolid(val<1>(pos), val<2>(pos), val<3>(pos))) continue; - - SPtr<BoundaryConditions> bc = bcMatrix->getBC( val<1>(pos), val<2>(pos), val<3>(pos) ); - if(!bc) - { - bc = SPtr<BoundaryConditions>(new BoundaryConditions); - bcMatrix->setBC( val<1>(pos), val<2>(pos), val<3>(pos), bc ); - } - - double x1w = qs[D3Q27System::FENDDIR+1+0]; - double x2w = qs[D3Q27System::FENDDIR+1+1]; - double x3w = qs[D3Q27System::FENDDIR+1+2]; - - - //TODO: HACK GEHOERT NICHT HIERHIER!!! - start - //es handelt sich un ein statisches Objekt und beim Propeller gibt - // es Schwierigkeiten an den Flügelspitzen, dass kann daher kommen, - //dass dort zuviel bc-flaggs sind und mit Geschwindigkeit ergibt dies ziemlich grosse Werte - bc->setBoundaryVelocityX1(0.0); - bc->setBoundaryVelocityX2(0.0); - bc->setBoundaryVelocityX3(0.0); - //TODO: HACK GEHOERT NICHT HIERHIER!!! - end - - bool gotQs = false; - for(int fdir=D3Q27System::FSTARTDIR; fdir<=D3Q27System::FENDDIR; fdir++) - { - if( UbMath::greater(qs[fdir], -1.0) && UbMath::less( qs[fdir], bc->getQ(fdir) ) ) - { - gotQs = true; - for(size_t index=0; index<this->bcAdapters.size(); index++) - this->bcAdapters[index]->adaptBCForDirection( *this, bc, x1w, x2w, x3w, qs[fdir], fdir); + // alle solid Bloecke wieder solid setzen + std::vector<SPtr<Block3D>> &solidBlocks = this->getSolidBlockSet(); + for (size_t i = 0; i < solidBlocks.size(); i++) { + solidBlocks[i]->setActive(false); //<- quick n dirty + } + + // alle solid-nodes wieder solid setzen (solids die quasi in den TransBloecken liegen) + std::map<SPtr<Block3D>, std::set<UbTupleInt3>>::iterator it1; + for (it1 = this->solidNodeIndicesMap.begin(); it1 != this->solidNodeIndicesMap.end(); ++it1) { + SPtr<Block3D> block = it1->first; + + SPtr<ILBMKernel> kernel = block->getKernel(); + SPtr<BCArray3D> bcMatrix = kernel->getBCProcessor()->getBCArray(); + std::set<UbTupleInt3> &indicesSet = it1->second; + + for (std::set<UbTupleInt3>::iterator setIt = indicesSet.begin(); setIt != indicesSet.end(); ++setIt) { + bcMatrix->setSolid(val<1>(*setIt), val<2>(*setIt), val<3>(*setIt)); + } + } + + // BCS WIEDERHERSTELLEN + std::map<SPtr<Block3D>, std::map<UbTupleInt3, std::vector<float>>>::iterator it; + for (it = bcNodeIndicesAndQsMap.begin(); it != bcNodeIndicesAndQsMap.end(); ++it) { + SPtr<Block3D> block = it->first; + SPtr<ILBMKernel> kernel = block->getKernel(); + SPtr<BCArray3D> bcMatrix = kernel->getBCProcessor()->getBCArray(); + + std::map<UbTupleInt3, std::vector<float>>::iterator it2; + for (it2 = it->second.begin(); it2 != it->second.end(); ++it2) { + const UbTupleInt3 &pos = it2->first; + std::vector<float> qs = it2->second; + + // SG_27.08.2010 + if (bcMatrix->isSolid(val<1>(pos), val<2>(pos), val<3>(pos))) + continue; + + SPtr<BoundaryConditions> bc = bcMatrix->getBC(val<1>(pos), val<2>(pos), val<3>(pos)); + if (!bc) { + bc = SPtr<BoundaryConditions>(new BoundaryConditions); + bcMatrix->setBC(val<1>(pos), val<2>(pos), val<3>(pos), bc); + } + + double x1w = qs[D3Q27System::FENDDIR + 1 + 0]; + double x2w = qs[D3Q27System::FENDDIR + 1 + 1]; + double x3w = qs[D3Q27System::FENDDIR + 1 + 2]; + + // TODO: HACK GEHOERT NICHT HIERHIER!!! - start + // es handelt sich un ein statisches Objekt und beim Propeller gibt + // es Schwierigkeiten an den Flügelspitzen, dass kann daher kommen, + // dass dort zuviel bc-flaggs sind und mit Geschwindigkeit ergibt dies ziemlich grosse Werte + bc->setBoundaryVelocityX1(0.0); + bc->setBoundaryVelocityX2(0.0); + bc->setBoundaryVelocityX3(0.0); + // TODO: HACK GEHOERT NICHT HIERHIER!!! - end + + bool gotQs = false; + for (int fdir = D3Q27System::FSTARTDIR; fdir <= D3Q27System::FENDDIR; fdir++) { + if (UbMath::greater(qs[fdir], -1.0) && UbMath::less(qs[fdir], bc->getQ(fdir))) { + gotQs = true; + for (size_t index = 0; index < this->bcAdapters.size(); index++) + this->bcAdapters[index]->adaptBCForDirection(*this, bc, x1w, x2w, x3w, qs[fdir], fdir); + } } - } - if(gotQs) - for(size_t index=0; index<this->bcAdapters.size(); index++) - this->bcAdapters[index]->adaptBC( *this, bc, x1w, x2w, x3w); - } - } + if (gotQs) + for (size_t index = 0; index < this->bcAdapters.size(); index++) + this->bcAdapters[index]->adaptBC(*this, bc, x1w, x2w, x3w); + } + } } ////////////////////////////////////////////////////////////////////////// -void D3Q27TriFaceMeshInteractor::updateInteractor( const double& /*timestep*//*=0*/ ) +void D3Q27TriFaceMeshInteractor::updateInteractor(const double & /*timestep*/ /*=0*/) { - UB_THROW( UbException("D3Q27TriFaceMeshInteractor::updateInteractor - toDo") ); + UB_THROW(UbException("D3Q27TriFaceMeshInteractor::updateInteractor - toDo")); } - - - - - - diff --git a/src/cpu/VirtualFluidsCore/Interactors/D3Q27TriFaceMeshInteractor.h b/src/cpu/VirtualFluidsCore/Interactors/D3Q27TriFaceMeshInteractor.h index 70e1b2d254e5d1b9e5b0f946f3cc87a223dc9529..ebd707a41ca454cb1e8b22f0020cfd98cadfab36 100644 --- a/src/cpu/VirtualFluidsCore/Interactors/D3Q27TriFaceMeshInteractor.h +++ b/src/cpu/VirtualFluidsCore/Interactors/D3Q27TriFaceMeshInteractor.h @@ -1,13 +1,13 @@ #ifndef D3Q19AMRTRIFACEMESHINTERACTOR_H #define D3Q19AMRTRIFACEMESHINTERACTOR_H +#include <PointerDefinitions.h> +#include <map> #include <string> #include <vector> -#include <map> -#include <PointerDefinitions.h> -#include "D3Q27Interactor.h" #include "CbArray3D.h" +#include "D3Q27Interactor.h" class GbObject3D; class Grid3D; @@ -15,91 +15,113 @@ class BCAdapter; class GbTriFaceMesh3D; class Block3D; -class D3Q27TriFaceMeshInteractor : public D3Q27Interactor +class D3Q27TriFaceMeshInteractor : public D3Q27Interactor { public: - static const int STRESSNORMAL=0; - static const int STRESSALTERNATIV=1; - - D3Q27TriFaceMeshInteractor(); - D3Q27TriFaceMeshInteractor(SPtr<Grid3D> grid, std::string name="D3Q27TriFaceMeshInteractor"); - D3Q27TriFaceMeshInteractor(SPtr<GbObject3D> geoObject3D, SPtr<Grid3D> grid, int type); - D3Q27TriFaceMeshInteractor(SPtr<GbTriFaceMesh3D> triFaceMesh, SPtr<Grid3D> grid, SPtr<BCAdapter> bcAdapter, int type); - D3Q27TriFaceMeshInteractor(SPtr<GbTriFaceMesh3D> triFaceMesh, SPtr<Grid3D> grid, SPtr<BCAdapter> bcAdapter, int type, Interactor3D::Accuracy a); - //D3Q27TriFaceMeshInteractor(SPtr<GbTriFaceMesh3D> triFaceMesh, D3Q27BoundaryConditionAdapterPtr bcAdapter, int type, std::string name="D3Q27TriFaceMeshInteractor"); - - ~D3Q27TriFaceMeshInteractor() override; - - void initInteractor(const double& timeStep=0) override; - virtual void initInteractor2(const double& timeStep=0); - - void updateInteractor(const double& timestep=0) override; - - void updateMovedGeometry(const double& timeStep=0); - void setQs(const double& timeStep); - void refineBlockGridToLevel(int level, double startDistance, double stopDistance); - - bool setDifferencesToGbObject3D(const SPtr<Block3D> block/*,const double& orgX1,const double& orgX2,const double& orgX3,const double& blockLengthX1,const double& blockLengthX2,const double& blockLengthX3, const double& timestep=0*/) override; - - void setRegardPointInObjectTest( bool opt ) { this->regardPIOTest = opt; } - - ObObject* clone() { throw UbException(UB_EXARGS,"not implemented"); } - - UbTupleDouble3 getForces() override; - UbTupleDouble3 getForcesTriangle(); - - void setStressMode(int stressMode) { this->stressMode = stressMode; } - void setUseHalfSpaceCheck(bool useHalfSpace ) { this->useHalfSpace = useHalfSpace; } - //void setReinitWithStoredQs(bool reinitWithStoredQsFlag) { this->reinitWithStoredQsFlag = reinitWithStoredQsFlag; } - - void calculateForces(); - void calculateStresses(); - void calculateStressesAlternativ(); - - void calcStressesLine(UbTupleDouble6& stresses, const double& weight, const UbTupleDouble6& stvW, const UbTupleDouble6& stvE ); - void calcStressesFace(UbTupleDouble6& stresses, const double& weightX, const double& weightY, const UbTupleDouble6& stvSW, const UbTupleDouble6& stvSE, const UbTupleDouble6& stvNE, const UbTupleDouble6& stvNW ); - void calcStressesCube(UbTupleDouble6& stresses, const double& weightX, const double& weightY, const double& weightZ, const UbTupleDouble6& stvBSW, const UbTupleDouble6& stvBSE, const UbTupleDouble6& stvBNE, const UbTupleDouble6& stvBNW, const UbTupleDouble6& stvTSW, const UbTupleDouble6& stvTSE, const UbTupleDouble6& stvTNE, const UbTupleDouble6& stvTNW ); - - void calculatePressure(); - void calcPressureLine(double &p, const double& weight, const double& pW, const double& pE ); - void calcPressureFace(double &p, const double& weightX, const double& weightY, const double& pSW, const double& pSE, const double& pNE, const double& pNW ); - void calcPressureCube(double &p, const double& weightX, const double& weightY, const double& weightZ, const double& pBSW, const double& pBSE, const double& pBNE, const double& pBNW, const double& pTSW, const double& pTSE, const double& pTNE, const double& pTNW ); - - void setForceShift(double forceshift) { this->forceshift = forceshift; this->forceshiftpolicy = true; } - void setVelocityShift(double velocityshift) { this->velocityshift = velocityshift; this->velocityshiftpolicy = true; } - double getForceShift() { return this->forceshift; } - double getVelocityShift() { return this->velocityshift; } - bool getForceShiftPolicy() { return forceshiftpolicy;} - bool getVelocityShiftPolicy() { return velocityshiftpolicy;} - - void clearBcNodeIndicesAndQsMap() { this->bcNodeIndicesAndQsMap.clear();} - - virtual std::string toString(); - + static const int STRESSNORMAL = 0; + static const int STRESSALTERNATIV = 1; + + D3Q27TriFaceMeshInteractor(); + D3Q27TriFaceMeshInteractor(SPtr<Grid3D> grid, std::string name = "D3Q27TriFaceMeshInteractor"); + D3Q27TriFaceMeshInteractor(SPtr<GbObject3D> geoObject3D, SPtr<Grid3D> grid, int type); + D3Q27TriFaceMeshInteractor(SPtr<GbTriFaceMesh3D> triFaceMesh, SPtr<Grid3D> grid, SPtr<BCAdapter> bcAdapter, + int type); + D3Q27TriFaceMeshInteractor(SPtr<GbTriFaceMesh3D> triFaceMesh, SPtr<Grid3D> grid, SPtr<BCAdapter> bcAdapter, + int type, Interactor3D::Accuracy a); + // D3Q27TriFaceMeshInteractor(SPtr<GbTriFaceMesh3D> triFaceMesh, D3Q27BoundaryConditionAdapterPtr bcAdapter, int + // type, std::string name="D3Q27TriFaceMeshInteractor"); + + ~D3Q27TriFaceMeshInteractor() override; + + void initInteractor(const double &timeStep = 0) override; + virtual void initInteractor2(const double &timeStep = 0); + + void updateInteractor(const double ×tep = 0) override; + + void updateMovedGeometry(const double &timeStep = 0); + void setQs(const double &timeStep); + void refineBlockGridToLevel(int level, double startDistance, double stopDistance); + + bool setDifferencesToGbObject3D(const SPtr<Block3D> block/*,const double& orgX1,const double& orgX2,const double& orgX3,const double& blockLengthX1,const double& blockLengthX2,const double& blockLengthX3, const double& timestep=0*/) override; + + void setRegardPointInObjectTest(bool opt) { this->regardPIOTest = opt; } + + ObObject *clone() { throw UbException(UB_EXARGS, "not implemented"); } + + UbTupleDouble3 getForces() override; + UbTupleDouble3 getForcesTriangle(); + + void setStressMode(int stressMode) { this->stressMode = stressMode; } + void setUseHalfSpaceCheck(bool useHalfSpace) { this->useHalfSpace = useHalfSpace; } + // void setReinitWithStoredQs(bool reinitWithStoredQsFlag) { this->reinitWithStoredQsFlag = reinitWithStoredQsFlag; + // } + + void calculateForces(); + void calculateStresses(); + void calculateStressesAlternativ(); + + void calcStressesLine(UbTupleDouble6 &stresses, const double &weight, const UbTupleDouble6 &stvW, + const UbTupleDouble6 &stvE); + void calcStressesFace(UbTupleDouble6 &stresses, const double &weightX, const double &weightY, + const UbTupleDouble6 &stvSW, const UbTupleDouble6 &stvSE, const UbTupleDouble6 &stvNE, + const UbTupleDouble6 &stvNW); + void calcStressesCube(UbTupleDouble6 &stresses, const double &weightX, const double &weightY, const double &weightZ, + const UbTupleDouble6 &stvBSW, const UbTupleDouble6 &stvBSE, const UbTupleDouble6 &stvBNE, + const UbTupleDouble6 &stvBNW, const UbTupleDouble6 &stvTSW, const UbTupleDouble6 &stvTSE, + const UbTupleDouble6 &stvTNE, const UbTupleDouble6 &stvTNW); + + void calculatePressure(); + void calcPressureLine(double &p, const double &weight, const double &pW, const double &pE); + void calcPressureFace(double &p, const double &weightX, const double &weightY, const double &pSW, const double &pSE, + const double &pNE, const double &pNW); + void calcPressureCube(double &p, const double &weightX, const double &weightY, const double &weightZ, + const double &pBSW, const double &pBSE, const double &pBNE, const double &pBNW, + const double &pTSW, const double &pTSE, const double &pTNE, const double &pTNW); + + void setForceShift(double forceshift) + { + this->forceshift = forceshift; + this->forceshiftpolicy = true; + } + void setVelocityShift(double velocityshift) + { + this->velocityshift = velocityshift; + this->velocityshiftpolicy = true; + } + double getForceShift() { return this->forceshift; } + double getVelocityShift() { return this->velocityshift; } + bool getForceShiftPolicy() { return forceshiftpolicy; } + bool getVelocityShiftPolicy() { return velocityshiftpolicy; } + + void clearBcNodeIndicesAndQsMap() { this->bcNodeIndicesAndQsMap.clear(); } + + virtual std::string toString(); protected: - int stressMode; - - double forceshift{0.0}; - double velocityshift{0.0}; - bool forceshiftpolicy{false}; - bool velocityshiftpolicy{false}; - bool useHalfSpace{true}; - bool regardPIOTest{true}; - - void reinitWithStoredQs(const double& timeStep); - // bool reinitWithStoredQsFlag; - std::map< SPtr<Block3D>, std::map < UbTupleInt3, std::vector< float > > > bcNodeIndicesAndQsMap; //!!! es kann sein, dass in diesem interactor - //an eine rpos eine BC gesetzt wurde, aber derselbe node in - //in einem anderen in einen anderen Typ (z.B. Solid) geaendert - //wurde --> es ist keine BC mehr an der stelle! - - enum SolidCheckMethod { ScanLine, PointInObject }; - - enum FLAGS { BC_FLAG, UNDEF_FLAG, FLUID_FLAG, SOLID_FLAG, OLDSOLID_FLAG }; - void recursiveGridFill(CbArray3D<FLAGS>& flagfield, const short& xs, const short& ys, const short& zs, const FLAGS& type); - void iterativeGridFill(CbArray3D<FLAGS>& flagfield, const short& xs, const short& ys, const short& zs, const FLAGS& type); + int stressMode; + + double forceshift{ 0.0 }; + double velocityshift{ 0.0 }; + bool forceshiftpolicy{ false }; + bool velocityshiftpolicy{ false }; + bool useHalfSpace{ true }; + bool regardPIOTest{ true }; + + void reinitWithStoredQs(const double &timeStep); + // bool reinitWithStoredQsFlag; + std::map<SPtr<Block3D>, std::map<UbTupleInt3, std::vector<float>>> + bcNodeIndicesAndQsMap; //!!! es kann sein, dass in diesem interactor + // an eine rpos eine BC gesetzt wurde, aber derselbe node in + // in einem anderen in einen anderen Typ (z.B. Solid) geaendert + // wurde --> es ist keine BC mehr an der stelle! + + enum SolidCheckMethod { ScanLine, PointInObject }; + + enum FLAGS { BC_FLAG, UNDEF_FLAG, FLUID_FLAG, SOLID_FLAG, OLDSOLID_FLAG }; + void recursiveGridFill(CbArray3D<FLAGS> &flagfield, const short &xs, const short &ys, const short &zs, + const FLAGS &type); + void iterativeGridFill(CbArray3D<FLAGS> &flagfield, const short &xs, const short &ys, const short &zs, + const FLAGS &type); }; - -#endif +#endif diff --git a/src/cpu/VirtualFluidsCore/Interactors/Interactor3D.cpp b/src/cpu/VirtualFluidsCore/Interactors/Interactor3D.cpp index 0899c8634a887c9e9af36c40830c1d3b1dcab347..0127c9c880f03d574f657ebc43e53ccaa4b67c7e 100644 --- a/src/cpu/VirtualFluidsCore/Interactors/Interactor3D.cpp +++ b/src/cpu/VirtualFluidsCore/Interactors/Interactor3D.cpp @@ -1,28 +1,28 @@ //======================================================================================= -// ____ ____ __ ______ __________ __ __ __ __ -// \ \ | | | | | _ \ |___ ___| | | | | / \ | | -// \ \ | | | | | |_) | | | | | | | / \ | | -// \ \ | | | | | _ / | | | | | | / /\ \ | | -// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ -// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| -// \ \ | | ________________________________________________________________ -// \ \ | | | ______________________________________________________________| -// \ \| | | | __ __ __ __ ______ _______ -// \ | | |_____ | | | | | | | | | _ \ / _____) -// \ | | _____| | | | | | | | | | | \ \ \_______ +// ____ ____ __ ______ __________ __ __ __ __ +// \ \ | | | | | _ \ |___ ___| | | | | / \ | | +// \ \ | | | | | |_) | | | | | | | / \ | | +// \ \ | | | | | _ / | | | | | | / /\ \ | | +// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ +// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| +// \ \ | | ________________________________________________________________ +// \ \ | | | ______________________________________________________________| +// \ \| | | | __ __ __ __ ______ _______ +// \ | | |_____ | | | | | | | | | _ \ / _____) +// \ | | _____| | | | | | | | | | | \ \ \_______ // \ | | | | |_____ | \_/ | | | | |_/ / _____ | -// \ _____| |__| |________| \_______/ |__| |______/ (_______/ +// \ _____| |__| |________| \_______/ |__| |______/ (_______/ // -// This file is part of VirtualFluids. VirtualFluids is free software: you can +// This file is part of VirtualFluids. VirtualFluids is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of +// License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. -// -// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// +// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License along // with VirtualFluids (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>. // @@ -33,312 +33,274 @@ #include "Interactor3D.h" +#include "UbException.h" +#include <basics/utilities/UbMath.h> #include <fstream> #include <geometry3d/GbCuboid3D.h> -#include <basics/utilities/UbMath.h> -#include "UbException.h" -#include "Grid3D.h" #include "Block3D.h" #include "GbObject3D.h" - +#include "Grid3D.h" using namespace std; -const int Interactor3D::SOLID = (1<<0); //1 -const int Interactor3D::INVERSESOLID = (1<<1); //2 -const int Interactor3D::TIMEDEPENDENT = (1<<2); //4 //zeitlich -const int Interactor3D::FLUID = (1<<3); //8 -const int Interactor3D::MOVEABLE = (1<<4); //16 // geometrisch -const int Interactor3D::CHANGENOTNECESSARY = (1<<5); //32 - - +const int Interactor3D::SOLID = (1 << 0); // 1 +const int Interactor3D::INVERSESOLID = (1 << 1); // 2 +const int Interactor3D::TIMEDEPENDENT = (1 << 2); // 4 //zeitlich +const int Interactor3D::FLUID = (1 << 3); // 8 +const int Interactor3D::MOVEABLE = (1 << 4); // 16 // geometrisch +const int Interactor3D::CHANGENOTNECESSARY = (1 << 5); // 32 ////////////////////////////////////////////////////////////////////////// -Interactor3D::Interactor3D() - : type(SOLID) -{ - -} +Interactor3D::Interactor3D() : type(SOLID) {} ////////////////////////////////////////////////////////////////////////// -Interactor3D::Interactor3D(SPtr<Grid3D> grid, int type) - : grid(grid), type(type) -{ - -} +Interactor3D::Interactor3D(SPtr<Grid3D> grid, int type) : grid(grid), type(type) {} ////////////////////////////////////////////////////////////////////////// Interactor3D::Interactor3D(SPtr<GbObject3D> geoObject3D, SPtr<Grid3D> grid, int type) - : geoObject3D(geoObject3D) - , grid(grid) - , type(type) - , accuracy(SIMPLE) + : geoObject3D(geoObject3D), grid(grid), type(type), accuracy(SIMPLE) { - } ////////////////////////////////////////////////////////////////////////// Interactor3D::Interactor3D(SPtr<GbObject3D> geoObject3D, SPtr<Grid3D> grid, int type, Interactor3D::Accuracy a) - : geoObject3D(geoObject3D) - , grid(grid) - , type(type) - , accuracy(a) + : geoObject3D(geoObject3D), grid(grid), type(type), accuracy(a) { - } ////////////////////////////////////////////////////////////////////////// -Interactor3D::~Interactor3D() -= default; +Interactor3D::~Interactor3D() = default; ////////////////////////////////////////////////////////////////////////// -bool Interactor3D::arePointsInsideGeoObject(double minX1, double minX2, double minX3, double maxX1, double maxX2, double maxX3, double delta) +bool Interactor3D::arePointsInsideGeoObject(double minX1, double minX2, double minX3, double maxX1, double maxX2, + double maxX3, double delta) { - bool result = true; - for (double ix3=minX3; ix3<=maxX3; ix3+=delta) - for (double ix2=minX2; ix2<=maxX2; ix2+=delta) - for (double ix1=minX1; ix1<=maxX1; ix1+=delta) - result = result && this->geoObject3D->isPointInGbObject3D(ix1, ix2, ix3); + bool result = true; + for (double ix3 = minX3; ix3 <= maxX3; ix3 += delta) + for (double ix2 = minX2; ix2 <= maxX2; ix2 += delta) + for (double ix1 = minX1; ix1 <= maxX1; ix1 += delta) + result = result && this->geoObject3D->isPointInGbObject3D(ix1, ix2, ix3); - return result; + return result; } ////////////////////////////////////////////////////////////////////////// -bool Interactor3D::arePointsOutsideGeoObject(double minX1, double minX2, double minX3, double maxX1, double maxX2, double maxX3, double delta) +bool Interactor3D::arePointsOutsideGeoObject(double minX1, double minX2, double minX3, double maxX1, double maxX2, + double maxX3, double delta) { - bool result = true; - for (double ix3=minX3; ix3<=maxX3; ix3+=delta) - for (double ix2=minX2; ix2<=maxX2; ix2+=delta) - for (double ix1=minX1; ix1<=maxX1; ix1+=delta) - result = result && (!this->geoObject3D->isPointInGbObject3D(ix1, ix2, ix3)); + bool result = true; + for (double ix3 = minX3; ix3 <= maxX3; ix3 += delta) + for (double ix2 = minX2; ix2 <= maxX2; ix2 += delta) + for (double ix1 = minX1; ix1 <= maxX1; ix1 += delta) + result = result && (!this->geoObject3D->isPointInGbObject3D(ix1, ix2, ix3)); - return result; + return result; } ////////////////////////////////////////////////////////////////////////// -bool Interactor3D::arePointsCuttingGeoObject(double minX1, double minX2, double minX3, double maxX1, double maxX2, double maxX3, double delta) +bool Interactor3D::arePointsCuttingGeoObject(double minX1, double minX2, double minX3, double maxX1, double maxX2, + double maxX3, double delta) { - bool result = true; - for (double ix3=minX3; ix3<=maxX3; ix3+=delta) - for (double ix2=minX2; ix2<=maxX2; ix2+=delta) - for (double ix1=minX1; ix1<=maxX1; ix1+=delta) - result = result || this->geoObject3D->isPointInGbObject3D(ix1, ix2, ix3); + bool result = true; + for (double ix3 = minX3; ix3 <= maxX3; ix3 += delta) + for (double ix2 = minX2; ix2 <= maxX2; ix2 += delta) + for (double ix1 = minX1; ix1 <= maxX1; ix1 += delta) + result = result || this->geoObject3D->isPointInGbObject3D(ix1, ix2, ix3); - return result; + return result; } ////////////////////////////////////////////////////////////////////////// -bool Interactor3D::isBlockOutsideGeoObject(double minX1, double minX2, double minX3, double maxX1, double maxX2, double maxX3, double delta) +bool Interactor3D::isBlockOutsideGeoObject(double minX1, double minX2, double minX3, double maxX1, double maxX2, + double maxX3, double delta) { - switch (accuracy) - { - //simple duff - case SIMPLE: - return !this->geoObject3D->isCellInsideOrCuttingGbObject3D(minX1,minX2,minX3,maxX1,maxX2,maxX3); - //test only edges - case EDGES: - return arePointsOutsideGeoObject(minX1, minX2, minX3, maxX1, minX2, minX3, delta) && - arePointsOutsideGeoObject(minX1, maxX2, minX3, maxX1, maxX2, minX3, delta) && - arePointsOutsideGeoObject(minX1, minX2, maxX3, maxX1, minX2, maxX3, delta) && - arePointsOutsideGeoObject(minX1, maxX2, maxX3, maxX1, maxX2, maxX3, delta) && - - arePointsOutsideGeoObject(minX1, minX2, minX3, minX1, maxX2, minX3, delta) && - arePointsOutsideGeoObject(maxX1, minX2, minX3, maxX1, maxX2, minX3, delta) && - arePointsOutsideGeoObject(minX1, minX2, maxX3, maxX1, minX2, maxX3, delta) && - arePointsOutsideGeoObject(maxX1, minX2, maxX3, maxX1, maxX2, maxX3, delta) && - - arePointsOutsideGeoObject(minX1, minX2, minX3, minX1, maxX2, maxX3, delta) && - arePointsOutsideGeoObject(maxX1, minX2, minX3, maxX1, maxX2, maxX3, delta) && - arePointsOutsideGeoObject(minX1, maxX2, minX3, maxX1, minX2, maxX3, delta) && - arePointsOutsideGeoObject(maxX1, maxX2, minX3, maxX1, maxX2, maxX3, delta); - //test only faces - case FACES: - return arePointsOutsideGeoObject(minX1, minX2, minX3, minX1, maxX2, maxX3, delta) && - arePointsOutsideGeoObject(maxX1, minX2, minX3, maxX1, maxX2, maxX3, delta) && - arePointsOutsideGeoObject(minX1, minX2, minX3, maxX1, minX2, maxX3, delta) && - arePointsOutsideGeoObject(minX1, maxX2, minX3, maxX1, maxX2, maxX3, delta) && - arePointsOutsideGeoObject(minX1, minX2, minX3, maxX1, maxX2, minX3, delta) && - arePointsOutsideGeoObject(minX1, minX2, maxX3, maxX1, maxX2, maxX3, delta); - //test all points - case POINTS: - return arePointsOutsideGeoObject(minX1, minX2, minX3, maxX1, maxX2, maxX3, delta); - default: - UB_THROW( UbException(UB_EXARGS, "Accuracy isn't correct") ); - break; - } + switch (accuracy) { + // simple duff + case SIMPLE: + return !this->geoObject3D->isCellInsideOrCuttingGbObject3D(minX1, minX2, minX3, maxX1, maxX2, maxX3); + // test only edges + case EDGES: + return arePointsOutsideGeoObject(minX1, minX2, minX3, maxX1, minX2, minX3, delta) && + arePointsOutsideGeoObject(minX1, maxX2, minX3, maxX1, maxX2, minX3, delta) && + arePointsOutsideGeoObject(minX1, minX2, maxX3, maxX1, minX2, maxX3, delta) && + arePointsOutsideGeoObject(minX1, maxX2, maxX3, maxX1, maxX2, maxX3, delta) && + + arePointsOutsideGeoObject(minX1, minX2, minX3, minX1, maxX2, minX3, delta) && + arePointsOutsideGeoObject(maxX1, minX2, minX3, maxX1, maxX2, minX3, delta) && + arePointsOutsideGeoObject(minX1, minX2, maxX3, maxX1, minX2, maxX3, delta) && + arePointsOutsideGeoObject(maxX1, minX2, maxX3, maxX1, maxX2, maxX3, delta) && + + arePointsOutsideGeoObject(minX1, minX2, minX3, minX1, maxX2, maxX3, delta) && + arePointsOutsideGeoObject(maxX1, minX2, minX3, maxX1, maxX2, maxX3, delta) && + arePointsOutsideGeoObject(minX1, maxX2, minX3, maxX1, minX2, maxX3, delta) && + arePointsOutsideGeoObject(maxX1, maxX2, minX3, maxX1, maxX2, maxX3, delta); + // test only faces + case FACES: + return arePointsOutsideGeoObject(minX1, minX2, minX3, minX1, maxX2, maxX3, delta) && + arePointsOutsideGeoObject(maxX1, minX2, minX3, maxX1, maxX2, maxX3, delta) && + arePointsOutsideGeoObject(minX1, minX2, minX3, maxX1, minX2, maxX3, delta) && + arePointsOutsideGeoObject(minX1, maxX2, minX3, maxX1, maxX2, maxX3, delta) && + arePointsOutsideGeoObject(minX1, minX2, minX3, maxX1, maxX2, minX3, delta) && + arePointsOutsideGeoObject(minX1, minX2, maxX3, maxX1, maxX2, maxX3, delta); + // test all points + case POINTS: + return arePointsOutsideGeoObject(minX1, minX2, minX3, maxX1, maxX2, maxX3, delta); + default: + UB_THROW(UbException(UB_EXARGS, "Accuracy isn't correct")); + break; + } } ////////////////////////////////////////////////////////////////////////// -bool Interactor3D::isBlockInsideGeoObject(double minX1, double minX2, double minX3, double maxX1, double maxX2, double maxX3, double delta) +bool Interactor3D::isBlockInsideGeoObject(double minX1, double minX2, double minX3, double maxX1, double maxX2, + double maxX3, double delta) { - switch (accuracy) - { - //simple duff - case SIMPLE: - return this->geoObject3D->isCellInsideGbObject3D(minX1,minX2,minX3,maxX1,maxX2,maxX3); - //test only edges - case EDGES: - return arePointsInsideGeoObject(minX1, minX2, minX3, maxX1, minX2, minX3, delta) && - arePointsInsideGeoObject(minX1, maxX2, minX3, maxX1, maxX2, minX3, delta) && - arePointsInsideGeoObject(minX1, minX2, maxX3, maxX1, minX2, maxX3, delta) && - arePointsInsideGeoObject(minX1, maxX2, maxX3, maxX1, maxX2, maxX3, delta) && - - arePointsInsideGeoObject(minX1, minX2, minX3, minX1, maxX2, minX3, delta) && - arePointsInsideGeoObject(maxX1, minX2, minX3, maxX1, maxX2, minX3, delta) && - arePointsInsideGeoObject(minX1, minX2, maxX3, maxX1, minX2, maxX3, delta) && - arePointsInsideGeoObject(maxX1, minX2, maxX3, maxX1, maxX2, maxX3, delta) && - - arePointsInsideGeoObject(minX1, minX2, minX3, minX1, maxX2, maxX3, delta) && - arePointsInsideGeoObject(maxX1, minX2, minX3, maxX1, maxX2, maxX3, delta) && - arePointsInsideGeoObject(minX1, maxX2, minX3, maxX1, minX2, maxX3, delta) && - arePointsInsideGeoObject(maxX1, maxX2, minX3, maxX1, maxX2, maxX3, delta); - //test only faces - case FACES: - return arePointsInsideGeoObject(minX1, minX2, minX3, minX1, maxX2, maxX3, delta) && - arePointsInsideGeoObject(maxX1, minX2, minX3, maxX1, maxX2, maxX3, delta) && - arePointsInsideGeoObject(minX1, minX2, minX3, maxX1, minX2, maxX3, delta) && - arePointsInsideGeoObject(minX1, maxX2, minX3, maxX1, maxX2, maxX3, delta) && - arePointsInsideGeoObject(minX1, minX2, minX3, maxX1, maxX2, minX3, delta) && - arePointsInsideGeoObject(minX1, minX2, maxX3, maxX1, maxX2, maxX3, delta); - //test all points - case POINTS: - return arePointsInsideGeoObject(minX1, minX2, minX3, maxX1, maxX2, maxX3, delta); - default: - UB_THROW( UbException(UB_EXARGS, "Accuracy isn't correct") ); - break; - } + switch (accuracy) { + // simple duff + case SIMPLE: + return this->geoObject3D->isCellInsideGbObject3D(minX1, minX2, minX3, maxX1, maxX2, maxX3); + // test only edges + case EDGES: + return arePointsInsideGeoObject(minX1, minX2, minX3, maxX1, minX2, minX3, delta) && + arePointsInsideGeoObject(minX1, maxX2, minX3, maxX1, maxX2, minX3, delta) && + arePointsInsideGeoObject(minX1, minX2, maxX3, maxX1, minX2, maxX3, delta) && + arePointsInsideGeoObject(minX1, maxX2, maxX3, maxX1, maxX2, maxX3, delta) && + + arePointsInsideGeoObject(minX1, minX2, minX3, minX1, maxX2, minX3, delta) && + arePointsInsideGeoObject(maxX1, minX2, minX3, maxX1, maxX2, minX3, delta) && + arePointsInsideGeoObject(minX1, minX2, maxX3, maxX1, minX2, maxX3, delta) && + arePointsInsideGeoObject(maxX1, minX2, maxX3, maxX1, maxX2, maxX3, delta) && + + arePointsInsideGeoObject(minX1, minX2, minX3, minX1, maxX2, maxX3, delta) && + arePointsInsideGeoObject(maxX1, minX2, minX3, maxX1, maxX2, maxX3, delta) && + arePointsInsideGeoObject(minX1, maxX2, minX3, maxX1, minX2, maxX3, delta) && + arePointsInsideGeoObject(maxX1, maxX2, minX3, maxX1, maxX2, maxX3, delta); + // test only faces + case FACES: + return arePointsInsideGeoObject(minX1, minX2, minX3, minX1, maxX2, maxX3, delta) && + arePointsInsideGeoObject(maxX1, minX2, minX3, maxX1, maxX2, maxX3, delta) && + arePointsInsideGeoObject(minX1, minX2, minX3, maxX1, minX2, maxX3, delta) && + arePointsInsideGeoObject(minX1, maxX2, minX3, maxX1, maxX2, maxX3, delta) && + arePointsInsideGeoObject(minX1, minX2, minX3, maxX1, maxX2, minX3, delta) && + arePointsInsideGeoObject(minX1, minX2, maxX3, maxX1, maxX2, maxX3, delta); + // test all points + case POINTS: + return arePointsInsideGeoObject(minX1, minX2, minX3, maxX1, maxX2, maxX3, delta); + default: + UB_THROW(UbException(UB_EXARGS, "Accuracy isn't correct")); + break; + } } ////////////////////////////////////////////////////////////////////////// -bool Interactor3D::isBlockCuttingGeoObject(double minX1, double minX2, double minX3, double maxX1, double maxX2, double maxX3, double delta) +bool Interactor3D::isBlockCuttingGeoObject(double minX1, double minX2, double minX3, double maxX1, double maxX2, + double maxX3, double delta) { - switch (accuracy) - { - //simple duff - case SIMPLE: - return this->geoObject3D->isCellCuttingGbObject3D(minX1,minX2,minX3,maxX1,maxX2,maxX3); - //test only edges - case EDGES: - return arePointsCuttingGeoObject(minX1, minX2, minX3, maxX1, minX2, minX3, delta) || - arePointsCuttingGeoObject(minX1, maxX2, minX3, maxX1, maxX2, minX3, delta) || - arePointsCuttingGeoObject(minX1, minX2, maxX3, maxX1, minX2, maxX3, delta) || - arePointsCuttingGeoObject(minX1, maxX2, maxX3, maxX1, maxX2, maxX3, delta) || - - arePointsCuttingGeoObject(minX1, minX2, minX3, minX1, maxX2, minX3, delta) || - arePointsCuttingGeoObject(maxX1, minX2, minX3, maxX1, maxX2, minX3, delta) || - arePointsCuttingGeoObject(minX1, minX2, maxX3, maxX1, minX2, maxX3, delta) || - arePointsCuttingGeoObject(maxX1, minX2, maxX3, maxX1, maxX2, maxX3, delta) || - - arePointsCuttingGeoObject(minX1, minX2, minX3, minX1, maxX2, maxX3, delta) || - arePointsCuttingGeoObject(maxX1, minX2, minX3, maxX1, maxX2, maxX3, delta) || - arePointsCuttingGeoObject(minX1, maxX2, minX3, maxX1, minX2, maxX3, delta) || - arePointsCuttingGeoObject(maxX1, maxX2, minX3, maxX1, maxX2, maxX3, delta); - //test only faceCutting - case FACES: - return arePointsCuttingGeoObject(minX1, minX2, minX3, minX1, maxX2, maxX3, delta) || - arePointsCuttingGeoObject(maxX1, minX2, minX3, maxX1, maxX2, maxX3, delta) || - arePointsCuttingGeoObject(minX1, minX2, minX3, maxX1, minX2, maxX3, delta) || - arePointsCuttingGeoObject(minX1, maxX2, minX3, maxX1, maxX2, maxX3, delta) || - arePointsCuttingGeoObject(minX1, minX2, minX3, maxX1, maxX2, minX3, delta) || - arePointsCuttingGeoObject(minX1, minX2, maxX3, maxX1, maxX2, maxX3, delta); - //test all pointCutting - case POINTS: - return arePointsCuttingGeoObject(minX1, minX2, minX3, maxX1, maxX2, maxX3, delta); - default: - UB_THROW( UbException(UB_EXARGS, "Accuracy isn't correct") ); - break; - } + switch (accuracy) { + // simple duff + case SIMPLE: + return this->geoObject3D->isCellCuttingGbObject3D(minX1, minX2, minX3, maxX1, maxX2, maxX3); + // test only edges + case EDGES: + return arePointsCuttingGeoObject(minX1, minX2, minX3, maxX1, minX2, minX3, delta) || + arePointsCuttingGeoObject(minX1, maxX2, minX3, maxX1, maxX2, minX3, delta) || + arePointsCuttingGeoObject(minX1, minX2, maxX3, maxX1, minX2, maxX3, delta) || + arePointsCuttingGeoObject(minX1, maxX2, maxX3, maxX1, maxX2, maxX3, delta) || + + arePointsCuttingGeoObject(minX1, minX2, minX3, minX1, maxX2, minX3, delta) || + arePointsCuttingGeoObject(maxX1, minX2, minX3, maxX1, maxX2, minX3, delta) || + arePointsCuttingGeoObject(minX1, minX2, maxX3, maxX1, minX2, maxX3, delta) || + arePointsCuttingGeoObject(maxX1, minX2, maxX3, maxX1, maxX2, maxX3, delta) || + + arePointsCuttingGeoObject(minX1, minX2, minX3, minX1, maxX2, maxX3, delta) || + arePointsCuttingGeoObject(maxX1, minX2, minX3, maxX1, maxX2, maxX3, delta) || + arePointsCuttingGeoObject(minX1, maxX2, minX3, maxX1, minX2, maxX3, delta) || + arePointsCuttingGeoObject(maxX1, maxX2, minX3, maxX1, maxX2, maxX3, delta); + // test only faceCutting + case FACES: + return arePointsCuttingGeoObject(minX1, minX2, minX3, minX1, maxX2, maxX3, delta) || + arePointsCuttingGeoObject(maxX1, minX2, minX3, maxX1, maxX2, maxX3, delta) || + arePointsCuttingGeoObject(minX1, minX2, minX3, maxX1, minX2, maxX3, delta) || + arePointsCuttingGeoObject(minX1, maxX2, minX3, maxX1, maxX2, maxX3, delta) || + arePointsCuttingGeoObject(minX1, minX2, minX3, maxX1, maxX2, minX3, delta) || + arePointsCuttingGeoObject(minX1, minX2, maxX3, maxX1, maxX2, maxX3, delta); + // test all pointCutting + case POINTS: + return arePointsCuttingGeoObject(minX1, minX2, minX3, maxX1, maxX2, maxX3, delta); + default: + UB_THROW(UbException(UB_EXARGS, "Accuracy isn't correct")); + break; + } } ////////////////////////////////////////////////////////////////////////// void Interactor3D::setSolidBlock(SPtr<Block3D> block) { - double minX1,minX2,minX3,maxX1,maxX2,maxX3; + double minX1, minX2, minX3, maxX1, maxX2, maxX3; - double deltaX = grid.lock()->getDeltaX(block); - UbTupleDouble3 blockLengths = grid.lock()->getBlockLengths(block); - UbTupleDouble3 org = grid.lock()->getBlockWorldCoordinates(block); - UbTupleDouble3 nodeOffset = grid.lock()->getNodeOffset(block); + double deltaX = grid.lock()->getDeltaX(block); + UbTupleDouble3 blockLengths = grid.lock()->getBlockLengths(block); + UbTupleDouble3 org = grid.lock()->getBlockWorldCoordinates(block); + UbTupleDouble3 nodeOffset = grid.lock()->getNodeOffset(block); - //coordinates of block without ghost layer - minX1 = val<1>(org) + val<1>(nodeOffset); - minX2 = val<2>(org) + val<2>(nodeOffset); - minX3 = val<3>(org) + val<3>(nodeOffset); - maxX1 = val<1>(org) + val<1>(blockLengths) - val<1>(nodeOffset); - maxX2 = val<2>(org) + val<2>(blockLengths) - val<2>(nodeOffset); - maxX3 = val<3>(org) + val<3>(blockLengths) - val<3>(nodeOffset); + // coordinates of block without ghost layer + minX1 = val<1>(org) + val<1>(nodeOffset); + minX2 = val<2>(org) + val<2>(nodeOffset); + minX3 = val<3>(org) + val<3>(nodeOffset); + maxX1 = val<1>(org) + val<1>(blockLengths) - val<1>(nodeOffset); + maxX2 = val<2>(org) + val<2>(blockLengths) - val<2>(nodeOffset); + maxX3 = val<3>(org) + val<3>(blockLengths) - val<3>(nodeOffset); - if(this->isInverseSolid()) - { - if(isBlockOutsideGeoObject(minX1, minX2, minX3, maxX1, maxX2, maxX3, deltaX)) - { - block->setActive(false); - this->solidBlocks.push_back(block); - } - } - else //solid - { - if(isBlockInsideGeoObject(minX1, minX2, minX3, maxX1, maxX2, maxX3, deltaX)) - { - block->setActive(false); - this->solidBlocks.push_back(block); - } - } + if (this->isInverseSolid()) { + if (isBlockOutsideGeoObject(minX1, minX2, minX3, maxX1, maxX2, maxX3, deltaX)) { + block->setActive(false); + this->solidBlocks.push_back(block); + } + } else // solid + { + if (isBlockInsideGeoObject(minX1, minX2, minX3, maxX1, maxX2, maxX3, deltaX)) { + block->setActive(false); + this->solidBlocks.push_back(block); + } + } } ////////////////////////////////////////////////////////////////////////// void Interactor3D::setBCBlock(SPtr<Block3D> block) { - double minX1,minX2,minX3,maxX1,maxX2,maxX3; + double minX1, minX2, minX3, maxX1, maxX2, maxX3; - double deltaX = grid.lock()->getDeltaX(block); - UbTupleDouble3 blockLengths = grid.lock()->getBlockLengths(block); - UbTupleDouble3 org = grid.lock()->getBlockWorldCoordinates(block); - UbTupleDouble3 nodeOffset = grid.lock()->getNodeOffset(block); + double deltaX = grid.lock()->getDeltaX(block); + UbTupleDouble3 blockLengths = grid.lock()->getBlockLengths(block); + UbTupleDouble3 org = grid.lock()->getBlockWorldCoordinates(block); + UbTupleDouble3 nodeOffset = grid.lock()->getNodeOffset(block); - //coordinates of block with ghost layer - minX1 = val<1>(org) - val<1>(nodeOffset); - minX2 = val<2>(org) - val<2>(nodeOffset); - minX3 = val<3>(org) - val<3>(nodeOffset); - maxX1 = val<1>(org) + val<1>(blockLengths) + val<1>(nodeOffset); - maxX2 = val<2>(org) + val<2>(blockLengths) + val<2>(nodeOffset); - maxX3 = val<3>(org) + val<3>(blockLengths) + val<3>(nodeOffset); + // coordinates of block with ghost layer + minX1 = val<1>(org) - val<1>(nodeOffset); + minX2 = val<2>(org) - val<2>(nodeOffset); + minX3 = val<3>(org) - val<3>(nodeOffset); + maxX1 = val<1>(org) + val<1>(blockLengths) + val<1>(nodeOffset); + maxX2 = val<2>(org) + val<2>(blockLengths) + val<2>(nodeOffset); + maxX3 = val<3>(org) + val<3>(blockLengths) + val<3>(nodeOffset); - if(isBlockCuttingGeoObject(minX1, minX2, minX3, maxX1, maxX2, maxX3, deltaX)) - this->bcBlocks.push_back(block); + if (isBlockCuttingGeoObject(minX1, minX2, minX3, maxX1, maxX2, maxX3, deltaX)) + this->bcBlocks.push_back(block); } UbTupleDouble3 Interactor3D::getForces() { - UB_THROW( UbException("UbTupleDouble3 getForces() - gehoert in die abgeleitete klasse") ); -} -void Interactor3D::setID(int id) -{ - this->id = id; + UB_THROW(UbException("UbTupleDouble3 getForces() - gehoert in die abgeleitete klasse")); } +void Interactor3D::setID(int id) { this->id = id; } ////////////////////////////////////////////////////////////////////////// -int Interactor3D::getID() -{ - return id; -} +int Interactor3D::getID() { return id; } ////////////////////////////////////////////////////////////////////////// -void Interactor3D::setActive() -{ - active = true; -} +void Interactor3D::setActive() { active = true; } ////////////////////////////////////////////////////////////////////////// -void Interactor3D::setInactive() -{ - active = false; -} +void Interactor3D::setInactive() { active = false; } ////////////////////////////////////////////////////////////////////////// -bool Interactor3D::isActive() -{ - return active; -} +bool Interactor3D::isActive() { return active; } ////////////////////////////////////////////////////////////////////////// -void Interactor3D::initInteractor(const double& /*timeStep*/) +void Interactor3D::initInteractor(const double & /*timeStep*/) { - //UBLOG(logINFO, "transBlocks.size = "<<transBlocks.size()); + // UBLOG(logINFO, "transBlocks.size = "<<transBlocks.size()); - for(SPtr<Block3D> block : bcBlocks) - { - this->setDifferencesToGbObject3D(block); - } + for (SPtr<Block3D> block : bcBlocks) { + this->setDifferencesToGbObject3D(block); + } } ////////////////////////////////////////////////////////////////////////// -void Interactor3D::updateInteractor(const double& /*timeStep*/) +void Interactor3D::updateInteractor(const double & /*timeStep*/) { - UB_THROW( UbException("Interactor3D::updateInteractor - toDo") ); + UB_THROW(UbException("Interactor3D::updateInteractor - toDo")); } ////////////////////////////////////////////////////////////////////////// - diff --git a/src/cpu/VirtualFluidsCore/Interactors/Interactor3D.h b/src/cpu/VirtualFluidsCore/Interactors/Interactor3D.h index ef7ac33dbbd1e34fa8518d3f719ccf0b8841bdf5..9bf3a03ba179a1da7fa932a209d78e39b6622bcf 100644 --- a/src/cpu/VirtualFluidsCore/Interactors/Interactor3D.h +++ b/src/cpu/VirtualFluidsCore/Interactors/Interactor3D.h @@ -1,28 +1,28 @@ //======================================================================================= -// ____ ____ __ ______ __________ __ __ __ __ -// \ \ | | | | | _ \ |___ ___| | | | | / \ | | -// \ \ | | | | | |_) | | | | | | | / \ | | -// \ \ | | | | | _ / | | | | | | / /\ \ | | -// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ -// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| -// \ \ | | ________________________________________________________________ -// \ \ | | | ______________________________________________________________| -// \ \| | | | __ __ __ __ ______ _______ -// \ | | |_____ | | | | | | | | | _ \ / _____) -// \ | | _____| | | | | | | | | | | \ \ \_______ +// ____ ____ __ ______ __________ __ __ __ __ +// \ \ | | | | | _ \ |___ ___| | | | | / \ | | +// \ \ | | | | | |_) | | | | | | | / \ | | +// \ \ | | | | | _ / | | | | | | / /\ \ | | +// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ +// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| +// \ \ | | ________________________________________________________________ +// \ \ | | | ______________________________________________________________| +// \ \| | | | __ __ __ __ ______ _______ +// \ | | |_____ | | | | | | | | | _ \ / _____) +// \ | | _____| | | | | | | | | | | \ \ \_______ // \ | | | | |_____ | \_/ | | | | |_/ / _____ | -// \ _____| |__| |________| \_______/ |__| |______/ (_______/ +// \ _____| |__| |________| \_______/ |__| |______/ (_______/ // -// This file is part of VirtualFluids. VirtualFluids is free software: you can +// This file is part of VirtualFluids. VirtualFluids is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of +// License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. -// -// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// +// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License along // with VirtualFluids (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>. // @@ -34,8 +34,8 @@ #ifndef INTERACTOR3D_H #define INTERACTOR3D_H -#include <vector> #include <PointerDefinitions.h> +#include <vector> #include "UbSystem.h" #include "UbTuple.h" @@ -48,99 +48,101 @@ class GbObject3D; class Interactor3D : public enableSharedFromThis<Interactor3D> { public: - enum Accuracy{SIMPLE, EDGES, FACES, POINTS}; - Interactor3D(); - Interactor3D(SPtr<Grid3D> grid, int type=Interactor3D::SOLID); - Interactor3D(SPtr<GbObject3D> geoObject3D, SPtr<Grid3D> grid, int type); - //! constructor - //! \param a set accuracy for arePointsInObject() and arePointsNotInObject() - Interactor3D(SPtr<GbObject3D> geoObject3D, SPtr<Grid3D> grid, int type, Interactor3D::Accuracy a); - - virtual ~Interactor3D(); - virtual void initInteractor(const double& timestep=0); - virtual void updateInteractor(const double& timestep=0)=0; - - void setSolidBlock(SPtr<Block3D> block); - void setBCBlock(SPtr<Block3D> block); + enum Accuracy { SIMPLE, EDGES, FACES, POINTS }; + Interactor3D(); + Interactor3D(SPtr<Grid3D> grid, int type = Interactor3D::SOLID); + Interactor3D(SPtr<GbObject3D> geoObject3D, SPtr<Grid3D> grid, int type); + //! constructor + //! \param a set accuracy for arePointsInObject() and arePointsNotInObject() + Interactor3D(SPtr<GbObject3D> geoObject3D, SPtr<Grid3D> grid, int type, Interactor3D::Accuracy a); + + virtual ~Interactor3D(); + virtual void initInteractor(const double ×tep = 0); + virtual void updateInteractor(const double ×tep = 0) = 0; + + void setSolidBlock(SPtr<Block3D> block); + void setBCBlock(SPtr<Block3D> block); virtual UbTupleDouble3 getForces(); - void setSolid() { UbSystem::setBit(this->type, SOLID ); } - void setMoveable() { UbSystem::setBit(this->type, MOVEABLE); } - - bool isSolid() { return UbSystem::bitCheck(this->type, SOLID ); } - bool isInverseSolid() { return UbSystem::bitCheck(this->type, INVERSESOLID ); } - bool isTimeDependent() { return UbSystem::bitCheck(this->type, TIMEDEPENDENT); } - bool isMoveable() { return UbSystem::bitCheck(this->type, MOVEABLE ); } - - SPtr<Grid3D> getGrid3D() const { return grid.lock(); } - void setGrid3D(SPtr<Grid3D> grid) { this->grid = grid; } - virtual SPtr<GbObject3D> getGbObject3D() const { return geoObject3D; } - virtual bool setDifferencesToGbObject3D(const SPtr<Block3D> /*block*//*, const double& x1, const double& x2, const double& x3, const double& blockLengthX1, const double& blockLengthX2, const double& blockLengthX3, const double& timestep=0*/) - { - //UBLOG(logINFO, "Interactor3D::setDifferencesToGbObject3D()"); - return false; - } - - virtual std::vector<SPtr<Block3D> >& getBcBlocks() { return this->bcBlocks; } - virtual void removeBcBlocks() { this->bcBlocks.clear(); } - virtual std::vector<SPtr<Block3D> >& getSolidBlockSet() { return this->solidBlocks; } - virtual void removeSolidBlocks() { this->solidBlocks.clear(); } - - void setID(int id); - int getID(); - - void setActive(); - void setInactive(); - bool isActive(); + void setSolid() { UbSystem::setBit(this->type, SOLID); } + void setMoveable() { UbSystem::setBit(this->type, MOVEABLE); } + + bool isSolid() { return UbSystem::bitCheck(this->type, SOLID); } + bool isInverseSolid() { return UbSystem::bitCheck(this->type, INVERSESOLID); } + bool isTimeDependent() { return UbSystem::bitCheck(this->type, TIMEDEPENDENT); } + bool isMoveable() { return UbSystem::bitCheck(this->type, MOVEABLE); } + + SPtr<Grid3D> getGrid3D() const { return grid.lock(); } + void setGrid3D(SPtr<Grid3D> grid) { this->grid = grid; } + virtual SPtr<GbObject3D> getGbObject3D() const { return geoObject3D; } + virtual bool setDifferencesToGbObject3D(const SPtr<Block3D> /*block*//*, const double& x1, const double& x2, const double& x3, const double& blockLengthX1, const double& blockLengthX2, const double& blockLengthX3, const double& timestep=0*/) + { + // UBLOG(logINFO, "Interactor3D::setDifferencesToGbObject3D()"); + return false; + } + + virtual std::vector<SPtr<Block3D>> &getBcBlocks() { return this->bcBlocks; } + virtual void removeBcBlocks() { this->bcBlocks.clear(); } + virtual std::vector<SPtr<Block3D>> &getSolidBlockSet() { return this->solidBlocks; } + virtual void removeSolidBlocks() { this->solidBlocks.clear(); } + + void setID(int id); + int getID(); + + void setActive(); + void setInactive(); + bool isActive(); protected: - void setTimeDependent() { UbSystem::setBit(this->type , TIMEDEPENDENT); } - void unsetTimeDependent() { UbSystem::unsetBit(this->type, TIMEDEPENDENT); } - - //! detect that points are inside object - //! \param min/max coordinates of bounding box - //! \param delta is delta x - bool arePointsInsideGeoObject(double minX1, double minX2, double minX3, double maxX1, double maxX2, double maxX3, double delta); - - //! detect that points aren't inside object - //! \param min/max coordinates of bounding box - //! \param delta is delta x - bool arePointsOutsideGeoObject(double minX1, double minX2, double minX3, double maxX1, double maxX2, double maxX3, double delta); - - //! detect that points are cutting object - //! \param min/max coordinates of bounding box - //! \param delta is delta x - bool arePointsCuttingGeoObject(double minX1, double minX2, double minX3, double maxX1, double maxX2, double maxX3, double delta); - - bool isBlockOutsideGeoObject(double minX1, double minX2, double minX3, double maxX1, double maxX2, double maxX3, double delta); - bool isBlockInsideGeoObject(double minX1, double minX2, double minX3, double maxX1, double maxX2, double maxX3, double delta); - bool isBlockCuttingGeoObject(double minX1, double minX2, double minX3, double maxX1, double maxX2, double maxX3, double delta); - - - SPtr<GbObject3D> geoObject3D; + void setTimeDependent() { UbSystem::setBit(this->type, TIMEDEPENDENT); } + void unsetTimeDependent() { UbSystem::unsetBit(this->type, TIMEDEPENDENT); } + + //! detect that points are inside object + //! \param min/max coordinates of bounding box + //! \param delta is delta x + bool arePointsInsideGeoObject(double minX1, double minX2, double minX3, double maxX1, double maxX2, double maxX3, + double delta); + + //! detect that points aren't inside object + //! \param min/max coordinates of bounding box + //! \param delta is delta x + bool arePointsOutsideGeoObject(double minX1, double minX2, double minX3, double maxX1, double maxX2, double maxX3, + double delta); + + //! detect that points are cutting object + //! \param min/max coordinates of bounding box + //! \param delta is delta x + bool arePointsCuttingGeoObject(double minX1, double minX2, double minX3, double maxX1, double maxX2, double maxX3, + double delta); + + bool isBlockOutsideGeoObject(double minX1, double minX2, double minX3, double maxX1, double maxX2, double maxX3, + double delta); + bool isBlockInsideGeoObject(double minX1, double minX2, double minX3, double maxX1, double maxX2, double maxX3, + double delta); + bool isBlockCuttingGeoObject(double minX1, double minX2, double minX3, double maxX1, double maxX2, double maxX3, + double delta); + + SPtr<GbObject3D> geoObject3D; WPtr<Grid3D> grid; int type; - std::vector<SPtr<Block3D> > bcBlocks; - std::vector<SPtr<Block3D> > solidBlocks; - int accuracy; - - bool active; - int id; + std::vector<SPtr<Block3D>> bcBlocks; + std::vector<SPtr<Block3D>> solidBlocks; + int accuracy; + + bool active; + int id; public: - static const int SOLID ;//= (1<<0); //1 - static const int INVERSESOLID ;//= (1<<1); //2 - static const int TIMEDEPENDENT ;//= (1<<2); //4 //zeitlich - static const int FLUID ;//= (1<<3); //8 - static const int MOVEABLE ;//= (1<<4); //16 // geometrisch - static const int CHANGENOTNECESSARY ;//= (1<<5); //32 + static const int SOLID; //= (1<<0); //1 + static const int INVERSESOLID; //= (1<<1); //2 + static const int TIMEDEPENDENT; //= (1<<2); //4 //zeitlich + static const int FLUID; //= (1<<3); //8 + static const int MOVEABLE; //= (1<<4); //16 // geometrisch + static const int CHANGENOTNECESSARY; //= (1<<5); //32 private: - }; - - #endif diff --git a/src/cpu/VirtualFluidsCore/Interactors/InteractorsHelper.cpp b/src/cpu/VirtualFluidsCore/Interactors/InteractorsHelper.cpp index 29ccab6babf4eae939b86fd06e96a5828ffdbfe7..d8ee6593400e8bc89dde7d2708f31595e86f1a5b 100644 --- a/src/cpu/VirtualFluidsCore/Interactors/InteractorsHelper.cpp +++ b/src/cpu/VirtualFluidsCore/Interactors/InteractorsHelper.cpp @@ -1,28 +1,28 @@ //======================================================================================= -// ____ ____ __ ______ __________ __ __ __ __ -// \ \ | | | | | _ \ |___ ___| | | | | / \ | | -// \ \ | | | | | |_) | | | | | | | / \ | | -// \ \ | | | | | _ / | | | | | | / /\ \ | | -// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ -// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| -// \ \ | | ________________________________________________________________ -// \ \ | | | ______________________________________________________________| -// \ \| | | | __ __ __ __ ______ _______ -// \ | | |_____ | | | | | | | | | _ \ / _____) -// \ | | _____| | | | | | | | | | | \ \ \_______ +// ____ ____ __ ______ __________ __ __ __ __ +// \ \ | | | | | _ \ |___ ___| | | | | / \ | | +// \ \ | | | | | |_) | | | | | | | / \ | | +// \ \ | | | | | _ / | | | | | | / /\ \ | | +// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ +// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| +// \ \ | | ________________________________________________________________ +// \ \ | | | ______________________________________________________________| +// \ \| | | | __ __ __ __ ______ _______ +// \ | | |_____ | | | | | | | | | _ \ / _____) +// \ | | _____| | | | | | | | | | | \ \ \_______ // \ | | | | |_____ | \_/ | | | | |_/ / _____ | -// \ _____| |__| |________| \_______/ |__| |______/ (_______/ +// \ _____| |__| |________| \_______/ |__| |______/ (_______/ // -// This file is part of VirtualFluids. VirtualFluids is free software: you can +// This file is part of VirtualFluids. VirtualFluids is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of +// License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. -// -// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// +// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License along // with VirtualFluids (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>. // @@ -33,73 +33,62 @@ #include "InteractorsHelper.h" -#include <Grid3DVisitor.h> -#include <Grid3D.h> -#include <Interactor3D.h> #include "Block3D.h" #include "Communicator.h" -#include "SetSolidBlocksBlockVisitor.h" #include "SetBcBlocksBlockVisitor.h" +#include "SetSolidBlocksBlockVisitor.h" +#include <Grid3D.h> +#include <Grid3DVisitor.h> +#include <Interactor3D.h> - -InteractorsHelper::InteractorsHelper(SPtr<Grid3D> grid, SPtr<Grid3DVisitor> visitor, bool deleteBlocks) : - grid(grid), visitor(visitor), deleteBlocks(deleteBlocks) +InteractorsHelper::InteractorsHelper(SPtr<Grid3D> grid, SPtr<Grid3DVisitor> visitor, bool deleteBlocks) + : grid(grid), visitor(visitor), deleteBlocks(deleteBlocks) { - } ////////////////////////////////////////////////////////////////////////// -InteractorsHelper::~InteractorsHelper() -= default; +InteractorsHelper::~InteractorsHelper() = default; ////////////////////////////////////////////////////////////////////////// -void InteractorsHelper::addInteractor( SPtr<Interactor3D> interactor ) -{ - interactors.push_back(interactor); -} +void InteractorsHelper::addInteractor(SPtr<Interactor3D> interactor) { interactors.push_back(interactor); } ////////////////////////////////////////////////////////////////////////// void InteractorsHelper::setBC() { - for(SPtr<Interactor3D> i : interactors) + for (SPtr<Interactor3D> i : interactors) i->initInteractor(); } -void InteractorsHelper::sendDomainDecompositionVisitor() const -{ - grid->accept( visitor ); -} +void InteractorsHelper::sendDomainDecompositionVisitor() const { grid->accept(visitor); } ////////////////////////////////////////////////////////////////////////// void InteractorsHelper::selectBlocks() { - sendDomainDecompositionVisitor(); - deleteSolidBlocks(); + sendDomainDecompositionVisitor(); + deleteSolidBlocks(); - sendDomainDecompositionVisitor(); - setBcBlocks(); + sendDomainDecompositionVisitor(); + setBcBlocks(); } ////////////////////////////////////////////////////////////////////////// void InteractorsHelper::deleteSolidBlocks() { - for(SPtr<Interactor3D> interactor : interactors) - { + for (SPtr<Interactor3D> interactor : interactors) { SetSolidBlocksBlockVisitor v(interactor); grid->accept(v); - if (deleteBlocks) - { - std::vector<SPtr<Block3D>>& sb = interactor->getSolidBlockSet(); - solidBlocks.insert(solidBlocks.end(), sb.begin(), sb.end()); - interactor->removeSolidBlocks(); + if (deleteBlocks) { + std::vector<SPtr<Block3D>> &sb = interactor->getSolidBlockSet(); + solidBlocks.insert(solidBlocks.end(), sb.begin(), sb.end()); + interactor->removeSolidBlocks(); } } - if (deleteBlocks) updateGrid(); + if (deleteBlocks) + updateGrid(); } ////////////////////////////////////////////////////////////////////////// void InteractorsHelper::setBcBlocks() { - for(const auto& interactor : interactors) - { - SetBcBlocksBlockVisitor v(interactor); - grid->accept(v); + for (const auto &interactor : interactors) { + SetBcBlocksBlockVisitor v(interactor); + grid->accept(v); } } ////////////////////////////////////////////////////////////////////////// @@ -107,11 +96,10 @@ void InteractorsHelper::updateGrid() { std::vector<int> ids; - for(const auto& block : solidBlocks) + for (const auto &block : solidBlocks) ids.push_back(block->getGlobalID()); std::vector<int> rids; Communicator::getInstance()->allGather(ids, rids); grid->deleteBlocks(rids); } - diff --git a/src/cpu/VirtualFluidsCore/Interactors/InteractorsHelper.h b/src/cpu/VirtualFluidsCore/Interactors/InteractorsHelper.h index 3d6d30f0cbe95e4b52ca26403e049ecb52c3ead8..2eb554905e5419f8c4a039d319191097bc5260a0 100644 --- a/src/cpu/VirtualFluidsCore/Interactors/InteractorsHelper.h +++ b/src/cpu/VirtualFluidsCore/Interactors/InteractorsHelper.h @@ -1,28 +1,28 @@ //======================================================================================= -// ____ ____ __ ______ __________ __ __ __ __ -// \ \ | | | | | _ \ |___ ___| | | | | / \ | | -// \ \ | | | | | |_) | | | | | | | / \ | | -// \ \ | | | | | _ / | | | | | | / /\ \ | | -// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ -// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| -// \ \ | | ________________________________________________________________ -// \ \ | | | ______________________________________________________________| -// \ \| | | | __ __ __ __ ______ _______ -// \ | | |_____ | | | | | | | | | _ \ / _____) -// \ | | _____| | | | | | | | | | | \ \ \_______ +// ____ ____ __ ______ __________ __ __ __ __ +// \ \ | | | | | _ \ |___ ___| | | | | / \ | | +// \ \ | | | | | |_) | | | | | | | / \ | | +// \ \ | | | | | _ / | | | | | | / /\ \ | | +// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ +// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| +// \ \ | | ________________________________________________________________ +// \ \ | | | ______________________________________________________________| +// \ \| | | | __ __ __ __ ______ _______ +// \ | | |_____ | | | | | | | | | _ \ / _____) +// \ | | _____| | | | | | | | | | | \ \ \_______ // \ | | | | |_____ | \_/ | | | | |_/ / _____ | -// \ _____| |__| |________| \_______/ |__| |______/ (_______/ +// \ _____| |__| |________| \_______/ |__| |______/ (_______/ // -// This file is part of VirtualFluids. VirtualFluids is free software: you can +// This file is part of VirtualFluids. VirtualFluids is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of +// License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. -// -// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// +// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License along // with VirtualFluids (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>. // @@ -31,12 +31,11 @@ //! \author Konstantin Kutscher //======================================================================================= -#ifndef InteractorsHelper_h +#ifndef InteractorsHelper_h #define InteractorsHelper_h -#include <vector> #include <PointerDefinitions.h> - +#include <vector> class Interactor3D; class Block3D; @@ -47,26 +46,26 @@ class Grid3DVisitor; class InteractorsHelper { public: - InteractorsHelper(SPtr<Grid3D> grid, SPtr<Grid3DVisitor> visitor, bool deleteBlocks=true); - ~InteractorsHelper(); + InteractorsHelper(SPtr<Grid3D> grid, SPtr<Grid3DVisitor> visitor, bool deleteBlocks = true); + ~InteractorsHelper(); - void addInteractor(SPtr<Interactor3D> interactor); - void selectBlocks(); - void setBC(); - void sendDomainDecompositionVisitor() const; + void addInteractor(SPtr<Interactor3D> interactor); + void selectBlocks(); + void setBC(); + void sendDomainDecompositionVisitor() const; protected: - void deleteSolidBlocks(); - void setBcBlocks(); + void deleteSolidBlocks(); + void setBcBlocks(); private: - void updateGrid(); + void updateGrid(); - std::vector<SPtr<Interactor3D> > interactors; - SPtr<Grid3D> grid; - std::vector<SPtr<Block3D> > solidBlocks; - SPtr<Grid3DVisitor> visitor; - bool deleteBlocks; + std::vector<SPtr<Interactor3D>> interactors; + SPtr<Grid3D> grid; + std::vector<SPtr<Block3D>> solidBlocks; + SPtr<Grid3DVisitor> visitor; + bool deleteBlocks; }; #endif diff --git a/src/cpu/VirtualFluidsCore/LBM/BGKLBMKernel.cpp b/src/cpu/VirtualFluidsCore/LBM/BGKLBMKernel.cpp index b2f5cd60fe90ef92a6b5a9a40157f2ccf3d17494..365373c09053c3e3292276ac39908e6bd66a26fd 100644 --- a/src/cpu/VirtualFluidsCore/LBM/BGKLBMKernel.cpp +++ b/src/cpu/VirtualFluidsCore/LBM/BGKLBMKernel.cpp @@ -1,298 +1,295 @@ #include "BGKLBMKernel.h" -#include "D3Q27System.h" -#include "D3Q27EsoTwist3DSplittedVector.h" +#include "BCArray3D.h" +#include "BCProcessor.h" #include "D3Q27EsoTwist3DSoA.h" +#include "D3Q27EsoTwist3DSplittedVector.h" +#include "D3Q27System.h" #include "DataSet3D.h" -#include "BCProcessor.h" -#include "BCArray3D.h" //#define PROOF_CORRECTNESS ////////////////////////////////////////////////////////////////////////// -BGKLBMKernel::BGKLBMKernel() -{ - this->compressible = false; -} +BGKLBMKernel::BGKLBMKernel() { this->compressible = false; } ////////////////////////////////////////////////////////////////////////// -BGKLBMKernel::~BGKLBMKernel(void) -= default; +BGKLBMKernel::~BGKLBMKernel(void) = default; ////////////////////////////////////////////////////////////////////////// void BGKLBMKernel::initDataSet() { - SPtr<DistributionArray3D> d(new D3Q27EsoTwist3DSplittedVector(nx[0]+2, nx[1]+2, nx[2]+2, -999.9)); - dataSet->setFdistributions(d); + SPtr<DistributionArray3D> d(new D3Q27EsoTwist3DSplittedVector(nx[0] + 2, nx[1] + 2, nx[2] + 2, -999.9)); + dataSet->setFdistributions(d); } ////////////////////////////////////////////////////////////////////////// SPtr<LBMKernel> BGKLBMKernel::clone() { - SPtr<LBMKernel> kernel(new BGKLBMKernel()); - std::dynamic_pointer_cast<BGKLBMKernel>(kernel)->initDataSet(); - kernel->setCollisionFactor(this->collFactor); - kernel->setBCProcessor(bcProcessor->clone(kernel)); - kernel->setWithForcing(withForcing); - kernel->setForcingX1(muForcingX1); - kernel->setForcingX2(muForcingX2); - kernel->setForcingX3(muForcingX3); - kernel->setIndex(ix1, ix2, ix3); - return kernel; + SPtr<LBMKernel> kernel(new BGKLBMKernel()); + std::dynamic_pointer_cast<BGKLBMKernel>(kernel)->initDataSet(); + kernel->setCollisionFactor(this->collFactor); + kernel->setBCProcessor(bcProcessor->clone(kernel)); + kernel->setWithForcing(withForcing); + kernel->setForcingX1(muForcingX1); + kernel->setForcingX2(muForcingX2); + kernel->setForcingX3(muForcingX3); + kernel->setIndex(ix1, ix2, ix3); + return kernel; } ////////////////////////////////////////////////////////////////////////// -void BGKLBMKernel::calculate(int /*step*/) +void BGKLBMKernel::calculate(int /*step*/) { - using namespace D3Q27System; - using namespace UbMath; + using namespace D3Q27System; + using namespace UbMath; - //initializing of forcing stuff - if (withForcing) - { - muForcingX1.DefineVar("x1",&muX1); muForcingX1.DefineVar("x2",&muX2); muForcingX1.DefineVar("x3",&muX3); - muForcingX2.DefineVar("x1",&muX1); muForcingX2.DefineVar("x2",&muX2); muForcingX2.DefineVar("x3",&muX3); - muForcingX3.DefineVar("x1",&muX1); muForcingX3.DefineVar("x2",&muX2); muForcingX3.DefineVar("x3",&muX3); - forcingX1 = 0; - forcingX2 = 0; - forcingX3 = 0; - } - ///////////////////////////////////// + // initializing of forcing stuff + if (withForcing) { + muForcingX1.DefineVar("x1", &muX1); + muForcingX1.DefineVar("x2", &muX2); + muForcingX1.DefineVar("x3", &muX3); + muForcingX2.DefineVar("x1", &muX1); + muForcingX2.DefineVar("x2", &muX2); + muForcingX2.DefineVar("x3", &muX3); + muForcingX3.DefineVar("x1", &muX1); + muForcingX3.DefineVar("x2", &muX2); + muForcingX3.DefineVar("x3", &muX3); + forcingX1 = 0; + forcingX2 = 0; + forcingX3 = 0; + } + ///////////////////////////////////// - localDistributions = std::dynamic_pointer_cast<D3Q27EsoTwist3DSplittedVector>(dataSet->getFdistributions())->getLocalDistributions(); - nonLocalDistributions = std::dynamic_pointer_cast<D3Q27EsoTwist3DSplittedVector>(dataSet->getFdistributions())->getNonLocalDistributions(); - zeroDistributions = std::dynamic_pointer_cast<D3Q27EsoTwist3DSplittedVector>(dataSet->getFdistributions())->getZeroDistributions(); + localDistributions = + std::dynamic_pointer_cast<D3Q27EsoTwist3DSplittedVector>(dataSet->getFdistributions())->getLocalDistributions(); + nonLocalDistributions = std::dynamic_pointer_cast<D3Q27EsoTwist3DSplittedVector>(dataSet->getFdistributions()) + ->getNonLocalDistributions(); + zeroDistributions = + std::dynamic_pointer_cast<D3Q27EsoTwist3DSplittedVector>(dataSet->getFdistributions())->getZeroDistributions(); - SPtr<BCArray3D> bcArray = this->getBCProcessor()->getBCArray(); - LBMReal f[D3Q27System::ENDF+1]; - LBMReal feq[D3Q27System::ENDF+1]; - LBMReal drho,vx1,vx2,vx3; - const int bcArrayMaxX1 = (int)bcArray->getNX1(); - const int bcArrayMaxX2 = (int)bcArray->getNX2(); - const int bcArrayMaxX3 = (int)bcArray->getNX3(); + SPtr<BCArray3D> bcArray = this->getBCProcessor()->getBCArray(); + LBMReal f[D3Q27System::ENDF + 1]; + LBMReal feq[D3Q27System::ENDF + 1]; + LBMReal drho, vx1, vx2, vx3; + const int bcArrayMaxX1 = (int)bcArray->getNX1(); + const int bcArrayMaxX2 = (int)bcArray->getNX2(); + const int bcArrayMaxX3 = (int)bcArray->getNX3(); - int minX1 = ghostLayerWidth; - int minX2 = ghostLayerWidth; - int minX3 = ghostLayerWidth; - int maxX1 = bcArrayMaxX1-ghostLayerWidth; - int maxX2 = bcArrayMaxX2-ghostLayerWidth; - int maxX3 = bcArrayMaxX3-ghostLayerWidth; + int minX1 = ghostLayerWidth; + int minX2 = ghostLayerWidth; + int minX3 = ghostLayerWidth; + int maxX1 = bcArrayMaxX1 - ghostLayerWidth; + int maxX2 = bcArrayMaxX2 - ghostLayerWidth; + int maxX3 = bcArrayMaxX3 - ghostLayerWidth; - for(int x3 = minX3; x3 < maxX3; x3++) - { - for(int x2 = minX2; x2 < maxX2; x2++) - { - for(int x1 = minX1; x1 < maxX1; x1++) - { - if(!bcArray->isSolid(x1,x2,x3) && !bcArray->isUndefined(x1,x2,x3)) - { - int x1p = x1 + 1; - int x2p = x2 + 1; - int x3p = x3 + 1; - ////////////////////////////////////////////////////////////////////////// - //read distribution - //////////////////////////////////////////////////////////////////////////// - f[ZERO] = (*this->zeroDistributions)(x1,x2,x3); + for (int x3 = minX3; x3 < maxX3; x3++) { + for (int x2 = minX2; x2 < maxX2; x2++) { + for (int x1 = minX1; x1 < maxX1; x1++) { + if (!bcArray->isSolid(x1, x2, x3) && !bcArray->isUndefined(x1, x2, x3)) { + int x1p = x1 + 1; + int x2p = x2 + 1; + int x3p = x3 + 1; + ////////////////////////////////////////////////////////////////////////// + // read distribution + //////////////////////////////////////////////////////////////////////////// + f[ZERO] = (*this->zeroDistributions)(x1, x2, x3); - f[E] = (*this->localDistributions)(D3Q27System::ET_E, x1,x2,x3); - f[N] = (*this->localDistributions)(D3Q27System::ET_N,x1,x2,x3); - f[T] = (*this->localDistributions)(D3Q27System::ET_T,x1,x2,x3); - f[NE] = (*this->localDistributions)(D3Q27System::ET_NE,x1,x2,x3); - f[NW] = (*this->localDistributions)(D3Q27System::ET_NW,x1p,x2,x3); - f[TE] = (*this->localDistributions)(D3Q27System::ET_TE,x1,x2,x3); - f[TW] = (*this->localDistributions)(D3Q27System::ET_TW, x1p,x2,x3); - f[TN] = (*this->localDistributions)(D3Q27System::ET_TN,x1,x2,x3); - f[TS] = (*this->localDistributions)(D3Q27System::ET_TS,x1,x2p,x3); - f[TNE] = (*this->localDistributions)(D3Q27System::ET_TNE,x1,x2,x3); - f[TNW] = (*this->localDistributions)(D3Q27System::ET_TNW,x1p,x2,x3); - f[TSE] = (*this->localDistributions)(D3Q27System::ET_TSE,x1,x2p,x3); - f[TSW] = (*this->localDistributions)(D3Q27System::ET_TSW,x1p,x2p,x3); + f[E] = (*this->localDistributions)(D3Q27System::ET_E, x1, x2, x3); + f[N] = (*this->localDistributions)(D3Q27System::ET_N, x1, x2, x3); + f[T] = (*this->localDistributions)(D3Q27System::ET_T, x1, x2, x3); + f[NE] = (*this->localDistributions)(D3Q27System::ET_NE, x1, x2, x3); + f[NW] = (*this->localDistributions)(D3Q27System::ET_NW, x1p, x2, x3); + f[TE] = (*this->localDistributions)(D3Q27System::ET_TE, x1, x2, x3); + f[TW] = (*this->localDistributions)(D3Q27System::ET_TW, x1p, x2, x3); + f[TN] = (*this->localDistributions)(D3Q27System::ET_TN, x1, x2, x3); + f[TS] = (*this->localDistributions)(D3Q27System::ET_TS, x1, x2p, x3); + f[TNE] = (*this->localDistributions)(D3Q27System::ET_TNE, x1, x2, x3); + f[TNW] = (*this->localDistributions)(D3Q27System::ET_TNW, x1p, x2, x3); + f[TSE] = (*this->localDistributions)(D3Q27System::ET_TSE, x1, x2p, x3); + f[TSW] = (*this->localDistributions)(D3Q27System::ET_TSW, x1p, x2p, x3); - f[W ] = (*this->nonLocalDistributions)(D3Q27System::ET_W,x1p,x2,x3 ); - f[S ] = (*this->nonLocalDistributions)(D3Q27System::ET_S,x1,x2p,x3 ); - f[B ] = (*this->nonLocalDistributions)(D3Q27System::ET_B,x1,x2,x3p ); - f[SW] = (*this->nonLocalDistributions)(D3Q27System::ET_SW,x1p,x2p,x3 ); - f[SE] = (*this->nonLocalDistributions)(D3Q27System::ET_SE,x1,x2p,x3 ); - f[BW] = (*this->nonLocalDistributions)(D3Q27System::ET_BW,x1p,x2,x3p ); - f[BE] = (*this->nonLocalDistributions)(D3Q27System::ET_BE,x1,x2,x3p ); - f[BS] = (*this->nonLocalDistributions)(D3Q27System::ET_BS,x1,x2p,x3p ); - f[BN] = (*this->nonLocalDistributions)(D3Q27System::ET_BN,x1,x2,x3p ); - f[BSW] = (*this->nonLocalDistributions)(D3Q27System::ET_BSW,x1p,x2p,x3p); - f[BSE] = (*this->nonLocalDistributions)(D3Q27System::ET_BSE,x1,x2p,x3p); - f[BNW] = (*this->nonLocalDistributions)(D3Q27System::ET_BNW,x1p,x2,x3p); - f[BNE] = (*this->nonLocalDistributions)(D3Q27System::ET_BNE,x1,x2,x3p); - ////////////////////////////////////////////////////////////////////////// + f[W] = (*this->nonLocalDistributions)(D3Q27System::ET_W, x1p, x2, x3); + f[S] = (*this->nonLocalDistributions)(D3Q27System::ET_S, x1, x2p, x3); + f[B] = (*this->nonLocalDistributions)(D3Q27System::ET_B, x1, x2, x3p); + f[SW] = (*this->nonLocalDistributions)(D3Q27System::ET_SW, x1p, x2p, x3); + f[SE] = (*this->nonLocalDistributions)(D3Q27System::ET_SE, x1, x2p, x3); + f[BW] = (*this->nonLocalDistributions)(D3Q27System::ET_BW, x1p, x2, x3p); + f[BE] = (*this->nonLocalDistributions)(D3Q27System::ET_BE, x1, x2, x3p); + f[BS] = (*this->nonLocalDistributions)(D3Q27System::ET_BS, x1, x2p, x3p); + f[BN] = (*this->nonLocalDistributions)(D3Q27System::ET_BN, x1, x2, x3p); + f[BSW] = (*this->nonLocalDistributions)(D3Q27System::ET_BSW, x1p, x2p, x3p); + f[BSE] = (*this->nonLocalDistributions)(D3Q27System::ET_BSE, x1, x2p, x3p); + f[BNW] = (*this->nonLocalDistributions)(D3Q27System::ET_BNW, x1p, x2, x3p); + f[BNE] = (*this->nonLocalDistributions)(D3Q27System::ET_BNE, x1, x2, x3p); + ////////////////////////////////////////////////////////////////////////// - drho = f[ZERO] + f[E] + f[W] + f[N] + f[S] + f[T] + f[B] - + f[NE] + f[SW] + f[SE] + f[NW] + f[TE] + f[BW] + f[BE] - + f[TW] + f[TN] + f[BS] + f[BN] + f[TS] + f[TNE] + f[TSW] - + f[TSE] + f[TNW] + f[BNE] + f[BSW] + f[BSE] + f[BNW]; + drho = f[ZERO] + f[E] + f[W] + f[N] + f[S] + f[T] + f[B] + f[NE] + f[SW] + f[SE] + f[NW] + f[TE] + + f[BW] + f[BE] + f[TW] + f[TN] + f[BS] + f[BN] + f[TS] + f[TNE] + f[TSW] + f[TSE] + f[TNW] + + f[BNE] + f[BSW] + f[BSE] + f[BNW]; - vx1 = f[E] - f[W] + f[NE] - f[SW] + f[SE] - f[NW] + f[TE] - f[BW] - + f[BE] - f[TW] + f[TNE] - f[TSW] + f[TSE] - f[TNW] + f[BNE] - f[BSW] - + f[BSE] - f[BNW]; + vx1 = f[E] - f[W] + f[NE] - f[SW] + f[SE] - f[NW] + f[TE] - f[BW] + f[BE] - f[TW] + f[TNE] - + f[TSW] + f[TSE] - f[TNW] + f[BNE] - f[BSW] + f[BSE] - f[BNW]; - vx2 = f[N] - f[S] + f[NE] - f[SW] - f[SE] + f[NW] + f[TN] - f[BS] + f[BN] - - f[TS] + f[TNE] - f[TSW] - f[TSE] + f[TNW] + f[BNE] - f[BSW] - f[BSE] - + f[BNW]; + vx2 = f[N] - f[S] + f[NE] - f[SW] - f[SE] + f[NW] + f[TN] - f[BS] + f[BN] - f[TS] + f[TNE] - + f[TSW] - f[TSE] + f[TNW] + f[BNE] - f[BSW] - f[BSE] + f[BNW]; - vx3 = f[T] - f[B] + f[TE] - f[BW] - f[BE] + f[TW] + f[TN] - f[BS] - f[BN] - + f[TS] + f[TNE] + f[TSW] + f[TSE] + f[TNW] - f[BNE] - f[BSW] - f[BSE] - - f[BNW]; + vx3 = f[T] - f[B] + f[TE] - f[BW] - f[BE] + f[TW] + f[TN] - f[BS] - f[BN] + f[TS] + f[TNE] + + f[TSW] + f[TSE] + f[TNW] - f[BNE] - f[BSW] - f[BSE] - f[BNW]; - LBMReal cu_sq=1.5*(vx1*vx1+vx2*vx2+vx3*vx3); + LBMReal cu_sq = 1.5 * (vx1 * vx1 + vx2 * vx2 + vx3 * vx3); - feq[ZERO] = c8o27*(drho-cu_sq); - feq[E] = c2o27*(drho+3.0*( vx1 )+c9o2*( vx1 )*( vx1 )-cu_sq); - feq[W] = c2o27*(drho+3.0*(-vx1 )+c9o2*(-vx1 )*(-vx1 )-cu_sq); - feq[N] = c2o27*(drho+3.0*( vx2)+c9o2*( vx2)*( vx2)-cu_sq); - feq[S] = c2o27*(drho+3.0*( -vx2)+c9o2*( -vx2)*( -vx2)-cu_sq); - feq[T] = c2o27*(drho+3.0*( vx3 )+c9o2*( vx3)*( vx3)-cu_sq); - feq[B] = c2o27*(drho+3.0*( -vx3)+c9o2*( -vx3)*( -vx3)-cu_sq); - feq[NE] = c1o54*(drho+3.0*( vx1+vx2)+c9o2*( vx1+vx2)*( vx1+vx2)-cu_sq); - feq[SW] = c1o54*(drho+3.0*(-vx1-vx2)+c9o2*(-vx1-vx2)*(-vx1-vx2)-cu_sq); - feq[SE] = c1o54*(drho+3.0*( vx1-vx2)+c9o2*( vx1-vx2)*( vx1-vx2)-cu_sq); - feq[NW] = c1o54*(drho+3.0*(-vx1+vx2)+c9o2*(-vx1+vx2)*(-vx1+vx2)-cu_sq); - feq[TE] = c1o54*(drho+3.0*( vx1+vx3)+c9o2*( vx1+vx3)*( vx1+vx3)-cu_sq); - feq[BW] = c1o54*(drho+3.0*(-vx1-vx3)+c9o2*(-vx1-vx3)*(-vx1-vx3)-cu_sq); - feq[BE] = c1o54*(drho+3.0*( vx1-vx3)+c9o2*( vx1-vx3)*( vx1-vx3)-cu_sq); - feq[TW] = c1o54*(drho+3.0*(-vx1+vx3)+c9o2*(-vx1+vx3)*(-vx1+vx3)-cu_sq); - feq[TN] = c1o54*(drho+3.0*( vx2+vx3)+c9o2*( vx2+vx3)*( vx2+vx3)-cu_sq); - feq[BS] = c1o54*(drho+3.0*(-vx2-vx3)+c9o2*(-vx2-vx3)*(-vx2-vx3)-cu_sq); - feq[BN] = c1o54*(drho+3.0*( vx2-vx3)+c9o2*( vx2-vx3)*( vx2-vx3)-cu_sq); - feq[TS] = c1o54*(drho+3.0*(-vx2+vx3)+c9o2*(-vx2+vx3)*(-vx2+vx3)-cu_sq); - feq[TNE]= c1o216*(drho+3.0*( vx1+vx2+vx3)+c9o2*( vx1+vx2+vx3)*( vx1+vx2+vx3)-cu_sq); - feq[BSW]= c1o216*(drho+3.0*(-vx1-vx2-vx3)+c9o2*(-vx1-vx2-vx3)*(-vx1-vx2-vx3)-cu_sq); - feq[BNE]= c1o216*(drho+3.0*( vx1+vx2-vx3)+c9o2*( vx1+vx2-vx3)*( vx1+vx2-vx3)-cu_sq); - feq[TSW]= c1o216*(drho+3.0*(-vx1-vx2+vx3)+c9o2*(-vx1-vx2+vx3)*(-vx1-vx2+vx3)-cu_sq); - feq[TSE]= c1o216*(drho+3.0*( vx1-vx2+vx3)+c9o2*( vx1-vx2+vx3)*( vx1-vx2+vx3)-cu_sq); - feq[BNW]= c1o216*(drho+3.0*(-vx1+vx2-vx3)+c9o2*(-vx1+vx2-vx3)*(-vx1+vx2-vx3)-cu_sq); - feq[BSE]= c1o216*(drho+3.0*( vx1-vx2-vx3)+c9o2*( vx1-vx2-vx3)*( vx1-vx2-vx3)-cu_sq); - feq[TNW]= c1o216*(drho+3.0*(-vx1+vx2+vx3)+c9o2*(-vx1+vx2+vx3)*(-vx1+vx2+vx3)-cu_sq); + feq[ZERO] = c8o27 * (drho - cu_sq); + feq[E] = c2o27 * (drho + 3.0 * (vx1) + c9o2 * (vx1) * (vx1)-cu_sq); + feq[W] = c2o27 * (drho + 3.0 * (-vx1) + c9o2 * (-vx1) * (-vx1) - cu_sq); + feq[N] = c2o27 * (drho + 3.0 * (vx2) + c9o2 * (vx2) * (vx2)-cu_sq); + feq[S] = c2o27 * (drho + 3.0 * (-vx2) + c9o2 * (-vx2) * (-vx2) - cu_sq); + feq[T] = c2o27 * (drho + 3.0 * (vx3) + c9o2 * (vx3) * (vx3)-cu_sq); + feq[B] = c2o27 * (drho + 3.0 * (-vx3) + c9o2 * (-vx3) * (-vx3) - cu_sq); + feq[NE] = c1o54 * (drho + 3.0 * (vx1 + vx2) + c9o2 * (vx1 + vx2) * (vx1 + vx2) - cu_sq); + feq[SW] = c1o54 * (drho + 3.0 * (-vx1 - vx2) + c9o2 * (-vx1 - vx2) * (-vx1 - vx2) - cu_sq); + feq[SE] = c1o54 * (drho + 3.0 * (vx1 - vx2) + c9o2 * (vx1 - vx2) * (vx1 - vx2) - cu_sq); + feq[NW] = c1o54 * (drho + 3.0 * (-vx1 + vx2) + c9o2 * (-vx1 + vx2) * (-vx1 + vx2) - cu_sq); + feq[TE] = c1o54 * (drho + 3.0 * (vx1 + vx3) + c9o2 * (vx1 + vx3) * (vx1 + vx3) - cu_sq); + feq[BW] = c1o54 * (drho + 3.0 * (-vx1 - vx3) + c9o2 * (-vx1 - vx3) * (-vx1 - vx3) - cu_sq); + feq[BE] = c1o54 * (drho + 3.0 * (vx1 - vx3) + c9o2 * (vx1 - vx3) * (vx1 - vx3) - cu_sq); + feq[TW] = c1o54 * (drho + 3.0 * (-vx1 + vx3) + c9o2 * (-vx1 + vx3) * (-vx1 + vx3) - cu_sq); + feq[TN] = c1o54 * (drho + 3.0 * (vx2 + vx3) + c9o2 * (vx2 + vx3) * (vx2 + vx3) - cu_sq); + feq[BS] = c1o54 * (drho + 3.0 * (-vx2 - vx3) + c9o2 * (-vx2 - vx3) * (-vx2 - vx3) - cu_sq); + feq[BN] = c1o54 * (drho + 3.0 * (vx2 - vx3) + c9o2 * (vx2 - vx3) * (vx2 - vx3) - cu_sq); + feq[TS] = c1o54 * (drho + 3.0 * (-vx2 + vx3) + c9o2 * (-vx2 + vx3) * (-vx2 + vx3) - cu_sq); + feq[TNE] = c1o216 * + (drho + 3.0 * (vx1 + vx2 + vx3) + c9o2 * (vx1 + vx2 + vx3) * (vx1 + vx2 + vx3) - cu_sq); + feq[BSW] = c1o216 * (drho + 3.0 * (-vx1 - vx2 - vx3) + + c9o2 * (-vx1 - vx2 - vx3) * (-vx1 - vx2 - vx3) - cu_sq); + feq[BNE] = c1o216 * + (drho + 3.0 * (vx1 + vx2 - vx3) + c9o2 * (vx1 + vx2 - vx3) * (vx1 + vx2 - vx3) - cu_sq); + feq[TSW] = c1o216 * (drho + 3.0 * (-vx1 - vx2 + vx3) + + c9o2 * (-vx1 - vx2 + vx3) * (-vx1 - vx2 + vx3) - cu_sq); + feq[TSE] = c1o216 * + (drho + 3.0 * (vx1 - vx2 + vx3) + c9o2 * (vx1 - vx2 + vx3) * (vx1 - vx2 + vx3) - cu_sq); + feq[BNW] = c1o216 * (drho + 3.0 * (-vx1 + vx2 - vx3) + + c9o2 * (-vx1 + vx2 - vx3) * (-vx1 + vx2 - vx3) - cu_sq); + feq[BSE] = c1o216 * + (drho + 3.0 * (vx1 - vx2 - vx3) + c9o2 * (vx1 - vx2 - vx3) * (vx1 - vx2 - vx3) - cu_sq); + feq[TNW] = c1o216 * (drho + 3.0 * (-vx1 + vx2 + vx3) + + c9o2 * (-vx1 + vx2 + vx3) * (-vx1 + vx2 + vx3) - cu_sq); - //Relaxation - f[ZERO] += (feq[ZERO]-f[ZERO])*collFactor; - f[E] += (feq[E]-f[E])*collFactor; - f[W] += (feq[W]-f[W])*collFactor; - f[N] += (feq[N]-f[N])*collFactor; - f[S] += (feq[S]-f[S])*collFactor; - f[T] += (feq[T]-f[T])*collFactor; - f[B] += (feq[B]-f[B])*collFactor; - f[NE] += (feq[NE]-f[NE])*collFactor; - f[SW] += (feq[SW]-f[SW])*collFactor; - f[SE] += (feq[SE]-f[SE])*collFactor; - f[NW] += (feq[NW]-f[NW])*collFactor; - f[TE] += (feq[TE]-f[TE])*collFactor; - f[BW] += (feq[BW]-f[BW])*collFactor; - f[BE] += (feq[BE]-f[BE])*collFactor; - f[TW] += (feq[TW]-f[TW])*collFactor; - f[TN] += (feq[TN]-f[TN])*collFactor; - f[BS] += (feq[BS]-f[BS])*collFactor; - f[BN] += (feq[BN]-f[BN])*collFactor; - f[TS] += (feq[TS]-f[TS])*collFactor; + // Relaxation + f[ZERO] += (feq[ZERO] - f[ZERO]) * collFactor; + f[E] += (feq[E] - f[E]) * collFactor; + f[W] += (feq[W] - f[W]) * collFactor; + f[N] += (feq[N] - f[N]) * collFactor; + f[S] += (feq[S] - f[S]) * collFactor; + f[T] += (feq[T] - f[T]) * collFactor; + f[B] += (feq[B] - f[B]) * collFactor; + f[NE] += (feq[NE] - f[NE]) * collFactor; + f[SW] += (feq[SW] - f[SW]) * collFactor; + f[SE] += (feq[SE] - f[SE]) * collFactor; + f[NW] += (feq[NW] - f[NW]) * collFactor; + f[TE] += (feq[TE] - f[TE]) * collFactor; + f[BW] += (feq[BW] - f[BW]) * collFactor; + f[BE] += (feq[BE] - f[BE]) * collFactor; + f[TW] += (feq[TW] - f[TW]) * collFactor; + f[TN] += (feq[TN] - f[TN]) * collFactor; + f[BS] += (feq[BS] - f[BS]) * collFactor; + f[BN] += (feq[BN] - f[BN]) * collFactor; + f[TS] += (feq[TS] - f[TS]) * collFactor; - f[TNE] += (feq[TNE]-f[TNE])*collFactor; - f[BSW] += (feq[BSW]-f[BSW])*collFactor; - f[BNE] += (feq[BNE]-f[BNE])*collFactor; - f[TSW] += (feq[TSW]-f[TSW])*collFactor; - f[TSE] += (feq[TSE]-f[TSE])*collFactor; - f[BNW] += (feq[BNW]-f[BNW])*collFactor; - f[BSE] += (feq[BSE]-f[BSE])*collFactor; - f[TNW] += (feq[TNW]-f[TNW])*collFactor; + f[TNE] += (feq[TNE] - f[TNE]) * collFactor; + f[BSW] += (feq[BSW] - f[BSW]) * collFactor; + f[BNE] += (feq[BNE] - f[BNE]) * collFactor; + f[TSW] += (feq[TSW] - f[TSW]) * collFactor; + f[TSE] += (feq[TSE] - f[TSE]) * collFactor; + f[BNW] += (feq[BNW] - f[BNW]) * collFactor; + f[BSE] += (feq[BSE] - f[BSE]) * collFactor; + f[TNW] += (feq[TNW] - f[TNW]) * collFactor; - ////////////////////////////////////////////////////////////////////////// - //forcing - if (withForcing) - { - muX1 = x1+ix1*bcArrayMaxX1; - muX2 = x2+ix2*bcArrayMaxX2; - muX3 = x3+ix3*bcArrayMaxX3; + ////////////////////////////////////////////////////////////////////////// + // forcing + if (withForcing) { + muX1 = x1 + ix1 * bcArrayMaxX1; + muX2 = x2 + ix2 * bcArrayMaxX2; + muX3 = x3 + ix3 * bcArrayMaxX3; - forcingX1 = muForcingX1.Eval(); - forcingX2 = muForcingX2.Eval(); - forcingX3 = muForcingX3.Eval(); + forcingX1 = muForcingX1.Eval(); + forcingX2 = muForcingX2.Eval(); + forcingX3 = muForcingX3.Eval(); - f[ZERO] += 0.0 ; - f[E ] += 3.0*c2o27 * (forcingX1) ; - f[W ] += 3.0*c2o27 * (-forcingX1) ; - f[N ] += 3.0*c2o27 * (forcingX2) ; - f[S ] += 3.0*c2o27 * (-forcingX2) ; - f[T ] += 3.0*c2o27 * (forcingX3) ; - f[B ] += 3.0*c2o27 * (-forcingX3); - f[NE ] += 3.0*c1o54 * ( forcingX1+forcingX2 ) ; - f[SW ] += 3.0*c1o54 * (-forcingX1-forcingX2 ) ; - f[SE ] += 3.0*c1o54 * ( forcingX1-forcingX2 ) ; - f[NW ] += 3.0*c1o54 * (-forcingX1+forcingX2 ) ; - f[TE ] += 3.0*c1o54 * ( forcingX1 +forcingX3) ; - f[BW ] += 3.0*c1o54 * (-forcingX1 -forcingX3) ; - f[BE ] += 3.0*c1o54 * ( forcingX1 -forcingX3) ; - f[TW ] += 3.0*c1o54 * (-forcingX1 +forcingX3) ; - f[TN ] += 3.0*c1o54 * ( forcingX2+forcingX3) ; - f[BS ] += 3.0*c1o54 * ( -forcingX2-forcingX3) ; - f[BN ] += 3.0*c1o54 * ( forcingX2-forcingX3) ; - f[TS ] += 3.0*c1o54 * ( -forcingX2+forcingX3) ; - f[TNE] += 3.0*c1o216* ( forcingX1+forcingX2+forcingX3) ; - f[BSW] += 3.0*c1o216* (-forcingX1-forcingX2-forcingX3) ; - f[BNE] += 3.0*c1o216* ( forcingX1+forcingX2-forcingX3) ; - f[TSW] += 3.0*c1o216* (-forcingX1-forcingX2+forcingX3) ; - f[TSE] += 3.0*c1o216* ( forcingX1-forcingX2+forcingX3) ; - f[BNW] += 3.0*c1o216* (-forcingX1+forcingX2-forcingX3) ; - f[BSE] += 3.0*c1o216* ( forcingX1-forcingX2-forcingX3) ; - f[TNW] += 3.0*c1o216* (-forcingX1+forcingX2+forcingX3) ; - } - ////////////////////////////////////////////////////////////////////////// -#ifdef PROOF_CORRECTNESS - LBMReal rho_post = f[ZERO] + f[E] + f[W] + f[N] + f[S] + f[T] + f[B] - + f[NE] + f[SW] + f[SE] + f[NW] + f[TE] + f[BW] + f[BE] - + f[TW] + f[TN] + f[BS] + f[BN] + f[TS] + f[TNE] + f[TSW] - + f[TSE] + f[TNW] + f[BNE] + f[BSW] + f[BSE] + f[BNW]; - LBMReal dif = drho - rho_post; + f[ZERO] += 0.0; + f[E] += 3.0 * c2o27 * (forcingX1); + f[W] += 3.0 * c2o27 * (-forcingX1); + f[N] += 3.0 * c2o27 * (forcingX2); + f[S] += 3.0 * c2o27 * (-forcingX2); + f[T] += 3.0 * c2o27 * (forcingX3); + f[B] += 3.0 * c2o27 * (-forcingX3); + f[NE] += 3.0 * c1o54 * (forcingX1 + forcingX2); + f[SW] += 3.0 * c1o54 * (-forcingX1 - forcingX2); + f[SE] += 3.0 * c1o54 * (forcingX1 - forcingX2); + f[NW] += 3.0 * c1o54 * (-forcingX1 + forcingX2); + f[TE] += 3.0 * c1o54 * (forcingX1 + forcingX3); + f[BW] += 3.0 * c1o54 * (-forcingX1 - forcingX3); + f[BE] += 3.0 * c1o54 * (forcingX1 - forcingX3); + f[TW] += 3.0 * c1o54 * (-forcingX1 + forcingX3); + f[TN] += 3.0 * c1o54 * (forcingX2 + forcingX3); + f[BS] += 3.0 * c1o54 * (-forcingX2 - forcingX3); + f[BN] += 3.0 * c1o54 * (forcingX2 - forcingX3); + f[TS] += 3.0 * c1o54 * (-forcingX2 + forcingX3); + f[TNE] += 3.0 * c1o216 * (forcingX1 + forcingX2 + forcingX3); + f[BSW] += 3.0 * c1o216 * (-forcingX1 - forcingX2 - forcingX3); + f[BNE] += 3.0 * c1o216 * (forcingX1 + forcingX2 - forcingX3); + f[TSW] += 3.0 * c1o216 * (-forcingX1 - forcingX2 + forcingX3); + f[TSE] += 3.0 * c1o216 * (forcingX1 - forcingX2 + forcingX3); + f[BNW] += 3.0 * c1o216 * (-forcingX1 + forcingX2 - forcingX3); + f[BSE] += 3.0 * c1o216 * (forcingX1 - forcingX2 - forcingX3); + f[TNW] += 3.0 * c1o216 * (-forcingX1 + forcingX2 + forcingX3); + } + ////////////////////////////////////////////////////////////////////////// +#ifdef PROOF_CORRECTNESS + LBMReal rho_post = f[ZERO] + f[E] + f[W] + f[N] + f[S] + f[T] + f[B] + f[NE] + f[SW] + f[SE] + + f[NW] + f[TE] + f[BW] + f[BE] + f[TW] + f[TN] + f[BS] + f[BN] + f[TS] + f[TNE] + + f[TSW] + f[TSE] + f[TNW] + f[BNE] + f[BSW] + f[BSE] + f[BNW]; + LBMReal dif = drho - rho_post; #ifdef SINGLEPRECISION - if(dif > 10.0E-7 || dif < -10.0E-7) + if (dif > 10.0E-7 || dif < -10.0E-7) #else - if(dif > 10.0E-15 || dif < -10.0E-15) + if (dif > 10.0E-15 || dif < -10.0E-15) #endif - { - UB_THROW(UbException(UB_EXARGS,"rho is not correct")); - } + { + UB_THROW(UbException(UB_EXARGS, "rho is not correct")); + } #endif - ////////////////////////////////////////////////////////////////////////// - //write distribution - ////////////////////////////////////////////////////////////////////////// - (*this->localDistributions)(D3Q27System::ET_E,x1, x2, x3) = f[D3Q27System::INV_E]; - (*this->localDistributions)(D3Q27System::ET_N,x1, x2, x3) = f[D3Q27System::INV_N]; - (*this->localDistributions)(D3Q27System::ET_T,x1, x2, x3) = f[D3Q27System::INV_T]; - (*this->localDistributions)(D3Q27System::ET_NE,x1, x2, x3) = f[D3Q27System::INV_NE]; - (*this->localDistributions)(D3Q27System::ET_NW,x1p,x2, x3) = f[D3Q27System::INV_NW]; - (*this->localDistributions)(D3Q27System::ET_TE,x1, x2, x3) = f[D3Q27System::INV_TE]; - (*this->localDistributions)(D3Q27System::ET_TW,x1p,x2, x3) = f[D3Q27System::INV_TW]; - (*this->localDistributions)(D3Q27System::ET_TN,x1, x2, x3) = f[D3Q27System::INV_TN]; - (*this->localDistributions)(D3Q27System::ET_TS,x1, x2p,x3) = f[D3Q27System::INV_TS]; - (*this->localDistributions)(D3Q27System::ET_TNE,x1, x2, x3) = f[D3Q27System::INV_TNE]; - (*this->localDistributions)(D3Q27System::ET_TNW,x1p,x2, x3) = f[D3Q27System::INV_TNW]; - (*this->localDistributions)(D3Q27System::ET_TSE,x1, x2p,x3) = f[D3Q27System::INV_TSE]; - (*this->localDistributions)(D3Q27System::ET_TSW,x1p,x2p,x3) = f[D3Q27System::INV_TSW]; - - (*this->nonLocalDistributions)(D3Q27System::ET_W,x1p,x2, x3 ) = f[D3Q27System::INV_W ]; - (*this->nonLocalDistributions)(D3Q27System::ET_S,x1, x2p,x3 ) = f[D3Q27System::INV_S ]; - (*this->nonLocalDistributions)(D3Q27System::ET_B,x1, x2, x3p ) = f[D3Q27System::INV_B ]; - (*this->nonLocalDistributions)(D3Q27System::ET_SW,x1p,x2p,x3 ) = f[D3Q27System::INV_SW]; - (*this->nonLocalDistributions)(D3Q27System::ET_SE,x1, x2p,x3 ) = f[D3Q27System::INV_SE]; - (*this->nonLocalDistributions)(D3Q27System::ET_BW,x1p,x2, x3p ) = f[D3Q27System::INV_BW]; - (*this->nonLocalDistributions)(D3Q27System::ET_BE,x1, x2, x3p ) = f[D3Q27System::INV_BE]; - (*this->nonLocalDistributions)(D3Q27System::ET_BS,x1, x2p,x3p ) = f[D3Q27System::INV_BS]; - (*this->nonLocalDistributions)(D3Q27System::ET_BN,x1, x2, x3p ) = f[D3Q27System::INV_BN]; - (*this->nonLocalDistributions)(D3Q27System::ET_BSW,x1p,x2p,x3p) = f[D3Q27System::INV_BSW]; - (*this->nonLocalDistributions)(D3Q27System::ET_BSE,x1, x2p,x3p) = f[D3Q27System::INV_BSE]; - (*this->nonLocalDistributions)(D3Q27System::ET_BNW,x1p,x2, x3p) = f[D3Q27System::INV_BNW]; - (*this->nonLocalDistributions)(D3Q27System::ET_BNE,x1, x2, x3p) = f[D3Q27System::INV_BNE]; - - (*this->zeroDistributions)(x1,x2,x3) = f[D3Q27System::ZERO]; - ////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////// + // write distribution + ////////////////////////////////////////////////////////////////////////// + (*this->localDistributions)(D3Q27System::ET_E, x1, x2, x3) = f[D3Q27System::INV_E]; + (*this->localDistributions)(D3Q27System::ET_N, x1, x2, x3) = f[D3Q27System::INV_N]; + (*this->localDistributions)(D3Q27System::ET_T, x1, x2, x3) = f[D3Q27System::INV_T]; + (*this->localDistributions)(D3Q27System::ET_NE, x1, x2, x3) = f[D3Q27System::INV_NE]; + (*this->localDistributions)(D3Q27System::ET_NW, x1p, x2, x3) = f[D3Q27System::INV_NW]; + (*this->localDistributions)(D3Q27System::ET_TE, x1, x2, x3) = f[D3Q27System::INV_TE]; + (*this->localDistributions)(D3Q27System::ET_TW, x1p, x2, x3) = f[D3Q27System::INV_TW]; + (*this->localDistributions)(D3Q27System::ET_TN, x1, x2, x3) = f[D3Q27System::INV_TN]; + (*this->localDistributions)(D3Q27System::ET_TS, x1, x2p, x3) = f[D3Q27System::INV_TS]; + (*this->localDistributions)(D3Q27System::ET_TNE, x1, x2, x3) = f[D3Q27System::INV_TNE]; + (*this->localDistributions)(D3Q27System::ET_TNW, x1p, x2, x3) = f[D3Q27System::INV_TNW]; + (*this->localDistributions)(D3Q27System::ET_TSE, x1, x2p, x3) = f[D3Q27System::INV_TSE]; + (*this->localDistributions)(D3Q27System::ET_TSW, x1p, x2p, x3) = f[D3Q27System::INV_TSW]; + (*this->nonLocalDistributions)(D3Q27System::ET_W, x1p, x2, x3) = f[D3Q27System::INV_W]; + (*this->nonLocalDistributions)(D3Q27System::ET_S, x1, x2p, x3) = f[D3Q27System::INV_S]; + (*this->nonLocalDistributions)(D3Q27System::ET_B, x1, x2, x3p) = f[D3Q27System::INV_B]; + (*this->nonLocalDistributions)(D3Q27System::ET_SW, x1p, x2p, x3) = f[D3Q27System::INV_SW]; + (*this->nonLocalDistributions)(D3Q27System::ET_SE, x1, x2p, x3) = f[D3Q27System::INV_SE]; + (*this->nonLocalDistributions)(D3Q27System::ET_BW, x1p, x2, x3p) = f[D3Q27System::INV_BW]; + (*this->nonLocalDistributions)(D3Q27System::ET_BE, x1, x2, x3p) = f[D3Q27System::INV_BE]; + (*this->nonLocalDistributions)(D3Q27System::ET_BS, x1, x2p, x3p) = f[D3Q27System::INV_BS]; + (*this->nonLocalDistributions)(D3Q27System::ET_BN, x1, x2, x3p) = f[D3Q27System::INV_BN]; + (*this->nonLocalDistributions)(D3Q27System::ET_BSW, x1p, x2p, x3p) = f[D3Q27System::INV_BSW]; + (*this->nonLocalDistributions)(D3Q27System::ET_BSE, x1, x2p, x3p) = f[D3Q27System::INV_BSE]; + (*this->nonLocalDistributions)(D3Q27System::ET_BNW, x1p, x2, x3p) = f[D3Q27System::INV_BNW]; + (*this->nonLocalDistributions)(D3Q27System::ET_BNE, x1, x2, x3p) = f[D3Q27System::INV_BNE]; + (*this->zeroDistributions)(x1, x2, x3) = f[D3Q27System::ZERO]; + ////////////////////////////////////////////////////////////////////////// + } } - } - } - } + } + } } ////////////////////////////////////////////////////////////////////////// -double BGKLBMKernel::getCalculationTime() -{ - return 0.0; -} +double BGKLBMKernel::getCalculationTime() { return 0.0; } diff --git a/src/cpu/VirtualFluidsCore/LBM/BGKLBMKernel.h b/src/cpu/VirtualFluidsCore/LBM/BGKLBMKernel.h index 0118352ba5fe18437d3733c0da7f88f2e51229f9..e998267c083c604d6387acf71d2e069315e595c8 100644 --- a/src/cpu/VirtualFluidsCore/LBM/BGKLBMKernel.h +++ b/src/cpu/VirtualFluidsCore/LBM/BGKLBMKernel.h @@ -2,35 +2,31 @@ #define LBMKERNELETD3Q27BGK_H #include "LBMKernel.h" -#include "basics/container/CbArray4D.h" #include "basics/container/CbArray3D.h" +#include "basics/container/CbArray4D.h" - - -class BGKLBMKernel : public LBMKernel +class BGKLBMKernel : public LBMKernel { public: - BGKLBMKernel(); - ~BGKLBMKernel() override; - void calculate(int step)override; - SPtr<LBMKernel> clone()override; - double getCalculationTime() override; + BGKLBMKernel(); + ~BGKLBMKernel() override; + void calculate(int step) override; + SPtr<LBMKernel> clone() override; + double getCalculationTime() override; private: - void initDataSet(); - //void collideAllCompressible(); - //void collideAllIncompressible(); - - CbArray4D<LBMReal,IndexerX4X3X2X1>::CbArray4DPtr localDistributions; - CbArray4D<LBMReal,IndexerX4X3X2X1>::CbArray4DPtr nonLocalDistributions; - CbArray3D<LBMReal,IndexerX3X2X1>::CbArray3DPtr zeroDistributions; - - mu::value_type muX1,muX2,muX3; - LBMReal forcingX1; - LBMReal forcingX2; - LBMReal forcingX3; - - + void initDataSet(); + // void collideAllCompressible(); + // void collideAllIncompressible(); + + CbArray4D<LBMReal, IndexerX4X3X2X1>::CbArray4DPtr localDistributions; + CbArray4D<LBMReal, IndexerX4X3X2X1>::CbArray4DPtr nonLocalDistributions; + CbArray3D<LBMReal, IndexerX3X2X1>::CbArray3DPtr zeroDistributions; + + mu::value_type muX1, muX2, muX3; + LBMReal forcingX1; + LBMReal forcingX2; + LBMReal forcingX3; }; #endif diff --git a/src/cpu/VirtualFluidsCore/LBM/D3Q27System.cpp b/src/cpu/VirtualFluidsCore/LBM/D3Q27System.cpp index ec791cbb30b718c34bf091bf440464de08d09d6c..6c2f84f06d701dc5cfe137e6a2cedf103a438efc 100644 --- a/src/cpu/VirtualFluidsCore/LBM/D3Q27System.cpp +++ b/src/cpu/VirtualFluidsCore/LBM/D3Q27System.cpp @@ -1,197 +1,208 @@ #include "D3Q27System.h" namespace D3Q27System { - using namespace UbMath; - - //index 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18//falsch - //f: ZERO, E, W, N, S, T, B, NE, SW, SE, NW, TE, BW, BE, TW, TN, BS, BN, TS, TNE TNW TSE TSW BNE BNW BSE BSW - //const int EX1[] = { 0, 1, -1, 0, 0, 0, 0, 1, -1, 1, -1, 1, -1, 1, -1, 0, 0, 0, 0, 1, -1, 1, -1, 1, -1, 1, -1 }; - //const int EX2[] = { 0, 0, 0, 1, -1, 0, 0, 1, -1, -1, 1, 0, 0, 0, 0, 1, -1, 1, -1, 1, 1, -1, -1, 1, 1, -1, -1 }; - //const int EX3[] = { 0, 0, 0, 0, 0, 1, -1, 0, 0, 0, 0, 1, -1, -1, 1, 1, -1, -1, 1, 1, 1, 1, 1, -1, -1, -1, -1 }; - - //index 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 - //f: E, W, N, S, T, B, NE, SW, SE, NW, TE, BW, BE, TW, TN, BS, BN, TS, TNE TNW TSE TSW BNE BNW BSE BSW - const int DX1[] = { 1, -1, 0, 0, 0, 0, 1, -1, 1, -1, 1, -1, 1, -1, 0, 0, 0, 0, 1, -1, 1, -1, 1, -1, 1, -1 }; - const int DX2[] = { 0, 0, 1, -1, 0, 0, 1, -1, -1, 1, 0, 0, 0, 0, 1, -1, 1, -1, 1, 1, -1, -1, 1, 1, -1, -1 }; - const int DX3[] = { 0, 0, 0, 0, 1, -1, 0, 0, 0, 0, 1, -1, -1, 1, 1, -1, -1, 1, 1, 1, 1, 1, -1, -1, -1, -1 }; - - ////index 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 - ////f: E, W, N, S, T, B, NE, SW, SE, NW, TE, BW, BE, TW, TN, BS, BN, TS, TNE TNW TSE TSW BNE BNW BSE BSW - const double WEIGTH[] = { c2o27, c2o27, c2o27, c2o27, c2o27, c2o27, c1o54, c1o54, c1o54, c1o54, c1o54, c1o54, c1o54, c1o54, c1o54, c1o54, c1o54, c1o54, c1o216, c1o216, c1o216, c1o216, c1o216, c1o216, c1o216, c1o216 , c8o27 }; - - - const int INVDIR[] = { - INV_E, - INV_W, - INV_N, - INV_S, - INV_T, - INV_B, - INV_NE, - INV_SW, - INV_SE, - INV_NW, - INV_TE, - INV_BW, - INV_BE, - INV_TW, - INV_TN, - INV_BS, - INV_BN, - INV_TS, - INV_TNE, - INV_TNW, - INV_TSE, - INV_TSW, - INV_BNE, - INV_BNW, - INV_BSE, - INV_BSW }; - - - // The x,y,z component for each normalized direction - const double cNorm[3][ENDDIR] = { - { - double(DX1[0]), double(DX1[1]), - double(DX1[2]), double(DX1[3]), - double(DX1[4]), double(DX1[5]), - double(DX1[6]) / std::sqrt(double(2)), double(DX1[7]) / std::sqrt(double(2)), - double(DX1[8]) / std::sqrt(double(2)), double(DX1[9]) / std::sqrt(double(2)), - double(DX1[10]) / std::sqrt(double(2)), double(DX1[11]) / std::sqrt(double(2)), - double(DX1[12]) / std::sqrt(double(2)), double(DX1[13]) / std::sqrt(double(2)), - double(DX1[14]), double(DX1[15]), - double(DX1[16]), double(DX1[17]), - double(DX1[18]) / std::sqrt(double(3)), double(DX1[19]) / std::sqrt(double(3)), - double(DX1[20]) / std::sqrt(double(3)), double(DX1[21]) / std::sqrt(double(3)), - double(DX1[22]) / std::sqrt(double(3)), double(DX1[23]) / std::sqrt(double(3)), - double(DX1[24]) / std::sqrt(double(3)), double(DX1[25]) / std::sqrt(double(3)) - },{ - double(DX2[0]), double(DX2[1]), - double(DX2[2]), double(DX2[3]), - double(DX2[4]), double(DX2[5]), - double(DX2[6]) / std::sqrt(double(2)), double(DX2[7]) / std::sqrt(double(2)), - double(DX2[8]) / std::sqrt(double(2)), double(DX2[9]) / std::sqrt(double(2)), - double(DX2[10]), double(DX2[11]), - double(DX2[12]), double(DX2[13]), - double(DX2[14]) / std::sqrt(double(2)), double(DX2[15]) / std::sqrt(double(2)), - double(DX2[16]) / std::sqrt(double(2)), double(DX2[17]) / std::sqrt(double(2)), - double(DX2[18]) / std::sqrt(double(3)), double(DX2[19]) / std::sqrt(double(3)), - double(DX2[20]) / std::sqrt(double(3)), double(DX2[21]) / std::sqrt(double(3)), - double(DX2[22]) / std::sqrt(double(3)), double(DX2[23]) / std::sqrt(double(3)), - double(DX2[24]) / std::sqrt(double(3)), double(DX2[25]) / std::sqrt(double(3)) - },{ - double(DX3[0]), double(DX3[1]), - double(DX3[2]), double(DX3[3]), - double(DX3[4]), double(DX3[5]), - double(DX3[6]), double(DX3[7]), - double(DX3[8]), double(DX3[9]), - double(DX3[10]) / std::sqrt(double(2)), double(DX3[11]) / std::sqrt(double(2)), - double(DX3[12]) / std::sqrt(double(2)), double(DX3[13]) / std::sqrt(double(2)), - double(DX3[14]) / std::sqrt(double(2)), double(DX3[15]) / std::sqrt(double(2)), - double(DX3[16]) / std::sqrt(double(2)), double(DX3[17]) / std::sqrt(double(2)), - double(DX3[18]) / std::sqrt(double(3)), double(DX3[19]) / std::sqrt(double(3)), - double(DX3[20]) / std::sqrt(double(3)), double(DX3[21]) / std::sqrt(double(3)), - double(DX3[22]) / std::sqrt(double(3)), double(DX3[23]) / std::sqrt(double(3)), - double(DX3[24]) / std::sqrt(double(3)), double(DX3[25]) / std::sqrt(double(3)) - } - }; - -} - -//const int FSTARTDIR = 0; -//const int FENDDIR = 25; //D3Q27 - -//const int STARTF = 0; -//const int ENDF = 26; //D3Q27 - -//const int EX1[ENDF+1]; -//const int EX2[ENDF+1]; -//const int EX3[ENDF+1]; - -//const int STARTDIR = 0; -//const int ENDDIR = 26; //alle geometrischen richtungen - -//const int DX1[ENDDIR+1]; -//const int DX2[ENDDIR+1]; -//const int DX3[ENDDIR+1]; - - -//const int E /*f1 */ = 0; -//const int W /*f2 */ = 1; -//const int N /*f3 */ = 2; -//const int S /*f4 */ = 3; -//const int T /*f5 */ = 4; -//const int B /*f6 */ = 5; -//const int NE /*f7 */ = 6; -//const int SW /*f8 */ = 7; -//const int SE /*f9 */ = 8; -//const int NW /*f10*/ = 9; -//const int TE /*f11*/ = 10; -//const int BW /*f12*/ = 11; -//const int BE /*f13*/ = 12; -//const int TW /*f14*/ = 13; -//const int TN /*f15*/ = 14; -//const int BS /*f16*/ = 15; -//const int BN /*f17*/ = 16; -//const int TS /*f18*/ = 17; -//const int TNE = 18; -//const int TNW = 19; -//const int TSE = 20; -//const int TSW = 21; -//const int BNE = 22; -//const int BNW = 23; -//const int BSE = 24; -//const int BSW = 25; -//const int ZERO /*f0 */ = 26; - -//const int INV_E = W; -//const int INV_W = E; -//const int INV_N = S; -//const int INV_S = N; -//const int INV_T = B; -//const int INV_B = T; -//const int INV_NE = SW; -//const int INV_SW = NE; -//const int INV_SE = NW; -//const int INV_NW = SE; -//const int INV_TE = BW; -//const int INV_BW = TE; -//const int INV_BE = TW; -//const int INV_TW = BE; -//const int INV_TN = BS; -//const int INV_BS = TN; -//const int INV_BN = TS; -//const int INV_TS = BN; -//const int INV_TNE = BSW; -//const int INV_TNW = BSE; -//const int INV_TSE = BNW; -//const int INV_TSW = BNE; -//const int INV_BNE = TSW; -//const int INV_BNW = TSE; -//const int INV_BSE = TNW; -//const int INV_BSW = TNE; - -//const int INVDIR[ENDDIR+1]; - -//const int M_RHO = 0; -//const int M_EN = 1; -//const int M_EPS = 2; -//const int M_JX1 = 3; -//const int M_QX1 = 4; -//const int M_JX2 = 5; -//const int M_QX2 = 6; -//const int M_JX3 = 7; -//const int M_QX3 = 8; -//const int M_3PX1X1 = 9; -//const int M_3PIX1X1 = 10; -//const int M_PWW = 11; -//const int M_PIWW = 12; -//const int M_PX1X2 = 13; -//const int M_PX2X3 = 14; -//const int M_PX1X3 = 15; -//const int M_MX1 = 16; -//const int M_MX2 = 17; -//const int M_MX3 = 18; - -//const int STARTM = 0; -//const int ENDM = 18; //D3Q27 +using namespace UbMath; + +// index 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18//falsch +// f: ZERO, E, W, N, S, T, B, NE, SW, SE, NW, TE, BW, BE, TW, TN, BS, BN, TS, TNE TNW TSE TSW BNE BNW +// BSE BSW const int EX1[] = { 0, 1, -1, 0, 0, 0, 0, 1, -1, 1, -1, 1, -1, 1, -1, 0, 0, 0, 0, 1, -1, 1, -1, +// 1, -1, 1, -1 }; const int EX2[] = { 0, 0, 0, 1, -1, 0, 0, 1, -1, -1, 1, 0, 0, 0, 0, 1, -1, 1, -1, 1, 1, +// -1, -1, 1, 1, -1, -1 }; const int EX3[] = { 0, 0, 0, 0, 0, 1, -1, 0, 0, 0, 0, 1, -1, -1, 1, 1, -1, -1, +// 1, 1, 1, 1, 1, -1, -1, -1, -1 }; + +// index 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 +// f: E, W, N, S, T, B, NE, SW, SE, NW, TE, BW, BE, TW, TN, BS, BN, TS, TNE TNW TSE TSW BNE BNW BSE +// BSW +const int DX1[] = { 1, -1, 0, 0, 0, 0, 1, -1, 1, -1, 1, -1, 1, -1, 0, 0, 0, 0, 1, -1, 1, -1, 1, -1, 1, -1 }; +const int DX2[] = { 0, 0, 1, -1, 0, 0, 1, -1, -1, 1, 0, 0, 0, 0, 1, -1, 1, -1, 1, 1, -1, -1, 1, 1, -1, -1 }; +const int DX3[] = { 0, 0, 0, 0, 1, -1, 0, 0, 0, 0, 1, -1, -1, 1, 1, -1, -1, 1, 1, 1, 1, 1, -1, -1, -1, -1 }; + +////index 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 +////f: E, W, N, S, T, B, NE, SW, SE, NW, TE, BW, BE, TW, TN, BS, BN, TS, TNE TNW TSE TSW BNE BNW +///BSE BSW +const double WEIGTH[] = { c2o27, c2o27, c2o27, c2o27, c2o27, c2o27, c1o54, c1o54, c1o54, + c1o54, c1o54, c1o54, c1o54, c1o54, c1o54, c1o54, c1o54, c1o54, + c1o216, c1o216, c1o216, c1o216, c1o216, c1o216, c1o216, c1o216, c8o27 }; + +const int INVDIR[] = { INV_E, INV_W, INV_N, INV_S, INV_T, INV_B, INV_NE, INV_SW, INV_SE, + INV_NW, INV_TE, INV_BW, INV_BE, INV_TW, INV_TN, INV_BS, INV_BN, INV_TS, + INV_TNE, INV_TNW, INV_TSE, INV_TSW, INV_BNE, INV_BNW, INV_BSE, INV_BSW }; + +// The x,y,z component for each normalized direction +const double cNorm[3][ENDDIR] = { { double(DX1[0]), + double(DX1[1]), + double(DX1[2]), + double(DX1[3]), + double(DX1[4]), + double(DX1[5]), + double(DX1[6]) / std::sqrt(double(2)), + double(DX1[7]) / std::sqrt(double(2)), + double(DX1[8]) / std::sqrt(double(2)), + double(DX1[9]) / std::sqrt(double(2)), + double(DX1[10]) / std::sqrt(double(2)), + double(DX1[11]) / std::sqrt(double(2)), + double(DX1[12]) / std::sqrt(double(2)), + double(DX1[13]) / std::sqrt(double(2)), + double(DX1[14]), + double(DX1[15]), + double(DX1[16]), + double(DX1[17]), + double(DX1[18]) / std::sqrt(double(3)), + double(DX1[19]) / std::sqrt(double(3)), + double(DX1[20]) / std::sqrt(double(3)), + double(DX1[21]) / std::sqrt(double(3)), + double(DX1[22]) / std::sqrt(double(3)), + double(DX1[23]) / std::sqrt(double(3)), + double(DX1[24]) / std::sqrt(double(3)), + double(DX1[25]) / std::sqrt(double(3)) }, + { double(DX2[0]), + double(DX2[1]), + double(DX2[2]), + double(DX2[3]), + double(DX2[4]), + double(DX2[5]), + double(DX2[6]) / std::sqrt(double(2)), + double(DX2[7]) / std::sqrt(double(2)), + double(DX2[8]) / std::sqrt(double(2)), + double(DX2[9]) / std::sqrt(double(2)), + double(DX2[10]), + double(DX2[11]), + double(DX2[12]), + double(DX2[13]), + double(DX2[14]) / std::sqrt(double(2)), + double(DX2[15]) / std::sqrt(double(2)), + double(DX2[16]) / std::sqrt(double(2)), + double(DX2[17]) / std::sqrt(double(2)), + double(DX2[18]) / std::sqrt(double(3)), + double(DX2[19]) / std::sqrt(double(3)), + double(DX2[20]) / std::sqrt(double(3)), + double(DX2[21]) / std::sqrt(double(3)), + double(DX2[22]) / std::sqrt(double(3)), + double(DX2[23]) / std::sqrt(double(3)), + double(DX2[24]) / std::sqrt(double(3)), + double(DX2[25]) / std::sqrt(double(3)) }, + { double(DX3[0]), + double(DX3[1]), + double(DX3[2]), + double(DX3[3]), + double(DX3[4]), + double(DX3[5]), + double(DX3[6]), + double(DX3[7]), + double(DX3[8]), + double(DX3[9]), + double(DX3[10]) / std::sqrt(double(2)), + double(DX3[11]) / std::sqrt(double(2)), + double(DX3[12]) / std::sqrt(double(2)), + double(DX3[13]) / std::sqrt(double(2)), + double(DX3[14]) / std::sqrt(double(2)), + double(DX3[15]) / std::sqrt(double(2)), + double(DX3[16]) / std::sqrt(double(2)), + double(DX3[17]) / std::sqrt(double(2)), + double(DX3[18]) / std::sqrt(double(3)), + double(DX3[19]) / std::sqrt(double(3)), + double(DX3[20]) / std::sqrt(double(3)), + double(DX3[21]) / std::sqrt(double(3)), + double(DX3[22]) / std::sqrt(double(3)), + double(DX3[23]) / std::sqrt(double(3)), + double(DX3[24]) / std::sqrt(double(3)), + double(DX3[25]) / std::sqrt(double(3)) } }; + +} // namespace D3Q27System + +// const int FSTARTDIR = 0; +// const int FENDDIR = 25; //D3Q27 + +// const int STARTF = 0; +// const int ENDF = 26; //D3Q27 + +// const int EX1[ENDF+1]; +// const int EX2[ENDF+1]; +// const int EX3[ENDF+1]; + +// const int STARTDIR = 0; +// const int ENDDIR = 26; //alle geometrischen richtungen + +// const int DX1[ENDDIR+1]; +// const int DX2[ENDDIR+1]; +// const int DX3[ENDDIR+1]; + +// const int E /*f1 */ = 0; +// const int W /*f2 */ = 1; +// const int N /*f3 */ = 2; +// const int S /*f4 */ = 3; +// const int T /*f5 */ = 4; +// const int B /*f6 */ = 5; +// const int NE /*f7 */ = 6; +// const int SW /*f8 */ = 7; +// const int SE /*f9 */ = 8; +// const int NW /*f10*/ = 9; +// const int TE /*f11*/ = 10; +// const int BW /*f12*/ = 11; +// const int BE /*f13*/ = 12; +// const int TW /*f14*/ = 13; +// const int TN /*f15*/ = 14; +// const int BS /*f16*/ = 15; +// const int BN /*f17*/ = 16; +// const int TS /*f18*/ = 17; +// const int TNE = 18; +// const int TNW = 19; +// const int TSE = 20; +// const int TSW = 21; +// const int BNE = 22; +// const int BNW = 23; +// const int BSE = 24; +// const int BSW = 25; +// const int ZERO /*f0 */ = 26; + +// const int INV_E = W; +// const int INV_W = E; +// const int INV_N = S; +// const int INV_S = N; +// const int INV_T = B; +// const int INV_B = T; +// const int INV_NE = SW; +// const int INV_SW = NE; +// const int INV_SE = NW; +// const int INV_NW = SE; +// const int INV_TE = BW; +// const int INV_BW = TE; +// const int INV_BE = TW; +// const int INV_TW = BE; +// const int INV_TN = BS; +// const int INV_BS = TN; +// const int INV_BN = TS; +// const int INV_TS = BN; +// const int INV_TNE = BSW; +// const int INV_TNW = BSE; +// const int INV_TSE = BNW; +// const int INV_TSW = BNE; +// const int INV_BNE = TSW; +// const int INV_BNW = TSE; +// const int INV_BSE = TNW; +// const int INV_BSW = TNE; + +// const int INVDIR[ENDDIR+1]; + +// const int M_RHO = 0; +// const int M_EN = 1; +// const int M_EPS = 2; +// const int M_JX1 = 3; +// const int M_QX1 = 4; +// const int M_JX2 = 5; +// const int M_QX2 = 6; +// const int M_JX3 = 7; +// const int M_QX3 = 8; +// const int M_3PX1X1 = 9; +// const int M_3PIX1X1 = 10; +// const int M_PWW = 11; +// const int M_PIWW = 12; +// const int M_PX1X2 = 13; +// const int M_PX2X3 = 14; +// const int M_PX1X3 = 15; +// const int M_MX1 = 16; +// const int M_MX2 = 17; +// const int M_MX3 = 18; + +// const int STARTM = 0; +// const int ENDM = 18; //D3Q27 diff --git a/src/cpu/VirtualFluidsCore/LBM/D3Q27System.h b/src/cpu/VirtualFluidsCore/LBM/D3Q27System.h index e5b93f54b7d855262f7c24ac6d5770a404e3fd0d..1376e0da61d5ba3f45ef7acf5e34abae66f89673 100644 --- a/src/cpu/VirtualFluidsCore/LBM/D3Q27System.h +++ b/src/cpu/VirtualFluidsCore/LBM/D3Q27System.h @@ -1,28 +1,28 @@ //======================================================================================= -// ____ ____ __ ______ __________ __ __ __ __ -// \ \ | | | | | _ \ |___ ___| | | | | / \ | | -// \ \ | | | | | |_) | | | | | | | / \ | | -// \ \ | | | | | _ / | | | | | | / /\ \ | | -// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ -// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| -// \ \ | | ________________________________________________________________ -// \ \ | | | ______________________________________________________________| -// \ \| | | | __ __ __ __ ______ _______ -// \ | | |_____ | | | | | | | | | _ \ / _____) -// \ | | _____| | | | | | | | | | | \ \ \_______ +// ____ ____ __ ______ __________ __ __ __ __ +// \ \ | | | | | _ \ |___ ___| | | | | / \ | | +// \ \ | | | | | |_) | | | | | | | / \ | | +// \ \ | | | | | _ / | | | | | | / /\ \ | | +// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ +// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| +// \ \ | | ________________________________________________________________ +// \ \ | | | ______________________________________________________________| +// \ \| | | | __ __ __ __ ______ _______ +// \ | | |_____ | | | | | | | | | _ \ / _____) +// \ | | _____| | | | | | | | | | | \ \ \_______ // \ | | | | |_____ | \_/ | | | | |_/ / _____ | -// \ _____| |__| |________| \_______/ |__| |______/ (_______/ +// \ _____| |__| |________| \_______/ |__| |______/ (_______/ // -// This file is part of VirtualFluids. VirtualFluids is free software: you can +// This file is part of VirtualFluids. VirtualFluids is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of +// License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. -// -// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// +// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License along // with VirtualFluids (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>. // @@ -35,609 +35,784 @@ #define D3Q27SYSTEM_H #include <cmath> -#include <string> #include <iostream> +#include <string> +#include "LBMSystem.h" #include "UbException.h" #include "UbMath.h" -#include "LBMSystem.h" //! \brief namespace for global system-functions namespace D3Q27System { - ////////////////////////////////////////////////////////////////////////// - //DIRECTION STUFF - static const int FSTARTDIR = 0; - static const int FENDDIR = 25; //D3Q27 +////////////////////////////////////////////////////////////////////////// +// DIRECTION STUFF +static const int FSTARTDIR = 0; +static const int FENDDIR = 25; // D3Q27 - static const int STARTF = 0; - static const int ENDF = 26; //D3Q27 +static const int STARTF = 0; +static const int ENDF = 26; // D3Q27 - static const int STARTDIR = 0; - static const int ENDDIR = 26; +static const int STARTDIR = 0; +static const int ENDDIR = 26; - extern const int DX1[ENDDIR+1]; - extern const int DX2[ENDDIR+1]; - extern const int DX3[ENDDIR+1]; - extern const double WEIGTH[ENDDIR+1]; +extern const int DX1[ENDDIR + 1]; +extern const int DX2[ENDDIR + 1]; +extern const int DX3[ENDDIR + 1]; +extern const double WEIGTH[ENDDIR + 1]; - extern const double cNorm[3][ENDDIR]; - - //static const int ZERO /*f0 */ = 0; - //static const int E /*f1 */ = 1; - //static const int W /*f2 */ = 2; - //static const int N /*f3 */ = 3; - //static const int S /*f4 */ = 4; - //static const int T /*f5 */ = 5; - //static const int B /*f6 */ = 6; - //static const int NE /*f7 */ = 7; - //static const int SW /*f8 */ = 8; - //static const int SE /*f9 */ = 9; - //static const int NW /*f10*/ = 10; - //static const int TE /*f11*/ = 11; - //static const int BW /*f12*/ = 12; - //static const int BE /*f13*/ = 13; - //static const int TW /*f14*/ = 14; - //static const int TN /*f15*/ = 15; - //static const int BS /*f16*/ = 16; - //static const int BN /*f17*/ = 17; - //static const int TS /*f18*/ = 18; - //static const int TNE = 19; - //static const int TNW = 20; - //static const int TSE = 21; - //static const int TSW = 22; - //static const int BNE = 23; - //static const int BNW = 24; - //static const int BSE = 25; - //static const int BSW = 26; +extern const double cNorm[3][ENDDIR]; - static const int E /*f1 */ = 0; - static const int W /*f2 */ = 1; - static const int N /*f3 */ = 2; - static const int S /*f4 */ = 3; - static const int T /*f5 */ = 4; - static const int B /*f6 */ = 5; - static const int NE /*f7 */ = 6; - static const int SW /*f8 */ = 7; - static const int SE /*f9 */ = 8; - static const int NW /*f10*/ = 9; - static const int TE /*f11*/ = 10; - static const int BW /*f12*/ = 11; - static const int BE /*f13*/ = 12; - static const int TW /*f14*/ = 13; - static const int TN /*f15*/ = 14; - static const int BS /*f16*/ = 15; - static const int BN /*f17*/ = 16; - static const int TS /*f18*/ = 17; - static const int TNE = 18; - static const int TNW = 19; - static const int TSE = 20; - static const int TSW = 21; - static const int BNE = 22; - static const int BNW = 23; - static const int BSE = 24; - static const int BSW = 25; - static const int ZERO /*f0 */ = 26; +// static const int ZERO /*f0 */ = 0; +// static const int E /*f1 */ = 1; +// static const int W /*f2 */ = 2; +// static const int N /*f3 */ = 3; +// static const int S /*f4 */ = 4; +// static const int T /*f5 */ = 5; +// static const int B /*f6 */ = 6; +// static const int NE /*f7 */ = 7; +// static const int SW /*f8 */ = 8; +// static const int SE /*f9 */ = 9; +// static const int NW /*f10*/ = 10; +// static const int TE /*f11*/ = 11; +// static const int BW /*f12*/ = 12; +// static const int BE /*f13*/ = 13; +// static const int TW /*f14*/ = 14; +// static const int TN /*f15*/ = 15; +// static const int BS /*f16*/ = 16; +// static const int BN /*f17*/ = 17; +// static const int TS /*f18*/ = 18; +// static const int TNE = 19; +// static const int TNW = 20; +// static const int TSE = 21; +// static const int TSW = 22; +// static const int BNE = 23; +// static const int BNW = 24; +// static const int BSE = 25; +// static const int BSW = 26; - static const int INV_E = W; - static const int INV_W = E; - static const int INV_N = S; - static const int INV_S = N; - static const int INV_T = B; - static const int INV_B = T; - static const int INV_NE = SW; - static const int INV_SW = NE; - static const int INV_SE = NW; - static const int INV_NW = SE; - static const int INV_TE = BW; - static const int INV_BW = TE; - static const int INV_BE = TW; - static const int INV_TW = BE; - static const int INV_TN = BS; - static const int INV_BS = TN; - static const int INV_BN = TS; - static const int INV_TS = BN; - static const int INV_TNE = BSW; - static const int INV_TNW = BSE; - static const int INV_TSE = BNW; - static const int INV_TSW = BNE; - static const int INV_BNE = TSW; - static const int INV_BNW = TSE; - static const int INV_BSE = TNW; - static const int INV_BSW = TNE; - - extern const int INVDIR[ENDDIR+1]; +static const int E /*f1 */ = 0; +static const int W /*f2 */ = 1; +static const int N /*f3 */ = 2; +static const int S /*f4 */ = 3; +static const int T /*f5 */ = 4; +static const int B /*f6 */ = 5; +static const int NE /*f7 */ = 6; +static const int SW /*f8 */ = 7; +static const int SE /*f9 */ = 8; +static const int NW /*f10*/ = 9; +static const int TE /*f11*/ = 10; +static const int BW /*f12*/ = 11; +static const int BE /*f13*/ = 12; +static const int TW /*f14*/ = 13; +static const int TN /*f15*/ = 14; +static const int BS /*f16*/ = 15; +static const int BN /*f17*/ = 16; +static const int TS /*f18*/ = 17; +static const int TNE = 18; +static const int TNW = 19; +static const int TSE = 20; +static const int TSW = 21; +static const int BNE = 22; +static const int BNW = 23; +static const int BSE = 24; +static const int BSW = 25; +static const int ZERO /*f0 */ = 26; - static const int ET_E = 0; - static const int ET_W = 0; - static const int ET_N = 1; - static const int ET_S = 1; - static const int ET_T = 2; - static const int ET_B = 2; - static const int ET_NE = 3; - static const int ET_SW = 3; - static const int ET_SE = 4; - static const int ET_NW = 4; - static const int ET_TE = 5; - static const int ET_BW = 5; - static const int ET_BE = 6; - static const int ET_TW = 6; - static const int ET_TN = 7; - static const int ET_BS = 7; - static const int ET_BN = 8; - static const int ET_TS = 8; - static const int ET_TNE = 9; - static const int ET_BSW = 9; - static const int ET_TNW = 10; - static const int ET_BSE = 10; - static const int ET_TSE = 11; - static const int ET_BNW = 11; - static const int ET_TSW = 12; - static const int ET_BNE = 12; +static const int INV_E = W; +static const int INV_W = E; +static const int INV_N = S; +static const int INV_S = N; +static const int INV_T = B; +static const int INV_B = T; +static const int INV_NE = SW; +static const int INV_SW = NE; +static const int INV_SE = NW; +static const int INV_NW = SE; +static const int INV_TE = BW; +static const int INV_BW = TE; +static const int INV_BE = TW; +static const int INV_TW = BE; +static const int INV_TN = BS; +static const int INV_BS = TN; +static const int INV_BN = TS; +static const int INV_TS = BN; +static const int INV_TNE = BSW; +static const int INV_TNW = BSE; +static const int INV_TSE = BNW; +static const int INV_TSW = BNE; +static const int INV_BNE = TSW; +static const int INV_BNW = TSE; +static const int INV_BSE = TNW; +static const int INV_BSW = TNE; - static const int M_RHO = 0; - static const int M_EN = 1; - static const int M_EPS = 2; - static const int M_JX1 = 3; - static const int M_QX1 = 4; - static const int M_JX2 = 5; - static const int M_QX2 = 6; - static const int M_JX3 = 7; - static const int M_QX3 = 8; - static const int M_3PX1X1 = 9; - static const int M_3PIX1X1 = 10; - static const int M_PWW = 11; - static const int M_PIWW = 12; - static const int M_PX1X2 = 13; - static const int M_PX2X3 = 14; - static const int M_PX1X3 = 15; - static const int M_MX1 = 16; - static const int M_MX2 = 17; - static const int M_MX3 = 18; - - static const int STARTM = 0; - static const int ENDM = 18; //D3Q27 +extern const int INVDIR[ENDDIR + 1]; +static const int ET_E = 0; +static const int ET_W = 0; +static const int ET_N = 1; +static const int ET_S = 1; +static const int ET_T = 2; +static const int ET_B = 2; +static const int ET_NE = 3; +static const int ET_SW = 3; +static const int ET_SE = 4; +static const int ET_NW = 4; +static const int ET_TE = 5; +static const int ET_BW = 5; +static const int ET_BE = 6; +static const int ET_TW = 6; +static const int ET_TN = 7; +static const int ET_BS = 7; +static const int ET_BN = 8; +static const int ET_TS = 8; +static const int ET_TNE = 9; +static const int ET_BSW = 9; +static const int ET_TNW = 10; +static const int ET_BSE = 10; +static const int ET_TSE = 11; +static const int ET_BNW = 11; +static const int ET_TSW = 12; +static const int ET_BNE = 12; - - ////////////////////////////////////////////////////////////////////////// - //MACROSCOPIC VALUES - /*=====================================================================*/ - static LBMReal getDensity(const LBMReal* const& f/*[27]*/) - { - return ((f[TNE] + f[BSW])+(f[TSE]+f[BNW]))+((f[BSE]+f[TNW])+ (f[TSW]+f[BNE])) - +(((f[NE] + f[SW]) + (f[SE] + f[NW]))+((f[TE] + f[BW])+(f[BE]+ f[TW])) - +((f[BN] + f[TS]) + (f[TN] + f[BS])))+((f[E] + f[W])+(f[N] + f[S]) - +(f[T] + f[B]))+f[ZERO]; - } - /*=====================================================================*/ - //ATTENTION: does not apply to all models -> use certificate instead of static! to do - static LBMReal getPressure(const LBMReal* const& f/*[27]*/) - { - return REAL_CAST( UbMath::c1o3 )*getDensity(f); - } - /*=====================================================================*/ - static LBMReal getIncompVelocityX1(const LBMReal* const& f/*[27]*/) - { - return ((((f[TNE]-f[BSW]) + (f[TSE]-f[BNW])) + ((f[BSE]-f[TNW]) + (f[BNE]-f[TSW]))) + - (((f[BE]-f[TW]) + (f[TE]-f[BW])) + ((f[SE]-f[NW]) + (f[NE]-f[SW]))) + - (f[E]-f[W])); - } - /*=====================================================================*/ - static LBMReal getIncompVelocityX2(const LBMReal* const& f/*[27]*/) - { - return ((((f[TNE]-f[BSW]) + (f[BNW]-f[TSE])) + ((f[TNW]-f[BSE]) + (f[BNE]-f[TSW]))) + - (((f[BN]-f[TS]) + (f[TN]-f[BS])) + ((f[NW]-f[SE]) + (f[NE]-f[SW]))) + - (f[N]-f[S])); - } - /*=====================================================================*/ - static LBMReal getIncompVelocityX3(const LBMReal* const& f/*[27]*/) - { - return ((((f[TNE] - f[BSW]) + (f[TSE] - f[BNW])) + ((f[TNW] - f[BSE]) + (f[TSW] - f[BNE]))) + - (((f[TS] - f[BN]) + (f[TN] - f[BS])) + ((f[TW] - f[BE]) + (f[TE] - f[BW]))) + - (f[T] - f[B])); - } - /*=====================================================================*/ - static void calcDensity(const LBMReal* const& f/*[27]*/, LBMReal& rho) - { - rho = ((f[TNE] + f[BSW])+(f[TSE]+f[BNW]))+((f[BSE]+f[TNW])+ (f[TSW]+f[BNE])) - +(((f[NE] + f[SW]) + (f[SE] + f[NW]))+((f[TE] + f[BW])+(f[BE]+ f[TW])) - +((f[BN] + f[TS]) + (f[TN] + f[BS])))+((f[E] + f[W])+(f[N] + f[S]) - +(f[T] + f[B]))+f[ZERO]; - - } - /*=====================================================================*/ - static void calcIncompVelocityX1(const LBMReal* const& f/*[27]*/, LBMReal& vx1) - { - vx1 = ((((f[TNE]-f[BSW]) + (f[TSE]-f[BNW])) + ((f[BSE]-f[TNW]) + (f[BNE]-f[TSW]))) + - (((f[BE]-f[TW]) + (f[TE]-f[BW])) + ((f[SE]-f[NW]) + (f[NE]-f[SW]))) + - (f[E]-f[W])); - } - /*=====================================================================*/ - static void calcIncompVelocityX2(const LBMReal* const& f/*[27]*/, LBMReal& vx2) - { - vx2 = ((((f[TNE]-f[BSW]) + (f[BNW]-f[TSE])) + ((f[TNW]-f[BSE]) + (f[BNE]-f[TSW]))) + - (((f[BN]-f[TS]) + (f[TN]-f[BS])) + ((f[NW]-f[SE]) + (f[NE]-f[SW]))) + - (f[N]-f[S])); - } - /*=====================================================================*/ - static void calcIncompVelocityX3(const LBMReal* const& f/*[27]*/, LBMReal& vx3) - { - vx3 =((((f[TNE]-f[BSW]) + (f[TSE]-f[BNW])) + ((f[TNW]-f[BSE]) + (f[TSW]-f[BNE]))) + - (((f[TS]-f[BN]) + (f[TN]-f[BS])) + ((f[TW]-f[BE]) + (f[TE]-f[BW]))) + - (f[T]-f[B])); - } - /*=====================================================================*/ - static LBMReal getCompVelocityX1(const LBMReal* const& f/*[27]*/) - { - return ((((f[TNE]-f[BSW]) + (f[TSE]-f[BNW])) + ((f[BSE]-f[TNW]) + (f[BNE]-f[TSW]))) + - (((f[BE]-f[TW]) + (f[TE]-f[BW])) + ((f[SE]-f[NW]) + (f[NE]-f[SW]))) + - (f[E]-f[W]))/getDensity(f); - } - /*=====================================================================*/ - static LBMReal getCompVelocityX2(const LBMReal* const& f/*[27]*/) - { - return ((((f[TNE]-f[BSW]) + (f[BNW]-f[TSE])) + ((f[TNW]-f[BSE]) + (f[BNE]-f[TSW]))) + - (((f[BN]-f[TS]) + (f[TN]-f[BS])) + ((f[NW]-f[SE]) + (f[NE]-f[SW]))) + - (f[N]-f[S]))/getDensity(f); - } - /*=====================================================================*/ - static LBMReal getCompVelocityX3(const LBMReal* const& f/*[27]*/) - { - return ((((f[TNE]-f[BSW]) + (f[TSE]-f[BNW])) + ((f[TNW]-f[BSE]) + (f[TSW]-f[BNE]))) + - (((f[TS]-f[BN]) + (f[TN]-f[BS])) + ((f[TW]-f[BE]) + (f[TE]-f[BW]))) + - (f[T]-f[B]))/getDensity(f); - } - /*=====================================================================*/ - static void calcCompVelocityX1(const LBMReal* const& f/*[27]*/, LBMReal& vx1) - { - vx1 = ((((f[TNE]-f[BSW]) + (f[TSE]-f[BNW])) + ((f[BSE]-f[TNW]) + (f[BNE]-f[TSW]))) + - (((f[BE]-f[TW]) + (f[TE]-f[BW])) + ((f[SE]-f[NW]) + (f[NE]-f[SW]))) + - (f[E]-f[W]))/getDensity(f); - } - /*=====================================================================*/ - static void calcCompVelocityX2(const LBMReal* const& f/*[27]*/, LBMReal& vx2) - { - vx2 = ((((f[TNE]-f[BSW]) + (f[BNW]-f[TSE])) + ((f[TNW]-f[BSE]) + (f[BNE]-f[TSW]))) + - (((f[BN]-f[TS]) + (f[TN]-f[BS])) + ((f[NW]-f[SE]) + (f[NE]-f[SW]))) + - (f[N]-f[S]))/getDensity(f); - } - /*=====================================================================*/ - static void calcCompVelocityX3(const LBMReal* const& f/*[27]*/, LBMReal& vx3) - { - vx3 = ((((f[TNE]-f[BSW]) + (f[TSE]-f[BNW])) + ((f[TNW]-f[BSE]) + (f[TSW]-f[BNE]))) + - (((f[TS]-f[BN]) + (f[TN]-f[BS])) + ((f[TW]-f[BE]) + (f[TE]-f[BW]))) + - (f[T]-f[B]))/getDensity(f); - } - /*=====================================================================*/ - static void calcIncompMacroscopicValues(const LBMReal* const& f/*[27]*/, LBMReal& rho, LBMReal& vx1, LBMReal& vx2, LBMReal& vx3) - { - D3Q27System::calcDensity(f, rho); - D3Q27System::calcIncompVelocityX1(f, vx1); - D3Q27System::calcIncompVelocityX2(f, vx2); - D3Q27System::calcIncompVelocityX3(f, vx3); - } +static const int M_RHO = 0; +static const int M_EN = 1; +static const int M_EPS = 2; +static const int M_JX1 = 3; +static const int M_QX1 = 4; +static const int M_JX2 = 5; +static const int M_QX2 = 6; +static const int M_JX3 = 7; +static const int M_QX3 = 8; +static const int M_3PX1X1 = 9; +static const int M_3PIX1X1 = 10; +static const int M_PWW = 11; +static const int M_PIWW = 12; +static const int M_PX1X2 = 13; +static const int M_PX2X3 = 14; +static const int M_PX1X3 = 15; +static const int M_MX1 = 16; +static const int M_MX2 = 17; +static const int M_MX3 = 18; - /*=====================================================================*/ - static void calcCompMacroscopicValues(const LBMReal* const& f/*[27]*/, LBMReal& drho, LBMReal& vx1, LBMReal& vx2, LBMReal& vx3) - { - D3Q27System::calcDensity(f, drho); - D3Q27System::calcIncompVelocityX1(f, vx1); - D3Q27System::calcIncompVelocityX2(f, vx2); - D3Q27System::calcIncompVelocityX3(f, vx3); - LBMReal rho = drho+UbMath::c1; - vx1/=rho; - vx2/=rho; - vx3/=rho; - } - ////////////////////////////////////////////////////////////////////////// - static LBMReal getCompFeqForDirection(const int& direction, const LBMReal& drho,const LBMReal& vx1,const LBMReal& vx2,const LBMReal& vx3) - { - using namespace UbMath; - LBMReal cu_sq=1.5*(vx1*vx1+vx2*vx2+vx3*vx3); +static const int STARTM = 0; +static const int ENDM = 18; // D3Q27 - ////----- - LBMReal rho = drho+c1; - switch (direction) - { - case ZERO: return REAL_CAST(c8o27*(drho+rho*(-cu_sq))); - case E: return REAL_CAST(c2o27*(drho+rho*(3.0*(vx1)+c9o2*(vx1)*(vx1)-cu_sq))); - case W: return REAL_CAST(c2o27*(drho+rho*(3.0*(-vx1)+c9o2*(-vx1)*(-vx1)-cu_sq))); - case N: return REAL_CAST(c2o27*(drho+rho*(3.0*(vx2)+c9o2*(vx2)*(vx2)-cu_sq))); - case S: return REAL_CAST(c2o27*(drho+rho*(3.0*(-vx2)+c9o2*(-vx2)*(-vx2)-cu_sq))); - case T: return REAL_CAST(c2o27*(drho+rho*(3.0*(vx3)+c9o2*(vx3)*(vx3)-cu_sq))); - case B: return REAL_CAST(c2o27*(drho+rho*(3.0*(-vx3)+c9o2*(-vx3)*(-vx3)-cu_sq))); - case NE: return REAL_CAST(c1o54*(drho+rho*(3.0*(vx1+vx2)+c9o2*(vx1+vx2)*(vx1+vx2)-cu_sq))); - case SW: return REAL_CAST(c1o54*(drho+rho*(3.0*(-vx1-vx2)+c9o2*(-vx1-vx2)*(-vx1-vx2)-cu_sq))); - case SE: return REAL_CAST(c1o54*(drho+rho*(3.0*(vx1-vx2)+c9o2*(vx1-vx2)*(vx1-vx2)-cu_sq))); - case NW: return REAL_CAST(c1o54*(drho+rho*(3.0*(-vx1+vx2)+c9o2*(-vx1+vx2)*(-vx1+vx2)-cu_sq))); - case TE: return REAL_CAST(c1o54*(drho+rho*(3.0*(vx1+vx3)+c9o2*(vx1+vx3)*(vx1+vx3)-cu_sq))); - case BW: return REAL_CAST(c1o54*(drho+rho*(3.0*(-vx1-vx3)+c9o2*(-vx1-vx3)*(-vx1-vx3)-cu_sq))); - case BE: return REAL_CAST(c1o54*(drho+rho*(3.0*(vx1-vx3)+c9o2*(vx1-vx3)*(vx1-vx3)-cu_sq))); - case TW: return REAL_CAST(c1o54*(drho+rho*(3.0*(-vx1+vx3)+c9o2*(-vx1+vx3)*(-vx1+vx3)-cu_sq))); - case TN: return REAL_CAST(c1o54*(drho+rho*(3.0*(vx2+vx3)+c9o2*(vx2+vx3)*(vx2+vx3)-cu_sq))); - case BS: return REAL_CAST(c1o54*(drho+rho*(3.0*(-vx2-vx3)+c9o2*(-vx2-vx3)*(-vx2-vx3)-cu_sq))); - case BN: return REAL_CAST(c1o54*(drho+rho*(3.0*(vx2-vx3)+c9o2*(vx2-vx3)*(vx2-vx3)-cu_sq))); - case TS: return REAL_CAST(c1o54*(drho+rho*(3.0*(-vx2+vx3)+c9o2*(-vx2+vx3)*(-vx2+vx3)-cu_sq))); - case TNE: return REAL_CAST(c1o216*(drho+rho*(3.0*(vx1+vx2+vx3)+c9o2*(vx1+vx2+vx3)*(vx1+vx2+vx3)-cu_sq))); - case BSW: return REAL_CAST(c1o216*(drho+rho*(3.0*(-vx1-vx2-vx3)+c9o2*(-vx1-vx2-vx3)*(-vx1-vx2-vx3)-cu_sq))); - case BNE: return REAL_CAST(c1o216*(drho+rho*(3.0*(vx1+vx2-vx3)+c9o2*(vx1+vx2-vx3)*(vx1+vx2-vx3)-cu_sq))); - case TSW: return REAL_CAST(c1o216*(drho+rho*(3.0*(-vx1-vx2+vx3)+c9o2*(-vx1-vx2+vx3)*(-vx1-vx2+vx3)-cu_sq))); - case TSE: return REAL_CAST(c1o216*(drho+rho*(3.0*(vx1-vx2+vx3)+c9o2*(vx1-vx2+vx3)*(vx1-vx2+vx3)-cu_sq))); - case BNW: return REAL_CAST(c1o216*(drho+rho*(3.0*(-vx1+vx2-vx3)+c9o2*(-vx1+vx2-vx3)*(-vx1+vx2-vx3)-cu_sq))); - case BSE: return REAL_CAST(c1o216*(drho+rho*(3.0*(vx1-vx2-vx3)+c9o2*(vx1-vx2-vx3)*(vx1-vx2-vx3)-cu_sq))); - case TNW: return REAL_CAST(c1o216*(drho+rho*(3.0*(-vx1+vx2+vx3)+c9o2*(-vx1+vx2+vx3)*(-vx1+vx2+vx3)-cu_sq))); - default: throw UbException(UB_EXARGS, "unknown dir"); - } +////////////////////////////////////////////////////////////////////////// +// MACROSCOPIC VALUES +/*=====================================================================*/ +static LBMReal getDensity(const LBMReal *const &f /*[27]*/) +{ + return ((f[TNE] + f[BSW]) + (f[TSE] + f[BNW])) + ((f[BSE] + f[TNW]) + (f[TSW] + f[BNE])) + + (((f[NE] + f[SW]) + (f[SE] + f[NW])) + ((f[TE] + f[BW]) + (f[BE] + f[TW])) + + ((f[BN] + f[TS]) + (f[TN] + f[BS]))) + + ((f[E] + f[W]) + (f[N] + f[S]) + (f[T] + f[B])) + f[ZERO]; +} +/*=====================================================================*/ +// ATTENTION: does not apply to all models -> use certificate instead of static! to do +static LBMReal getPressure(const LBMReal *const &f /*[27]*/) { return REAL_CAST(UbMath::c1o3) * getDensity(f); } +/*=====================================================================*/ +static LBMReal getIncompVelocityX1(const LBMReal *const &f /*[27]*/) +{ + return ((((f[TNE] - f[BSW]) + (f[TSE] - f[BNW])) + ((f[BSE] - f[TNW]) + (f[BNE] - f[TSW]))) + + (((f[BE] - f[TW]) + (f[TE] - f[BW])) + ((f[SE] - f[NW]) + (f[NE] - f[SW]))) + (f[E] - f[W])); +} +/*=====================================================================*/ +static LBMReal getIncompVelocityX2(const LBMReal *const &f /*[27]*/) +{ + return ((((f[TNE] - f[BSW]) + (f[BNW] - f[TSE])) + ((f[TNW] - f[BSE]) + (f[BNE] - f[TSW]))) + + (((f[BN] - f[TS]) + (f[TN] - f[BS])) + ((f[NW] - f[SE]) + (f[NE] - f[SW]))) + (f[N] - f[S])); +} +/*=====================================================================*/ +static LBMReal getIncompVelocityX3(const LBMReal *const &f /*[27]*/) +{ + return ((((f[TNE] - f[BSW]) + (f[TSE] - f[BNW])) + ((f[TNW] - f[BSE]) + (f[TSW] - f[BNE]))) + + (((f[TS] - f[BN]) + (f[TN] - f[BS])) + ((f[TW] - f[BE]) + (f[TE] - f[BW]))) + (f[T] - f[B])); +} +/*=====================================================================*/ +static void calcDensity(const LBMReal *const &f /*[27]*/, LBMReal &rho) +{ + rho = ((f[TNE] + f[BSW]) + (f[TSE] + f[BNW])) + ((f[BSE] + f[TNW]) + (f[TSW] + f[BNE])) + + (((f[NE] + f[SW]) + (f[SE] + f[NW])) + ((f[TE] + f[BW]) + (f[BE] + f[TW])) + + ((f[BN] + f[TS]) + (f[TN] + f[BS]))) + + ((f[E] + f[W]) + (f[N] + f[S]) + (f[T] + f[B])) + f[ZERO]; +} +/*=====================================================================*/ +static void calcIncompVelocityX1(const LBMReal *const &f /*[27]*/, LBMReal &vx1) +{ + vx1 = ((((f[TNE] - f[BSW]) + (f[TSE] - f[BNW])) + ((f[BSE] - f[TNW]) + (f[BNE] - f[TSW]))) + + (((f[BE] - f[TW]) + (f[TE] - f[BW])) + ((f[SE] - f[NW]) + (f[NE] - f[SW]))) + (f[E] - f[W])); +} +/*=====================================================================*/ +static void calcIncompVelocityX2(const LBMReal *const &f /*[27]*/, LBMReal &vx2) +{ + vx2 = ((((f[TNE] - f[BSW]) + (f[BNW] - f[TSE])) + ((f[TNW] - f[BSE]) + (f[BNE] - f[TSW]))) + + (((f[BN] - f[TS]) + (f[TN] - f[BS])) + ((f[NW] - f[SE]) + (f[NE] - f[SW]))) + (f[N] - f[S])); +} +/*=====================================================================*/ +static void calcIncompVelocityX3(const LBMReal *const &f /*[27]*/, LBMReal &vx3) +{ + vx3 = ((((f[TNE] - f[BSW]) + (f[TSE] - f[BNW])) + ((f[TNW] - f[BSE]) + (f[TSW] - f[BNE]))) + + (((f[TS] - f[BN]) + (f[TN] - f[BS])) + ((f[TW] - f[BE]) + (f[TE] - f[BW]))) + (f[T] - f[B])); +} +/*=====================================================================*/ +static LBMReal getCompVelocityX1(const LBMReal *const &f /*[27]*/) +{ + return ((((f[TNE] - f[BSW]) + (f[TSE] - f[BNW])) + ((f[BSE] - f[TNW]) + (f[BNE] - f[TSW]))) + + (((f[BE] - f[TW]) + (f[TE] - f[BW])) + ((f[SE] - f[NW]) + (f[NE] - f[SW]))) + (f[E] - f[W])) / + getDensity(f); +} +/*=====================================================================*/ +static LBMReal getCompVelocityX2(const LBMReal *const &f /*[27]*/) +{ + return ((((f[TNE] - f[BSW]) + (f[BNW] - f[TSE])) + ((f[TNW] - f[BSE]) + (f[BNE] - f[TSW]))) + + (((f[BN] - f[TS]) + (f[TN] - f[BS])) + ((f[NW] - f[SE]) + (f[NE] - f[SW]))) + (f[N] - f[S])) / + getDensity(f); +} +/*=====================================================================*/ +static LBMReal getCompVelocityX3(const LBMReal *const &f /*[27]*/) +{ + return ((((f[TNE] - f[BSW]) + (f[TSE] - f[BNW])) + ((f[TNW] - f[BSE]) + (f[TSW] - f[BNE]))) + + (((f[TS] - f[BN]) + (f[TN] - f[BS])) + ((f[TW] - f[BE]) + (f[TE] - f[BW]))) + (f[T] - f[B])) / + getDensity(f); +} +/*=====================================================================*/ +static void calcCompVelocityX1(const LBMReal *const &f /*[27]*/, LBMReal &vx1) +{ + vx1 = ((((f[TNE] - f[BSW]) + (f[TSE] - f[BNW])) + ((f[BSE] - f[TNW]) + (f[BNE] - f[TSW]))) + + (((f[BE] - f[TW]) + (f[TE] - f[BW])) + ((f[SE] - f[NW]) + (f[NE] - f[SW]))) + (f[E] - f[W])) / + getDensity(f); +} +/*=====================================================================*/ +static void calcCompVelocityX2(const LBMReal *const &f /*[27]*/, LBMReal &vx2) +{ + vx2 = ((((f[TNE] - f[BSW]) + (f[BNW] - f[TSE])) + ((f[TNW] - f[BSE]) + (f[BNE] - f[TSW]))) + + (((f[BN] - f[TS]) + (f[TN] - f[BS])) + ((f[NW] - f[SE]) + (f[NE] - f[SW]))) + (f[N] - f[S])) / + getDensity(f); +} +/*=====================================================================*/ +static void calcCompVelocityX3(const LBMReal *const &f /*[27]*/, LBMReal &vx3) +{ + vx3 = ((((f[TNE] - f[BSW]) + (f[TSE] - f[BNW])) + ((f[TNW] - f[BSE]) + (f[TSW] - f[BNE]))) + + (((f[TS] - f[BN]) + (f[TN] - f[BS])) + ((f[TW] - f[BE]) + (f[TE] - f[BW]))) + (f[T] - f[B])) / + getDensity(f); +} +/*=====================================================================*/ +static void calcIncompMacroscopicValues(const LBMReal *const &f /*[27]*/, LBMReal &rho, LBMReal &vx1, LBMReal &vx2, + LBMReal &vx3) +{ + D3Q27System::calcDensity(f, rho); + D3Q27System::calcIncompVelocityX1(f, vx1); + D3Q27System::calcIncompVelocityX2(f, vx2); + D3Q27System::calcIncompVelocityX3(f, vx3); +} - } - ////////////////////////////////////////////////////////////////////////// - static void calcCompFeq(LBMReal* const& feq/*[27]*/,const LBMReal& drho,const LBMReal& vx1,const LBMReal& vx2,const LBMReal& vx3) - { - using namespace UbMath; +/*=====================================================================*/ +static void calcCompMacroscopicValues(const LBMReal *const &f /*[27]*/, LBMReal &drho, LBMReal &vx1, LBMReal &vx2, + LBMReal &vx3) +{ + D3Q27System::calcDensity(f, drho); + D3Q27System::calcIncompVelocityX1(f, vx1); + D3Q27System::calcIncompVelocityX2(f, vx2); + D3Q27System::calcIncompVelocityX3(f, vx3); + LBMReal rho = drho + UbMath::c1; + vx1 /= rho; + vx2 /= rho; + vx3 /= rho; +} +////////////////////////////////////////////////////////////////////////// +static LBMReal getCompFeqForDirection(const int &direction, const LBMReal &drho, const LBMReal &vx1, const LBMReal &vx2, + const LBMReal &vx3) +{ + using namespace UbMath; + LBMReal cu_sq = 1.5 * (vx1 * vx1 + vx2 * vx2 + vx3 * vx3); + + ////----- + LBMReal rho = drho + c1; + switch (direction) { + case ZERO: + return REAL_CAST(c8o27 * (drho + rho * (-cu_sq))); + case E: + return REAL_CAST(c2o27 * (drho + rho * (3.0 * (vx1) + c9o2 * (vx1) * (vx1)-cu_sq))); + case W: + return REAL_CAST(c2o27 * (drho + rho * (3.0 * (-vx1) + c9o2 * (-vx1) * (-vx1) - cu_sq))); + case N: + return REAL_CAST(c2o27 * (drho + rho * (3.0 * (vx2) + c9o2 * (vx2) * (vx2)-cu_sq))); + case S: + return REAL_CAST(c2o27 * (drho + rho * (3.0 * (-vx2) + c9o2 * (-vx2) * (-vx2) - cu_sq))); + case T: + return REAL_CAST(c2o27 * (drho + rho * (3.0 * (vx3) + c9o2 * (vx3) * (vx3)-cu_sq))); + case B: + return REAL_CAST(c2o27 * (drho + rho * (3.0 * (-vx3) + c9o2 * (-vx3) * (-vx3) - cu_sq))); + case NE: + return REAL_CAST(c1o54 * (drho + rho * (3.0 * (vx1 + vx2) + c9o2 * (vx1 + vx2) * (vx1 + vx2) - cu_sq))); + case SW: + return REAL_CAST(c1o54 * (drho + rho * (3.0 * (-vx1 - vx2) + c9o2 * (-vx1 - vx2) * (-vx1 - vx2) - cu_sq))); + case SE: + return REAL_CAST(c1o54 * (drho + rho * (3.0 * (vx1 - vx2) + c9o2 * (vx1 - vx2) * (vx1 - vx2) - cu_sq))); + case NW: + return REAL_CAST(c1o54 * (drho + rho * (3.0 * (-vx1 + vx2) + c9o2 * (-vx1 + vx2) * (-vx1 + vx2) - cu_sq))); + case TE: + return REAL_CAST(c1o54 * (drho + rho * (3.0 * (vx1 + vx3) + c9o2 * (vx1 + vx3) * (vx1 + vx3) - cu_sq))); + case BW: + return REAL_CAST(c1o54 * (drho + rho * (3.0 * (-vx1 - vx3) + c9o2 * (-vx1 - vx3) * (-vx1 - vx3) - cu_sq))); + case BE: + return REAL_CAST(c1o54 * (drho + rho * (3.0 * (vx1 - vx3) + c9o2 * (vx1 - vx3) * (vx1 - vx3) - cu_sq))); + case TW: + return REAL_CAST(c1o54 * (drho + rho * (3.0 * (-vx1 + vx3) + c9o2 * (-vx1 + vx3) * (-vx1 + vx3) - cu_sq))); + case TN: + return REAL_CAST(c1o54 * (drho + rho * (3.0 * (vx2 + vx3) + c9o2 * (vx2 + vx3) * (vx2 + vx3) - cu_sq))); + case BS: + return REAL_CAST(c1o54 * (drho + rho * (3.0 * (-vx2 - vx3) + c9o2 * (-vx2 - vx3) * (-vx2 - vx3) - cu_sq))); + case BN: + return REAL_CAST(c1o54 * (drho + rho * (3.0 * (vx2 - vx3) + c9o2 * (vx2 - vx3) * (vx2 - vx3) - cu_sq))); + case TS: + return REAL_CAST(c1o54 * (drho + rho * (3.0 * (-vx2 + vx3) + c9o2 * (-vx2 + vx3) * (-vx2 + vx3) - cu_sq))); + case TNE: + return REAL_CAST(c1o216 * (drho + rho * (3.0 * (vx1 + vx2 + vx3) + + c9o2 * (vx1 + vx2 + vx3) * (vx1 + vx2 + vx3) - cu_sq))); + case BSW: + return REAL_CAST(c1o216 * (drho + rho * (3.0 * (-vx1 - vx2 - vx3) + + c9o2 * (-vx1 - vx2 - vx3) * (-vx1 - vx2 - vx3) - cu_sq))); + case BNE: + return REAL_CAST(c1o216 * (drho + rho * (3.0 * (vx1 + vx2 - vx3) + + c9o2 * (vx1 + vx2 - vx3) * (vx1 + vx2 - vx3) - cu_sq))); + case TSW: + return REAL_CAST(c1o216 * (drho + rho * (3.0 * (-vx1 - vx2 + vx3) + + c9o2 * (-vx1 - vx2 + vx3) * (-vx1 - vx2 + vx3) - cu_sq))); + case TSE: + return REAL_CAST(c1o216 * (drho + rho * (3.0 * (vx1 - vx2 + vx3) + + c9o2 * (vx1 - vx2 + vx3) * (vx1 - vx2 + vx3) - cu_sq))); + case BNW: + return REAL_CAST(c1o216 * (drho + rho * (3.0 * (-vx1 + vx2 - vx3) + + c9o2 * (-vx1 + vx2 - vx3) * (-vx1 + vx2 - vx3) - cu_sq))); + case BSE: + return REAL_CAST(c1o216 * (drho + rho * (3.0 * (vx1 - vx2 - vx3) + + c9o2 * (vx1 - vx2 - vx3) * (vx1 - vx2 - vx3) - cu_sq))); + case TNW: + return REAL_CAST(c1o216 * (drho + rho * (3.0 * (-vx1 + vx2 + vx3) + + c9o2 * (-vx1 + vx2 + vx3) * (-vx1 + vx2 + vx3) - cu_sq))); + default: + throw UbException(UB_EXARGS, "unknown dir"); + } +} +////////////////////////////////////////////////////////////////////////// +static void calcCompFeq(LBMReal *const &feq /*[27]*/, const LBMReal &drho, const LBMReal &vx1, const LBMReal &vx2, + const LBMReal &vx3) +{ + using namespace UbMath; - LBMReal cu_sq = 1.5*(vx1*vx1+vx2*vx2+vx3*vx3); - LBMReal rho = drho+c1; + LBMReal cu_sq = 1.5 * (vx1 * vx1 + vx2 * vx2 + vx3 * vx3); + LBMReal rho = drho + c1; - feq[ZERO] = c8o27*(drho+rho*(-cu_sq)); - feq[E] = c2o27*(drho+rho*(3.0*(vx1)+c9o2*(vx1)*(vx1)-cu_sq)); - feq[W] = c2o27*(drho+rho*(3.0*(-vx1)+c9o2*(-vx1)*(-vx1)-cu_sq)); - feq[N] = c2o27*(drho+rho*(3.0*(vx2)+c9o2*(vx2)*(vx2)-cu_sq)); - feq[S] = c2o27*(drho+rho*(3.0*(-vx2)+c9o2*(-vx2)*(-vx2)-cu_sq)); - feq[T] = c2o27*(drho+rho*(3.0*(vx3)+c9o2*(vx3)*(vx3)-cu_sq)); - feq[B] = c2o27*(drho+rho*(3.0*(-vx3)+c9o2*(-vx3)*(-vx3)-cu_sq)); - feq[NE] = c1o54*(drho+rho*(3.0*(vx1+vx2)+c9o2*(vx1+vx2)*(vx1+vx2)-cu_sq)); - feq[SW] = c1o54*(drho+rho*(3.0*(-vx1-vx2)+c9o2*(-vx1-vx2)*(-vx1-vx2)-cu_sq)); - feq[SE] = c1o54*(drho+rho*(3.0*(vx1-vx2)+c9o2*(vx1-vx2)*(vx1-vx2)-cu_sq)); - feq[NW] = c1o54*(drho+rho*(3.0*(-vx1+vx2)+c9o2*(-vx1+vx2)*(-vx1+vx2)-cu_sq)); - feq[TE] = c1o54*(drho+rho*(3.0*(vx1+vx3)+c9o2*(vx1+vx3)*(vx1+vx3)-cu_sq)); - feq[BW] = c1o54*(drho+rho*(3.0*(-vx1-vx3)+c9o2*(-vx1-vx3)*(-vx1-vx3)-cu_sq)); - feq[BE] = c1o54*(drho+rho*(3.0*(vx1-vx3)+c9o2*(vx1-vx3)*(vx1-vx3)-cu_sq)); - feq[TW] = c1o54*(drho+rho*(3.0*(-vx1+vx3)+c9o2*(-vx1+vx3)*(-vx1+vx3)-cu_sq)); - feq[TN] = c1o54*(drho+rho*(3.0*(vx2+vx3)+c9o2*(vx2+vx3)*(vx2+vx3)-cu_sq)); - feq[BS] = c1o54*(drho+rho*(3.0*(-vx2-vx3)+c9o2*(-vx2-vx3)*(-vx2-vx3)-cu_sq)); - feq[BN] = c1o54*(drho+rho*(3.0*(vx2-vx3)+c9o2*(vx2-vx3)*(vx2-vx3)-cu_sq)); - feq[TS] = c1o54*(drho+rho*(3.0*(-vx2+vx3)+c9o2*(-vx2+vx3)*(-vx2+vx3)-cu_sq)); - feq[TNE] = c1o216*(drho+rho*(3.0*(vx1+vx2+vx3)+c9o2*(vx1+vx2+vx3)*(vx1+vx2+vx3)-cu_sq)); - feq[BSW] = c1o216*(drho+rho*(3.0*(-vx1-vx2-vx3)+c9o2*(-vx1-vx2-vx3)*(-vx1-vx2-vx3)-cu_sq)); - feq[BNE] = c1o216*(drho+rho*(3.0*(vx1+vx2-vx3)+c9o2*(vx1+vx2-vx3)*(vx1+vx2-vx3)-cu_sq)); - feq[TSW] = c1o216*(drho+rho*(3.0*(-vx1-vx2+vx3)+c9o2*(-vx1-vx2+vx3)*(-vx1-vx2+vx3)-cu_sq)); - feq[TSE] = c1o216*(drho+rho*(3.0*(vx1-vx2+vx3)+c9o2*(vx1-vx2+vx3)*(vx1-vx2+vx3)-cu_sq)); - feq[BNW] = c1o216*(drho+rho*(3.0*(-vx1+vx2-vx3)+c9o2*(-vx1+vx2-vx3)*(-vx1+vx2-vx3)-cu_sq)); - feq[BSE] = c1o216*(drho+rho*(3.0*(vx1-vx2-vx3)+c9o2*(vx1-vx2-vx3)*(vx1-vx2-vx3)-cu_sq)); - feq[TNW] = c1o216*(drho+rho*(3.0*(-vx1+vx2+vx3)+c9o2*(-vx1+vx2+vx3)*(-vx1+vx2+vx3)-cu_sq)); - } - ////////////////////////////////////////////////////////////////////////// - static LBMReal getIncompFeqForDirection(const int& direction,const LBMReal& drho, const LBMReal& vx1,const LBMReal& vx2,const LBMReal& vx3) - { - using namespace UbMath; + feq[ZERO] = c8o27 * (drho + rho * (-cu_sq)); + feq[E] = c2o27 * (drho + rho * (3.0 * (vx1) + c9o2 * (vx1) * (vx1)-cu_sq)); + feq[W] = c2o27 * (drho + rho * (3.0 * (-vx1) + c9o2 * (-vx1) * (-vx1) - cu_sq)); + feq[N] = c2o27 * (drho + rho * (3.0 * (vx2) + c9o2 * (vx2) * (vx2)-cu_sq)); + feq[S] = c2o27 * (drho + rho * (3.0 * (-vx2) + c9o2 * (-vx2) * (-vx2) - cu_sq)); + feq[T] = c2o27 * (drho + rho * (3.0 * (vx3) + c9o2 * (vx3) * (vx3)-cu_sq)); + feq[B] = c2o27 * (drho + rho * (3.0 * (-vx3) + c9o2 * (-vx3) * (-vx3) - cu_sq)); + feq[NE] = c1o54 * (drho + rho * (3.0 * (vx1 + vx2) + c9o2 * (vx1 + vx2) * (vx1 + vx2) - cu_sq)); + feq[SW] = c1o54 * (drho + rho * (3.0 * (-vx1 - vx2) + c9o2 * (-vx1 - vx2) * (-vx1 - vx2) - cu_sq)); + feq[SE] = c1o54 * (drho + rho * (3.0 * (vx1 - vx2) + c9o2 * (vx1 - vx2) * (vx1 - vx2) - cu_sq)); + feq[NW] = c1o54 * (drho + rho * (3.0 * (-vx1 + vx2) + c9o2 * (-vx1 + vx2) * (-vx1 + vx2) - cu_sq)); + feq[TE] = c1o54 * (drho + rho * (3.0 * (vx1 + vx3) + c9o2 * (vx1 + vx3) * (vx1 + vx3) - cu_sq)); + feq[BW] = c1o54 * (drho + rho * (3.0 * (-vx1 - vx3) + c9o2 * (-vx1 - vx3) * (-vx1 - vx3) - cu_sq)); + feq[BE] = c1o54 * (drho + rho * (3.0 * (vx1 - vx3) + c9o2 * (vx1 - vx3) * (vx1 - vx3) - cu_sq)); + feq[TW] = c1o54 * (drho + rho * (3.0 * (-vx1 + vx3) + c9o2 * (-vx1 + vx3) * (-vx1 + vx3) - cu_sq)); + feq[TN] = c1o54 * (drho + rho * (3.0 * (vx2 + vx3) + c9o2 * (vx2 + vx3) * (vx2 + vx3) - cu_sq)); + feq[BS] = c1o54 * (drho + rho * (3.0 * (-vx2 - vx3) + c9o2 * (-vx2 - vx3) * (-vx2 - vx3) - cu_sq)); + feq[BN] = c1o54 * (drho + rho * (3.0 * (vx2 - vx3) + c9o2 * (vx2 - vx3) * (vx2 - vx3) - cu_sq)); + feq[TS] = c1o54 * (drho + rho * (3.0 * (-vx2 + vx3) + c9o2 * (-vx2 + vx3) * (-vx2 + vx3) - cu_sq)); + feq[TNE] = c1o216 * (drho + rho * (3.0 * (vx1 + vx2 + vx3) + c9o2 * (vx1 + vx2 + vx3) * (vx1 + vx2 + vx3) - cu_sq)); + feq[BSW] = + c1o216 * (drho + rho * (3.0 * (-vx1 - vx2 - vx3) + c9o2 * (-vx1 - vx2 - vx3) * (-vx1 - vx2 - vx3) - cu_sq)); + feq[BNE] = c1o216 * (drho + rho * (3.0 * (vx1 + vx2 - vx3) + c9o2 * (vx1 + vx2 - vx3) * (vx1 + vx2 - vx3) - cu_sq)); + feq[TSW] = + c1o216 * (drho + rho * (3.0 * (-vx1 - vx2 + vx3) + c9o2 * (-vx1 - vx2 + vx3) * (-vx1 - vx2 + vx3) - cu_sq)); + feq[TSE] = c1o216 * (drho + rho * (3.0 * (vx1 - vx2 + vx3) + c9o2 * (vx1 - vx2 + vx3) * (vx1 - vx2 + vx3) - cu_sq)); + feq[BNW] = + c1o216 * (drho + rho * (3.0 * (-vx1 + vx2 - vx3) + c9o2 * (-vx1 + vx2 - vx3) * (-vx1 + vx2 - vx3) - cu_sq)); + feq[BSE] = c1o216 * (drho + rho * (3.0 * (vx1 - vx2 - vx3) + c9o2 * (vx1 - vx2 - vx3) * (vx1 - vx2 - vx3) - cu_sq)); + feq[TNW] = + c1o216 * (drho + rho * (3.0 * (-vx1 + vx2 + vx3) + c9o2 * (-vx1 + vx2 + vx3) * (-vx1 + vx2 + vx3) - cu_sq)); +} +////////////////////////////////////////////////////////////////////////// +static LBMReal getIncompFeqForDirection(const int &direction, const LBMReal &drho, const LBMReal &vx1, + const LBMReal &vx2, const LBMReal &vx3) +{ + using namespace UbMath; - LBMReal cu_sq=1.5f*(vx1*vx1+vx2*vx2+vx3*vx3); + LBMReal cu_sq = 1.5f * (vx1 * vx1 + vx2 * vx2 + vx3 * vx3); - switch(direction) - { - case ZERO : return REAL_CAST( c8o27*(drho-cu_sq)); - case E : return REAL_CAST( c2o27*(drho+3.0*( vx1 )+c9o2*( vx1 )*( vx1 )-cu_sq)); - case W : return REAL_CAST( c2o27*(drho+3.0*(-vx1 )+c9o2*(-vx1 )*(-vx1 )-cu_sq)); - case N : return REAL_CAST( c2o27*(drho+3.0*( vx2)+c9o2*( vx2)*( vx2)-cu_sq)); - case S : return REAL_CAST( c2o27*(drho+3.0*( -vx2)+c9o2*( -vx2)*( -vx2)-cu_sq)); - case T : return REAL_CAST( c2o27*(drho+3.0*( vx3 )+c9o2*( vx3)*( vx3)-cu_sq)); - case B : return REAL_CAST( c2o27*(drho+3.0*( -vx3)+c9o2*( -vx3)*( -vx3)-cu_sq)); - case NE : return REAL_CAST( c1o54*(drho+3.0*( vx1+vx2)+c9o2*( vx1+vx2)*( vx1+vx2)-cu_sq)); - case SW : return REAL_CAST( c1o54*(drho+3.0*(-vx1-vx2)+c9o2*(-vx1-vx2)*(-vx1-vx2)-cu_sq)); - case SE : return REAL_CAST( c1o54*(drho+3.0*( vx1-vx2)+c9o2*( vx1-vx2)*( vx1-vx2)-cu_sq)); - case NW : return REAL_CAST( c1o54*(drho+3.0*(-vx1+vx2)+c9o2*(-vx1+vx2)*(-vx1+vx2)-cu_sq)); - case TE : return REAL_CAST( c1o54*(drho+3.0*( vx1+vx3)+c9o2*( vx1+vx3)*( vx1+vx3)-cu_sq)); - case BW : return REAL_CAST( c1o54*(drho+3.0*(-vx1-vx3)+c9o2*(-vx1-vx3)*(-vx1-vx3)-cu_sq)); - case BE : return REAL_CAST( c1o54*(drho+3.0*( vx1-vx3)+c9o2*( vx1-vx3)*( vx1-vx3)-cu_sq)); - case TW : return REAL_CAST( c1o54*(drho+3.0*(-vx1+vx3)+c9o2*(-vx1+vx3)*(-vx1+vx3)-cu_sq)); - case TN : return REAL_CAST( c1o54*(drho+3.0*( vx2+vx3)+c9o2*( vx2+vx3)*( vx2+vx3)-cu_sq)); - case BS : return REAL_CAST( c1o54*(drho+3.0*(-vx2-vx3)+c9o2*(-vx2-vx3)*(-vx2-vx3)-cu_sq)); - case BN : return REAL_CAST( c1o54*(drho+3.0*( vx2-vx3)+c9o2*( vx2-vx3)*( vx2-vx3)-cu_sq)); - case TS : return REAL_CAST( c1o54*(drho+3.0*(-vx2+vx3)+c9o2*(-vx2+vx3)*(-vx2+vx3)-cu_sq)); - case TNE : return REAL_CAST(c1o216*(drho+3.0*( vx1+vx2+vx3)+c9o2*( vx1+vx2+vx3)*( vx1+vx2+vx3)-cu_sq)); - case BSW : return REAL_CAST(c1o216*(drho+3.0*(-vx1-vx2-vx3)+c9o2*(-vx1-vx2-vx3)*(-vx1-vx2-vx3)-cu_sq)); - case BNE : return REAL_CAST(c1o216*(drho+3.0*( vx1+vx2-vx3)+c9o2*( vx1+vx2-vx3)*( vx1+vx2-vx3)-cu_sq)); - case TSW : return REAL_CAST(c1o216*(drho+3.0*(-vx1-vx2+vx3)+c9o2*(-vx1-vx2+vx3)*(-vx1-vx2+vx3)-cu_sq)); - case TSE : return REAL_CAST(c1o216*(drho+3.0*( vx1-vx2+vx3)+c9o2*( vx1-vx2+vx3)*( vx1-vx2+vx3)-cu_sq)); - case BNW : return REAL_CAST(c1o216*(drho+3.0*(-vx1+vx2-vx3)+c9o2*(-vx1+vx2-vx3)*(-vx1+vx2-vx3)-cu_sq)); - case BSE : return REAL_CAST(c1o216*(drho+3.0*( vx1-vx2-vx3)+c9o2*( vx1-vx2-vx3)*( vx1-vx2-vx3)-cu_sq)); - case TNW : return REAL_CAST(c1o216*(drho+3.0*(-vx1+vx2+vx3)+c9o2*(-vx1+vx2+vx3)*(-vx1+vx2+vx3)-cu_sq)); - default: throw UbException(UB_EXARGS,"unknown dir"); - } - } - ////////////////////////////////////////////////////////////////////////// - static void calcIncompFeq(LBMReal* const& feq/*[27]*/,const LBMReal& drho,const LBMReal& vx1,const LBMReal& vx2,const LBMReal& vx3) - { - using namespace UbMath; + switch (direction) { + case ZERO: + return REAL_CAST(c8o27 * (drho - cu_sq)); + case E: + return REAL_CAST(c2o27 * (drho + 3.0 * (vx1) + c9o2 * (vx1) * (vx1)-cu_sq)); + case W: + return REAL_CAST(c2o27 * (drho + 3.0 * (-vx1) + c9o2 * (-vx1) * (-vx1) - cu_sq)); + case N: + return REAL_CAST(c2o27 * (drho + 3.0 * (vx2) + c9o2 * (vx2) * (vx2)-cu_sq)); + case S: + return REAL_CAST(c2o27 * (drho + 3.0 * (-vx2) + c9o2 * (-vx2) * (-vx2) - cu_sq)); + case T: + return REAL_CAST(c2o27 * (drho + 3.0 * (vx3) + c9o2 * (vx3) * (vx3)-cu_sq)); + case B: + return REAL_CAST(c2o27 * (drho + 3.0 * (-vx3) + c9o2 * (-vx3) * (-vx3) - cu_sq)); + case NE: + return REAL_CAST(c1o54 * (drho + 3.0 * (vx1 + vx2) + c9o2 * (vx1 + vx2) * (vx1 + vx2) - cu_sq)); + case SW: + return REAL_CAST(c1o54 * (drho + 3.0 * (-vx1 - vx2) + c9o2 * (-vx1 - vx2) * (-vx1 - vx2) - cu_sq)); + case SE: + return REAL_CAST(c1o54 * (drho + 3.0 * (vx1 - vx2) + c9o2 * (vx1 - vx2) * (vx1 - vx2) - cu_sq)); + case NW: + return REAL_CAST(c1o54 * (drho + 3.0 * (-vx1 + vx2) + c9o2 * (-vx1 + vx2) * (-vx1 + vx2) - cu_sq)); + case TE: + return REAL_CAST(c1o54 * (drho + 3.0 * (vx1 + vx3) + c9o2 * (vx1 + vx3) * (vx1 + vx3) - cu_sq)); + case BW: + return REAL_CAST(c1o54 * (drho + 3.0 * (-vx1 - vx3) + c9o2 * (-vx1 - vx3) * (-vx1 - vx3) - cu_sq)); + case BE: + return REAL_CAST(c1o54 * (drho + 3.0 * (vx1 - vx3) + c9o2 * (vx1 - vx3) * (vx1 - vx3) - cu_sq)); + case TW: + return REAL_CAST(c1o54 * (drho + 3.0 * (-vx1 + vx3) + c9o2 * (-vx1 + vx3) * (-vx1 + vx3) - cu_sq)); + case TN: + return REAL_CAST(c1o54 * (drho + 3.0 * (vx2 + vx3) + c9o2 * (vx2 + vx3) * (vx2 + vx3) - cu_sq)); + case BS: + return REAL_CAST(c1o54 * (drho + 3.0 * (-vx2 - vx3) + c9o2 * (-vx2 - vx3) * (-vx2 - vx3) - cu_sq)); + case BN: + return REAL_CAST(c1o54 * (drho + 3.0 * (vx2 - vx3) + c9o2 * (vx2 - vx3) * (vx2 - vx3) - cu_sq)); + case TS: + return REAL_CAST(c1o54 * (drho + 3.0 * (-vx2 + vx3) + c9o2 * (-vx2 + vx3) * (-vx2 + vx3) - cu_sq)); + case TNE: + return REAL_CAST(c1o216 * + (drho + 3.0 * (vx1 + vx2 + vx3) + c9o2 * (vx1 + vx2 + vx3) * (vx1 + vx2 + vx3) - cu_sq)); + case BSW: + return REAL_CAST( + c1o216 * (drho + 3.0 * (-vx1 - vx2 - vx3) + c9o2 * (-vx1 - vx2 - vx3) * (-vx1 - vx2 - vx3) - cu_sq)); + case BNE: + return REAL_CAST(c1o216 * + (drho + 3.0 * (vx1 + vx2 - vx3) + c9o2 * (vx1 + vx2 - vx3) * (vx1 + vx2 - vx3) - cu_sq)); + case TSW: + return REAL_CAST( + c1o216 * (drho + 3.0 * (-vx1 - vx2 + vx3) + c9o2 * (-vx1 - vx2 + vx3) * (-vx1 - vx2 + vx3) - cu_sq)); + case TSE: + return REAL_CAST(c1o216 * + (drho + 3.0 * (vx1 - vx2 + vx3) + c9o2 * (vx1 - vx2 + vx3) * (vx1 - vx2 + vx3) - cu_sq)); + case BNW: + return REAL_CAST( + c1o216 * (drho + 3.0 * (-vx1 + vx2 - vx3) + c9o2 * (-vx1 + vx2 - vx3) * (-vx1 + vx2 - vx3) - cu_sq)); + case BSE: + return REAL_CAST(c1o216 * + (drho + 3.0 * (vx1 - vx2 - vx3) + c9o2 * (vx1 - vx2 - vx3) * (vx1 - vx2 - vx3) - cu_sq)); + case TNW: + return REAL_CAST( + c1o216 * (drho + 3.0 * (-vx1 + vx2 + vx3) + c9o2 * (-vx1 + vx2 + vx3) * (-vx1 + vx2 + vx3) - cu_sq)); + default: + throw UbException(UB_EXARGS, "unknown dir"); + } +} +////////////////////////////////////////////////////////////////////////// +static void calcIncompFeq(LBMReal *const &feq /*[27]*/, const LBMReal &drho, const LBMReal &vx1, const LBMReal &vx2, + const LBMReal &vx3) +{ + using namespace UbMath; - LBMReal cu_sq=1.5*(vx1*vx1+vx2*vx2+vx3*vx3); + LBMReal cu_sq = 1.5 * (vx1 * vx1 + vx2 * vx2 + vx3 * vx3); - feq[ZERO] = c8o27*(drho-cu_sq); - feq[E] = c2o27*(drho+3.0*( vx1 )+c9o2*( vx1 )*( vx1 )-cu_sq); - feq[W] = c2o27*(drho+3.0*(-vx1 )+c9o2*(-vx1 )*(-vx1 )-cu_sq); - feq[N] = c2o27*(drho+3.0*( vx2)+c9o2*( vx2)*( vx2)-cu_sq); - feq[S] = c2o27*(drho+3.0*( -vx2)+c9o2*( -vx2)*( -vx2)-cu_sq); - feq[T] = c2o27*(drho+3.0*( vx3 )+c9o2*( vx3)*( vx3)-cu_sq); - feq[B] = c2o27*(drho+3.0*( -vx3)+c9o2*( -vx3)*( -vx3)-cu_sq); - feq[NE] = c1o54*(drho+3.0*( vx1+vx2)+c9o2*( vx1+vx2)*( vx1+vx2)-cu_sq); - feq[SW] = c1o54*(drho+3.0*(-vx1-vx2)+c9o2*(-vx1-vx2)*(-vx1-vx2)-cu_sq); - feq[SE] = c1o54*(drho+3.0*( vx1-vx2)+c9o2*( vx1-vx2)*( vx1-vx2)-cu_sq); - feq[NW] = c1o54*(drho+3.0*(-vx1+vx2)+c9o2*(-vx1+vx2)*(-vx1+vx2)-cu_sq); - feq[TE] = c1o54*(drho+3.0*( vx1+vx3)+c9o2*( vx1+vx3)*( vx1+vx3)-cu_sq); - feq[BW] = c1o54*(drho+3.0*(-vx1-vx3)+c9o2*(-vx1-vx3)*(-vx1-vx3)-cu_sq); - feq[BE] = c1o54*(drho+3.0*( vx1-vx3)+c9o2*( vx1-vx3)*( vx1-vx3)-cu_sq); - feq[TW] = c1o54*(drho+3.0*(-vx1+vx3)+c9o2*(-vx1+vx3)*(-vx1+vx3)-cu_sq); - feq[TN] = c1o54*(drho+3.0*( vx2+vx3)+c9o2*( vx2+vx3)*( vx2+vx3)-cu_sq); - feq[BS] = c1o54*(drho+3.0*(-vx2-vx3)+c9o2*(-vx2-vx3)*(-vx2-vx3)-cu_sq); - feq[BN] = c1o54*(drho+3.0*( vx2-vx3)+c9o2*( vx2-vx3)*( vx2-vx3)-cu_sq); - feq[TS] = c1o54*(drho+3.0*(-vx2+vx3)+c9o2*(-vx2+vx3)*(-vx2+vx3)-cu_sq); - feq[TNE] = c1o216*(drho+3.0*( vx1+vx2+vx3)+c9o2*( vx1+vx2+vx3)*( vx1+vx2+vx3)-cu_sq); - feq[BSW] = c1o216*(drho+3.0*(-vx1-vx2-vx3)+c9o2*(-vx1-vx2-vx3)*(-vx1-vx2-vx3)-cu_sq); - feq[BNE] = c1o216*(drho+3.0*( vx1+vx2-vx3)+c9o2*( vx1+vx2-vx3)*( vx1+vx2-vx3)-cu_sq); - feq[TSW] = c1o216*(drho+3.0*(-vx1-vx2+vx3)+c9o2*(-vx1-vx2+vx3)*(-vx1-vx2+vx3)-cu_sq); - feq[TSE] = c1o216*(drho+3.0*( vx1-vx2+vx3)+c9o2*( vx1-vx2+vx3)*( vx1-vx2+vx3)-cu_sq); - feq[BNW] = c1o216*(drho+3.0*(-vx1+vx2-vx3)+c9o2*(-vx1+vx2-vx3)*(-vx1+vx2-vx3)-cu_sq); - feq[BSE] = c1o216*(drho+3.0*( vx1-vx2-vx3)+c9o2*( vx1-vx2-vx3)*( vx1-vx2-vx3)-cu_sq); - feq[TNW] = c1o216*(drho+3.0*(-vx1+vx2+vx3)+c9o2*(-vx1+vx2+vx3)*(-vx1+vx2+vx3)-cu_sq); - } - ////////////////////////////////////////////////////////////////////////// - static inline float getBoundaryVelocityForDirection(const int& direction, const float& bcVelocityX1,const float& bcVelocityX2,const float& bcVelocityX3) - { - using namespace UbMath; + feq[ZERO] = c8o27 * (drho - cu_sq); + feq[E] = c2o27 * (drho + 3.0 * (vx1) + c9o2 * (vx1) * (vx1)-cu_sq); + feq[W] = c2o27 * (drho + 3.0 * (-vx1) + c9o2 * (-vx1) * (-vx1) - cu_sq); + feq[N] = c2o27 * (drho + 3.0 * (vx2) + c9o2 * (vx2) * (vx2)-cu_sq); + feq[S] = c2o27 * (drho + 3.0 * (-vx2) + c9o2 * (-vx2) * (-vx2) - cu_sq); + feq[T] = c2o27 * (drho + 3.0 * (vx3) + c9o2 * (vx3) * (vx3)-cu_sq); + feq[B] = c2o27 * (drho + 3.0 * (-vx3) + c9o2 * (-vx3) * (-vx3) - cu_sq); + feq[NE] = c1o54 * (drho + 3.0 * (vx1 + vx2) + c9o2 * (vx1 + vx2) * (vx1 + vx2) - cu_sq); + feq[SW] = c1o54 * (drho + 3.0 * (-vx1 - vx2) + c9o2 * (-vx1 - vx2) * (-vx1 - vx2) - cu_sq); + feq[SE] = c1o54 * (drho + 3.0 * (vx1 - vx2) + c9o2 * (vx1 - vx2) * (vx1 - vx2) - cu_sq); + feq[NW] = c1o54 * (drho + 3.0 * (-vx1 + vx2) + c9o2 * (-vx1 + vx2) * (-vx1 + vx2) - cu_sq); + feq[TE] = c1o54 * (drho + 3.0 * (vx1 + vx3) + c9o2 * (vx1 + vx3) * (vx1 + vx3) - cu_sq); + feq[BW] = c1o54 * (drho + 3.0 * (-vx1 - vx3) + c9o2 * (-vx1 - vx3) * (-vx1 - vx3) - cu_sq); + feq[BE] = c1o54 * (drho + 3.0 * (vx1 - vx3) + c9o2 * (vx1 - vx3) * (vx1 - vx3) - cu_sq); + feq[TW] = c1o54 * (drho + 3.0 * (-vx1 + vx3) + c9o2 * (-vx1 + vx3) * (-vx1 + vx3) - cu_sq); + feq[TN] = c1o54 * (drho + 3.0 * (vx2 + vx3) + c9o2 * (vx2 + vx3) * (vx2 + vx3) - cu_sq); + feq[BS] = c1o54 * (drho + 3.0 * (-vx2 - vx3) + c9o2 * (-vx2 - vx3) * (-vx2 - vx3) - cu_sq); + feq[BN] = c1o54 * (drho + 3.0 * (vx2 - vx3) + c9o2 * (vx2 - vx3) * (vx2 - vx3) - cu_sq); + feq[TS] = c1o54 * (drho + 3.0 * (-vx2 + vx3) + c9o2 * (-vx2 + vx3) * (-vx2 + vx3) - cu_sq); + feq[TNE] = c1o216 * (drho + 3.0 * (vx1 + vx2 + vx3) + c9o2 * (vx1 + vx2 + vx3) * (vx1 + vx2 + vx3) - cu_sq); + feq[BSW] = c1o216 * (drho + 3.0 * (-vx1 - vx2 - vx3) + c9o2 * (-vx1 - vx2 - vx3) * (-vx1 - vx2 - vx3) - cu_sq); + feq[BNE] = c1o216 * (drho + 3.0 * (vx1 + vx2 - vx3) + c9o2 * (vx1 + vx2 - vx3) * (vx1 + vx2 - vx3) - cu_sq); + feq[TSW] = c1o216 * (drho + 3.0 * (-vx1 - vx2 + vx3) + c9o2 * (-vx1 - vx2 + vx3) * (-vx1 - vx2 + vx3) - cu_sq); + feq[TSE] = c1o216 * (drho + 3.0 * (vx1 - vx2 + vx3) + c9o2 * (vx1 - vx2 + vx3) * (vx1 - vx2 + vx3) - cu_sq); + feq[BNW] = c1o216 * (drho + 3.0 * (-vx1 + vx2 - vx3) + c9o2 * (-vx1 + vx2 - vx3) * (-vx1 + vx2 - vx3) - cu_sq); + feq[BSE] = c1o216 * (drho + 3.0 * (vx1 - vx2 - vx3) + c9o2 * (vx1 - vx2 - vx3) * (vx1 - vx2 - vx3) - cu_sq); + feq[TNW] = c1o216 * (drho + 3.0 * (-vx1 + vx2 + vx3) + c9o2 * (-vx1 + vx2 + vx3) * (-vx1 + vx2 + vx3) - cu_sq); +} +////////////////////////////////////////////////////////////////////////// +static inline float getBoundaryVelocityForDirection(const int &direction, const float &bcVelocityX1, + const float &bcVelocityX2, const float &bcVelocityX3) +{ + using namespace UbMath; - switch(direction) - { - case E: return (float)( UbMath::c4o9*(+bcVelocityX1) ); - case W: return (float)( UbMath::c4o9*(-bcVelocityX1) ); - case N: return (float)( UbMath::c4o9*(+bcVelocityX2) ); - case S: return (float)( UbMath::c4o9*(-bcVelocityX2) ); - case T: return (float)( UbMath::c4o9*(+bcVelocityX3) ); - case B: return (float)( UbMath::c4o9*(-bcVelocityX3) ); - case NE: return (float)( UbMath::c1o9*(+bcVelocityX1+bcVelocityX2 ) ); - case SW: return (float)( UbMath::c1o9*(-bcVelocityX1-bcVelocityX2 ) ); - case SE: return (float)( UbMath::c1o9*(+bcVelocityX1-bcVelocityX2 ) ); - case NW: return (float)( UbMath::c1o9*(-bcVelocityX1+bcVelocityX2 ) ); - case TE: return (float)( UbMath::c1o9*(+bcVelocityX1 +bcVelocityX3) ); - case BW: return (float)( UbMath::c1o9*(-bcVelocityX1 -bcVelocityX3) ); - case BE: return (float)( UbMath::c1o9*(+bcVelocityX1 -bcVelocityX3) ); - case TW: return (float)( UbMath::c1o9*(-bcVelocityX1 +bcVelocityX3) ); - case TN: return (float)( UbMath::c1o9*( +bcVelocityX2+bcVelocityX3) ); - case BS: return (float)( UbMath::c1o9*( -bcVelocityX2-bcVelocityX3) ); - case BN: return (float)( UbMath::c1o9*( +bcVelocityX2-bcVelocityX3) ); - case TS: return (float)( UbMath::c1o9*( -bcVelocityX2+bcVelocityX3) ); - case TNE: return (float)( UbMath::c1o36*(+bcVelocityX1+bcVelocityX2+bcVelocityX3) ); - case BSW: return (float)( UbMath::c1o36*(-bcVelocityX1-bcVelocityX2-bcVelocityX3) ); - case BNE: return (float)( UbMath::c1o36*(+bcVelocityX1+bcVelocityX2-bcVelocityX3) ); - case TSW: return (float)( UbMath::c1o36*(-bcVelocityX1-bcVelocityX2+bcVelocityX3) ); - case TSE: return (float)( UbMath::c1o36*(+bcVelocityX1-bcVelocityX2+bcVelocityX3) ); - case BNW: return (float)( UbMath::c1o36*(-bcVelocityX1+bcVelocityX2-bcVelocityX3) ); - case BSE: return (float)( UbMath::c1o36*(+bcVelocityX1-bcVelocityX2-bcVelocityX3) ); - case TNW: return (float)( UbMath::c1o36*(-bcVelocityX1+bcVelocityX2+bcVelocityX3) ); - default: throw UbException(UB_EXARGS,"unknown direction"); - } - } - /*=====================================================================*/ - static const int& getInvertDirection(const int& direction) - { - #ifdef _DEBUG - if(direction<STARTDIR || direction>ENDDIR) - throw UbException(UB_EXARGS,"unknown direction"); - #endif - return INVDIR[direction]; - } - /*=====================================================================*/ - static void getLBMDirections(std::vector<int>& dirs, bool onlyLBdirs = false) - { - std::vector<int> D3Q27Dirs; - if(onlyLBdirs) /*FSTARTDIR->FENDDIR*/ - { - dirs.resize(FENDDIR+1); - for(int dir=FSTARTDIR; dir<=FENDDIR; ++dir) + switch (direction) { + case E: + return (float)(UbMath::c4o9 * (+bcVelocityX1)); + case W: + return (float)(UbMath::c4o9 * (-bcVelocityX1)); + case N: + return (float)(UbMath::c4o9 * (+bcVelocityX2)); + case S: + return (float)(UbMath::c4o9 * (-bcVelocityX2)); + case T: + return (float)(UbMath::c4o9 * (+bcVelocityX3)); + case B: + return (float)(UbMath::c4o9 * (-bcVelocityX3)); + case NE: + return (float)(UbMath::c1o9 * (+bcVelocityX1 + bcVelocityX2)); + case SW: + return (float)(UbMath::c1o9 * (-bcVelocityX1 - bcVelocityX2)); + case SE: + return (float)(UbMath::c1o9 * (+bcVelocityX1 - bcVelocityX2)); + case NW: + return (float)(UbMath::c1o9 * (-bcVelocityX1 + bcVelocityX2)); + case TE: + return (float)(UbMath::c1o9 * (+bcVelocityX1 + bcVelocityX3)); + case BW: + return (float)(UbMath::c1o9 * (-bcVelocityX1 - bcVelocityX3)); + case BE: + return (float)(UbMath::c1o9 * (+bcVelocityX1 - bcVelocityX3)); + case TW: + return (float)(UbMath::c1o9 * (-bcVelocityX1 + bcVelocityX3)); + case TN: + return (float)(UbMath::c1o9 * (+bcVelocityX2 + bcVelocityX3)); + case BS: + return (float)(UbMath::c1o9 * (-bcVelocityX2 - bcVelocityX3)); + case BN: + return (float)(UbMath::c1o9 * (+bcVelocityX2 - bcVelocityX3)); + case TS: + return (float)(UbMath::c1o9 * (-bcVelocityX2 + bcVelocityX3)); + case TNE: + return (float)(UbMath::c1o36 * (+bcVelocityX1 + bcVelocityX2 + bcVelocityX3)); + case BSW: + return (float)(UbMath::c1o36 * (-bcVelocityX1 - bcVelocityX2 - bcVelocityX3)); + case BNE: + return (float)(UbMath::c1o36 * (+bcVelocityX1 + bcVelocityX2 - bcVelocityX3)); + case TSW: + return (float)(UbMath::c1o36 * (-bcVelocityX1 - bcVelocityX2 + bcVelocityX3)); + case TSE: + return (float)(UbMath::c1o36 * (+bcVelocityX1 - bcVelocityX2 + bcVelocityX3)); + case BNW: + return (float)(UbMath::c1o36 * (-bcVelocityX1 + bcVelocityX2 - bcVelocityX3)); + case BSE: + return (float)(UbMath::c1o36 * (+bcVelocityX1 - bcVelocityX2 - bcVelocityX3)); + case TNW: + return (float)(UbMath::c1o36 * (-bcVelocityX1 + bcVelocityX2 + bcVelocityX3)); + default: + throw UbException(UB_EXARGS, "unknown direction"); + } +} +/*=====================================================================*/ +static const int &getInvertDirection(const int &direction) +{ +#ifdef _DEBUG + if (direction < STARTDIR || direction > ENDDIR) + throw UbException(UB_EXARGS, "unknown direction"); +#endif + return INVDIR[direction]; +} +/*=====================================================================*/ +static void getLBMDirections(std::vector<int> &dirs, bool onlyLBdirs = false) +{ + std::vector<int> D3Q27Dirs; + if (onlyLBdirs) /*FSTARTDIR->FENDDIR*/ + { + dirs.resize(FENDDIR + 1); + for (int dir = FSTARTDIR; dir <= FENDDIR; ++dir) dirs[dir] = dir; - } - else /*STARTDIR->ENDDIR*/ - { - dirs.resize(ENDDIR+1); - for(int dir=STARTDIR; dir<=ENDDIR; ++dir) + } else /*STARTDIR->ENDDIR*/ + { + dirs.resize(ENDDIR + 1); + for (int dir = STARTDIR; dir <= ENDDIR; ++dir) dirs[dir] = dir; - } - } + } +} ////////////////////////////////////////////////////////////////////////// - static std::vector<int> getEX(const int& exn) - { - std::vector<int> ex; - ex.resize(ENDDIR+1); - switch (exn) - { - case 1: - for(int dir=STARTDIR; dir<ENDDIR; ++dir) - ex[dir] = DX1[dir]; - break; - case 2: - for(int dir=STARTDIR; dir<ENDDIR; ++dir) - ex[dir] = DX2[dir]; - break; - case 3: - for(int dir=STARTDIR; dir<ENDDIR; ++dir) - ex[dir] = DX3[dir]; - break; - } - return ex; - } +static std::vector<int> getEX(const int &exn) +{ + std::vector<int> ex; + ex.resize(ENDDIR + 1); + switch (exn) { + case 1: + for (int dir = STARTDIR; dir < ENDDIR; ++dir) + ex[dir] = DX1[dir]; + break; + case 2: + for (int dir = STARTDIR; dir < ENDDIR; ++dir) + ex[dir] = DX2[dir]; + break; + case 3: + for (int dir = STARTDIR; dir < ENDDIR; ++dir) + ex[dir] = DX3[dir]; + break; + } + return ex; +} ////////////////////////////////////////////////////////////////////////// - static inline void calcDistanceToNeighbors(std::vector<double>& distNeigh, const double& deltaX1) - { - //distNeigh.resize(FENDDIR+1, UbMath::sqrt2*deltaX1); - double sqrt3 = UbMath::sqrt3; - double sqrt2 = UbMath::sqrt2; - distNeigh[E] = distNeigh[W] = distNeigh[N] = deltaX1; - distNeigh[S] = distNeigh[T] = distNeigh[B] = deltaX1; - distNeigh[NE] = distNeigh[NW] = distNeigh[SW] = distNeigh[SE] = sqrt2*deltaX1; - distNeigh[TE] = distNeigh[TN] = distNeigh[TW] = distNeigh[TS] = sqrt2*deltaX1; - distNeigh[BE] = distNeigh[BN] = distNeigh[BW] = distNeigh[BS] = sqrt2*deltaX1; - distNeigh[TNE] = distNeigh[TNW] = distNeigh[TSE] = distNeigh[TSW] = sqrt3*deltaX1; - distNeigh[BNE] = distNeigh[BNW] = distNeigh[BSE] = distNeigh[BSW] = sqrt3*deltaX1; - } +static inline void calcDistanceToNeighbors(std::vector<double> &distNeigh, const double &deltaX1) +{ + // distNeigh.resize(FENDDIR+1, UbMath::sqrt2*deltaX1); + double sqrt3 = UbMath::sqrt3; + double sqrt2 = UbMath::sqrt2; + distNeigh[E] = distNeigh[W] = distNeigh[N] = deltaX1; + distNeigh[S] = distNeigh[T] = distNeigh[B] = deltaX1; + distNeigh[NE] = distNeigh[NW] = distNeigh[SW] = distNeigh[SE] = sqrt2 * deltaX1; + distNeigh[TE] = distNeigh[TN] = distNeigh[TW] = distNeigh[TS] = sqrt2 * deltaX1; + distNeigh[BE] = distNeigh[BN] = distNeigh[BW] = distNeigh[BS] = sqrt2 * deltaX1; + distNeigh[TNE] = distNeigh[TNW] = distNeigh[TSE] = distNeigh[TSW] = sqrt3 * deltaX1; + distNeigh[BNE] = distNeigh[BNW] = distNeigh[BSE] = distNeigh[BSW] = sqrt3 * deltaX1; +} ////////////////////////////////////////////////////////////////////////// - static inline void calcDistanceToNeighbors(std::vector<double>& distNeigh, const double& deltaX1,const double& deltaX2,const double& deltaX3) - { - //distNeigh.resize(FENDDIR+1, UbMath::sqrt2*deltaX1); - distNeigh[E] = distNeigh[W] = deltaX1; - distNeigh[N] = distNeigh[S] = deltaX2; - distNeigh[T] = distNeigh[B] = deltaX3; - distNeigh[NE] = distNeigh[NW] = distNeigh[SW] = distNeigh[SE] = sqrt(deltaX1*deltaX1+deltaX2*deltaX2); - distNeigh[TE] = distNeigh[TN] = distNeigh[TW] = distNeigh[TS] = sqrt(deltaX1*deltaX1+deltaX3*deltaX3); - distNeigh[BE] = distNeigh[BN] = distNeigh[BW] = distNeigh[BS] = sqrt(deltaX2*deltaX2+deltaX3*deltaX3); - distNeigh[TNE] = distNeigh[TNW] = distNeigh[TSE] = distNeigh[TSW] = sqrt(deltaX1*deltaX1+deltaX2*deltaX2+deltaX3*deltaX3); - distNeigh[BNE] = distNeigh[BNW] = distNeigh[BSE] = distNeigh[BSW] = sqrt(deltaX1*deltaX1+deltaX2*deltaX2+deltaX3*deltaX3); - } +static inline void calcDistanceToNeighbors(std::vector<double> &distNeigh, const double &deltaX1, const double &deltaX2, + const double &deltaX3) +{ + // distNeigh.resize(FENDDIR+1, UbMath::sqrt2*deltaX1); + distNeigh[E] = distNeigh[W] = deltaX1; + distNeigh[N] = distNeigh[S] = deltaX2; + distNeigh[T] = distNeigh[B] = deltaX3; + distNeigh[NE] = distNeigh[NW] = distNeigh[SW] = distNeigh[SE] = sqrt(deltaX1 * deltaX1 + deltaX2 * deltaX2); + distNeigh[TE] = distNeigh[TN] = distNeigh[TW] = distNeigh[TS] = sqrt(deltaX1 * deltaX1 + deltaX3 * deltaX3); + distNeigh[BE] = distNeigh[BN] = distNeigh[BW] = distNeigh[BS] = sqrt(deltaX2 * deltaX2 + deltaX3 * deltaX3); + distNeigh[TNE] = distNeigh[TNW] = distNeigh[TSE] = distNeigh[TSW] = + sqrt(deltaX1 * deltaX1 + deltaX2 * deltaX2 + deltaX3 * deltaX3); + distNeigh[BNE] = distNeigh[BNW] = distNeigh[BSE] = distNeigh[BSW] = + sqrt(deltaX1 * deltaX1 + deltaX2 * deltaX2 + deltaX3 * deltaX3); +} ////////////////////////////////////////////////////////////////////////// - static inline void initRayVectors(double* const& rayX1, double* const& rayX2, double* const& rayX3) - { - using namespace UbMath; +static inline void initRayVectors(double *const &rayX1, double *const &rayX2, double *const &rayX3) +{ + using namespace UbMath; - int fdir; - double c1oS2 = UbMath::one_over_sqrt2; - double c1oS3 = UbMath::one_over_sqrt3; - fdir = E; rayX1[fdir] = 1.0; rayX2[fdir] = 0.0; rayX3[fdir] = 0.0; - fdir = W; rayX1[fdir] = -1.0; rayX2[fdir] = 0.0; rayX3[fdir] = 0.0; - fdir = N; rayX1[fdir] = 0.0; rayX2[fdir] = 1.0; rayX3[fdir] = 0.0; - fdir = S; rayX1[fdir] = 0.0; rayX2[fdir] = -1.0; rayX3[fdir] = 0.0; - fdir = T; rayX1[fdir] = 0.0; rayX2[fdir] = 0.0; rayX3[fdir] = 1.0; - fdir = B; rayX1[fdir] = 0.0; rayX2[fdir] = 0.0; rayX3[fdir] = -1.0; - fdir = NE; rayX1[fdir] = c1oS2; rayX2[fdir] = c1oS2; rayX3[fdir] = 0.0; - fdir = SW; rayX1[fdir] = -c1oS2; rayX2[fdir] = -c1oS2; rayX3[fdir] = 0.0; - fdir = SE; rayX1[fdir] = c1oS2; rayX2[fdir] = -c1oS2; rayX3[fdir] = 0.0; - fdir = NW; rayX1[fdir] = -c1oS2; rayX2[fdir] = c1oS2; rayX3[fdir] = 0.0; - fdir = TE; rayX1[fdir] = c1oS2; rayX2[fdir] = 0.0; rayX3[fdir] = c1oS2; - fdir = BW; rayX1[fdir] = -c1oS2; rayX2[fdir] = 0.0; rayX3[fdir] = -c1oS2; - fdir = BE; rayX1[fdir] = c1oS2; rayX2[fdir] = 0.0; rayX3[fdir] = -c1oS2; - fdir = TW; rayX1[fdir] = -c1oS2; rayX2[fdir] = 0.0; rayX3[fdir] = c1oS2; - fdir = TN; rayX1[fdir] = 0.0; rayX2[fdir] = c1oS2; rayX3[fdir] = c1oS2; - fdir = BS; rayX1[fdir] = 0.0; rayX2[fdir] =-c1oS2; rayX3[fdir] = -c1oS2; - fdir = BN; rayX1[fdir] = 0.0; rayX2[fdir] = c1oS2; rayX3[fdir] = -c1oS2; - fdir = TS; rayX1[fdir] = 0.0; rayX2[fdir] =-c1oS2; rayX3[fdir] = c1oS2; - fdir = TNE; rayX1[fdir] = c1oS3; rayX2[fdir] = c1oS3; rayX3[fdir] = c1oS3; - fdir = TNW; rayX1[fdir] = -c1oS3; rayX2[fdir] = c1oS3; rayX3[fdir] = c1oS3; - fdir = TSE; rayX1[fdir] = c1oS3; rayX2[fdir] = -c1oS3; rayX3[fdir] = c1oS3; - fdir = TSW; rayX1[fdir] = -c1oS3; rayX2[fdir] = -c1oS3; rayX3[fdir] = c1oS3; - fdir = BNE; rayX1[fdir] = c1oS3; rayX2[fdir] = c1oS3; rayX3[fdir] = -c1oS3; - fdir = BNW; rayX1[fdir] = -c1oS3; rayX2[fdir] = c1oS3; rayX3[fdir] = -c1oS3; - fdir = BSE; rayX1[fdir] = c1oS3; rayX2[fdir] = -c1oS3; rayX3[fdir] = -c1oS3; - fdir = BSW; rayX1[fdir] = -c1oS3; rayX2[fdir] = -c1oS3; rayX3[fdir] = -c1oS3; - } + int fdir; + double c1oS2 = UbMath::one_over_sqrt2; + double c1oS3 = UbMath::one_over_sqrt3; + fdir = E; + rayX1[fdir] = 1.0; + rayX2[fdir] = 0.0; + rayX3[fdir] = 0.0; + fdir = W; + rayX1[fdir] = -1.0; + rayX2[fdir] = 0.0; + rayX3[fdir] = 0.0; + fdir = N; + rayX1[fdir] = 0.0; + rayX2[fdir] = 1.0; + rayX3[fdir] = 0.0; + fdir = S; + rayX1[fdir] = 0.0; + rayX2[fdir] = -1.0; + rayX3[fdir] = 0.0; + fdir = T; + rayX1[fdir] = 0.0; + rayX2[fdir] = 0.0; + rayX3[fdir] = 1.0; + fdir = B; + rayX1[fdir] = 0.0; + rayX2[fdir] = 0.0; + rayX3[fdir] = -1.0; + fdir = NE; + rayX1[fdir] = c1oS2; + rayX2[fdir] = c1oS2; + rayX3[fdir] = 0.0; + fdir = SW; + rayX1[fdir] = -c1oS2; + rayX2[fdir] = -c1oS2; + rayX3[fdir] = 0.0; + fdir = SE; + rayX1[fdir] = c1oS2; + rayX2[fdir] = -c1oS2; + rayX3[fdir] = 0.0; + fdir = NW; + rayX1[fdir] = -c1oS2; + rayX2[fdir] = c1oS2; + rayX3[fdir] = 0.0; + fdir = TE; + rayX1[fdir] = c1oS2; + rayX2[fdir] = 0.0; + rayX3[fdir] = c1oS2; + fdir = BW; + rayX1[fdir] = -c1oS2; + rayX2[fdir] = 0.0; + rayX3[fdir] = -c1oS2; + fdir = BE; + rayX1[fdir] = c1oS2; + rayX2[fdir] = 0.0; + rayX3[fdir] = -c1oS2; + fdir = TW; + rayX1[fdir] = -c1oS2; + rayX2[fdir] = 0.0; + rayX3[fdir] = c1oS2; + fdir = TN; + rayX1[fdir] = 0.0; + rayX2[fdir] = c1oS2; + rayX3[fdir] = c1oS2; + fdir = BS; + rayX1[fdir] = 0.0; + rayX2[fdir] = -c1oS2; + rayX3[fdir] = -c1oS2; + fdir = BN; + rayX1[fdir] = 0.0; + rayX2[fdir] = c1oS2; + rayX3[fdir] = -c1oS2; + fdir = TS; + rayX1[fdir] = 0.0; + rayX2[fdir] = -c1oS2; + rayX3[fdir] = c1oS2; + fdir = TNE; + rayX1[fdir] = c1oS3; + rayX2[fdir] = c1oS3; + rayX3[fdir] = c1oS3; + fdir = TNW; + rayX1[fdir] = -c1oS3; + rayX2[fdir] = c1oS3; + rayX3[fdir] = c1oS3; + fdir = TSE; + rayX1[fdir] = c1oS3; + rayX2[fdir] = -c1oS3; + rayX3[fdir] = c1oS3; + fdir = TSW; + rayX1[fdir] = -c1oS3; + rayX2[fdir] = -c1oS3; + rayX3[fdir] = c1oS3; + fdir = BNE; + rayX1[fdir] = c1oS3; + rayX2[fdir] = c1oS3; + rayX3[fdir] = -c1oS3; + fdir = BNW; + rayX1[fdir] = -c1oS3; + rayX2[fdir] = c1oS3; + rayX3[fdir] = -c1oS3; + fdir = BSE; + rayX1[fdir] = c1oS3; + rayX2[fdir] = -c1oS3; + rayX3[fdir] = -c1oS3; + fdir = BSW; + rayX1[fdir] = -c1oS3; + rayX2[fdir] = -c1oS3; + rayX3[fdir] = -c1oS3; +} ////////////////////////////////////////////////////////////////////////// - static inline LBMReal calcPress(const LBMReal* const f, LBMReal rho, LBMReal vx1, LBMReal vx2, LBMReal vx3) - { - using namespace UbMath; - LBMReal OxxPyyPzz = c1; - return ((f[E]+f[W]+f[N]+f[S]+f[T]+f[B]+c2*(f[NE]+f[SW]+f[SE]+f[NW]+f[TE]+f[BW]+f[BE]+f[TW]+f[TN]+f[BS]+f[BN]+f[TS])+ - c3*(f[TNE]+f[TSW]+f[TSE]+f[TNW]+f[BNE]+f[BSW]+f[BSE]+f[BNW])-(vx1*vx1+vx2*vx2+vx3*vx3))*(c1-c1o2*OxxPyyPzz)+OxxPyyPzz*c1o2*(rho))*c1o3; - } +static inline LBMReal calcPress(const LBMReal *const f, LBMReal rho, LBMReal vx1, LBMReal vx2, LBMReal vx3) +{ + using namespace UbMath; + LBMReal OxxPyyPzz = c1; + return ((f[E] + f[W] + f[N] + f[S] + f[T] + f[B] + + c2 * (f[NE] + f[SW] + f[SE] + f[NW] + f[TE] + f[BW] + f[BE] + f[TW] + f[TN] + f[BS] + f[BN] + f[TS]) + + c3 * (f[TNE] + f[TSW] + f[TSE] + f[TNW] + f[BNE] + f[BSW] + f[BSE] + f[BNW]) - + (vx1 * vx1 + vx2 * vx2 + vx3 * vx3)) * + (c1 - c1o2 * OxxPyyPzz) + + OxxPyyPzz * c1o2 * (rho)) * + c1o3; } +} // namespace D3Q27System #endif - - - diff --git a/src/cpu/VirtualFluidsCore/LBM/ICell.h b/src/cpu/VirtualFluidsCore/LBM/ICell.h index 897a4134fa7df689d2a01e3713dccfbdd474e364..c080033b8bbdbe1741f6f624c2726ffa145bf080 100644 --- a/src/cpu/VirtualFluidsCore/LBM/ICell.h +++ b/src/cpu/VirtualFluidsCore/LBM/ICell.h @@ -4,30 +4,29 @@ #include "LBMSystem.h" #include <vector> -struct ICell3D -{ - ICell3D(int size); +struct ICell3D { + ICell3D(int size); - std::vector<LBMReal> TSW; - std::vector<LBMReal> TNW; - std::vector<LBMReal> TNE; - std::vector<LBMReal> TSE; - std::vector<LBMReal> BSW; - std::vector<LBMReal> BNW; - std::vector<LBMReal> BNE; - std::vector<LBMReal> BSE; + std::vector<LBMReal> TSW; + std::vector<LBMReal> TNW; + std::vector<LBMReal> TNE; + std::vector<LBMReal> TSE; + std::vector<LBMReal> BSW; + std::vector<LBMReal> BNW; + std::vector<LBMReal> BNE; + std::vector<LBMReal> BSE; }; inline ICell3D::ICell3D(int size) { - TSW.resize(size); - TNW.resize(size); - TNE.resize(size); - TSE.resize(size); - BSW.resize(size); - BNW.resize(size); - BNE.resize(size); - BSE.resize(size); + TSW.resize(size); + TNW.resize(size); + TNE.resize(size); + TSE.resize(size); + BSW.resize(size); + BNW.resize(size); + BNE.resize(size); + BSE.resize(size); } #endif diff --git a/src/cpu/VirtualFluidsCore/LBM/ILBMKernel.h b/src/cpu/VirtualFluidsCore/LBM/ILBMKernel.h index 71ed3246cc33aaf21b7b6f75eaeeba77b64a1984..4dbe8eee09a37c0c220f47619b72bade2e6ec527 100644 --- a/src/cpu/VirtualFluidsCore/LBM/ILBMKernel.h +++ b/src/cpu/VirtualFluidsCore/LBM/ILBMKernel.h @@ -1,28 +1,28 @@ //======================================================================================= -// ____ ____ __ ______ __________ __ __ __ __ -// \ \ | | | | | _ \ |___ ___| | | | | / \ | | -// \ \ | | | | | |_) | | | | | | | / \ | | -// \ \ | | | | | _ / | | | | | | / /\ \ | | -// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ -// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| -// \ \ | | ________________________________________________________________ -// \ \ | | | ______________________________________________________________| -// \ \| | | | __ __ __ __ ______ _______ -// \ | | |_____ | | | | | | | | | _ \ / _____) -// \ | | _____| | | | | | | | | | | \ \ \_______ +// ____ ____ __ ______ __________ __ __ __ __ +// \ \ | | | | | _ \ |___ ___| | | | | / \ | | +// \ \ | | | | | |_) | | | | | | | / \ | | +// \ \ | | | | | _ / | | | | | | / /\ \ | | +// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ +// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| +// \ \ | | ________________________________________________________________ +// \ \ | | | ______________________________________________________________| +// \ \| | | | __ __ __ __ ______ _______ +// \ | | |_____ | | | | | | | | | _ \ / _____) +// \ | | _____| | | | | | | | | | | \ \ \_______ // \ | | | | |_____ | \_/ | | | | |_/ / _____ | -// \ _____| |__| |________| \_______/ |__| |______/ (_______/ +// \ _____| |__| |________| \_______/ |__| |______/ (_______/ // -// This file is part of VirtualFluids. VirtualFluids is free software: you can +// This file is part of VirtualFluids. VirtualFluids is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of +// License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. -// -// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// +// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License along // with VirtualFluids (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>. // @@ -45,20 +45,20 @@ class ILBMKernel public: virtual ~ILBMKernel() = default; - virtual void calculate(int step) = 0; + virtual void calculate(int step) = 0; virtual double getCalculationTime() = 0; - virtual void swapDistributions() = 0; + virtual void swapDistributions() = 0; - virtual bool getCompressible() const = 0; - virtual SPtr<BCProcessor> getBCProcessor() const = 0; - virtual void setBCProcessor(SPtr<BCProcessor> bcProcessor) = 0; - virtual SPtr<DataSet3D> getDataSet() const = 0; - virtual double getCollisionFactor() const = 0; - virtual void setCollisionFactor(double collFactor) = 0; + virtual bool getCompressible() const = 0; + virtual SPtr<BCProcessor> getBCProcessor() const = 0; + virtual void setBCProcessor(SPtr<BCProcessor> bcProcessor) = 0; + virtual SPtr<DataSet3D> getDataSet() const = 0; + virtual double getCollisionFactor() const = 0; + virtual void setCollisionFactor(double collFactor) = 0; virtual bool isInsideOfDomain(const int &x1, const int &x2, const int &x3) const = 0; - virtual int getGhostLayerWidth() const = 0; - virtual double getDeltaT() const = 0; - virtual bool getWithForcing() const = 0; + virtual int getGhostLayerWidth() const = 0; + virtual double getDeltaT() const = 0; + virtual bool getWithForcing() const = 0; }; #endif diff --git a/src/cpu/VirtualFluidsCore/LBM/InterpolationHelper.cpp b/src/cpu/VirtualFluidsCore/LBM/InterpolationHelper.cpp index 0942a9f0691b67c6d1e8d7cec938aaaa494f5e45..efe2c8e7cfb39b960c0c86405a05633816fe56ef 100644 --- a/src/cpu/VirtualFluidsCore/LBM/InterpolationHelper.cpp +++ b/src/cpu/VirtualFluidsCore/LBM/InterpolationHelper.cpp @@ -1,37 +1,34 @@ #include "InterpolationHelper.h" - - -InterpolationHelper::InterpolationHelper(InterpolationProcessorPtr iProcessor) : iProcessor(iProcessor) -{ - -} +InterpolationHelper::InterpolationHelper(InterpolationProcessorPtr iProcessor) : iProcessor(iProcessor) {} ////////////////////////////////////////////////////////////////////////// -InterpolationHelper::~InterpolationHelper() -= default; +InterpolationHelper::~InterpolationHelper() = default; ////////////////////////////////////////////////////////////////////////// -void InterpolationHelper::interpolate8to1( D3Q27ICell& icellF, LBMReal* icellC, double /*x1*/, double /*x2*/, double /*x3*/, LBMReal omega ) +void InterpolationHelper::interpolate8to1(D3Q27ICell &icellF, LBMReal *icellC, double /*x1*/, double /*x2*/, + double /*x3*/, LBMReal omega) { - iProcessor->calcInterpolatedCoefficiets(icellF, omega, 1.0); - iProcessor->calcInterpolatedNodeFC(icellC, omega); + iProcessor->calcInterpolatedCoefficiets(icellF, omega, 1.0); + iProcessor->calcInterpolatedNodeFC(icellC, omega); } ////////////////////////////////////////////////////////////////////////// -void InterpolationHelper::interpolate8to1WithVelocity( D3Q27ICell& icellF, double x1, double x2, double x3, LBMReal omega, LBMReal &vx1, LBMReal &vx2, LBMReal &vx3 ) +void InterpolationHelper::interpolate8to1WithVelocity(D3Q27ICell &icellF, double x1, double x2, double x3, + LBMReal omega, LBMReal &vx1, LBMReal &vx2, LBMReal &vx3) { - iProcessor->setOffsets(0.0, 0.0, 0.0); - iProcessor->calcInterpolatedCoefficiets(icellF, omega, 0.0); - iProcessor->calcInterpolatedVelocity(x1, x2, x3, vx1, vx2, vx3); + iProcessor->setOffsets(0.0, 0.0, 0.0); + iProcessor->calcInterpolatedCoefficiets(icellF, omega, 0.0); + iProcessor->calcInterpolatedVelocity(x1, x2, x3, vx1, vx2, vx3); } ////////////////////////////////////////////////////////////////////////// -void InterpolationHelper::interpolate8to1WithVelocityWithShearStress( D3Q27ICell& icellF, double x1, double x2, double x3, LBMReal omega, - LBMReal &vx1, LBMReal &vx2, LBMReal &vx3, - LBMReal &tauxx, LBMReal &tauyy, LBMReal &tauzz,LBMReal &tauxy, LBMReal &tauxz, LBMReal &tauyz ) +void InterpolationHelper::interpolate8to1WithVelocityWithShearStress(D3Q27ICell &icellF, double x1, double x2, + double x3, LBMReal omega, LBMReal &vx1, + LBMReal &vx2, LBMReal &vx3, LBMReal &tauxx, + LBMReal &tauyy, LBMReal &tauzz, LBMReal &tauxy, + LBMReal &tauxz, LBMReal &tauyz) { - iProcessor->setOffsets(0.0, 0.0, 0.0); - iProcessor->calcInterpolatedCoefficiets(icellF, omega, 0.0); - iProcessor->calcInterpolatedVelocity(x1, x2, x3, vx1, vx2, vx3); - iProcessor->calcInterpolatedShearStress(x1,x2,x3,tauxx,tauyy,tauzz,tauxy,tauxz,tauyz); + iProcessor->setOffsets(0.0, 0.0, 0.0); + iProcessor->calcInterpolatedCoefficiets(icellF, omega, 0.0); + iProcessor->calcInterpolatedVelocity(x1, x2, x3, vx1, vx2, vx3); + iProcessor->calcInterpolatedShearStress(x1, x2, x3, tauxx, tauyy, tauzz, tauxy, tauxz, tauyz); } ////////////////////////////////////////////////////////////////////////// - diff --git a/src/cpu/VirtualFluidsCore/LBM/InterpolationHelper.h b/src/cpu/VirtualFluidsCore/LBM/InterpolationHelper.h index 56cedd8f7ad5e7a666618731f43d5f76627d80e3..0e7318a8c44785679cdad1292bf561cc631b2041 100644 --- a/src/cpu/VirtualFluidsCore/LBM/InterpolationHelper.h +++ b/src/cpu/VirtualFluidsCore/LBM/InterpolationHelper.h @@ -9,17 +9,19 @@ using InterpolationHelperPtr = SPtr<InterpolationHelper>; class InterpolationHelper { public: - InterpolationHelper(InterpolationProcessorPtr iProcessor); - ~InterpolationHelper(); - void interpolate8to1(D3Q27ICell& icellF, LBMReal* icellC, double x1, double x2, double x3, LBMReal omega); - void interpolate8to1WithVelocity(D3Q27ICell& icellF, double x1, double x2, double x3, LBMReal omega, LBMReal &vx1, LBMReal &vx2, LBMReal &vx3); - void interpolate8to1WithVelocityWithShearStress(D3Q27ICell& icellF, double x1, double x2, double x3, LBMReal omega, - LBMReal &vx1, LBMReal &vx2, LBMReal &vx3, - LBMReal &tauxx, LBMReal &tauyy, LBMReal &tauzz,LBMReal &tauxy, LBMReal &tauxz, LBMReal &tauyz); + InterpolationHelper(InterpolationProcessorPtr iProcessor); + ~InterpolationHelper(); + void interpolate8to1(D3Q27ICell &icellF, LBMReal *icellC, double x1, double x2, double x3, LBMReal omega); + void interpolate8to1WithVelocity(D3Q27ICell &icellF, double x1, double x2, double x3, LBMReal omega, LBMReal &vx1, + LBMReal &vx2, LBMReal &vx3); + void interpolate8to1WithVelocityWithShearStress(D3Q27ICell &icellF, double x1, double x2, double x3, LBMReal omega, + LBMReal &vx1, LBMReal &vx2, LBMReal &vx3, LBMReal &tauxx, + LBMReal &tauyy, LBMReal &tauzz, LBMReal &tauxy, LBMReal &tauxz, + LBMReal &tauyz); + protected: private: - InterpolationProcessorPtr iProcessor; + InterpolationProcessorPtr iProcessor; }; #endif - diff --git a/src/cpu/VirtualFluidsCore/LBM/InterpolationProcessor.cpp b/src/cpu/VirtualFluidsCore/LBM/InterpolationProcessor.cpp index 60893e2b2ca546358bf86b99d4933cb7338ce484..8d2a4163b3127d5199c0419e34e1c4b28d505e2c 100644 --- a/src/cpu/VirtualFluidsCore/LBM/InterpolationProcessor.cpp +++ b/src/cpu/VirtualFluidsCore/LBM/InterpolationProcessor.cpp @@ -1,309 +1,333 @@ #include "InterpolationProcessor.h" - ////////////////////////////////////////////////////////////////////////// -InterpolationProcessor::InterpolationProcessor() -= default; +InterpolationProcessor::InterpolationProcessor() = default; ////////////////////////////////////////////////////////////////////////// -InterpolationProcessor::~InterpolationProcessor() -= default; +InterpolationProcessor::~InterpolationProcessor() = default; ////////////////////////////////////////////////////////////////////////// -void InterpolationProcessor::readICell(SPtr<DistributionArray3D> f, D3Q27ICell& icell, int x1, int x2, int x3) +void InterpolationProcessor::readICell(SPtr<DistributionArray3D> f, D3Q27ICell &icell, int x1, int x2, int x3) { - f->getDistribution(icell.BSW, x1, x2, x3); - f->getDistribution(icell.BSE, x1+1, x2, x3); - f->getDistribution(icell.BNW, x1, x2+1, x3); - f->getDistribution(icell.BNE, x1+1, x2+1, x3); - f->getDistribution(icell.TSW, x1, x2, x3+1); - f->getDistribution(icell.TSE, x1+1, x2, x3+1); - f->getDistribution(icell.TNW, x1, x2+1, x3+1); - f->getDistribution(icell.TNE, x1+1, x2+1, x3+1); + f->getDistribution(icell.BSW, x1, x2, x3); + f->getDistribution(icell.BSE, x1 + 1, x2, x3); + f->getDistribution(icell.BNW, x1, x2 + 1, x3); + f->getDistribution(icell.BNE, x1 + 1, x2 + 1, x3); + f->getDistribution(icell.TSW, x1, x2, x3 + 1); + f->getDistribution(icell.TSE, x1 + 1, x2, x3 + 1); + f->getDistribution(icell.TNW, x1, x2 + 1, x3 + 1); + f->getDistribution(icell.TNE, x1 + 1, x2 + 1, x3 + 1); } ////////////////////////////////////////////////////////////////////////// -void InterpolationProcessor::writeICell(SPtr<DistributionArray3D> f, const D3Q27ICell& icell, int x1, int x2, int x3) +void InterpolationProcessor::writeICell(SPtr<DistributionArray3D> f, const D3Q27ICell &icell, int x1, int x2, int x3) { - f->setDistribution(icell.BSW, x1, x2, x3); - f->setDistribution(icell.BSE, x1+1, x2, x3); - f->setDistribution(icell.BNW, x1, x2+1, x3); - f->setDistribution(icell.BNE, x1+1, x2+1, x3); - f->setDistribution(icell.TSW, x1, x2, x3+1); - f->setDistribution(icell.TSE, x1+1, x2, x3+1); - f->setDistribution(icell.TNW, x1, x2+1, x3+1); - f->setDistribution(icell.TNE, x1+1, x2+1, x3+1); + f->setDistribution(icell.BSW, x1, x2, x3); + f->setDistribution(icell.BSE, x1 + 1, x2, x3); + f->setDistribution(icell.BNW, x1, x2 + 1, x3); + f->setDistribution(icell.BNE, x1 + 1, x2 + 1, x3); + f->setDistribution(icell.TSW, x1, x2, x3 + 1); + f->setDistribution(icell.TSE, x1 + 1, x2, x3 + 1); + f->setDistribution(icell.TNW, x1, x2 + 1, x3 + 1); + f->setDistribution(icell.TNE, x1 + 1, x2 + 1, x3 + 1); } ////////////////////////////////////////////////////////////////////////// -void InterpolationProcessor::writeICellInv(SPtr<DistributionArray3D> f, const D3Q27ICell& icell, int x1, int x2, int x3) +void InterpolationProcessor::writeICellInv(SPtr<DistributionArray3D> f, const D3Q27ICell &icell, int x1, int x2, int x3) { - f->setDistributionInv(icell.BSW, x1, x2, x3); - f->setDistributionInv(icell.BSE, x1+1, x2, x3); - f->setDistributionInv(icell.BNW, x1, x2+1, x3); - f->setDistributionInv(icell.BNE, x1+1, x2+1, x3); - f->setDistributionInv(icell.TSW, x1, x2, x3+1); - f->setDistributionInv(icell.TSE, x1+1, x2, x3+1); - f->setDistributionInv(icell.TNW, x1, x2+1, x3+1); - f->setDistributionInv(icell.TNE, x1+1, x2+1, x3+1); + f->setDistributionInv(icell.BSW, x1, x2, x3); + f->setDistributionInv(icell.BSE, x1 + 1, x2, x3); + f->setDistributionInv(icell.BNW, x1, x2 + 1, x3); + f->setDistributionInv(icell.BNE, x1 + 1, x2 + 1, x3); + f->setDistributionInv(icell.TSW, x1, x2, x3 + 1); + f->setDistributionInv(icell.TSE, x1 + 1, x2, x3 + 1); + f->setDistributionInv(icell.TNW, x1, x2 + 1, x3 + 1); + f->setDistributionInv(icell.TNE, x1 + 1, x2 + 1, x3 + 1); } ////////////////////////////////////////////////////////////////////////// -void InterpolationProcessor::writeINode(SPtr<DistributionArray3D> f, const LBMReal* const inode, int x1, int x2, int x3) +void InterpolationProcessor::writeINode(SPtr<DistributionArray3D> f, const LBMReal *const inode, int x1, int x2, int x3) { - f->setDistribution(inode, x1, x2, x3); + f->setDistribution(inode, x1, x2, x3); } ////////////////////////////////////////////////////////////////////////// -void InterpolationProcessor::writeINodeInv(SPtr<DistributionArray3D> f, const LBMReal* const inode, int x1, int x2, int x3) +void InterpolationProcessor::writeINodeInv(SPtr<DistributionArray3D> f, const LBMReal *const inode, int x1, int x2, + int x3) { - f->setDistributionInv(inode, x1, x2, x3); + f->setDistributionInv(inode, x1, x2, x3); } ////////////////////////////////////////////////////////////////////////// -bool InterpolationProcessor::iCellHasSolid(const SPtr<BCArray3D> bcArray, int x1, int x2, int x3) +bool InterpolationProcessor::iCellHasSolid(const SPtr<BCArray3D> bcArray, int x1, int x2, int x3) { - for (int ix3 = x3; ix3 <= x3 + 1; ix3++) - for(int ix2 = x2; ix2 <= x2 + 1; ix2++) - for(int ix1 = x1; ix1 <= x1 + 1; ix1++) - { - if(bcArray->isSolid(ix1, ix2, ix3)) - return true; - } - return false; + for (int ix3 = x3; ix3 <= x3 + 1; ix3++) + for (int ix2 = x2; ix2 <= x2 + 1; ix2++) + for (int ix1 = x1; ix1 <= x1 + 1; ix1++) { + if (bcArray->isSolid(ix1, ix2, ix3)) + return true; + } + return false; } ////////////////////////////////////////////////////////////////////////// -bool InterpolationProcessor::findNeighborICell(const SPtr<BCArray3D> bcArray, SPtr<DistributionArray3D> f, - D3Q27ICell& icell, int maxX1, int maxX2, int maxX3, - int x1, int x2, int x3, LBMReal& xoff, LBMReal& yoff, LBMReal& zoff) +bool InterpolationProcessor::findNeighborICell(const SPtr<BCArray3D> bcArray, SPtr<DistributionArray3D> f, + D3Q27ICell &icell, int maxX1, int maxX2, int maxX3, int x1, int x2, + int x3, LBMReal &xoff, LBMReal &yoff, LBMReal &zoff) { - m_maxX1 = maxX1; - m_maxX2 = maxX2; - m_maxX3 = maxX3; + m_maxX1 = maxX1; + m_maxX2 = maxX2; + m_maxX3 = maxX3; - //GoWest - if(inRange(x1-1,x2,x3) && !iCellHasSolid(bcArray, x1-1,x2,x3)) - { - readICell(f,icell,x1-1,x2,x3); - xoff = 1; - yoff = 0; - zoff = 0; - } - //GoEast - else if(inRange(x1+2,x2,x3) && !iCellHasSolid(bcArray, x1+1,x2,x3)) // ist �bern�chster Knoten auch im Gebiet (Grundknoten bei 0,0,0 - { - readICell(f,icell,x1+1,x2,x3); - xoff = -1; - yoff = 0; - zoff = 0; - } - //GoSouth - else if(inRange(x1,x2-1,x3) && !iCellHasSolid(bcArray, x1,x2-1,x3)) - { - readICell(f,icell,x1,x2-1,x3); - xoff = 0; - yoff = 1; - zoff = 0; - } - //GoNorth - else if(inRange(x1,x2+2,x3) && !iCellHasSolid(bcArray, x1,x2+1,x3)) // ist �bern�chster Knoten auch im Gebiet (Grundknoten bei 0,0,0 - { - readICell(f,icell,x1,x2+1,x3); - xoff = 0; - yoff = -1; - zoff = 0; - } - //GoBottom - else if(inRange(x1,x2,x3-1) && !iCellHasSolid(bcArray, x1,x2,x3-1)) - { - readICell(f,icell,x1,x2,x3-1); - xoff = 0; - yoff = 0; - zoff = 1; - } - //GoTop - else if(inRange(x1,x2,x3+2) && !iCellHasSolid(bcArray, x1,x2,x3+1)) // ist �bern�chster Knoten auch im Gebiet (Grundknoten bei 0,0,0 - { - readICell(f,icell,x1,x2,x3+1); - xoff = 0; - yoff = 0; - zoff = -1; - } - //GoNW - else if(inRange(x1-1,x2+2,x3) && !iCellHasSolid(bcArray, x1-1,x2+1,x3)) // ist �bern�chster Knoten auch im Gebiet (Grundknoten bei 0,0,0 - { - readICell(f,icell,x1-1,x2+1,x3); - xoff = 1; - yoff = -1; - zoff = 0; - } - //GoNE - else if(inRange(x1+2,x2+2,x3) && !iCellHasSolid(bcArray, x1+1,x2+1,x3)) // ist �bern�chster Knoten auch im Gebiet (Grundknoten bei 0,0,0 - { - readICell(f,icell,x1+1,x2+1,x3); - xoff = -1; - yoff = -1; - zoff = 0; - } - //GoSW - else if(inRange(x1-1,x2-1,x3) && !iCellHasSolid(bcArray, x1-1,x2-1,x3)) // ist �bern�chster Knoten auch im Gebiet (Grundknoten bei 0,0,0 - { - readICell(f,icell,x1-1,x2-1,x3); - xoff = 1; - yoff = 1; - zoff = 0; - } - //GoSE - else if(inRange(x1+2,x2-1,x3) && !iCellHasSolid(bcArray, x1+1,x2-1,x3)) // ist �bern�chster Knoten auch im Gebiet (Grundknoten bei 0,0,0 - { - readICell(f,icell,x1+1,x2-1,x3); - xoff = -1; - yoff = 1; - zoff = 0; - } - //GoBW - else if(inRange(x1-1,x2,x3-1) && !iCellHasSolid(bcArray, x1-1,x2,x3-1)) - { - readICell(f,icell,x1-1,x2,x3-1); - xoff = 1; - yoff = 0; - zoff = 1; - } - //GoBE - else if(inRange(x1+2,x2,x3-1) && !iCellHasSolid(bcArray, x1+1,x2,x3-1)) // ist �bern�chster Knoten auch im Gebiet (Grundknoten bei 0,0,0 - { - readICell(f,icell,x1+1,x2,x3-1); - xoff = -1; - yoff = 0; - zoff = 1; - } - //GoBS - else if(inRange(x1,x2-1,x3-1) && !iCellHasSolid(bcArray, x1,x2-1,x3-1)) - { - readICell(f,icell,x1,x2-1,x3-1); - xoff = 0; - yoff = 1; - zoff = 1; - } - //GoBN - else if(inRange(x1,x2+2,x3-1) && !iCellHasSolid(bcArray, x1,x2+1,x3-1)) // ist �bern�chster Knoten auch im Gebiet (Grundknoten bei 0,0,0 - { - readICell(f,icell,x1,x2+1,x3-1); - xoff = 0; - yoff = -1; - zoff = 1; - } - //GoTW - else if(inRange(x1-1,x2,x3+2) && !iCellHasSolid(bcArray, x1-1,x2,x3+1)) - { - readICell(f,icell,x1-1,x2,x3+1); - xoff = 1; - yoff = 0; - zoff = -1; - } - //GoTE - else if(inRange(x1+2,x2,x3+2) && !iCellHasSolid(bcArray, x1+1,x2,x3+1)) // ist �bern�chster Knoten auch im Gebiet (Grundknoten bei 0,0,0 - { - readICell(f,icell,x1+1,x2,x3+1); - xoff = -1; - yoff = 0; - zoff = -1; - } - //GoTS - else if(inRange(x1,x2-1,x3+2) && !iCellHasSolid(bcArray, x1,x2-1,x3+1)) - { - readICell(f,icell,x1,x2-1,x3+1); - xoff = 0; - yoff = 1; - zoff = -1; - } - //GoTN - else if(inRange(x1,x2+2,x3+2) && !iCellHasSolid(bcArray, x1,x2+1,x3+1)) // ist �bern�chster Knoten auch im Gebiet (Grundknoten bei 0,0,0 - { - readICell(f,icell,x1,x2+1,x3+1); - xoff = 0; - yoff = -1; - zoff = -1; - } - //GoTNW - else if(inRange(x1-1,x2+2,x3+2) && !iCellHasSolid(bcArray, x1-1,x2+1,x3+1)) // ist �bern�chster Knoten auch im Gebiet (Grundknoten bei 0,0,0 - { - readICell(f,icell,x1-1,x2+1,x3+1); - xoff = 1; - yoff = -1; - zoff = -1; - } - //GoTNE - else if(inRange(x1+2,x2+2,x3+2) && !iCellHasSolid(bcArray, x1+1,x2+1,x3+1)) // ist �bern�chster Knoten auch im Gebiet (Grundknoten bei 0,0,0 - { - readICell(f,icell,x1+1,x2+1,x3+1); - xoff = -1; - yoff = -1; - zoff = -1; - } - //GoTSE - else if(inRange(x1+2,x2-1,x3+2) && !iCellHasSolid(bcArray, x1+1,x2-1,x3+1)) // ist �bern�chster Knoten auch im Gebiet (Grundknoten bei 0,0,0 - { - readICell(f,icell,x1+1,x2-1,x3+1); - xoff = -1; - yoff = 1; - zoff = -1; - } - //GoTSW - else if(inRange(x1-1,x2-1,x3+2) && !iCellHasSolid(bcArray, x1-1,x2-1,x3+1)) // ist �bern�chster Knoten auch im Gebiet (Grundknoten bei 0,0,0 - { - readICell(f,icell,x1-1,x2-1,x3+1); - xoff = 1; - yoff = 1; - zoff = -1; - } - //GoBNW - else if(inRange(x1-1,x2+2,x3-1) && !iCellHasSolid(bcArray, x1-1,x2+1,x3-1)) // ist �bern�chster Knoten auch im Gebiet (Grundknoten bei 0,0,0 - { - readICell(f,icell,x1-1,x2+1,x3-1); - xoff = 1; - yoff = -1; - zoff = 1; - } - //GoBNE - else if(inRange(x1+2,x2+2,x3-1) && !iCellHasSolid(bcArray, x1+1,x2+1,x3-1)) // ist �bern�chster Knoten auch im Gebiet (Grundknoten bei 0,0,0 - { - readICell(f,icell,x1+1,x2+1,x3-1); - xoff = -1; - yoff = -1; - zoff = 1; - } - //GoBSE - else if(inRange(x1+2,x2-1,x3-1) && !iCellHasSolid(bcArray, x1+1,x2-1,x3-1)) // ist �bern�chster Knoten auch im Gebiet (Grundknoten bei 0,0,0 - { - readICell(f,icell,x1+1,x2-1,x3-1); - xoff = -1; - yoff = 1; - zoff = 1; - } - //GoBSW - else if(inRange(x1-1,x2-1,x3-1) && !iCellHasSolid(bcArray, x1-1,x2-1,x3-1)) // ist �bern�chster Knoten auch im Gebiet (Grundknoten bei 0,0,0 - { - readICell(f,icell,x1-1,x2-1,x3-1); - xoff = 1; - yoff = 1; - zoff = 1; - } - //default - else - { - //std::string err = "For x1="+StringUtil::toString(x1)+", x2=" + StringUtil::toString(x2)+", x3=" + StringUtil::toString(x3)+ - // " interpolation is not implemented for other direction"+ - // " by using in: "+(std::string)typeid(*this).name()+ - // " or maybe you have a solid on the block boundary"; - //UB_THROW(UbException(UB_EXARGS, err)); - return false; - } - return true; + // GoWest + if (inRange(x1 - 1, x2, x3) && !iCellHasSolid(bcArray, x1 - 1, x2, x3)) { + readICell(f, icell, x1 - 1, x2, x3); + xoff = 1; + yoff = 0; + zoff = 0; + } + // GoEast + else if (inRange(x1 + 2, x2, x3) && + !iCellHasSolid(bcArray, x1 + 1, x2, x3)) // ist �bern�chster Knoten auch im Gebiet (Grundknoten bei 0,0,0 + { + readICell(f, icell, x1 + 1, x2, x3); + xoff = -1; + yoff = 0; + zoff = 0; + } + // GoSouth + else if (inRange(x1, x2 - 1, x3) && !iCellHasSolid(bcArray, x1, x2 - 1, x3)) { + readICell(f, icell, x1, x2 - 1, x3); + xoff = 0; + yoff = 1; + zoff = 0; + } + // GoNorth + else if (inRange(x1, x2 + 2, x3) && + !iCellHasSolid(bcArray, x1, x2 + 1, x3)) // ist �bern�chster Knoten auch im Gebiet (Grundknoten bei 0,0,0 + { + readICell(f, icell, x1, x2 + 1, x3); + xoff = 0; + yoff = -1; + zoff = 0; + } + // GoBottom + else if (inRange(x1, x2, x3 - 1) && !iCellHasSolid(bcArray, x1, x2, x3 - 1)) { + readICell(f, icell, x1, x2, x3 - 1); + xoff = 0; + yoff = 0; + zoff = 1; + } + // GoTop + else if (inRange(x1, x2, x3 + 2) && + !iCellHasSolid(bcArray, x1, x2, x3 + 1)) // ist �bern�chster Knoten auch im Gebiet (Grundknoten bei 0,0,0 + { + readICell(f, icell, x1, x2, x3 + 1); + xoff = 0; + yoff = 0; + zoff = -1; + } + // GoNW + else if (inRange(x1 - 1, x2 + 2, x3) && + !iCellHasSolid(bcArray, x1 - 1, x2 + 1, + x3)) // ist �bern�chster Knoten auch im Gebiet (Grundknoten bei 0,0,0 + { + readICell(f, icell, x1 - 1, x2 + 1, x3); + xoff = 1; + yoff = -1; + zoff = 0; + } + // GoNE + else if (inRange(x1 + 2, x2 + 2, x3) && + !iCellHasSolid(bcArray, x1 + 1, x2 + 1, + x3)) // ist �bern�chster Knoten auch im Gebiet (Grundknoten bei 0,0,0 + { + readICell(f, icell, x1 + 1, x2 + 1, x3); + xoff = -1; + yoff = -1; + zoff = 0; + } + // GoSW + else if (inRange(x1 - 1, x2 - 1, x3) && + !iCellHasSolid(bcArray, x1 - 1, x2 - 1, + x3)) // ist �bern�chster Knoten auch im Gebiet (Grundknoten bei 0,0,0 + { + readICell(f, icell, x1 - 1, x2 - 1, x3); + xoff = 1; + yoff = 1; + zoff = 0; + } + // GoSE + else if (inRange(x1 + 2, x2 - 1, x3) && + !iCellHasSolid(bcArray, x1 + 1, x2 - 1, + x3)) // ist �bern�chster Knoten auch im Gebiet (Grundknoten bei 0,0,0 + { + readICell(f, icell, x1 + 1, x2 - 1, x3); + xoff = -1; + yoff = 1; + zoff = 0; + } + // GoBW + else if (inRange(x1 - 1, x2, x3 - 1) && !iCellHasSolid(bcArray, x1 - 1, x2, x3 - 1)) { + readICell(f, icell, x1 - 1, x2, x3 - 1); + xoff = 1; + yoff = 0; + zoff = 1; + } + // GoBE + else if (inRange(x1 + 2, x2, x3 - 1) && + !iCellHasSolid(bcArray, x1 + 1, x2, + x3 - 1)) // ist �bern�chster Knoten auch im Gebiet (Grundknoten bei 0,0,0 + { + readICell(f, icell, x1 + 1, x2, x3 - 1); + xoff = -1; + yoff = 0; + zoff = 1; + } + // GoBS + else if (inRange(x1, x2 - 1, x3 - 1) && !iCellHasSolid(bcArray, x1, x2 - 1, x3 - 1)) { + readICell(f, icell, x1, x2 - 1, x3 - 1); + xoff = 0; + yoff = 1; + zoff = 1; + } + // GoBN + else if (inRange(x1, x2 + 2, x3 - 1) && + !iCellHasSolid(bcArray, x1, x2 + 1, + x3 - 1)) // ist �bern�chster Knoten auch im Gebiet (Grundknoten bei 0,0,0 + { + readICell(f, icell, x1, x2 + 1, x3 - 1); + xoff = 0; + yoff = -1; + zoff = 1; + } + // GoTW + else if (inRange(x1 - 1, x2, x3 + 2) && !iCellHasSolid(bcArray, x1 - 1, x2, x3 + 1)) { + readICell(f, icell, x1 - 1, x2, x3 + 1); + xoff = 1; + yoff = 0; + zoff = -1; + } + // GoTE + else if (inRange(x1 + 2, x2, x3 + 2) && + !iCellHasSolid(bcArray, x1 + 1, x2, + x3 + 1)) // ist �bern�chster Knoten auch im Gebiet (Grundknoten bei 0,0,0 + { + readICell(f, icell, x1 + 1, x2, x3 + 1); + xoff = -1; + yoff = 0; + zoff = -1; + } + // GoTS + else if (inRange(x1, x2 - 1, x3 + 2) && !iCellHasSolid(bcArray, x1, x2 - 1, x3 + 1)) { + readICell(f, icell, x1, x2 - 1, x3 + 1); + xoff = 0; + yoff = 1; + zoff = -1; + } + // GoTN + else if (inRange(x1, x2 + 2, x3 + 2) && + !iCellHasSolid(bcArray, x1, x2 + 1, + x3 + 1)) // ist �bern�chster Knoten auch im Gebiet (Grundknoten bei 0,0,0 + { + readICell(f, icell, x1, x2 + 1, x3 + 1); + xoff = 0; + yoff = -1; + zoff = -1; + } + // GoTNW + else if (inRange(x1 - 1, x2 + 2, x3 + 2) && + !iCellHasSolid(bcArray, x1 - 1, x2 + 1, + x3 + 1)) // ist �bern�chster Knoten auch im Gebiet (Grundknoten bei 0,0,0 + { + readICell(f, icell, x1 - 1, x2 + 1, x3 + 1); + xoff = 1; + yoff = -1; + zoff = -1; + } + // GoTNE + else if (inRange(x1 + 2, x2 + 2, x3 + 2) && + !iCellHasSolid(bcArray, x1 + 1, x2 + 1, + x3 + 1)) // ist �bern�chster Knoten auch im Gebiet (Grundknoten bei 0,0,0 + { + readICell(f, icell, x1 + 1, x2 + 1, x3 + 1); + xoff = -1; + yoff = -1; + zoff = -1; + } + // GoTSE + else if (inRange(x1 + 2, x2 - 1, x3 + 2) && + !iCellHasSolid(bcArray, x1 + 1, x2 - 1, + x3 + 1)) // ist �bern�chster Knoten auch im Gebiet (Grundknoten bei 0,0,0 + { + readICell(f, icell, x1 + 1, x2 - 1, x3 + 1); + xoff = -1; + yoff = 1; + zoff = -1; + } + // GoTSW + else if (inRange(x1 - 1, x2 - 1, x3 + 2) && + !iCellHasSolid(bcArray, x1 - 1, x2 - 1, + x3 + 1)) // ist �bern�chster Knoten auch im Gebiet (Grundknoten bei 0,0,0 + { + readICell(f, icell, x1 - 1, x2 - 1, x3 + 1); + xoff = 1; + yoff = 1; + zoff = -1; + } + // GoBNW + else if (inRange(x1 - 1, x2 + 2, x3 - 1) && + !iCellHasSolid(bcArray, x1 - 1, x2 + 1, + x3 - 1)) // ist �bern�chster Knoten auch im Gebiet (Grundknoten bei 0,0,0 + { + readICell(f, icell, x1 - 1, x2 + 1, x3 - 1); + xoff = 1; + yoff = -1; + zoff = 1; + } + // GoBNE + else if (inRange(x1 + 2, x2 + 2, x3 - 1) && + !iCellHasSolid(bcArray, x1 + 1, x2 + 1, + x3 - 1)) // ist �bern�chster Knoten auch im Gebiet (Grundknoten bei 0,0,0 + { + readICell(f, icell, x1 + 1, x2 + 1, x3 - 1); + xoff = -1; + yoff = -1; + zoff = 1; + } + // GoBSE + else if (inRange(x1 + 2, x2 - 1, x3 - 1) && + !iCellHasSolid(bcArray, x1 + 1, x2 - 1, + x3 - 1)) // ist �bern�chster Knoten auch im Gebiet (Grundknoten bei 0,0,0 + { + readICell(f, icell, x1 + 1, x2 - 1, x3 - 1); + xoff = -1; + yoff = 1; + zoff = 1; + } + // GoBSW + else if (inRange(x1 - 1, x2 - 1, x3 - 1) && + !iCellHasSolid(bcArray, x1 - 1, x2 - 1, + x3 - 1)) // ist �bern�chster Knoten auch im Gebiet (Grundknoten bei 0,0,0 + { + readICell(f, icell, x1 - 1, x2 - 1, x3 - 1); + xoff = 1; + yoff = 1; + zoff = 1; + } + // default + else { + // std::string err = "For x1="+StringUtil::toString(x1)+", x2=" + StringUtil::toString(x2)+", x3=" + + // StringUtil::toString(x3)+ + // " interpolation is not implemented for other direction"+ + // " by using in: "+(std::string)typeid(*this).name()+ + // " or maybe you have a solid on the block boundary"; + // UB_THROW(UbException(UB_EXARGS, err)); + return false; + } + return true; } ////////////////////////////////////////////////////////////////////////// -int InterpolationProcessor::iCellHowManySolids( const SPtr<BCArray3D> bcArray, int x1, int x2, int x3 ) +int InterpolationProcessor::iCellHowManySolids(const SPtr<BCArray3D> bcArray, int x1, int x2, int x3) { - int count = 0; - for (int ix3 = x3; ix3 <= x3 + 1; ix3++) - for(int ix2 = x2; ix2 <= x2 + 1; ix2++) - for(int ix1 = x1; ix1 <= x1 + 1; ix1++) - { - if(bcArray->isSolid(ix1, ix2, ix3)) - count++; - } - return count; + int count = 0; + for (int ix3 = x3; ix3 <= x3 + 1; ix3++) + for (int ix2 = x2; ix2 <= x2 + 1; ix2++) + for (int ix1 = x1; ix1 <= x1 + 1; ix1++) { + if (bcArray->isSolid(ix1, ix2, ix3)) + count++; + } + return count; } diff --git a/src/cpu/VirtualFluidsCore/LBM/InterpolationProcessor.h b/src/cpu/VirtualFluidsCore/LBM/InterpolationProcessor.h index fb9ade9aa43ea24384710ace3a0ded9fffbdda69..b3de5c873ecb361049e25ec05e0660cf29d1dc30 100644 --- a/src/cpu/VirtualFluidsCore/LBM/InterpolationProcessor.h +++ b/src/cpu/VirtualFluidsCore/LBM/InterpolationProcessor.h @@ -1,23 +1,21 @@ #ifndef D3Q27INTRPOLATIOPROCESSOR_H_ #define D3Q27INTRPOLATIOPROCESSOR_H_ +#include "BCArray3D.h" +#include "BoundaryConditions.h" +#include "DistributionArray3D.h" #include "InterpolationProcessor.h" #include "LBMSystem.h" -#include "DistributionArray3D.h" -#include "BoundaryConditions.h" -#include "BCArray3D.h" - -struct D3Q27ICell -{ - LBMReal TSW[27]; - LBMReal TNW[27]; - LBMReal TNE[27]; - LBMReal TSE[27]; - LBMReal BSW[27]; - LBMReal BNW[27]; - LBMReal BNE[27]; - LBMReal BSE[27]; +struct D3Q27ICell { + LBMReal TSW[27]; + LBMReal TNW[27]; + LBMReal TNE[27]; + LBMReal TSE[27]; + LBMReal BSW[27]; + LBMReal BNW[27]; + LBMReal BNE[27]; + LBMReal BSE[27]; }; class InterpolationProcessor; @@ -28,43 +26,48 @@ using InterpolationProcessorPtr = SPtr<InterpolationProcessor>; class InterpolationProcessor { public: - InterpolationProcessor(); - virtual ~InterpolationProcessor(); - virtual InterpolationProcessorPtr clone() = 0; - virtual void setOmegas(LBMReal omegaC, LBMReal omegaF) = 0; - virtual void interpolateCoarseToFine(D3Q27ICell& icellC, D3Q27ICell& icellF) = 0; - virtual void interpolateCoarseToFine(D3Q27ICell& icellC, D3Q27ICell& icellF, LBMReal xoff, LBMReal yoff, LBMReal zoff) = 0; - virtual void interpolateFineToCoarse(D3Q27ICell& icellF, LBMReal* icellC) = 0; - virtual void interpolateFineToCoarse(D3Q27ICell& icellF, LBMReal* icellC, LBMReal xoff, LBMReal yoff, LBMReal zoff) = 0; + InterpolationProcessor(); + virtual ~InterpolationProcessor(); + virtual InterpolationProcessorPtr clone() = 0; + virtual void setOmegas(LBMReal omegaC, LBMReal omegaF) = 0; + virtual void interpolateCoarseToFine(D3Q27ICell &icellC, D3Q27ICell &icellF) = 0; + virtual void interpolateCoarseToFine(D3Q27ICell &icellC, D3Q27ICell &icellF, LBMReal xoff, LBMReal yoff, + LBMReal zoff) = 0; + virtual void interpolateFineToCoarse(D3Q27ICell &icellF, LBMReal *icellC) = 0; + virtual void interpolateFineToCoarse(D3Q27ICell &icellF, LBMReal *icellC, LBMReal xoff, LBMReal yoff, + LBMReal zoff) = 0; - static void readICell(SPtr<DistributionArray3D> f, D3Q27ICell& icell, int x1, int x2, int x3); - static void writeICell(SPtr<DistributionArray3D> f, const D3Q27ICell& icell, int x1, int x2, int x3); - static void writeICellInv(SPtr<DistributionArray3D> f, const D3Q27ICell& icell, int x1, int x2, int x3); - static void writeINode(SPtr<DistributionArray3D> f, const LBMReal* const inode, int x1, int x2, int x3); - static void writeINodeInv(SPtr<DistributionArray3D> f, const LBMReal* const inode, int x1, int x2, int x3); - static bool iCellHasSolid(const SPtr<BCArray3D> bcArray, int x1, int x2, int x3); - static int iCellHowManySolids(const SPtr<BCArray3D> bcArray, int x1, int x2, int x3); + static void readICell(SPtr<DistributionArray3D> f, D3Q27ICell &icell, int x1, int x2, int x3); + static void writeICell(SPtr<DistributionArray3D> f, const D3Q27ICell &icell, int x1, int x2, int x3); + static void writeICellInv(SPtr<DistributionArray3D> f, const D3Q27ICell &icell, int x1, int x2, int x3); + static void writeINode(SPtr<DistributionArray3D> f, const LBMReal *const inode, int x1, int x2, int x3); + static void writeINodeInv(SPtr<DistributionArray3D> f, const LBMReal *const inode, int x1, int x2, int x3); + static bool iCellHasSolid(const SPtr<BCArray3D> bcArray, int x1, int x2, int x3); + static int iCellHowManySolids(const SPtr<BCArray3D> bcArray, int x1, int x2, int x3); - bool findNeighborICell(const SPtr<BCArray3D> bcArray, SPtr<DistributionArray3D> f, - D3Q27ICell& icell, int maxX1, int maxX2, int maxX3, - int x1, int x2, int x3, LBMReal& xoff, LBMReal& yoff, LBMReal& zoff); + bool findNeighborICell(const SPtr<BCArray3D> bcArray, SPtr<DistributionArray3D> f, D3Q27ICell &icell, int maxX1, + int maxX2, int maxX3, int x1, int x2, int x3, LBMReal &xoff, LBMReal &yoff, LBMReal &zoff); protected: - virtual void calcInterpolatedCoefficiets(const D3Q27ICell& icell, LBMReal omega, LBMReal eps_new){} - virtual void calcInterpolatedNodeFC(LBMReal* f, LBMReal omega){} - virtual void calcInterpolatedVelocity(LBMReal x, LBMReal y, LBMReal z,LBMReal& vx1, LBMReal& vx2, LBMReal& vx3){} - virtual void calcInterpolatedShearStress(LBMReal x, LBMReal y, LBMReal z,LBMReal& tauxx, LBMReal& tauyy, LBMReal& tauzz,LBMReal& tauxy, LBMReal& tauxz, LBMReal& tauyz){} - virtual void setOffsets(LBMReal xoff, LBMReal yoff, LBMReal zoff){} - friend class InterpolationHelper; + virtual void calcInterpolatedCoefficiets(const D3Q27ICell &icell, LBMReal omega, LBMReal eps_new) {} + virtual void calcInterpolatedNodeFC(LBMReal *f, LBMReal omega) {} + virtual void calcInterpolatedVelocity(LBMReal x, LBMReal y, LBMReal z, LBMReal &vx1, LBMReal &vx2, LBMReal &vx3) {} + virtual void calcInterpolatedShearStress(LBMReal x, LBMReal y, LBMReal z, LBMReal &tauxx, LBMReal &tauyy, + LBMReal &tauzz, LBMReal &tauxy, LBMReal &tauxz, LBMReal &tauyz) + { + } + virtual void setOffsets(LBMReal xoff, LBMReal yoff, LBMReal zoff) {} + friend class InterpolationHelper; + private: - bool inRange(int x1, int x2, int x3); - int m_maxX1, m_maxX2, m_maxX3; + bool inRange(int x1, int x2, int x3); + int m_maxX1, m_maxX2, m_maxX3; }; ////////////////////////////////////////////////////////////////////////// inline bool InterpolationProcessor::inRange(int x1, int x2, int x3) { - return x1 >= 0 && x1 < m_maxX1 && x2 >= 0 && x2 < m_maxX2 && x3 >= 0 && x3 < m_maxX3; + return x1 >= 0 && x1 < m_maxX1 && x2 >= 0 && x2 < m_maxX2 && x3 >= 0 && x3 < m_maxX3; } #endif diff --git a/src/cpu/VirtualFluidsCore/LBM/LBMKernel.cpp b/src/cpu/VirtualFluidsCore/LBM/LBMKernel.cpp index 7004a4d734c5aff518148631d5881fc0ba0a7f8b..1d387655bc0b177fa8f80972ac99aeee3caba6a8 100644 --- a/src/cpu/VirtualFluidsCore/LBM/LBMKernel.cpp +++ b/src/cpu/VirtualFluidsCore/LBM/LBMKernel.cpp @@ -1,28 +1,28 @@ //======================================================================================= -// ____ ____ __ ______ __________ __ __ __ __ -// \ \ | | | | | _ \ |___ ___| | | | | / \ | | -// \ \ | | | | | |_) | | | | | | | / \ | | -// \ \ | | | | | _ / | | | | | | / /\ \ | | -// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ -// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| -// \ \ | | ________________________________________________________________ -// \ \ | | | ______________________________________________________________| -// \ \| | | | __ __ __ __ ______ _______ -// \ | | |_____ | | | | | | | | | _ \ / _____) -// \ | | _____| | | | | | | | | | | \ \ \_______ +// ____ ____ __ ______ __________ __ __ __ __ +// \ \ | | | | | _ \ |___ ___| | | | | / \ | | +// \ \ | | | | | |_) | | | | | | | / \ | | +// \ \ | | | | | _ / | | | | | | / /\ \ | | +// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ +// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| +// \ \ | | ________________________________________________________________ +// \ \ | | | ______________________________________________________________| +// \ \| | | | __ __ __ __ ______ _______ +// \ | | |_____ | | | | | | | | | _ \ / _____) +// \ | | _____| | | | | | | | | | | \ \ \_______ // \ | | | | |_____ | \_/ | | | | |_/ / _____ | -// \ _____| |__| |________| \_______/ |__| |______/ (_______/ +// \ _____| |__| |________| \_______/ |__| |______/ (_______/ // -// This file is part of VirtualFluids. VirtualFluids is free software: you can +// This file is part of VirtualFluids. VirtualFluids is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of +// License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. -// -// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// +// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License along // with VirtualFluids (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>. // @@ -32,221 +32,155 @@ //======================================================================================= #include "LBMKernel.h" -#include "DataSet3D.h" +#include "BCArray3D.h" #include "BCProcessor.h" #include "Block3D.h" -#include "BCArray3D.h" +#include "DataSet3D.h" + +LBMKernel::LBMKernel() -LBMKernel::LBMKernel() - { - this->setForcingX1(0.0); - this->setForcingX2(0.0); - this->setForcingX3(0.0); - dataSet = std::make_shared<DataSet3D>(); - this->nx[0] = 0; - this->nx[1] = 0; - this->nx[2] = 0; + this->setForcingX1(0.0); + this->setForcingX2(0.0); + this->setForcingX3(0.0); + dataSet = std::make_shared<DataSet3D>(); + this->nx[0] = 0; + this->nx[1] = 0; + this->nx[2] = 0; } ////////////////////////////////////////////////////////////////////////// -void LBMKernel::setBCProcessor(SPtr<BCProcessor> bcp) -{ - bcProcessor = bcp; -} +void LBMKernel::setBCProcessor(SPtr<BCProcessor> bcp) { bcProcessor = bcp; } ////////////////////////////////////////////////////////////////////////// -SPtr<BCProcessor> LBMKernel::getBCProcessor() const -{ - return bcProcessor; -} +SPtr<BCProcessor> LBMKernel::getBCProcessor() const { return bcProcessor; } ////////////////////////////////////////////////////////////////////////// -void LBMKernel::setCollisionFactor(double collFactor) -{ - this->collFactor = collFactor; -} +void LBMKernel::setCollisionFactor(double collFactor) { this->collFactor = collFactor; } ////////////////////////////////////////////////////////////////////////// -double LBMKernel::getCollisionFactor() const -{ - return collFactor; -} +double LBMKernel::getCollisionFactor() const { return collFactor; } ////////////////////////////////////////////////////////////////////////// void LBMKernel::setForcingX1(LBMReal forcingX1) { - this->muForcingX1.SetExpr( UbSystem::toString(forcingX1,LBMRealLim::digits10) ); - this->checkFunction(muForcingX1); + this->muForcingX1.SetExpr(UbSystem::toString(forcingX1, LBMRealLim::digits10)); + this->checkFunction(muForcingX1); } ////////////////////////////////////////////////////////////////////////// void LBMKernel::setForcingX2(LBMReal forcingX2) { - this->muForcingX2.SetExpr( UbSystem::toString(forcingX2,LBMRealLim::digits10) ); - this->checkFunction(muForcingX2); + this->muForcingX2.SetExpr(UbSystem::toString(forcingX2, LBMRealLim::digits10)); + this->checkFunction(muForcingX2); } void LBMKernel::setForcingX3(LBMReal forcingX3) { - this->muForcingX3.SetExpr( UbSystem::toString(forcingX3,LBMRealLim::digits10) ); - this->checkFunction(muForcingX3); + this->muForcingX3.SetExpr(UbSystem::toString(forcingX3, LBMRealLim::digits10)); + this->checkFunction(muForcingX3); } ////////////////////////////////////////////////////////////////////////// -void LBMKernel::setForcingX1( const mu::Parser& parser) -{ - this->checkFunction(parser); - this->muForcingX1 = parser; +void LBMKernel::setForcingX1(const mu::Parser &parser) +{ + this->checkFunction(parser); + this->muForcingX1 = parser; } ////////////////////////////////////////////////////////////////////////// -void LBMKernel::setForcingX2( const mu::Parser& parser) -{ - this->checkFunction(parser); - this->muForcingX2 = parser; +void LBMKernel::setForcingX2(const mu::Parser &parser) +{ + this->checkFunction(parser); + this->muForcingX2 = parser; } ////////////////////////////////////////////////////////////////////////// -void LBMKernel::setForcingX3( const mu::Parser& parser) -{ - this->checkFunction(parser); - this->muForcingX3 = parser; +void LBMKernel::setForcingX3(const mu::Parser &parser) +{ + this->checkFunction(parser); + this->muForcingX3 = parser; } ////////////////////////////////////////////////////////////////////////// -void LBMKernel::setForcingX1( const std::string& muParserString) -{ - this->muForcingX1.SetExpr(muParserString); - this->checkFunction(muForcingX1); +void LBMKernel::setForcingX1(const std::string &muParserString) +{ + this->muForcingX1.SetExpr(muParserString); + this->checkFunction(muForcingX1); } ////////////////////////////////////////////////////////////////////////// -void LBMKernel::setForcingX2( const std::string& muParserString) -{ - this->muForcingX2.SetExpr(muParserString); - this->checkFunction(muForcingX2); +void LBMKernel::setForcingX2(const std::string &muParserString) +{ + this->muForcingX2.SetExpr(muParserString); + this->checkFunction(muForcingX2); } -void LBMKernel::setForcingX3( const std::string& muParserString) -{ - this->muForcingX3.SetExpr(muParserString); - this->checkFunction(muForcingX3); +void LBMKernel::setForcingX3(const std::string &muParserString) +{ + this->muForcingX3.SetExpr(muParserString); + this->checkFunction(muForcingX3); } ////////////////////////////////////////////////////////////////////////// void LBMKernel::checkFunction(mu::Parser fct) { - double x1=1.0,x2=1.0,x3=1.0, dt=1.0, nue=1.0; - fct.DefineVar("x1",&x1); - fct.DefineVar("x2",&x2); - fct.DefineVar("x3",&x3); - fct.DefineVar("dt",&dt); - fct.DefineVar("nue",&nue); + double x1 = 1.0, x2 = 1.0, x3 = 1.0, dt = 1.0, nue = 1.0; + fct.DefineVar("x1", &x1); + fct.DefineVar("x2", &x2); + fct.DefineVar("x3", &x3); + fct.DefineVar("dt", &dt); + fct.DefineVar("nue", &nue); - try - { - fct.Eval(); - fct.ClearVar(); - } - catch(mu::ParserError& e) - { - throw UbException(UB_EXARGS,"function: "+e.GetExpr() + (std::string)"error: "+e.GetMsg() - +(std::string)", only x1,x2,x3,dx are allowed as variables" ); - } + try { + fct.Eval(); + fct.ClearVar(); + } catch (mu::ParserError &e) { + throw UbException(UB_EXARGS, "function: " + e.GetExpr() + (std::string) "error: " + e.GetMsg() + + (std::string) ", only x1,x2,x3,dx are allowed as variables"); + } } ////////////////////////////////////////////////////////////////////////// -void LBMKernel::setGhostLayerWidth(int witdh) -{ - ghostLayerWidth = witdh; -} +void LBMKernel::setGhostLayerWidth(int witdh) { ghostLayerWidth = witdh; } ////////////////////////////////////////////////////////////////////////// -int LBMKernel::getGhostLayerWidth() const -{ - return ghostLayerWidth; -} +int LBMKernel::getGhostLayerWidth() const { return ghostLayerWidth; } ////////////////////////////////////////////////////////////////////////// -void LBMKernel::setIndex( int x1, int x2, int x3 ) +void LBMKernel::setIndex(int x1, int x2, int x3) { - this->ix1 = x1; - this->ix2 = x2; - this->ix3 = x3; + this->ix1 = x1; + this->ix2 = x2; + this->ix3 = x3; } ////////////////////////////////////////////////////////////////////////// -SPtr<DataSet3D> LBMKernel::getDataSet() const -{ - return this->dataSet; -} +SPtr<DataSet3D> LBMKernel::getDataSet() const { return this->dataSet; } ////////////////////////////////////////////////////////////////////////// -LBMReal LBMKernel::getDeltaT() const -{ - return this->deltaT; -} +LBMReal LBMKernel::getDeltaT() const { return this->deltaT; } ////////////////////////////////////////////////////////////////////////// -void LBMKernel::setDeltaT( LBMReal dt ) -{ - deltaT = dt; -} +void LBMKernel::setDeltaT(LBMReal dt) { deltaT = dt; } ////////////////////////////////////////////////////////////////////////// -bool LBMKernel::getCompressible() const -{ - return compressible; -} +bool LBMKernel::getCompressible() const { return compressible; } ////////////////////////////////////////////////////////////////////////// -void LBMKernel::setCompressible(bool val) -{ - compressible = val; -} +void LBMKernel::setCompressible(bool val) { compressible = val; } ////////////////////////////////////////////////////////////////////////// -bool LBMKernel::getWithForcing() const -{ - return withForcing; -} +bool LBMKernel::getWithForcing() const { return withForcing; } ////////////////////////////////////////////////////////////////////////// -void LBMKernel::setWithForcing( bool val ) -{ - withForcing = val; -} +void LBMKernel::setWithForcing(bool val) { withForcing = val; } ////////////////////////////////////////////////////////////////////////// -void LBMKernel::setBlock( SPtr<Block3D> block ) -{ - this->block = block; -} +void LBMKernel::setBlock(SPtr<Block3D> block) { this->block = block; } ////////////////////////////////////////////////////////////////////////// -SPtr<Block3D> LBMKernel::getBlock() const -{ - return block.lock(); -} +SPtr<Block3D> LBMKernel::getBlock() const { return block.lock(); } ////////////////////////////////////////////////////////////////////////// -bool LBMKernel::getWithSpongeLayer() const -{ - return withSpongeLayer; -} +bool LBMKernel::getWithSpongeLayer() const { return withSpongeLayer; } ////////////////////////////////////////////////////////////////////////// -void LBMKernel::setWithSpongeLayer( bool val ) -{ - withSpongeLayer = val; -} +void LBMKernel::setWithSpongeLayer(bool val) { withSpongeLayer = val; } ////////////////////////////////////////////////////////////////////////// -void LBMKernel::setSpongeLayer( const mu::Parser& parser ) +void LBMKernel::setSpongeLayer(const mu::Parser &parser) { - this->checkFunction(parser); - this->muSpongeLayer = parser; + this->checkFunction(parser); + this->muSpongeLayer = parser; } ////////////////////////////////////////////////////////////////////////// -void LBMKernel::setSpongeLayer( const std::string& muParserString ) +void LBMKernel::setSpongeLayer(const std::string &muParserString) { - this->muSpongeLayer.SetExpr(muParserString); - this->checkFunction(muSpongeLayer); + this->muSpongeLayer.SetExpr(muParserString); + this->checkFunction(muSpongeLayer); } ////////////////////////////////////////////////////////////////////////// -void LBMKernel::setDataSet(SPtr<DataSet3D> dataSet) -{ - this->dataSet = dataSet; -} +void LBMKernel::setDataSet(SPtr<DataSet3D> dataSet) { this->dataSet = dataSet; } ////////////////////////////////////////////////////////////////////////// -void LBMKernel::swapDistributions() -{ - dataSet->getFdistributions()->swap(); -} +void LBMKernel::swapDistributions() { dataSet->getFdistributions()->swap(); } ////////////////////////////////////////////////////////////////////////// -void LBMKernel::setNX(std::array<int, 3> nx) -{ - this->nx = nx; -} +void LBMKernel::setNX(std::array<int, 3> nx) { this->nx = nx; } ////////////////////////////////////////////////////////////////////////// -std::array<int, 3> LBMKernel::getNX() -{ - return nx; -} +std::array<int, 3> LBMKernel::getNX() { return nx; } ////////////////////////////////////////////////////////////////////////// -bool LBMKernel::isInsideOfDomain(const int& x1, const int& x2, const int& x3) const +bool LBMKernel::isInsideOfDomain(const int &x1, const int &x2, const int &x3) const { const SPtr<BCArray3D> bcArray = this->bcProcessor->getBCArray(); return bcArray->isInsideOfDomain(x1, x2, x3, ghostLayerWidth); diff --git a/src/cpu/VirtualFluidsCore/LBM/LBMKernel.h b/src/cpu/VirtualFluidsCore/LBM/LBMKernel.h index 9703bf6c56349c93618f330d38e60b7af4148e72..be29589b9b7ab239bece700126ae906795c83977 100644 --- a/src/cpu/VirtualFluidsCore/LBM/LBMKernel.h +++ b/src/cpu/VirtualFluidsCore/LBM/LBMKernel.h @@ -1,28 +1,28 @@ //======================================================================================= -// ____ ____ __ ______ __________ __ __ __ __ -// \ \ | | | | | _ \ |___ ___| | | | | / \ | | -// \ \ | | | | | |_) | | | | | | | / \ | | -// \ \ | | | | | _ / | | | | | | / /\ \ | | -// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ -// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| -// \ \ | | ________________________________________________________________ -// \ \ | | | ______________________________________________________________| -// \ \| | | | __ __ __ __ ______ _______ -// \ | | |_____ | | | | | | | | | _ \ / _____) -// \ | | _____| | | | | | | | | | | \ \ \_______ +// ____ ____ __ ______ __________ __ __ __ __ +// \ \ | | | | | _ \ |___ ___| | | | | / \ | | +// \ \ | | | | | |_) | | | | | | | / \ | | +// \ \ | | | | | _ / | | | | | | / /\ \ | | +// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ +// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| +// \ \ | | ________________________________________________________________ +// \ \ | | | ______________________________________________________________| +// \ \| | | | __ __ __ __ ______ _______ +// \ | | |_____ | | | | | | | | | _ \ / _____) +// \ | | _____| | | | | | | | | | | \ \ \_______ // \ | | | | |_____ | \_/ | | | | |_/ / _____ | -// \ _____| |__| |________| \_______/ |__| |______/ (_______/ +// \ _____| |__| |________| \_______/ |__| |______/ (_______/ // -// This file is part of VirtualFluids. VirtualFluids is free software: you can +// This file is part of VirtualFluids. VirtualFluids is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of +// License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. -// -// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// +// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License along // with VirtualFluids (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>. // @@ -34,9 +34,9 @@ #ifndef LBMKERNEL_H #define LBMKERNEL_H -#include <PointerDefinitions.h> -#include "LBMSystem.h" #include "ILBMKernel.h" +#include "LBMSystem.h" +#include <PointerDefinitions.h> #include <array> #include <limits> #include <muParser.h> @@ -45,17 +45,18 @@ class BCProcessor; class DataSet3D; class Block3D; -//! \brief A base class provides basic functionality for LBM kernel +//! \brief A base class provides basic functionality for LBM kernel class LBMKernel : public ILBMKernel, public enableSharedFromThis<LBMKernel> { public: using LBMRealLim = std::numeric_limits<LBMReal>; + public: LBMKernel(); virtual SPtr<LBMKernel> clone() = 0; - void calculate(int step) override = 0; + void calculate(int step) override = 0; double getCalculationTime() override = 0; void setBCProcessor(SPtr<BCProcessor> bcp) override; @@ -65,7 +66,7 @@ public: double getCollisionFactor() const override; void setGhostLayerWidth(int witdh); - int getGhostLayerWidth() const override; + int getGhostLayerWidth() const override; void setDataSet(SPtr<DataSet3D> dataSet); SPtr<DataSet3D> getDataSet() const override; @@ -74,13 +75,13 @@ public: void setForcingX2(LBMReal forcingX2); void setForcingX3(LBMReal forcingX3); - void setForcingX1(const mu::Parser& parser); - void setForcingX2(const mu::Parser& parser); - void setForcingX3(const mu::Parser& parser); + void setForcingX1(const mu::Parser &parser); + void setForcingX2(const mu::Parser &parser); + void setForcingX3(const mu::Parser &parser); - void setForcingX1(const std::string& muParserString); - void setForcingX2(const std::string& muParserString); - void setForcingX3(const std::string& muParserString); + void setForcingX1(const std::string &muParserString); + void setForcingX2(const std::string &muParserString); + void setForcingX3(const std::string &muParserString); void setIndex(int x1, int x2, int x3); @@ -96,8 +97,8 @@ public: bool getWithSpongeLayer() const; void setWithSpongeLayer(bool val); - void setSpongeLayer(const mu::Parser& parser); - void setSpongeLayer(const std::string& muParserString); + void setSpongeLayer(const mu::Parser &parser); + void setSpongeLayer(const std::string &muParserString); void setBlock(SPtr<Block3D> block); SPtr<Block3D> getBlock() const; @@ -113,19 +114,19 @@ protected: SPtr<DataSet3D> dataSet; SPtr<BCProcessor> bcProcessor; LBMReal collFactor; - int ghostLayerWidth{1}; - bool compressible{false}; + int ghostLayerWidth{ 1 }; + bool compressible{ false }; - //forcing - bool withForcing{false}; + // forcing + bool withForcing{ false }; mu::Parser muForcingX1; mu::Parser muForcingX2; mu::Parser muForcingX3; int ix1, ix2, ix3; - LBMReal deltaT{1.0}; + LBMReal deltaT{ 1.0 }; - //sponge layer - bool withSpongeLayer{false}; + // sponge layer + bool withSpongeLayer{ false }; mu::Parser muSpongeLayer; WPtr<Block3D> block; diff --git a/src/cpu/VirtualFluidsCore/LBM/LBMSystem.cpp b/src/cpu/VirtualFluidsCore/LBM/LBMSystem.cpp index b6fcbe12fa4a13a5c2597beb1ad97e55a84c2dac..9c8e8990bc8e247d21dcfb80fb222d084620a408 100644 --- a/src/cpu/VirtualFluidsCore/LBM/LBMSystem.cpp +++ b/src/cpu/VirtualFluidsCore/LBM/LBMSystem.cpp @@ -1,28 +1,28 @@ //======================================================================================= -// ____ ____ __ ______ __________ __ __ __ __ -// \ \ | | | | | _ \ |___ ___| | | | | / \ | | -// \ \ | | | | | |_) | | | | | | | / \ | | -// \ \ | | | | | _ / | | | | | | / /\ \ | | -// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ -// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| -// \ \ | | ________________________________________________________________ -// \ \ | | | ______________________________________________________________| -// \ \| | | | __ __ __ __ ______ _______ -// \ | | |_____ | | | | | | | | | _ \ / _____) -// \ | | _____| | | | | | | | | | | \ \ \_______ +// ____ ____ __ ______ __________ __ __ __ __ +// \ \ | | | | | _ \ |___ ___| | | | | / \ | | +// \ \ | | | | | |_) | | | | | | | / \ | | +// \ \ | | | | | _ / | | | | | | / /\ \ | | +// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ +// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| +// \ \ | | ________________________________________________________________ +// \ \ | | | ______________________________________________________________| +// \ \| | | | __ __ __ __ ______ _______ +// \ | | |_____ | | | | | | | | | _ \ / _____) +// \ | | _____| | | | | | | | | | | \ \ \_______ // \ | | | | |_____ | \_/ | | | | |_/ / _____ | -// \ _____| |__| |________| \_______/ |__| |______/ (_______/ +// \ _____| |__| |________| \_______/ |__| |______/ (_______/ // -// This file is part of VirtualFluids. VirtualFluids is free software: you can +// This file is part of VirtualFluids. VirtualFluids is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of +// License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. -// -// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// +// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License along // with VirtualFluids (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>. // @@ -35,5 +35,5 @@ namespace LBMSystem { - real SMAG_CONST = REAL_CAST(0.18); +real SMAG_CONST = REAL_CAST(0.18); } diff --git a/src/cpu/VirtualFluidsCore/LBM/LBMSystem.h b/src/cpu/VirtualFluidsCore/LBM/LBMSystem.h index 7b016a3b75675d9551d62c111e60364385c95493..d24775aef0fbe6822fbdc03d42e2acfeb3021430 100644 --- a/src/cpu/VirtualFluidsCore/LBM/LBMSystem.h +++ b/src/cpu/VirtualFluidsCore/LBM/LBMSystem.h @@ -1,28 +1,28 @@ //======================================================================================= -// ____ ____ __ ______ __________ __ __ __ __ -// \ \ | | | | | _ \ |___ ___| | | | | / \ | | -// \ \ | | | | | |_) | | | | | | | / \ | | -// \ \ | | | | | _ / | | | | | | / /\ \ | | -// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ -// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| -// \ \ | | ________________________________________________________________ -// \ \ | | | ______________________________________________________________| -// \ \| | | | __ __ __ __ ______ _______ -// \ | | |_____ | | | | | | | | | _ \ / _____) -// \ | | _____| | | | | | | | | | | \ \ \_______ +// ____ ____ __ ______ __________ __ __ __ __ +// \ \ | | | | | _ \ |___ ___| | | | | / \ | | +// \ \ | | | | | |_) | | | | | | | / \ | | +// \ \ | | | | | _ / | | | | | | / /\ \ | | +// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ +// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| +// \ \ | | ________________________________________________________________ +// \ \ | | | ______________________________________________________________| +// \ \| | | | __ __ __ __ ______ _______ +// \ | | |_____ | | | | | | | | | _ \ / _____) +// \ | | _____| | | | | | | | | | | \ \ \_______ // \ | | | | |_____ | \_/ | | | | |_/ / _____ | -// \ _____| |__| |________| \_______/ |__| |______/ (_______/ +// \ _____| |__| |________| \_______/ |__| |______/ (_______/ // -// This file is part of VirtualFluids. VirtualFluids is free software: you can +// This file is part of VirtualFluids. VirtualFluids is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of +// License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. -// -// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// +// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License along // with VirtualFluids (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>. // @@ -34,9 +34,8 @@ #define LBMSYSTEM_H #include <cmath> -#include <string> #include <iostream> - +#include <string> //! \brief namespace for global system-functions @@ -46,50 +45,43 @@ namespace LBMSystem //#define SINGLEPRECISION #ifdef SINGLEPRECISION - typedef float real; - #define REAL_CAST(x) ( (LBMSystem::real)(x) ) +typedef float real; +#define REAL_CAST(x) ((LBMSystem::real)(x)) #else - using real = double; - #define REAL_CAST(x) ( x ) +using real = double; +#define REAL_CAST(x) (x) #endif - extern real SMAG_CONST; +extern real SMAG_CONST; - ////////////////////////////////////////////////////////////////////////// - //!get LBM deltaT is equal LBM DeltaX - //!deltaT is dependent from grid level - //!for first grid level is deltaT = 1.0 - //!for next grid level 1/2 etc. - static real getDeltaT(int level) - { - return REAL_CAST(1.0/REAL_CAST(1<<level)); - } +////////////////////////////////////////////////////////////////////////// +//! get LBM deltaT is equal LBM DeltaX +//! deltaT is dependent from grid level +//! for first grid level is deltaT = 1.0 +//! for next grid level 1/2 etc. +static real getDeltaT(int level) { return REAL_CAST(1.0 / REAL_CAST(1 << level)); } - ////////////////////////////////////////////////////////////////////////// - //!calculate collision factor omega = 1.0/(3.0*viscosity/deltaT+0.5) - //!deltaT is dependent from grid level - //!for first grid level is deltaT = 1.0 - //!for next grid level 1/2 etc. - static real calcCollisionFactor(real viscosity, int level) - { - //return REAL_CAST(1.0/(3.0*viscosity/deltaT+0.5)); - return REAL_CAST(1.0/(3.0*viscosity/(1.0/REAL_CAST(1<<level))+0.5)); - } +////////////////////////////////////////////////////////////////////////// +//! calculate collision factor omega = 1.0/(3.0*viscosity/deltaT+0.5) +//! deltaT is dependent from grid level +//! for first grid level is deltaT = 1.0 +//! for next grid level 1/2 etc. +static real calcCollisionFactor(real viscosity, int level) +{ + // return REAL_CAST(1.0/(3.0*viscosity/deltaT+0.5)); + return REAL_CAST(1.0 / (3.0 * viscosity / (1.0 / REAL_CAST(1 << level)) + 0.5)); +} - //!bulk viscosity - static real calcOmega2(real viscosity, int level) - { - return REAL_CAST(1.0/(4.5*viscosity/(1.0/REAL_CAST(1<<level))+0.5)); - } - //!bulk viscosity - static real calcOmega2(real viscosity, real deltaT) - { - return REAL_CAST(1.0/(4.5*viscosity/deltaT+0.5)); - } +//! bulk viscosity +static real calcOmega2(real viscosity, int level) +{ + return REAL_CAST(1.0 / (4.5 * viscosity / (1.0 / REAL_CAST(1 << level)) + 0.5)); } +//! bulk viscosity +static real calcOmega2(real viscosity, real deltaT) { return REAL_CAST(1.0 / (4.5 * viscosity / deltaT + 0.5)); } +} // namespace LBMSystem -//some typedefs for global namespace +// some typedefs for global namespace using LBMReal = LBMSystem::real; #endif - diff --git a/src/cpu/VirtualFluidsCore/LBM/LBMUnitConverter.h b/src/cpu/VirtualFluidsCore/LBM/LBMUnitConverter.h index 89514acd6b4e6ee2221fea85e805c5679192ce20..3059fd3831d3daf1bc05254c67b3d671a0d81cb7 100644 --- a/src/cpu/VirtualFluidsCore/LBM/LBMUnitConverter.h +++ b/src/cpu/VirtualFluidsCore/LBM/LBMUnitConverter.h @@ -1,11 +1,11 @@ #ifndef LBMUNITCONVERTER_H #define LBMUNITCONVERTER_H -#include <iostream> +#include <cmath> #include <iomanip> -#include <string> +#include <iostream> #include <sstream> -#include <cmath> +#include <string> //#include "LBMUnitConverter.h" @@ -16,171 +16,187 @@ // LBMUnitConverter conv( 100 /*L_World*/, 1484/*cs_water*/ , 1000/*rho_water*/ // , 1000/*L_LB*/ , 1./srqt(3.)/*cs_Lb*/, 1/*rho_Lb*/ ); // cout<<conv.toString()<<endl; -// +// // cout<<"100m = "<< 100 * conv.getFactorLentghWToLb() << "dx " << std::endl; // cout<<"1000dx = "<< 1000 * conv.getFactorLentghLbToW() << "m " << std::endl; -// +// // cout<<"25m/s = "<< 25 * conv.getFactorVelocityWToLb() << "dx/dt " << std::endl; // cout<<"0.04 dx/dt = "<< 0.04 * conv.getFactorVelocityLbToW() << "m/s " << std::endl; // -//alternativ +// alternativ // LBMUnitConverter conv(, 100 /*L_World*/, LBMUnitConverter::WATER, 1000/*L_LB*/ ); - class LBMUnitConverter { public: - - enum WORLD_MATERIAL { WATER = 0, SEAWWATER = 1, AIR_20C = 2, OIL = 3 }; - - LBMUnitConverter() = default; - - LBMUnitConverter( const double& refLengthWorld, const double& csWorld, const double& rhoWorld - , const double& refLengthLb , const double& csLb = 1.0/std::sqrt(3.0) , const double& rhoLb = 1.0 ) - { - this->init( refLengthWorld, csWorld, rhoWorld, csWorld, refLengthLb, rhoLb, csLb ); - - } - - LBMUnitConverter( const double& refLengthWorld, WORLD_MATERIAL worldMaterial - , const double& refLengthLb , const double& csLb = 1.0/std::sqrt(3.0) , const double& rhoLb = 1.0 ) - { - double csWorld; - double rhoWorld; - - if ( worldMaterial == WATER ) { csWorld = 1484/*m/s*/; rhoWorld = 1000/*kg/m^3*/; } - else if( worldMaterial == SEAWWATER) { csWorld = 1500/*m/s*/; rhoWorld = 1025/*kg/m^3*/; } - else if( worldMaterial == AIR_20C ) { csWorld = 343/*m/s*/; rhoWorld = 1.290/*kg/m^3*/; } - else if( worldMaterial == OIL ) { csWorld = 1740/*m/s*/; rhoWorld = 830/*kg/m^3*/; } - else throw UbException(UB_EXARGS,"unknown material"); - - this->init( refLengthWorld, csWorld, rhoWorld, csWorld, refLengthLb, rhoLb, csLb ); - - } - - LBMUnitConverter(int /*dummy*/, double uReal, double uLB, double nuReal, double nuLB) - { - factorVelocityLbToW = uReal/uLB; - factorViscosityLbToW = nuReal/nuLB; - factorDensityLbToW = factorViscosityLbToW * factorVelocityLbToW * factorVelocityLbToW; - factorPressureLbToW = factorDensityLbToW; - } - - virtual ~LBMUnitConverter() = default; - - double getRefRhoLb() { return refRhoLb; } - - double getFactorLentghLbToW() { return factorLengthLbToW; } - double getFactorLentghWToLb() { return 1.0/this->getFactorLentghLbToW(); } - - double getFactorTimeLbToW() { return factorTimeLbToW; } - double getFactorTimeWToLb() { return 1.0/this->getFactorTimeLbToW(); } - - double getFactorVelocityLbToW() { return factorLengthLbToW/factorTimeLbToW; } - double getFactorVelocityWToLb() { return 1.0/this->getFactorVelocityLbToW(); } - - double getFactorViscosityLbToW() { return factorLengthLbToW*factorLengthLbToW/factorTimeLbToW; } - double getFactorViscosityWToLb() { return 1.0/this->getFactorViscosityLbToW(); } - - double getFactorDensityLbToW() { return this->factorMassLbToW/std::pow(factorLengthLbToW,3.0); } - double getFactorDensityWToLb() { return 1.0/this->getFactorDensityLbToW(); } - - double getFactorPressureLbToW() { return this->factorMassLbToW/(std::pow(factorTimeLbToW,2.0)*factorLengthLbToW); } - double getFactorPressureWToLb() { return 1.0/this->getFactorPressureLbToW(); } - - double getFactorMassLbToW() { return this->factorMassLbToW; } - double getFactorMassWToLb() { return 1.0/this->getFactorMassLbToW(); } - - double getFactorForceLbToW() { return factorMassLbToW*factorLengthLbToW/(factorTimeLbToW*factorTimeLbToW); } - double getFactorForceWToLb() { return 1.0/this->getFactorForceLbToW(); } - - double getFactorAccLbToW() { return factorLengthLbToW/(factorTimeLbToW*factorTimeLbToW); } - double getFactorAccWToLb() { return 1.0/this->getFactorAccLbToW(); } - - double getFactorTimeLbToW(double deltaX) const { return factorTimeWithoutDx * deltaX; } - ////////////////////////////////////////////////////////////////////////// - double getFactorVelocityLbToW2() { return factorVelocityLbToW; } - double getFactorDensityLbToW2() { return factorDensityLbToW; } - double getFactorPressureLbToW2() { return factorPressureLbToW; } - - - - /*==========================================================*/ - friend inline std::ostream& operator << (std::ostream& os, LBMUnitConverter c) - { - os<<c.toString(); - return os; - } - /*==========================================================*/ - std::string toString() - { - std::ostringstream out; - out<<"LB --> WORLD" << std::endl; - out<<" * lentgh 1[dx ] = " << std::setw(12) << this->getFactorLentghLbToW() << " [m ] " << std::endl; - out<<" * time 1[dt ] = " << std::setw(12) << this->getFactorTimeLbToW() << " [s ] " << std::endl; - out<<" * mass 1[mass] = " << std::setw(12) << this->getFactorMassLbToW() << " [kg ] " << std::endl; - out<<std::endl; - out<<"WORLD --> LB" << std::endl; - out<<" * lentgh 1[m ] = " << std::setw(12) << this->getFactorLentghWToLb() << " [dx ] " << std::endl; - out<<" * time 1[s ] = " << std::setw(12) << this->getFactorTimeWToLb() << " [dt ] " << std::endl; - out<<" * mass 1[kg ] = " << std::setw(12) << this->getFactorMassWToLb() << " [mass] " << std::endl; - out<<std::endl; - out<<"LB --> WORLD (combined units)" << std::endl; - out<<" * velocity 1 [dx/dt ] = " << std::setw(12) << this->getFactorVelocityLbToW() << " [m/s ]" << std::endl; - out<<" * density 1 [mass/dx^3] = " << std::setw(12) << this->getFactorDensityLbToW() << " [kg/m^3 ]" << std::endl; - out<<" * pressure 1 [F_lb/dx^2] = " << std::setw(12) << this->getFactorPressureLbToW() << " [N/m^2 ]" << std::endl; - out<<" * viscosity 1 [dx^2/dt ] = " << std::setw(12) << this->getFactorViscosityLbToW() << " [m^2/s ]" << std::endl; - out<<" * force 1 [F_lb ] = " << std::setw(12) << this->getFactorForceLbToW() << " [N ]" << std::endl; - out<<" * acceleration 1 [dx/dt^2 ] = " << std::setw(12) << this->getFactorAccLbToW() << " [m/s^2 ]" << std::endl; - out<<std::endl; - out<<"WORLD --> LB (combined units)" << std::endl; - out<<" * velocity 1 [m/s ] = " << std::setw(12) << this->getFactorVelocityWToLb() << " [dx/dt ]" << std::endl; - out<<" * density 1 [kg/m^3 ] = " << std::setw(12) << this->getFactorDensityWToLb() << " [mass/dx^3]" << std::endl; - out<<" * pressure 1 [N/m^2 ] = " << std::setw(12) << this->getFactorPressureWToLb() << " [F_lb/dx^2]" << std::endl; - out<<" * viscosity 1 [m^2/s ] = " << std::setw(12) << this->getFactorViscosityWToLb() << " [dx^2/dt ]" << std::endl; - out<<" * force 1 [N ] = " << std::setw(12) << this->getFactorForceWToLb() << " [F_lb ]" << std::endl; - out<<" * acceleration 1 [m/s^2 ] = " << std::setw(12) << this->getFactorAccWToLb() << " [dx/dt^2 ]" << std::endl; - - return out.str(); - } - /*==========================================================*/ - virtual void write(UbFileOutput* out) - { - out->writeDouble(factorLengthLbToW); - out->writeDouble(factorTimeLbToW ); - out->writeDouble(factorMassLbToW ); - } - /*==========================================================*/ - virtual void read(UbFileInput* in) - { - factorLengthLbToW = in->readDouble(); - factorTimeLbToW = in->readDouble(); - factorMassLbToW = in->readDouble(); - } - - - - void init( const double& refLengthWorld, const double& /*csWorld*/, const double& rhoWorld, const double& vWorld, - const double& refLengthLb, const double& rhoLb, const double& vLb ) - { - factorLengthLbToW = refLengthWorld / refLengthLb; - factorTimeLbToW = vLb / vWorld * factorLengthLbToW; - factorMassLbToW = rhoWorld/rhoLb*factorLengthLbToW*factorLengthLbToW*factorLengthLbToW; - factorTimeWithoutDx=vLb/vWorld; - this->refRhoLb = rhoLb; - } - protected: - double factorLengthLbToW{1.0}; - double factorTimeLbToW{1.0}; - double factorMassLbToW{1.0}; - double refRhoLb{1.0}; - double factorTimeWithoutDx{0.0}; - - double factorVelocityLbToW{1.0}; - double factorViscosityLbToW{1.0}; - double factorDensityLbToW{1.0}; - double factorPressureLbToW{1.0}; - + enum WORLD_MATERIAL { WATER = 0, SEAWWATER = 1, AIR_20C = 2, OIL = 3 }; + + LBMUnitConverter() = default; + + LBMUnitConverter(const double &refLengthWorld, const double &csWorld, const double &rhoWorld, + const double &refLengthLb, const double &csLb = 1.0 / std::sqrt(3.0), const double &rhoLb = 1.0) + { + this->init(refLengthWorld, csWorld, rhoWorld, csWorld, refLengthLb, rhoLb, csLb); + } + + LBMUnitConverter(const double &refLengthWorld, WORLD_MATERIAL worldMaterial, const double &refLengthLb, + const double &csLb = 1.0 / std::sqrt(3.0), const double &rhoLb = 1.0) + { + double csWorld; + double rhoWorld; + + if (worldMaterial == WATER) { + csWorld = 1484 /*m/s*/; + rhoWorld = 1000 /*kg/m^3*/; + } else if (worldMaterial == SEAWWATER) { + csWorld = 1500 /*m/s*/; + rhoWorld = 1025 /*kg/m^3*/; + } else if (worldMaterial == AIR_20C) { + csWorld = 343 /*m/s*/; + rhoWorld = 1.290 /*kg/m^3*/; + } else if (worldMaterial == OIL) { + csWorld = 1740 /*m/s*/; + rhoWorld = 830 /*kg/m^3*/; + } else + throw UbException(UB_EXARGS, "unknown material"); + + this->init(refLengthWorld, csWorld, rhoWorld, csWorld, refLengthLb, rhoLb, csLb); + } + + LBMUnitConverter(int /*dummy*/, double uReal, double uLB, double nuReal, double nuLB) + { + factorVelocityLbToW = uReal / uLB; + factorViscosityLbToW = nuReal / nuLB; + factorDensityLbToW = factorViscosityLbToW * factorVelocityLbToW * factorVelocityLbToW; + factorPressureLbToW = factorDensityLbToW; + } + + virtual ~LBMUnitConverter() = default; + + double getRefRhoLb() { return refRhoLb; } + + double getFactorLentghLbToW() { return factorLengthLbToW; } + double getFactorLentghWToLb() { return 1.0 / this->getFactorLentghLbToW(); } + + double getFactorTimeLbToW() { return factorTimeLbToW; } + double getFactorTimeWToLb() { return 1.0 / this->getFactorTimeLbToW(); } + + double getFactorVelocityLbToW() { return factorLengthLbToW / factorTimeLbToW; } + double getFactorVelocityWToLb() { return 1.0 / this->getFactorVelocityLbToW(); } + + double getFactorViscosityLbToW() { return factorLengthLbToW * factorLengthLbToW / factorTimeLbToW; } + double getFactorViscosityWToLb() { return 1.0 / this->getFactorViscosityLbToW(); } + + double getFactorDensityLbToW() { return this->factorMassLbToW / std::pow(factorLengthLbToW, 3.0); } + double getFactorDensityWToLb() { return 1.0 / this->getFactorDensityLbToW(); } + + double getFactorPressureLbToW() + { + return this->factorMassLbToW / (std::pow(factorTimeLbToW, 2.0) * factorLengthLbToW); + } + double getFactorPressureWToLb() { return 1.0 / this->getFactorPressureLbToW(); } + + double getFactorMassLbToW() { return this->factorMassLbToW; } + double getFactorMassWToLb() { return 1.0 / this->getFactorMassLbToW(); } + + double getFactorForceLbToW() { return factorMassLbToW * factorLengthLbToW / (factorTimeLbToW * factorTimeLbToW); } + double getFactorForceWToLb() { return 1.0 / this->getFactorForceLbToW(); } + + double getFactorAccLbToW() { return factorLengthLbToW / (factorTimeLbToW * factorTimeLbToW); } + double getFactorAccWToLb() { return 1.0 / this->getFactorAccLbToW(); } + + double getFactorTimeLbToW(double deltaX) const { return factorTimeWithoutDx * deltaX; } + ////////////////////////////////////////////////////////////////////////// + double getFactorVelocityLbToW2() { return factorVelocityLbToW; } + double getFactorDensityLbToW2() { return factorDensityLbToW; } + double getFactorPressureLbToW2() { return factorPressureLbToW; } + + /*==========================================================*/ + friend inline std::ostream &operator<<(std::ostream &os, LBMUnitConverter c) + { + os << c.toString(); + return os; + } + /*==========================================================*/ + std::string toString() + { + std::ostringstream out; + out << "LB --> WORLD" << std::endl; + out << " * lentgh 1[dx ] = " << std::setw(12) << this->getFactorLentghLbToW() << " [m ] " << std::endl; + out << " * time 1[dt ] = " << std::setw(12) << this->getFactorTimeLbToW() << " [s ] " << std::endl; + out << " * mass 1[mass] = " << std::setw(12) << this->getFactorMassLbToW() << " [kg ] " << std::endl; + out << std::endl; + out << "WORLD --> LB" << std::endl; + out << " * lentgh 1[m ] = " << std::setw(12) << this->getFactorLentghWToLb() << " [dx ] " << std::endl; + out << " * time 1[s ] = " << std::setw(12) << this->getFactorTimeWToLb() << " [dt ] " << std::endl; + out << " * mass 1[kg ] = " << std::setw(12) << this->getFactorMassWToLb() << " [mass] " << std::endl; + out << std::endl; + out << "LB --> WORLD (combined units)" << std::endl; + out << " * velocity 1 [dx/dt ] = " << std::setw(12) << this->getFactorVelocityLbToW() << " [m/s ]" + << std::endl; + out << " * density 1 [mass/dx^3] = " << std::setw(12) << this->getFactorDensityLbToW() << " [kg/m^3 ]" + << std::endl; + out << " * pressure 1 [F_lb/dx^2] = " << std::setw(12) << this->getFactorPressureLbToW() << " [N/m^2 ]" + << std::endl; + out << " * viscosity 1 [dx^2/dt ] = " << std::setw(12) << this->getFactorViscosityLbToW() << " [m^2/s ]" + << std::endl; + out << " * force 1 [F_lb ] = " << std::setw(12) << this->getFactorForceLbToW() << " [N ]" + << std::endl; + out << " * acceleration 1 [dx/dt^2 ] = " << std::setw(12) << this->getFactorAccLbToW() << " [m/s^2 ]" + << std::endl; + out << std::endl; + out << "WORLD --> LB (combined units)" << std::endl; + out << " * velocity 1 [m/s ] = " << std::setw(12) << this->getFactorVelocityWToLb() << " [dx/dt ]" + << std::endl; + out << " * density 1 [kg/m^3 ] = " << std::setw(12) << this->getFactorDensityWToLb() << " [mass/dx^3]" + << std::endl; + out << " * pressure 1 [N/m^2 ] = " << std::setw(12) << this->getFactorPressureWToLb() << " [F_lb/dx^2]" + << std::endl; + out << " * viscosity 1 [m^2/s ] = " << std::setw(12) << this->getFactorViscosityWToLb() << " [dx^2/dt ]" + << std::endl; + out << " * force 1 [N ] = " << std::setw(12) << this->getFactorForceWToLb() << " [F_lb ]" + << std::endl; + out << " * acceleration 1 [m/s^2 ] = " << std::setw(12) << this->getFactorAccWToLb() << " [dx/dt^2 ]" + << std::endl; + + return out.str(); + } + /*==========================================================*/ + virtual void write(UbFileOutput *out) + { + out->writeDouble(factorLengthLbToW); + out->writeDouble(factorTimeLbToW); + out->writeDouble(factorMassLbToW); + } + /*==========================================================*/ + virtual void read(UbFileInput *in) + { + factorLengthLbToW = in->readDouble(); + factorTimeLbToW = in->readDouble(); + factorMassLbToW = in->readDouble(); + } + + void init(const double &refLengthWorld, const double & /*csWorld*/, const double &rhoWorld, const double &vWorld, + const double &refLengthLb, const double &rhoLb, const double &vLb) + { + factorLengthLbToW = refLengthWorld / refLengthLb; + factorTimeLbToW = vLb / vWorld * factorLengthLbToW; + factorMassLbToW = rhoWorld / rhoLb * factorLengthLbToW * factorLengthLbToW * factorLengthLbToW; + factorTimeWithoutDx = vLb / vWorld; + this->refRhoLb = rhoLb; + } + +protected: + double factorLengthLbToW{ 1.0 }; + double factorTimeLbToW{ 1.0 }; + double factorMassLbToW{ 1.0 }; + double refRhoLb{ 1.0 }; + double factorTimeWithoutDx{ 0.0 }; + + double factorVelocityLbToW{ 1.0 }; + double factorViscosityLbToW{ 1.0 }; + double factorDensityLbToW{ 1.0 }; + double factorPressureLbToW{ 1.0 }; }; -#endif //LBMUNITCONVERTER_H +#endif // LBMUNITCONVERTER_H diff --git a/src/cpu/VirtualFluidsCore/LBM/VoidLBMKernel.cpp b/src/cpu/VirtualFluidsCore/LBM/VoidLBMKernel.cpp index 8e4a73a7bd7330947b99d124fb031bcebc314c3b..d9ce56aa8c4ca5f7a0e2318a9d48120b66f06705 100644 --- a/src/cpu/VirtualFluidsCore/LBM/VoidLBMKernel.cpp +++ b/src/cpu/VirtualFluidsCore/LBM/VoidLBMKernel.cpp @@ -1,42 +1,34 @@ #include "VoidLBMKernel.h" -#include "VoidData3D.h" #include "BCProcessor.h" #include "DataSet3D.h" +#include "VoidData3D.h" -VoidLBMKernel::VoidLBMKernel() -= default; +VoidLBMKernel::VoidLBMKernel() = default; ////////////////////////////////////////////////////////////////////////// -VoidLBMKernel::~VoidLBMKernel() -= default; +VoidLBMKernel::~VoidLBMKernel() = default; ////////////////////////////////////////////////////////////////////////// void VoidLBMKernel::initDataSet() { - SPtr<DistributionArray3D> d(new VoidData3D(nx[0]+2, nx[1]+2, nx[2]+2, -999.9)); - dataSet->setFdistributions(d); + SPtr<DistributionArray3D> d(new VoidData3D(nx[0] + 2, nx[1] + 2, nx[2] + 2, -999.9)); + dataSet->setFdistributions(d); } ////////////////////////////////////////////////////////////////////////// SPtr<LBMKernel> VoidLBMKernel::clone() { - SPtr<LBMKernel> kernel(new VoidLBMKernel()); - kernel->setNX(nx); - dynamicPointerCast<VoidLBMKernel>(kernel)->initDataSet(); - kernel->setCollisionFactor(this->collFactor); - kernel->setBCProcessor(bcProcessor->clone(kernel)); - kernel->setWithForcing(withForcing); - kernel->setForcingX1(muForcingX1); - kernel->setForcingX2(muForcingX2); - kernel->setForcingX3(muForcingX3); - kernel->setIndex(ix1, ix2, ix3); - kernel->setDeltaT(deltaT); - return kernel; + SPtr<LBMKernel> kernel(new VoidLBMKernel()); + kernel->setNX(nx); + dynamicPointerCast<VoidLBMKernel>(kernel)->initDataSet(); + kernel->setCollisionFactor(this->collFactor); + kernel->setBCProcessor(bcProcessor->clone(kernel)); + kernel->setWithForcing(withForcing); + kernel->setForcingX1(muForcingX1); + kernel->setForcingX2(muForcingX2); + kernel->setForcingX3(muForcingX3); + kernel->setIndex(ix1, ix2, ix3); + kernel->setDeltaT(deltaT); + return kernel; } ////////////////////////////////////////////////////////////////////////// -void VoidLBMKernel::calculate(int step) -{ - -} +void VoidLBMKernel::calculate(int step) {} ////////////////////////////////////////////////////////////////////////// -double VoidLBMKernel::getCalculationTime() -{ - return 0.0; -} +double VoidLBMKernel::getCalculationTime() { return 0.0; } diff --git a/src/cpu/VirtualFluidsCore/LBM/VoidLBMKernel.h b/src/cpu/VirtualFluidsCore/LBM/VoidLBMKernel.h index 4ae754ccae75e5f12e0e09baa5e6ec0076fb3510..b9b4b5d2d2c53f91871c3770a3acda0401842efe 100644 --- a/src/cpu/VirtualFluidsCore/LBM/VoidLBMKernel.h +++ b/src/cpu/VirtualFluidsCore/LBM/VoidLBMKernel.h @@ -6,13 +6,13 @@ class VoidLBMKernel : public LBMKernel { public: - VoidLBMKernel(); - ~VoidLBMKernel() override; - SPtr<LBMKernel> clone() override; - void calculate(int step) override; - double getCalculationTime() override; - void initDataSet(); -protected: + VoidLBMKernel(); + ~VoidLBMKernel() override; + SPtr<LBMKernel> clone() override; + void calculate(int step) override; + double getCalculationTime() override; + void initDataSet(); +protected: }; #endif // VoidLBMKernel_h__ diff --git a/src/cpu/VirtualFluidsCore/Parallel/BlocksDistributor.cpp b/src/cpu/VirtualFluidsCore/Parallel/BlocksDistributor.cpp index aa010ef631bc11feb76373b704f4967da656d95d..09f0af7ac74b79d18220de90dab10be78f580a88 100644 --- a/src/cpu/VirtualFluidsCore/Parallel/BlocksDistributor.cpp +++ b/src/cpu/VirtualFluidsCore/Parallel/BlocksDistributor.cpp @@ -1,7 +1,3 @@ #include "BlocksDistributor.h" -BlocksDistributor::BlocksDistributor(SPtr<Grid3D> grid, SPtr<Communicator> comm) : grid(grid), comm(comm) -{ - -} - +BlocksDistributor::BlocksDistributor(SPtr<Grid3D> grid, SPtr<Communicator> comm) : grid(grid), comm(comm) {} diff --git a/src/cpu/VirtualFluidsCore/Parallel/BlocksDistributor.h b/src/cpu/VirtualFluidsCore/Parallel/BlocksDistributor.h index 08ab5a8a8de0680d6c4f099c6356e47df2ce7e88..7af79dc293676ae84fe2943e3316ebb4d4ddd866 100644 --- a/src/cpu/VirtualFluidsCore/Parallel/BlocksDistributor.h +++ b/src/cpu/VirtualFluidsCore/Parallel/BlocksDistributor.h @@ -9,15 +9,13 @@ class BlocksDistributor { public: - BlocksDistributor(SPtr<Grid3D> grid, SPtr<Communicator> comm); - ~BlocksDistributor(); + BlocksDistributor(SPtr<Grid3D> grid, SPtr<Communicator> comm); + ~BlocksDistributor(); protected: private: - SPtr<Grid3D> grid; - SPtr<Communicator> comm; + SPtr<Grid3D> grid; + SPtr<Communicator> comm; }; #endif - - diff --git a/src/cpu/VirtualFluidsCore/Parallel/Communicator.cpp b/src/cpu/VirtualFluidsCore/Parallel/Communicator.cpp index 2b6938267bda842f43e63fe521261803ff3273f6..b7ea54267edb7126573e512a7593e3f3f4312bd6 100644 --- a/src/cpu/VirtualFluidsCore/Parallel/Communicator.cpp +++ b/src/cpu/VirtualFluidsCore/Parallel/Communicator.cpp @@ -1,28 +1,28 @@ //======================================================================================= -// ____ ____ __ ______ __________ __ __ __ __ -// \ \ | | | | | _ \ |___ ___| | | | | / \ | | -// \ \ | | | | | |_) | | | | | | | / \ | | -// \ \ | | | | | _ / | | | | | | / /\ \ | | -// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ -// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| -// \ \ | | ________________________________________________________________ -// \ \ | | | ______________________________________________________________| -// \ \| | | | __ __ __ __ ______ _______ -// \ | | |_____ | | | | | | | | | _ \ / _____) -// \ | | _____| | | | | | | | | | | \ \ \_______ +// ____ ____ __ ______ __________ __ __ __ __ +// \ \ | | | | | _ \ |___ ___| | | | | / \ | | +// \ \ | | | | | |_) | | | | | | | / \ | | +// \ \ | | | | | _ / | | | | | | / /\ \ | | +// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ +// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| +// \ \ | | ________________________________________________________________ +// \ \ | | | ______________________________________________________________| +// \ \| | | | __ __ __ __ ______ _______ +// \ | | |_____ | | | | | | | | | _ \ / _____) +// \ | | _____| | | | | | | | | | | \ \ \_______ // \ | | | | |_____ | \_/ | | | | |_/ / _____ | -// \ _____| |__| |________| \_______/ |__| |______/ (_______/ +// \ _____| |__| |________| \_______/ |__| |______/ (_______/ // -// This file is part of VirtualFluids. VirtualFluids is free software: you can +// This file is part of VirtualFluids. VirtualFluids is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of +// License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. -// -// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// +// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License along // with VirtualFluids (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>. // @@ -38,8 +38,8 @@ SPtr<Communicator> Communicator::instance = SPtr<Communicator>(); ////////////////////////////////////////////////////////////////////////// SPtr<Communicator> Communicator::getInstance() { - if( !instance ) - UB_THROW(UbException(UB_EXARGS,"Communicator isn't initialized correctly! You can not create a new instance of abstract Communicator class!")); - return instance; + if (!instance) + UB_THROW(UbException(UB_EXARGS, "Communicator isn't initialized correctly! You can not create a new instance " + "of abstract Communicator class!")); + return instance; } - diff --git a/src/cpu/VirtualFluidsCore/Parallel/Communicator.h b/src/cpu/VirtualFluidsCore/Parallel/Communicator.h index 1ab893e56196a37c20622b8cf985babee02ca8d0..28ba705480a6291aac3d31b3341f93f73a35f829 100644 --- a/src/cpu/VirtualFluidsCore/Parallel/Communicator.h +++ b/src/cpu/VirtualFluidsCore/Parallel/Communicator.h @@ -1,28 +1,28 @@ //======================================================================================= -// ____ ____ __ ______ __________ __ __ __ __ -// \ \ | | | | | _ \ |___ ___| | | | | / \ | | -// \ \ | | | | | |_) | | | | | | | / \ | | -// \ \ | | | | | _ / | | | | | | / /\ \ | | -// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ -// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| -// \ \ | | ________________________________________________________________ -// \ \ | | | ______________________________________________________________| -// \ \| | | | __ __ __ __ ______ _______ -// \ | | |_____ | | | | | | | | | _ \ / _____) -// \ | | _____| | | | | | | | | | | \ \ \_______ +// ____ ____ __ ______ __________ __ __ __ __ +// \ \ | | | | | _ \ |___ ___| | | | | / \ | | +// \ \ | | | | | |_) | | | | | | | / \ | | +// \ \ | | | | | _ / | | | | | | / /\ \ | | +// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ +// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| +// \ \ | | ________________________________________________________________ +// \ \ | | | ______________________________________________________________| +// \ \| | | | __ __ __ __ ______ _______ +// \ | | |_____ | | | | | | | | | _ \ / _____) +// \ | | _____| | | | | | | | | | | \ \ \_______ // \ | | | | |_____ | \_/ | | | | |_/ / _____ | -// \ _____| |__| |________| \_______/ |__| |______/ (_______/ +// \ _____| |__| |________| \_______/ |__| |______/ (_______/ // -// This file is part of VirtualFluids. VirtualFluids is free software: you can +// This file is part of VirtualFluids. VirtualFluids is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of +// License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. -// -// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// +// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License along // with VirtualFluids (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>. // @@ -34,8 +34,8 @@ #ifndef COMMUNICATOR_H #define COMMUNICATOR_H -#include <vector> #include <string> +#include <vector> #include <PointerDefinitions.h> @@ -43,50 +43,50 @@ class Communicator { public: - virtual ~Communicator()= default; - static SPtr<Communicator> getInstance(); - virtual int getBundleID() = 0; - virtual int getNumberOfBundles() = 0; - virtual int getProcessID() = 0; - virtual int getProcessID(int bundle, int rank) = 0; - virtual int getNumberOfProcesses() = 0; - virtual bool isRoot() = 0; - virtual void* getNativeCommunicator() = 0; + virtual ~Communicator() = default; + static SPtr<Communicator> getInstance(); + virtual int getBundleID() = 0; + virtual int getNumberOfBundles() = 0; + virtual int getProcessID() = 0; + virtual int getProcessID(int bundle, int rank) = 0; + virtual int getNumberOfProcesses() = 0; + virtual bool isRoot() = 0; + virtual void *getNativeCommunicator() = 0; - virtual void sendSerializedObject(std::stringstream& ss, int target) = 0; - virtual void receiveSerializedObject(std::stringstream& ss, int source) = 0; + virtual void sendSerializedObject(std::stringstream &ss, int target) = 0; + virtual void receiveSerializedObject(std::stringstream &ss, int source) = 0; - virtual int getRoot() = 0; - virtual int getBundleRoot() = 0; - virtual int getProcessRoot() = 0; - virtual int getNumberOfProcessesInBundle(int bundle) = 0; - virtual void barrier() = 0; - virtual void abort(int errorcode) = 0; + virtual int getRoot() = 0; + virtual int getBundleRoot() = 0; + virtual int getProcessRoot() = 0; + virtual int getNumberOfProcessesInBundle(int bundle) = 0; + virtual void barrier() = 0; + virtual void abort(int errorcode) = 0; - virtual std::vector<std::string> gather(const std::string& str) = 0; - virtual std::vector<int> gather(std::vector<int>& values) = 0; - virtual std::vector<float> gather(std::vector<float>& values) = 0; - virtual std::vector<double> gather(std::vector<double>& values) = 0; - virtual std::vector<unsigned long long> gather(std::vector<unsigned long long>& values) = 0; + virtual std::vector<std::string> gather(const std::string &str) = 0; + virtual std::vector<int> gather(std::vector<int> &values) = 0; + virtual std::vector<float> gather(std::vector<float> &values) = 0; + virtual std::vector<double> gather(std::vector<double> &values) = 0; + virtual std::vector<unsigned long long> gather(std::vector<unsigned long long> &values) = 0; + + virtual void allGather(std::vector<int> &svalues, std::vector<int> &rvalues) = 0; + virtual void allGather(std::vector<float> &svalues, std::vector<float> &rvalues) = 0; + virtual void allGather(std::vector<double> &svalues, std::vector<double> &rvalues) = 0; + virtual void allGather(std::vector<unsigned long long> &svalues, std::vector<unsigned long long> &rvalues) = 0; + + virtual void broadcast(int &value) = 0; + virtual void broadcast(float &value) = 0; + virtual void broadcast(double &value) = 0; + virtual void broadcast(long int &value) = 0; + virtual void broadcast(std::vector<int> &values) = 0; + virtual void broadcast(std::vector<float> &values) = 0; + virtual void broadcast(std::vector<double> &values) = 0; + virtual void broadcast(std::vector<long int> &values) = 0; - virtual void allGather(std::vector<int>& svalues, std::vector<int>& rvalues) = 0; - virtual void allGather(std::vector<float>& svalues, std::vector<float>& rvalues) = 0; - virtual void allGather(std::vector<double>& svalues, std::vector<double>& rvalues) = 0; - virtual void allGather(std::vector<unsigned long long>& svalues, std::vector<unsigned long long>& rvalues) = 0; - - virtual void broadcast(int& value) = 0; - virtual void broadcast(float& value) = 0; - virtual void broadcast(double& value) = 0; - virtual void broadcast(long int& value) = 0; - virtual void broadcast(std::vector<int>& values) = 0; - virtual void broadcast(std::vector<float>& values) = 0; - virtual void broadcast(std::vector<double>& values) = 0; - virtual void broadcast(std::vector<long int>& values) = 0; protected: - Communicator()= default; - Communicator( const Communicator& )= default; - static SPtr<Communicator> instance; + Communicator() = default; + Communicator(const Communicator &) = default; + static SPtr<Communicator> instance; }; #endif - diff --git a/src/cpu/VirtualFluidsCore/Parallel/MPICommunicator.cpp b/src/cpu/VirtualFluidsCore/Parallel/MPICommunicator.cpp index 0c785fc3da54cae00043ab2a830a9fc42860ce14..4e5b5cb79ac01f730d5f1b92a8238605992d3825 100644 --- a/src/cpu/VirtualFluidsCore/Parallel/MPICommunicator.cpp +++ b/src/cpu/VirtualFluidsCore/Parallel/MPICommunicator.cpp @@ -8,238 +8,160 @@ using namespace std; ////////////////////////////////////////////////////////////////////////// MPICommunicator::MPICommunicator() { - //proof if MPI is initialized - int mpiInitialized = (int)false; - MPI_Initialized(&mpiInitialized); - if (!mpiInitialized) - { - MPI_Init(NULL, NULL); - //MPI_Init_thread(NULL, NULL, MPI_THREAD_FUNNELED, NULL); - } - MPI_Comm_rank(MPI_COMM_WORLD, &PID); - MPI_Comm_size(MPI_COMM_WORLD, &numprocs); - //numprocs = 1000; - comm = MPI_COMM_WORLD; - root = 0; + // proof if MPI is initialized + int mpiInitialized = (int)false; + MPI_Initialized(&mpiInitialized); + if (!mpiInitialized) { + MPI_Init(NULL, NULL); + // MPI_Init_thread(NULL, NULL, MPI_THREAD_FUNNELED, NULL); + } + MPI_Comm_rank(MPI_COMM_WORLD, &PID); + MPI_Comm_size(MPI_COMM_WORLD, &numprocs); + // numprocs = 1000; + comm = MPI_COMM_WORLD; + root = 0; } ////////////////////////////////////////////////////////////////////////// MPICommunicator::~MPICommunicator() { - //proof if MPI is finalized - int _mpiFinalized = (int)false; - MPI_Finalized(&_mpiFinalized); - if (!_mpiFinalized) - { - MPI_Finalize(); - //UBLOG(logINFO, "MPI_Finalize()"); - } - } + // proof if MPI is finalized + int _mpiFinalized = (int)false; + MPI_Finalized(&_mpiFinalized); + if (!_mpiFinalized) { + MPI_Finalize(); + // UBLOG(logINFO, "MPI_Finalize()"); + } +} ////////////////////////////////////////////////////////////////////////// SPtr<Communicator> MPICommunicator::getInstance() { - if( !Communicator::instance ) - Communicator::instance = SPtr<Communicator>(new MPICommunicator()); - return Communicator::instance; + if (!Communicator::instance) + Communicator::instance = SPtr<Communicator>(new MPICommunicator()); + return Communicator::instance; } ////////////////////////////////////////////////////////////////////////// -void MPICommunicator::abort(int errorcode) -{ - MPI_Abort(comm, errorcode); -} +void MPICommunicator::abort(int errorcode) { MPI_Abort(comm, errorcode); } //////////////////////////////////////////////////////////////////////////// -vector<string> MPICommunicator::gather(const string& str) -{ - vector<string> parts; - vector<string> strings; - int scount; - vector<char> rbuf(1); - vector<int> rcounts(1); - MPI_Status status; +vector<string> MPICommunicator::gather(const string &str) +{ + vector<string> parts; + vector<string> strings; + int scount; + vector<char> rbuf(1); + vector<int> rcounts(1); + MPI_Status status; - if (PID == root) - { - rcounts.resize(numprocs - 1); - strings.push_back(str); + if (PID == root) { + rcounts.resize(numprocs - 1); + strings.push_back(str); - for (int i = 1; i < numprocs; i++) - { - MPI_Recv(&rcounts[i-1], 1, MPI_INT, i, 0, comm, &status); - } - for (int i = 1; i < numprocs; i++) - { - rbuf.resize(rcounts[i-1]); - MPI_Recv(&rbuf[0], rcounts[i-1], MPI_CHAR, i, 0, comm, &status); - string s(&rbuf[0], rcounts[i-1]); - if (s != "") strings.push_back(s); - } - } - else - { - scount = (int)str.length(); - MPI_Send(&scount, 1, MPI_INT, root, 0, comm); - MPI_Send((char *)str.c_str(), scount, MPI_CHAR, root, 0, comm); - } - return strings; + for (int i = 1; i < numprocs; i++) { + MPI_Recv(&rcounts[i - 1], 1, MPI_INT, i, 0, comm, &status); + } + for (int i = 1; i < numprocs; i++) { + rbuf.resize(rcounts[i - 1]); + MPI_Recv(&rbuf[0], rcounts[i - 1], MPI_CHAR, i, 0, comm, &status); + string s(&rbuf[0], rcounts[i - 1]); + if (s != "") + strings.push_back(s); + } + } else { + scount = (int)str.length(); + MPI_Send(&scount, 1, MPI_INT, root, 0, comm); + MPI_Send((char *)str.c_str(), scount, MPI_CHAR, root, 0, comm); + } + return strings; } ////////////////////////////////////////////////////////////////////////// -vector<int> MPICommunicator::gather(vector<int>& values) -{ - return gather<int>(values); -} +vector<int> MPICommunicator::gather(vector<int> &values) { return gather<int>(values); } ////////////////////////////////////////////////////////////////////////// -vector<float> MPICommunicator::gather(vector<float>& values) -{ - return gather<float>(values); -} +vector<float> MPICommunicator::gather(vector<float> &values) { return gather<float>(values); } ////////////////////////////////////////////////////////////////////////// -vector<double> MPICommunicator::gather(vector<double>& values) -{ - return gather<double>(values); -} +vector<double> MPICommunicator::gather(vector<double> &values) { return gather<double>(values); } ////////////////////////////////////////////////////////////////////////// -std::vector<unsigned long long> MPICommunicator::gather(std::vector<unsigned long long>& values) +std::vector<unsigned long long> MPICommunicator::gather(std::vector<unsigned long long> &values) { - return gather<unsigned long long>(values); + return gather<unsigned long long>(values); } ////////////////////////////////////////////////////////////////////////// -int MPICommunicator::getProcessID() -{ - return PID; -} +int MPICommunicator::getProcessID() { return PID; } ////////////////////////////////////////////////////////////////////////// -int MPICommunicator::getProcessID(int /*bundle*/, int /*rank*/) -{ - return PID; -} +int MPICommunicator::getProcessID(int /*bundle*/, int /*rank*/) { return PID; } ////////////////////////////////////////////////////////////////////////// -int MPICommunicator::getNumberOfProcesses() -{ - return numprocs; -} +int MPICommunicator::getNumberOfProcesses() { return numprocs; } ////////////////////////////////////////////////////////////////////////// -void* MPICommunicator::getNativeCommunicator() -{ - return &comm; -} +void *MPICommunicator::getNativeCommunicator() { return &comm; } ////////////////////////////////////////////////////////////////////////// -int MPICommunicator::getBundleID() -{ - return 0; -} +int MPICommunicator::getBundleID() { return 0; } ////////////////////////////////////////////////////////////////////////// -int MPICommunicator::getNumberOfBundles() -{ - return 1; -} +int MPICommunicator::getNumberOfBundles() { return 1; } ////////////////////////////////////////////////////////////////////////// -int MPICommunicator::getRoot() -{ - return root; -} +int MPICommunicator::getRoot() { return root; } ////////////////////////////////////////////////////////////////////////// -int MPICommunicator::getBundleRoot() -{ - return 0; -} +int MPICommunicator::getBundleRoot() { return 0; } ////////////////////////////////////////////////////////////////////////// -int MPICommunicator::getProcessRoot() -{ - return 0; -} +int MPICommunicator::getProcessRoot() { return 0; } ////////////////////////////////////////////////////////////////////////// -int MPICommunicator::getNumberOfProcessesInBundle(int /*bundle*/) -{ - return numprocs; -} +int MPICommunicator::getNumberOfProcessesInBundle(int /*bundle*/) { return numprocs; } ////////////////////////////////////////////////////////////////////////// -bool MPICommunicator::isRoot() -{ - return PID == root; -} +bool MPICommunicator::isRoot() { return PID == root; } ////////////////////////////////////////////////////////////////////////// -void MPICommunicator::sendSerializedObject( std::stringstream& ss, int target) +void MPICommunicator::sendSerializedObject(std::stringstream &ss, int target) { - string str = ss.str(); - int scount = static_cast<int> (str.length()); - MPI_Send(&scount,1,MPI_INT,target,0,comm); - MPI_Send((char *)str.c_str(),scount,MPI_CHAR,target,0,comm); + string str = ss.str(); + int scount = static_cast<int>(str.length()); + MPI_Send(&scount, 1, MPI_INT, target, 0, comm); + MPI_Send((char *)str.c_str(), scount, MPI_CHAR, target, 0, comm); } ////////////////////////////////////////////////////////////////////////// -void MPICommunicator::receiveSerializedObject( std::stringstream& ss, int source ) +void MPICommunicator::receiveSerializedObject(std::stringstream &ss, int source) { - vector<char> rbuf; - int rcount; - MPI_Status status; - MPI_Recv(&rcount,1,MPI_INT,source,0,comm,&status); - rbuf.resize(rcount); - MPI_Recv(&rbuf[0],rcount,MPI_CHAR,source,0,comm,&status); - ss.rdbuf()->pubsetbuf(&rbuf[0],rcount); - string str (&rbuf[0]); - ss.str(str); + vector<char> rbuf; + int rcount; + MPI_Status status; + MPI_Recv(&rcount, 1, MPI_INT, source, 0, comm, &status); + rbuf.resize(rcount); + MPI_Recv(&rbuf[0], rcount, MPI_CHAR, source, 0, comm, &status); + ss.rdbuf()->pubsetbuf(&rbuf[0], rcount); + string str(&rbuf[0]); + ss.str(str); } ////////////////////////////////////////////////////////////////////////// -void MPICommunicator::barrier() -{ - MPI_Barrier(comm); -} +void MPICommunicator::barrier() { MPI_Barrier(comm); } ////////////////////////////////////////////////////////////////////////// -void MPICommunicator::allGather(std::vector<int>& svalues, std::vector<int>& rvalues) +void MPICommunicator::allGather(std::vector<int> &svalues, std::vector<int> &rvalues) { - allGather<int>(svalues, rvalues); + allGather<int>(svalues, rvalues); } ////////////////////////////////////////////////////////////////////////// -void MPICommunicator::allGather(std::vector<float>& svalues, std::vector<float>& rvalues) +void MPICommunicator::allGather(std::vector<float> &svalues, std::vector<float> &rvalues) { - allGather<float>(svalues, rvalues); + allGather<float>(svalues, rvalues); } ////////////////////////////////////////////////////////////////////////// -void MPICommunicator::allGather(std::vector<double>& svalues, std::vector<double>& rvalues) +void MPICommunicator::allGather(std::vector<double> &svalues, std::vector<double> &rvalues) { - allGather<double>(svalues, rvalues); + allGather<double>(svalues, rvalues); } ////////////////////////////////////////////////////////////////////////// -void MPICommunicator::allGather(std::vector<unsigned long long>& svalues, std::vector<unsigned long long>& rvalues) +void MPICommunicator::allGather(std::vector<unsigned long long> &svalues, std::vector<unsigned long long> &rvalues) { - allGather<unsigned long long>(svalues, rvalues); + allGather<unsigned long long>(svalues, rvalues); } ////////////////////////////////////////////////////////////////////////// -void MPICommunicator::broadcast(std::vector<int>& values) -{ - broadcast<int>(values); -} +void MPICommunicator::broadcast(std::vector<int> &values) { broadcast<int>(values); } ////////////////////////////////////////////////////////////////////////// -void MPICommunicator::broadcast(std::vector<float>& values) -{ - broadcast<float>(values); -} +void MPICommunicator::broadcast(std::vector<float> &values) { broadcast<float>(values); } ////////////////////////////////////////////////////////////////////////// -void MPICommunicator::broadcast(std::vector<double>& values) -{ - broadcast<double>(values); -} +void MPICommunicator::broadcast(std::vector<double> &values) { broadcast<double>(values); } ////////////////////////////////////////////////////////////////////////// -void MPICommunicator::broadcast(std::vector<long int>& values) -{ - broadcast<long int>(values); -} +void MPICommunicator::broadcast(std::vector<long int> &values) { broadcast<long int>(values); } ////////////////////////////////////////////////////////////////////////// -void MPICommunicator::broadcast(int& value) -{ - broadcast<int>(value); -} +void MPICommunicator::broadcast(int &value) { broadcast<int>(value); } ////////////////////////////////////////////////////////////////////////// -void MPICommunicator::broadcast(float& value) -{ - broadcast<float>(value); -} +void MPICommunicator::broadcast(float &value) { broadcast<float>(value); } ////////////////////////////////////////////////////////////////////////// -void MPICommunicator::broadcast(double& value) -{ - broadcast<double>(value); -} +void MPICommunicator::broadcast(double &value) { broadcast<double>(value); } ////////////////////////////////////////////////////////////////////////// -void MPICommunicator::broadcast(long int& value) -{ - broadcast<long int>(value); -} +void MPICommunicator::broadcast(long int &value) { broadcast<long int>(value); } #endif diff --git a/src/cpu/VirtualFluidsCore/Parallel/MPICommunicator.h b/src/cpu/VirtualFluidsCore/Parallel/MPICommunicator.h index 20b6b85b377cd43c5c02373ed39ed2196b96546d..26f814476ad6ad57b0801849535cb5275e9bcadb 100644 --- a/src/cpu/VirtualFluidsCore/Parallel/MPICommunicator.h +++ b/src/cpu/VirtualFluidsCore/Parallel/MPICommunicator.h @@ -3,14 +3,13 @@ #ifndef MPICOMMUNICATOR_H #define MPICOMMUNICATOR_H -#include <mpi.h> -#include <vector> -#include <string> +#include "Communicator.h" #include <PointerDefinitions.h> #include <basics/utilities/UbException.h> #include <basics/utilities/UbLogger.h> -#include "Communicator.h" - +#include <mpi.h> +#include <string> +#include <vector> //! \brief A class uses MPI library to communication. //! \details Support MPI communication. Implements singleton pattern. @@ -19,169 +18,186 @@ class MPICommunicator : public Communicator { private: - MPICommunicator(); - MPICommunicator( const MPICommunicator& ){} + MPICommunicator(); + MPICommunicator(const MPICommunicator &) {} + public: - ~MPICommunicator() override; - static SPtr<Communicator> getInstance(); - int getBundleID() override; - int getNumberOfBundles() override; - int getProcessID() override; - int getProcessID(int bundle, int rank) override; - int getNumberOfProcesses() override; - void* getNativeCommunicator() override; - int getRoot() override; - int getBundleRoot() override; - int getProcessRoot() override; - int getNumberOfProcessesInBundle(int bundle) override; - bool isRoot() override; - void abort(int errorcode) override; - - void sendSerializedObject(std::stringstream& ss, int target) override; - void receiveSerializedObject(std::stringstream& ss, int source) override; - - void barrier() override; - - std::vector<std::string> gather(const std::string& str) override; - std::vector<int> gather(std::vector<int>& values) override; - std::vector<float> gather(std::vector<float>& values) override; - std::vector<double> gather(std::vector<double>& values) override; - std::vector<unsigned long long> gather(std::vector<unsigned long long>& values) override; - - void allGather(std::vector<int>& svalues, std::vector<int>& rvalues) override; - void allGather(std::vector<float>& svalues, std::vector<float>& rvalues) override; - void allGather(std::vector<double>& svalues, std::vector<double>& rvalues) override; - void allGather(std::vector<unsigned long long>& svalues, std::vector<unsigned long long>& rvalues) override; - - void broadcast(int& value) override; - void broadcast(float& value) override; - void broadcast(double& value) override; - void broadcast(long int& value) override; - void broadcast(std::vector<int>& values) override; - void broadcast(std::vector<float>& values) override; - void broadcast(std::vector<double>& values) override; - void broadcast(std::vector<long int>& values) override; - - template <class T> - std::vector<T> gather(std::vector<T>& values); - - template <class T> - void allGather(std::vector<T>& svalues, std::vector<T>& rvalues); - - template <class T> - void broadcast(std::vector<T>& values); - - template <class T> - void broadcast(T& value); + ~MPICommunicator() override; + static SPtr<Communicator> getInstance(); + int getBundleID() override; + int getNumberOfBundles() override; + int getProcessID() override; + int getProcessID(int bundle, int rank) override; + int getNumberOfProcesses() override; + void *getNativeCommunicator() override; + int getRoot() override; + int getBundleRoot() override; + int getProcessRoot() override; + int getNumberOfProcessesInBundle(int bundle) override; + bool isRoot() override; + void abort(int errorcode) override; + + void sendSerializedObject(std::stringstream &ss, int target) override; + void receiveSerializedObject(std::stringstream &ss, int source) override; + + void barrier() override; + + std::vector<std::string> gather(const std::string &str) override; + std::vector<int> gather(std::vector<int> &values) override; + std::vector<float> gather(std::vector<float> &values) override; + std::vector<double> gather(std::vector<double> &values) override; + std::vector<unsigned long long> gather(std::vector<unsigned long long> &values) override; + + void allGather(std::vector<int> &svalues, std::vector<int> &rvalues) override; + void allGather(std::vector<float> &svalues, std::vector<float> &rvalues) override; + void allGather(std::vector<double> &svalues, std::vector<double> &rvalues) override; + void allGather(std::vector<unsigned long long> &svalues, std::vector<unsigned long long> &rvalues) override; + + void broadcast(int &value) override; + void broadcast(float &value) override; + void broadcast(double &value) override; + void broadcast(long int &value) override; + void broadcast(std::vector<int> &values) override; + void broadcast(std::vector<float> &values) override; + void broadcast(std::vector<double> &values) override; + void broadcast(std::vector<long int> &values) override; + + template <class T> + std::vector<T> gather(std::vector<T> &values); + + template <class T> + void allGather(std::vector<T> &svalues, std::vector<T> &rvalues); + + template <class T> + void broadcast(std::vector<T> &values); + + template <class T> + void broadcast(T &value); private: - int numprocs, PID; - MPI_Comm comm; - int root; + int numprocs, PID; + MPI_Comm comm; + int root; }; ////////////////////////////////////////////////////////////////////////// template <class T> -std::vector<T> MPICommunicator::gather(std::vector<T>& values) +std::vector<T> MPICommunicator::gather(std::vector<T> &values) { - MPI_Datatype mpiDataType; - if ((std::string)typeid(T).name()==(std::string)typeid(double).name()) mpiDataType = MPI_DOUBLE; - else if ((std::string)typeid(T).name()==(std::string)typeid(float).name()) mpiDataType = MPI_FLOAT; - else if ((std::string)typeid(T).name()==(std::string)typeid(int).name()) mpiDataType = MPI_INT; - else if ((std::string)typeid(T).name()==(std::string)typeid(unsigned long long).name()) mpiDataType = MPI_UNSIGNED_LONG_LONG; - else throw UbException(UB_EXARGS, "no MpiDataType for T"+(std::string)typeid(T).name()); - - int count = static_cast<int> (values.size()); - std::vector<T> rvalues(1); - - if (PID == root) - { - rvalues.resize(numprocs*count); - } - - MPI_Gather(&values[0], count, mpiDataType, &rvalues[0], count, mpiDataType, root, comm); - - return rvalues; + MPI_Datatype mpiDataType; + if ((std::string) typeid(T).name() == (std::string) typeid(double).name()) + mpiDataType = MPI_DOUBLE; + else if ((std::string) typeid(T).name() == (std::string) typeid(float).name()) + mpiDataType = MPI_FLOAT; + else if ((std::string) typeid(T).name() == (std::string) typeid(int).name()) + mpiDataType = MPI_INT; + else if ((std::string) typeid(T).name() == (std::string) typeid(unsigned long long).name()) + mpiDataType = MPI_UNSIGNED_LONG_LONG; + else + throw UbException(UB_EXARGS, "no MpiDataType for T" + (std::string) typeid(T).name()); + + int count = static_cast<int>(values.size()); + std::vector<T> rvalues(1); + + if (PID == root) { + rvalues.resize(numprocs * count); + } + + MPI_Gather(&values[0], count, mpiDataType, &rvalues[0], count, mpiDataType, root, comm); + + return rvalues; } ////////////////////////////////////////////////////////////////////////// template <class T> -void MPICommunicator::allGather(std::vector<T>& svalues, std::vector<T>& rvalues) +void MPICommunicator::allGather(std::vector<T> &svalues, std::vector<T> &rvalues) { - MPI_Datatype mpiDataType; - if ((std::string)typeid(T).name()==(std::string)typeid(double).name()) mpiDataType = MPI_DOUBLE; - else if ((std::string)typeid(T).name()==(std::string)typeid(float).name()) mpiDataType = MPI_FLOAT; - else if ((std::string)typeid(T).name()==(std::string)typeid(int).name()) mpiDataType = MPI_INT; - else if ((std::string)typeid(T).name()==(std::string)typeid(unsigned long long).name()) mpiDataType = MPI_UNSIGNED_LONG_LONG; - else throw UbException(UB_EXARGS, "no MpiDataType for T"+(std::string)typeid(T).name()); - - int scount; - std::vector<int> displs, rcounts; - - scount = (int)(svalues.size()); - - rcounts.resize(numprocs); - MPI_Allgather(&scount, 1, MPI_INT, &rcounts[0], 1, MPI_INT, comm); - displs.resize(numprocs); - - displs[0] = 0; - for (int i=1; i<numprocs; ++i) - { - displs[i] = displs[i-1]+rcounts[i-1]; - } - - rvalues.resize(displs[numprocs-1]+rcounts[numprocs-1]); - - if (rvalues.size() == 0) - { - rvalues.resize(1); - rvalues[0] = -999; //FIXME warning C4245: As svalues and rvalues are of type vector<T> there could be a potenial signed/unsigned mismatch storring a negative number - } - if (scount == 0) - { - svalues.resize(1); - svalues[0] = -999; //FIXME warning C4245: As svalues and rvalues are of type vector<T> there could be a potenial signed/unsigned mismatch storring a negative number - } - - MPI_Allgatherv(&svalues[0], scount, mpiDataType, &rvalues[0], &rcounts[0], &displs[0], mpiDataType, comm); + MPI_Datatype mpiDataType; + if ((std::string) typeid(T).name() == (std::string) typeid(double).name()) + mpiDataType = MPI_DOUBLE; + else if ((std::string) typeid(T).name() == (std::string) typeid(float).name()) + mpiDataType = MPI_FLOAT; + else if ((std::string) typeid(T).name() == (std::string) typeid(int).name()) + mpiDataType = MPI_INT; + else if ((std::string) typeid(T).name() == (std::string) typeid(unsigned long long).name()) + mpiDataType = MPI_UNSIGNED_LONG_LONG; + else + throw UbException(UB_EXARGS, "no MpiDataType for T" + (std::string) typeid(T).name()); + + int scount; + std::vector<int> displs, rcounts; + + scount = (int)(svalues.size()); + + rcounts.resize(numprocs); + MPI_Allgather(&scount, 1, MPI_INT, &rcounts[0], 1, MPI_INT, comm); + displs.resize(numprocs); + + displs[0] = 0; + for (int i = 1; i < numprocs; ++i) { + displs[i] = displs[i - 1] + rcounts[i - 1]; + } + + rvalues.resize(displs[numprocs - 1] + rcounts[numprocs - 1]); + + if (rvalues.size() == 0) { + rvalues.resize(1); + rvalues[0] = -999; // FIXME warning C4245: As svalues and rvalues are of type vector<T> there could be a + // potenial signed/unsigned mismatch storring a negative number + } + if (scount == 0) { + svalues.resize(1); + svalues[0] = -999; // FIXME warning C4245: As svalues and rvalues are of type vector<T> there could be a + // potenial signed/unsigned mismatch storring a negative number + } + + MPI_Allgatherv(&svalues[0], scount, mpiDataType, &rvalues[0], &rcounts[0], &displs[0], mpiDataType, comm); } ////////////////////////////////////////////////////////////////////////// template <class T> -void MPICommunicator::broadcast(std::vector<T>& values) +void MPICommunicator::broadcast(std::vector<T> &values) { - MPI_Datatype mpiDataType; - if ((std::string)typeid(T).name()==(std::string)typeid(double).name()) mpiDataType = MPI_DOUBLE; - else if ((std::string)typeid(T).name()==(std::string)typeid(float).name()) mpiDataType = MPI_FLOAT; - else if ((std::string)typeid(T).name()==(std::string)typeid(int).name()) mpiDataType = MPI_INT; - else if ((std::string)typeid(T).name()==(std::string)typeid(long int).name()) mpiDataType = MPI_LONG_INT; - else throw UbException(UB_EXARGS, "no MpiDataType for T"+(std::string)typeid(T).name()); - - int rcount; - if (this->PID == this->root) - { - rcount = (int)values.size(); - } - - MPI_Bcast(&rcount, 1, MPI_INT, this->root, comm); - - if (this->PID != this->root) - { - values.resize(rcount); - } - - MPI_Bcast(&values[0], (int)values.size(), mpiDataType, this->root, comm); + MPI_Datatype mpiDataType; + if ((std::string) typeid(T).name() == (std::string) typeid(double).name()) + mpiDataType = MPI_DOUBLE; + else if ((std::string) typeid(T).name() == (std::string) typeid(float).name()) + mpiDataType = MPI_FLOAT; + else if ((std::string) typeid(T).name() == (std::string) typeid(int).name()) + mpiDataType = MPI_INT; + else if ((std::string) typeid(T).name() == (std::string) typeid(long int).name()) + mpiDataType = MPI_LONG_INT; + else + throw UbException(UB_EXARGS, "no MpiDataType for T" + (std::string) typeid(T).name()); + + int rcount; + if (this->PID == this->root) { + rcount = (int)values.size(); + } + + MPI_Bcast(&rcount, 1, MPI_INT, this->root, comm); + + if (this->PID != this->root) { + values.resize(rcount); + } + + MPI_Bcast(&values[0], (int)values.size(), mpiDataType, this->root, comm); } ////////////////////////////////////////////////////////////////////////// template <class T> -void MPICommunicator::broadcast(T& value) +void MPICommunicator::broadcast(T &value) { - MPI_Datatype mpiDataType; - if ((std::string)typeid(T).name() == (std::string)typeid(double).name()) mpiDataType = MPI_DOUBLE; - else if ((std::string)typeid(T).name() == (std::string)typeid(float).name()) mpiDataType = MPI_FLOAT; - else if ((std::string)typeid(T).name() == (std::string)typeid(int).name()) mpiDataType = MPI_INT; - else if ((std::string)typeid(T).name()==(std::string)typeid(long int).name()) mpiDataType = MPI_LONG_INT; - else throw UbException(UB_EXARGS, "no MpiDataType for T" + (std::string)typeid(T).name()); - - MPI_Bcast(&value, 1, mpiDataType, this->root, comm); + MPI_Datatype mpiDataType; + if ((std::string) typeid(T).name() == (std::string) typeid(double).name()) + mpiDataType = MPI_DOUBLE; + else if ((std::string) typeid(T).name() == (std::string) typeid(float).name()) + mpiDataType = MPI_FLOAT; + else if ((std::string) typeid(T).name() == (std::string) typeid(int).name()) + mpiDataType = MPI_INT; + else if ((std::string) typeid(T).name() == (std::string) typeid(long int).name()) + mpiDataType = MPI_LONG_INT; + else + throw UbException(UB_EXARGS, "no MpiDataType for T" + (std::string) typeid(T).name()); + + MPI_Bcast(&value, 1, mpiDataType, this->root, comm); } ////////////////////////////////////////////////////////////////////////// diff --git a/src/cpu/VirtualFluidsCore/Parallel/MPIIODataStructures.h b/src/cpu/VirtualFluidsCore/Parallel/MPIIODataStructures.h index c50e67cfbc0fb53268b924aeff6f7a1d94b54982..6a21caab66e22a192efb591d7bba81675326f206 100644 --- a/src/cpu/VirtualFluidsCore/Parallel/MPIIODataStructures.h +++ b/src/cpu/VirtualFluidsCore/Parallel/MPIIODataStructures.h @@ -3,179 +3,167 @@ namespace MPIIODataStructures { - //! \struct GridParam - //! \brief Structure describes parameters of the grid - //! \details The structure is nessasary to restore the grid correctly - struct GridParam - { - double trafoParams[33]; - double deltaX; - int blockNx1; - int blockNx2; - int blockNx3; - int nx1; - int nx2; - int nx3; - bool periodicX1; - bool periodicX2; - bool periodicX3; - bool active; - bool transformation; - }; +//! \struct GridParam +//! \brief Structure describes parameters of the grid +//! \details The structure is nessasary to restore the grid correctly +struct GridParam { + double trafoParams[33]; + double deltaX; + int blockNx1; + int blockNx2; + int blockNx3; + int nx1; + int nx2; + int nx3; + bool periodicX1; + bool periodicX2; + bool periodicX3; + bool active; + bool transformation; +}; - //! \struct Block3d - //! \brief Structure contains information of the block - //! \details The structure is used to write the data describing the block in the grid when saving the grid - //! and to read it when restoring the grid - struct Block3d - { - int x1; - int x2; - int x3; - int bundle; - int rank; - int lrank; - int part; - int globalID; - int localID; - int level; - int interpolationFlagCF; - int interpolationFlagFC; - int counter; - bool active; - }; +//! \struct Block3d +//! \brief Structure contains information of the block +//! \details The structure is used to write the data describing the block in the grid when saving the grid +//! and to read it when restoring the grid +struct Block3d { + int x1; + int x2; + int x3; + int bundle; + int rank; + int lrank; + int part; + int globalID; + int localID; + int level; + int interpolationFlagCF; + int interpolationFlagFC; + int counter; + bool active; +}; - //! \struct dataSetParam - //! \brief Structure describes parameters of the dataSet that are equal in all blocks - //! \details The structure used to store some parameters needed to restore dataSet arrays - struct dataSetParam - { - int nx1; - int nx2; - int nx3; - int nx[4]; //nx1, nx2, nx3, nx4 - }; +//! \struct dataSetParam +//! \brief Structure describes parameters of the dataSet that are equal in all blocks +//! \details The structure used to store some parameters needed to restore dataSet arrays +struct dataSetParam { + int nx1; + int nx2; + int nx3; + int nx[4]; // nx1, nx2, nx3, nx4 +}; - //! \struct DataSetRestart - //! \brief Structure describes parameters of the dataSet in MPIIORestartCoProcessor format - //! \details The structure is used when reading from the file - struct DataSetRestart - { - double collFactor; - double deltaT; - int x1; - int x2; - int x3; - int level; - int ghostLayerWidth; - bool compressible; - bool withForcing; - }; +//! \struct DataSetRestart +//! \brief Structure describes parameters of the dataSet in MPIIORestartCoProcessor format +//! \details The structure is used when reading from the file +struct DataSetRestart { + double collFactor; + double deltaT; + int x1; + int x2; + int x3; + int level; + int ghostLayerWidth; + bool compressible; + bool withForcing; +}; - //! \struct DataSetMigration - //! \brief Structure describes parameters of the dataSet in MPIIOMigrationCoProcessor format - //! \details The structure is used to find the needed block in the grid when restoring a dataSet - struct DataSetMigration - { - double collFactor; - double deltaT; - int globalID; - int ghostLayerWidth; - bool compressible; - bool withForcing; - }; +//! \struct DataSetMigration +//! \brief Structure describes parameters of the dataSet in MPIIOMigrationCoProcessor format +//! \details The structure is used to find the needed block in the grid when restoring a dataSet +struct DataSetMigration { + double collFactor; + double deltaT; + int globalID; + int ghostLayerWidth; + bool compressible; + bool withForcing; +}; - //! \struct DataSetSmallRead - //! \brief Structure describes parameters of the DataSetSmall in MPIIORestartCoProcessor format - //! \details The structure is used when reading from the file - struct DataSetSmallRestart - { - int x1; - int x2; - int x3; - int level; - }; - //! \struct dataSetSmall - //! \brief Structure containes information identifying the block in MPIIOMigrationCoProcessor format - //! \details The structure is used to find the needed block in the grid when restoring a dataSet arrays - struct DataSetSmallMigration - { - int globalID; - }; +//! \struct DataSetSmallRead +//! \brief Structure describes parameters of the DataSetSmall in MPIIORestartCoProcessor format +//! \details The structure is used when reading from the file +struct DataSetSmallRestart { + int x1; + int x2; + int x3; + int level; +}; +//! \struct dataSetSmall +//! \brief Structure containes information identifying the block in MPIIOMigrationCoProcessor format +//! \details The structure is used to find the needed block in the grid when restoring a dataSet arrays +struct DataSetSmallMigration { + int globalID; +}; - //! \struct BoundaryCondition - //! \brief Structure containes information about boundary conditions of the block - //! \details The structure is used to write data describing boundary conditions of the blocks when saving the grid - //! and to read it when restoring the grid - struct BoundaryCondition - { - long long noslipBoundaryFlags; // MPI_LONG_LONG - long long slipBoundaryFlags; - long long velocityBoundaryFlags; - long long densityBoundaryFlags; - long long wallModelBoundaryFlags; +//! \struct BoundaryCondition +//! \brief Structure containes information about boundary conditions of the block +//! \details The structure is used to write data describing boundary conditions of the blocks when saving the grid +//! and to read it when restoring the grid +struct BoundaryCondition { + long long noslipBoundaryFlags; // MPI_LONG_LONG + long long slipBoundaryFlags; + long long velocityBoundaryFlags; + long long densityBoundaryFlags; + long long wallModelBoundaryFlags; - float bcVelocityX1; - float bcVelocityX2; - float bcVelocityX3; - float bcDensity; + float bcVelocityX1; + float bcVelocityX2; + float bcVelocityX3; + float bcDensity; - float bcLodiDensity; - float bcLodiVelocityX1; - float bcLodiVelocityX2; - float bcLodiVelocityX3; - float bcLodiLentgh; + float bcLodiDensity; + float bcLodiVelocityX1; + float bcLodiVelocityX2; + float bcLodiVelocityX3; + float bcLodiLentgh; - float nx1, nx2, nx3; - float q[26]; + float nx1, nx2, nx3; + float q[26]; - char algorithmType; - }; + char algorithmType; +}; - //! \struct boundCondParam - //! \brief Structure describes parameters of the boundaryConditions that are equal in all blocks - //! \details The structure used to store some parameters needed to restore boundaryConditions arrays - struct boundCondParam - { - int nx1; - int nx2; - int nx3; - int bcindexmatrixCount; // how many bcindexmatrix-values in one (any) block - }; +//! \struct boundCondParam +//! \brief Structure describes parameters of the boundaryConditions that are equal in all blocks +//! \details The structure used to store some parameters needed to restore boundaryConditions arrays +struct boundCondParam { + int nx1; + int nx2; + int nx3; + int bcindexmatrixCount; // how many bcindexmatrix-values in one (any) block +}; - //! \struct BCAddRead - //! \brief Structure describes parameters of the BCAdd in MPIIORestartCoProcessor format - //! \details The structure is used when reading from the file - struct BCAddRestart - { - int x1; // to find the right block - int x2; - int x3; - int level; - int boundCond_count; // how many BoundaryCondition-structures are in this block - int indexContainer_count; // how many indexContainer-values are in this block - }; +//! \struct BCAddRead +//! \brief Structure describes parameters of the BCAdd in MPIIORestartCoProcessor format +//! \details The structure is used when reading from the file +struct BCAddRestart { + int x1; // to find the right block + int x2; + int x3; + int level; + int boundCond_count; // how many BoundaryCondition-structures are in this block + int indexContainer_count; // how many indexContainer-values are in this block +}; - //! \struct BCAdd - //! \brief Structure containes information identifying the block and some parameters of the arrays - //! \of boundary conditions that are equal in all blocks in MPIIOMigrationCoProcessor format - //! \details The structure is used to find the needed block in the grid when restoring a dataSet - //! and to set common parameters - struct BCAddMigration - { - int globalID; - int boundCond_count; // how many BoundaryCondition-structures are in this block - int indexContainer_count; // how many indexContainer-values are in this block - }; +//! \struct BCAdd +//! \brief Structure containes information identifying the block and some parameters of the arrays +//! \of boundary conditions that are equal in all blocks in MPIIOMigrationCoProcessor format +//! \details The structure is used to find the needed block in the grid when restoring a dataSet +//! and to set common parameters +struct BCAddMigration { + int globalID; + int boundCond_count; // how many BoundaryCondition-structures are in this block + int indexContainer_count; // how many indexContainer-values are in this block +}; - struct DSArraysPresence - { - bool isAverageDensityArrayPresent; - bool isAverageVelocityArrayPresent; - bool isAverageFluktuationsArrayPresent; - bool isAverageTripleArrayPresent; - bool isShearStressValArrayPresent; - bool isRelaxationFactorPresent; - }; +struct DSArraysPresence { + bool isAverageDensityArrayPresent; + bool isAverageVelocityArrayPresent; + bool isAverageFluktuationsArrayPresent; + bool isAverageTripleArrayPresent; + bool isShearStressValArrayPresent; + bool isRelaxationFactorPresent; }; -#endif \ No newline at end of file +}; // namespace MPIIODataStructures +#endif \ No newline at end of file diff --git a/src/cpu/VirtualFluidsCore/Parallel/MetisPartitioner.cpp b/src/cpu/VirtualFluidsCore/Parallel/MetisPartitioner.cpp index 86a8e1e72c4ca2b342bf68abfb360105554c9b44..93776668460650d5b7015f57cb00fe303277a3a7 100644 --- a/src/cpu/VirtualFluidsCore/Parallel/MetisPartitioner.cpp +++ b/src/cpu/VirtualFluidsCore/Parallel/MetisPartitioner.cpp @@ -2,78 +2,76 @@ #include "MetisPartitioner.h" - MetisPartitioner::MetisPartitioner() { - METIS_SetDefaultOptions(options); - options[METIS_OPTION_NUMBERING] = 0; - vsize = NULL; - tpwgts = NULL; - ubvec = NULL; + METIS_SetDefaultOptions(options); + options[METIS_OPTION_NUMBERING] = 0; + vsize = NULL; + tpwgts = NULL; + ubvec = NULL; - //options[METIS_OPTION_OBJTYPE] = METIS_OBJTYPE_CUT; - ////options[METIS_OPTION_OBJTYPE] = METIS_OBJTYPE_VOL; + // options[METIS_OPTION_OBJTYPE] = METIS_OBJTYPE_CUT; + ////options[METIS_OPTION_OBJTYPE] = METIS_OBJTYPE_VOL; - //options[METIS_OPTION_CTYPE] = METIS_CTYPE_SHEM; - //options[METIS_OPTION_IPTYPE] = METIS_IPTYPE_GROW; + // options[METIS_OPTION_CTYPE] = METIS_CTYPE_SHEM; + // options[METIS_OPTION_IPTYPE] = METIS_IPTYPE_GROW; } ////////////////////////////////////////////////////////////////////////// -MetisPartitioner::~MetisPartitioner() -= default; +MetisPartitioner::~MetisPartitioner() = default; ////////////////////////////////////////////////////////////////////////// -idx_t* MetisPartitioner::getMetisOptions() -{ - return options; -} -void MetisPartitioner::setMetisOptions(int option, idx_t value) -{ - options[option] = value; -} +idx_t *MetisPartitioner::getMetisOptions() { return options; } +void MetisPartitioner::setMetisOptions(int option, idx_t value) { options[option] = value; } ////////////////////////////////////////////////////////////////////////// int MetisPartitioner::partition(int nofParts, MetisPartitioner::PartType ptype) { - int rc; - idx_t nvtxs = (idx_t)xadj.size()-1; // number of nodes - idx_t ncon = (idx_t)vwgt.size()/nvtxs; // number Of node constraints; - part.resize(nvtxs); - idx_t edgecutCount = 0; - idx_t nofPartsMetis = (idx_t)nofParts; + int rc; + idx_t nvtxs = (idx_t)xadj.size() - 1; // number of nodes + idx_t ncon = (idx_t)vwgt.size() / nvtxs; // number Of node constraints; + part.resize(nvtxs); + idx_t edgecutCount = 0; + idx_t nofPartsMetis = (idx_t)nofParts; + + switch (ptype) { + case MetisPartitioner::RECURSIVE: + if (nofParts < 1) + UB_THROW(UbException(UB_EXARGS, "invalid nofParts<1")); + else if (nofParts == 1) { + part.resize(nvtxs, 0); + return 0; + } + // else if( nofParts > 8 ) UBLOG(logWARNING, "MetisPartitioner::Recursive: !!!Warning!!! best for + // nofParts<=8 --> Kway is maybe a better option"); - switch (ptype) - { - case MetisPartitioner::RECURSIVE: - if ( nofParts < 1 ) UB_THROW( UbException(UB_EXARGS,"invalid nofParts<1") ); - else if (nofParts == 1) { part.resize(nvtxs, 0); return 0; } - //else if( nofParts > 8 ) UBLOG(logWARNING, "MetisPartitioner::Recursive: !!!Warning!!! best for nofParts<=8 --> Kway is maybe a better option"); - - rc = METIS_PartGraphRecursive(&nvtxs, &ncon, &xadj[0], &adjncy[0], - &vwgt[0], vsize, &adjwgt[0], &nofPartsMetis, - tpwgts, ubvec, options, &edgecutCount, &part[0]); - break; - case MetisPartitioner::KWAY: - if ( nofParts < 1 ) UB_THROW( UbException(UB_EXARGS,"invalid nofParts<1") ); - else if (nofParts == 1) { part.resize(nvtxs, 0); return 0; } - //else if( nofParts < 9 ) UBLOG(logWARNING, "MetisPartitioner::Kway: !!!Warning!!! best for nofParts>8 --> Recursive is maybe a better option"); + rc = METIS_PartGraphRecursive(&nvtxs, &ncon, &xadj[0], &adjncy[0], &vwgt[0], vsize, &adjwgt[0], + &nofPartsMetis, tpwgts, ubvec, options, &edgecutCount, &part[0]); + break; + case MetisPartitioner::KWAY: + if (nofParts < 1) + UB_THROW(UbException(UB_EXARGS, "invalid nofParts<1")); + else if (nofParts == 1) { + part.resize(nvtxs, 0); + return 0; + } + // else if( nofParts < 9 ) UBLOG(logWARNING, "MetisPartitioner::Kway: !!!Warning!!! best for nofParts>8 + // --> Recursive is maybe a better option"); - rc = METIS_PartGraphKway(&nvtxs, &ncon, &xadj[0], &adjncy[0], - &vwgt[0], vsize, &adjwgt[0], &nofPartsMetis, - tpwgts, ubvec, options, &edgecutCount, &part[0]); - break; - } + rc = METIS_PartGraphKway(&nvtxs, &ncon, &xadj[0], &adjncy[0], &vwgt[0], vsize, &adjwgt[0], &nofPartsMetis, + tpwgts, ubvec, options, &edgecutCount, &part[0]); + break; + } - switch (rc) - { - case METIS_ERROR_INPUT: - throw UbException(UB_EXARGS,"METIS: input error"); - break; - case METIS_ERROR_MEMORY: - throw UbException(UB_EXARGS,"METIS: it could not allocate the required memory"); - break; - case METIS_ERROR: - throw UbException(UB_EXARGS,"METIS: error"); - break; - } + switch (rc) { + case METIS_ERROR_INPUT: + throw UbException(UB_EXARGS, "METIS: input error"); + break; + case METIS_ERROR_MEMORY: + throw UbException(UB_EXARGS, "METIS: it could not allocate the required memory"); + break; + case METIS_ERROR: + throw UbException(UB_EXARGS, "METIS: error"); + break; + } - return edgecutCount; + return edgecutCount; } #endif diff --git a/src/cpu/VirtualFluidsCore/Parallel/MetisPartitioner.h b/src/cpu/VirtualFluidsCore/Parallel/MetisPartitioner.h index 339238684ce497f637b965538b9208186201bc97..8fd7a82d52e1ac4c7199d5b2e1a1cbe43ea25369 100644 --- a/src/cpu/VirtualFluidsCore/Parallel/MetisPartitioner.h +++ b/src/cpu/VirtualFluidsCore/Parallel/MetisPartitioner.h @@ -1,59 +1,63 @@ /** -* @file MetisPartitioner.h -* @brief Class use METIS library for graph-based partitioning. -* @author Kostyantyn Kucher -* @date 22.09.2011 -*/ + * @file MetisPartitioner.h + * @brief Class use METIS library for graph-based partitioning. + * @author Kostyantyn Kucher + * @date 22.09.2011 + */ #ifndef METISPARTITIONER_H #define METISPARTITIONER_H #if defined VF_METIS -#include "metis.h" -#include <vector> -#include <string> -#include <PointerDefinitions.h> #include "basics/utilities/UbLogger.h" #include "basics/utilities/UbSystem.h" +#include "metis.h" +#include <PointerDefinitions.h> +#include <string> +#include <vector> class MetisPartitioner { public: - enum PartType { RECURSIVE, KWAY }; + enum PartType { RECURSIVE, KWAY }; + public: - MetisPartitioner(); - virtual ~MetisPartitioner(); - idx_t* getMetisOptions(); - void setMetisOptions(int option, idx_t value); - int partition(int nofParts, PartType ptype); + MetisPartitioner(); + virtual ~MetisPartitioner(); + idx_t *getMetisOptions(); + void setMetisOptions(int option, idx_t value); + int partition(int nofParts, PartType ptype); + public: - std::vector<idx_t> xadj; // adjncy offset of nodes - //(size = n+1, n=nofNodes) - std::vector<idx_t> adjncy; // array that stores the adjacency lists of nodes - //(size = m*2, m= nofEdged, factor 2 because edge A->B AND B->A has to be stored) - std::vector<idx_t> vwgt; // vertex weights (size=n*ncon, ncon=nofNodeWeightsPerNode) - std::vector<idx_t> adjwgt; // array that stores the weights of the adjacency lists - // (size=2*m) - idx_t * vsize; // array that stores the computation weights per node - // (size=n) - - real_t * tpwgts; // holds the wished fratcion of segment i, e.g. tpwgts={0.2, 0.2, 0.6} - // -> patisions 0 and one will get 20% of the weight each and part 3 60%! - // (size=nofPartitions) sum of tpwgts must be 1.0 - - real_t * ubvec; //This is an array of size ncon that specifies the allowed load imbalance tolerance for each constraint. - //For the ith partition and jth constraint the allowed weight is the ubvec[j]*tpwgts[i*ncon+j] fraction - //of the jth’s constraint total weight. The load imbalances must be greater than 1.0. - //A NULL value can be passed indicating that the load imbalance tolerance for each constraint should - //be 1.001 (for ncon=1) or 1.01 (for ncon¿1). - - std::vector<idx_t> part; // This is a vector of size n that upon successful completion stores the partition vector of the graph. - // The numbering of this vector starts from 0 + std::vector<idx_t> xadj; // adjncy offset of nodes + //(size = n+1, n=nofNodes) + std::vector<idx_t> adjncy; // array that stores the adjacency lists of nodes + //(size = m*2, m= nofEdged, factor 2 because edge A->B AND B->A has to be stored) + std::vector<idx_t> vwgt; // vertex weights (size=n*ncon, ncon=nofNodeWeightsPerNode) + std::vector<idx_t> adjwgt; // array that stores the weights of the adjacency lists + // (size=2*m) + idx_t *vsize; // array that stores the computation weights per node + // (size=n) + + real_t *tpwgts; // holds the wished fratcion of segment i, e.g. tpwgts={0.2, 0.2, 0.6} + // -> patisions 0 and one will get 20% of the weight each and part 3 60%! + // (size=nofPartitions) sum of tpwgts must be 1.0 + + real_t * + ubvec; // This is an array of size ncon that specifies the allowed load imbalance tolerance for each constraint. + // For the ith partition and jth constraint the allowed weight is the ubvec[j]*tpwgts[i*ncon+j] fraction + // of the jth’s constraint total weight. The load imbalances must be greater than 1.0. + // A NULL value can be passed indicating that the load imbalance tolerance for each constraint should + // be 1.001 (for ncon=1) or 1.01 (for ncon¿1). + + std::vector<idx_t> + part; // This is a vector of size n that upon successful completion stores the partition vector of the graph. + // The numbering of this vector starts from 0 private: - idx_t options[METIS_NOPTIONS]; + idx_t options[METIS_NOPTIONS]; }; #endif -#endif +#endif diff --git a/src/cpu/VirtualFluidsCore/Parallel/NullCommunicator.cpp b/src/cpu/VirtualFluidsCore/Parallel/NullCommunicator.cpp index 520206d48817828f51d901035f8d1b0f81dc7a7c..d3846dfd36a765891936e45c80a62dcd88025c15 100644 --- a/src/cpu/VirtualFluidsCore/Parallel/NullCommunicator.cpp +++ b/src/cpu/VirtualFluidsCore/Parallel/NullCommunicator.cpp @@ -1,28 +1,28 @@ //======================================================================================= -// ____ ____ __ ______ __________ __ __ __ __ -// \ \ | | | | | _ \ |___ ___| | | | | / \ | | -// \ \ | | | | | |_) | | | | | | | / \ | | -// \ \ | | | | | _ / | | | | | | / /\ \ | | -// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ -// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| -// \ \ | | ________________________________________________________________ -// \ \ | | | ______________________________________________________________| -// \ \| | | | __ __ __ __ ______ _______ -// \ | | |_____ | | | | | | | | | _ \ / _____) -// \ | | _____| | | | | | | | | | | \ \ \_______ +// ____ ____ __ ______ __________ __ __ __ __ +// \ \ | | | | | _ \ |___ ___| | | | | / \ | | +// \ \ | | | | | |_) | | | | | | | / \ | | +// \ \ | | | | | _ / | | | | | | / /\ \ | | +// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ +// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| +// \ \ | | ________________________________________________________________ +// \ \ | | | ______________________________________________________________| +// \ \| | | | __ __ __ __ ______ _______ +// \ | | |_____ | | | | | | | | | _ \ / _____) +// \ | | _____| | | | | | | | | | | \ \ \_______ // \ | | | | |_____ | \_/ | | | | |_/ / _____ | -// \ _____| |__| |________| \_______/ |__| |______/ (_______/ +// \ _____| |__| |________| \_______/ |__| |______/ (_______/ // -// This file is part of VirtualFluids. VirtualFluids is free software: you can +// This file is part of VirtualFluids. VirtualFluids is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of +// License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. -// -// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// +// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License along // with VirtualFluids (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>. // @@ -33,74 +33,32 @@ #include "NullCommunicator.h" - -NullCommunicator::NullCommunicator() -= default; +NullCommunicator::NullCommunicator() = default; ////////////////////////////////////////////////////////////////////////// -NullCommunicator::~NullCommunicator() -= default; +NullCommunicator::~NullCommunicator() = default; ////////////////////////////////////////////////////////////////////////// -int NullCommunicator::getBundleID() -{ - return 0; -} +int NullCommunicator::getBundleID() { return 0; } ////////////////////////////////////////////////////////////////////////// -int NullCommunicator::getNumberOfBundles() -{ - return 0; -} +int NullCommunicator::getNumberOfBundles() { return 0; } ////////////////////////////////////////////////////////////////////////// -int NullCommunicator::getProcessID() -{ - return 0; -} +int NullCommunicator::getProcessID() { return 0; } ////////////////////////////////////////////////////////////////////////// -int NullCommunicator::getNumberOfProcesses() -{ - return 0; -} +int NullCommunicator::getNumberOfProcesses() { return 0; } ////////////////////////////////////////////////////////////////////////// -void* NullCommunicator::getNativeCommunicator() -{ - return NULL; -} +void *NullCommunicator::getNativeCommunicator() { return NULL; } ////////////////////////////////////////////////////////////////////////// -int NullCommunicator::getRoot() -{ - return 0; -} +int NullCommunicator::getRoot() { return 0; } ////////////////////////////////////////////////////////////////////////// -int NullCommunicator::getBundleRoot() -{ - return 0; -} +int NullCommunicator::getBundleRoot() { return 0; } ////////////////////////////////////////////////////////////////////////// -int NullCommunicator::getProcessRoot() -{ - return 0; -} +int NullCommunicator::getProcessRoot() { return 0; } ////////////////////////////////////////////////////////////////////////// -std::vector<std::string> NullCommunicator::gather(const std::string& /*str*/) -{ - return std::vector<std::string>(); -} +std::vector<std::string> NullCommunicator::gather(const std::string & /*str*/) { return std::vector<std::string>(); } ////////////////////////////////////////////////////////////////////////// -std::vector<double> NullCommunicator::gatherDoubles(std::vector<double>& /*values*/) -{ - return std::vector<double>(); -} +std::vector<double> NullCommunicator::gatherDoubles(std::vector<double> & /*values*/) { return std::vector<double>(); } ////////////////////////////////////////////////////////////////////////// -void NullCommunicator::allGatherInts(std::vector<int>& svalues, std::vector<int>& rvalues) -{ - -} +void NullCommunicator::allGatherInts(std::vector<int> &svalues, std::vector<int> &rvalues) {} ////////////////////////////////////////////////////////////////////////// -void NullCommunicator::sendSerializedObject(std::stringstream& ss, int target) -{ - -} +void NullCommunicator::sendSerializedObject(std::stringstream &ss, int target) {} ////////////////////////////////////////////////////////////////////////// -void NullCommunicator::receiveSerializedObject(std::stringstream& ss, int source) -{ - -} +void NullCommunicator::receiveSerializedObject(std::stringstream &ss, int source) {} diff --git a/src/cpu/VirtualFluidsCore/Parallel/NullCommunicator.h b/src/cpu/VirtualFluidsCore/Parallel/NullCommunicator.h index 2495b7766357a7f1b9a0e4200aed9a8a3945af77..3dad3395a34b5d3a049c3b0bb8d960e924078324 100644 --- a/src/cpu/VirtualFluidsCore/Parallel/NullCommunicator.h +++ b/src/cpu/VirtualFluidsCore/Parallel/NullCommunicator.h @@ -1,28 +1,28 @@ //======================================================================================= -// ____ ____ __ ______ __________ __ __ __ __ -// \ \ | | | | | _ \ |___ ___| | | | | / \ | | -// \ \ | | | | | |_) | | | | | | | / \ | | -// \ \ | | | | | _ / | | | | | | / /\ \ | | -// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ -// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| -// \ \ | | ________________________________________________________________ -// \ \ | | | ______________________________________________________________| -// \ \| | | | __ __ __ __ ______ _______ -// \ | | |_____ | | | | | | | | | _ \ / _____) -// \ | | _____| | | | | | | | | | | \ \ \_______ +// ____ ____ __ ______ __________ __ __ __ __ +// \ \ | | | | | _ \ |___ ___| | | | | / \ | | +// \ \ | | | | | |_) | | | | | | | / \ | | +// \ \ | | | | | _ / | | | | | | / /\ \ | | +// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ +// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| +// \ \ | | ________________________________________________________________ +// \ \ | | | ______________________________________________________________| +// \ \| | | | __ __ __ __ ______ _______ +// \ | | |_____ | | | | | | | | | _ \ / _____) +// \ | | _____| | | | | | | | | | | \ \ \_______ // \ | | | | |_____ | \_/ | | | | |_/ / _____ | -// \ _____| |__| |________| \_______/ |__| |______/ (_______/ +// \ _____| |__| |________| \_______/ |__| |______/ (_______/ // -// This file is part of VirtualFluids. VirtualFluids is free software: you can +// This file is part of VirtualFluids. VirtualFluids is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of +// License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. -// -// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// +// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License along // with VirtualFluids (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>. // @@ -43,21 +43,22 @@ class NullCommunicator : public Communicator { public: - NullCommunicator(); - ~NullCommunicator() override; - int getBundleID() override; - int getNumberOfBundles() override; - int getProcessID() override; - int getNumberOfProcesses() override; - void* getNativeCommunicator() override; - int getRoot() override; - int getBundleRoot() override; - int getProcessRoot() override; - std::vector<std::string> gather(const std::string& str) override; - std::vector<double> gatherDoubles(std::vector<double>& values); - void allGatherInts(std::vector<int>& svalues, std::vector<int>& rvalues); - void sendSerializedObject(std::stringstream& ss, int target) override; - void receiveSerializedObject(std::stringstream& ss, int source) override; + NullCommunicator(); + ~NullCommunicator() override; + int getBundleID() override; + int getNumberOfBundles() override; + int getProcessID() override; + int getNumberOfProcesses() override; + void *getNativeCommunicator() override; + int getRoot() override; + int getBundleRoot() override; + int getProcessRoot() override; + std::vector<std::string> gather(const std::string &str) override; + std::vector<double> gatherDoubles(std::vector<double> &values); + void allGatherInts(std::vector<int> &svalues, std::vector<int> &rvalues); + void sendSerializedObject(std::stringstream &ss, int target) override; + void receiveSerializedObject(std::stringstream &ss, int source) override; + protected: private: }; diff --git a/src/cpu/VirtualFluidsCore/Parallel/PriorityQueueDecompositor.cpp b/src/cpu/VirtualFluidsCore/Parallel/PriorityQueueDecompositor.cpp index 4d3ad420156616cc4da094e1e500bec924bbc9b7..75c16210d87219e301d7f28b057d776010ebf9d0 100644 --- a/src/cpu/VirtualFluidsCore/Parallel/PriorityQueueDecompositor.cpp +++ b/src/cpu/VirtualFluidsCore/Parallel/PriorityQueueDecompositor.cpp @@ -1,2 +1 @@ #include "PriorityQueueDecompositor.h" - diff --git a/src/cpu/VirtualFluidsCore/Parallel/PriorityQueueDecompositor.h b/src/cpu/VirtualFluidsCore/Parallel/PriorityQueueDecompositor.h index a5234fd9583935a155711c9fbd4521713e9a98d4..b6d8d8f0ac360a4efa5b10c3e5957183682e3f58 100644 --- a/src/cpu/VirtualFluidsCore/Parallel/PriorityQueueDecompositor.h +++ b/src/cpu/VirtualFluidsCore/Parallel/PriorityQueueDecompositor.h @@ -1,66 +1,62 @@ /** -* @file PriorityQueueDecompositor.h -* @brief Priority Queue for threads decomposition. -* @author Kostyantyn Kucher -* @date 06/06/2011 -*/ + * @file PriorityQueueDecompositor.h + * @brief Priority Queue for threads decomposition. + * @author Kostyantyn Kucher + * @date 06/06/2011 + */ #ifndef PRIORITYQUEUEDECOMPOSITOR_H #define PRIORITYQUEUEDECOMPOSITOR_H #include <algorithm> -#include <vector> #include <map> +#include <vector> struct sortMinMax { - bool operator() (int i,int j) const { return (i<j);} + bool operator()(int i, int j) const { return (i < j); } }; struct sortMaxMin { - bool operator() (int i,int j) const { return (i>j);} + bool operator()(int i, int j) const { return (i > j); } }; template <class T> class PriorityQueueDecompositor { public: - PriorityQueueDecompositor(const std::vector<T>& objcts, const std::vector<int>& weights, const int& numberOfParts) - { - for (int i = 0; i < (int)objcts.size(); i++) - { - objects.insert(std::pair<int, T>(weights[i], objcts[i])); - } - for (int i = 0; i < numberOfParts; i++) - { - std::vector<T> part; - parts.insert(std::pair<int,std::vector<T> >(0, part)); - } - } - virtual ~PriorityQueueDecompositor() - = default; - void getDecomposition(std::vector< std::vector<T> >& prts) - { - for( itOb=objects.begin() ; itOb != objects.end(); itOb++) - { - itP = parts.begin(); - int weight = (*itP).first; - std::vector<T> obj = (*itP).second; - parts.erase(itP); - weight += (*itOb).first; - obj.push_back((*itOb).second); - parts.insert(std::pair<int,std::vector<T> >(weight, obj)); - } + PriorityQueueDecompositor(const std::vector<T> &objcts, const std::vector<int> &weights, const int &numberOfParts) + { + for (int i = 0; i < (int)objcts.size(); i++) { + objects.insert(std::pair<int, T>(weights[i], objcts[i])); + } + for (int i = 0; i < numberOfParts; i++) { + std::vector<T> part; + parts.insert(std::pair<int, std::vector<T>>(0, part)); + } + } + virtual ~PriorityQueueDecompositor() = default; + void getDecomposition(std::vector<std::vector<T>> &prts) + { + for (itOb = objects.begin(); itOb != objects.end(); itOb++) { + itP = parts.begin(); + int weight = (*itP).first; + std::vector<T> obj = (*itP).second; + parts.erase(itP); + weight += (*itOb).first; + obj.push_back((*itOb).second); + parts.insert(std::pair<int, std::vector<T>>(weight, obj)); + } + + for (itP = parts.begin(); itP != parts.end(); itP++) { + prts.push_back((*itP).second); + } + } - for( itP=parts.begin() ; itP != parts.end(); itP++) - { - prts.push_back((*itP).second); - } - } protected: private: - std::multimap<int, T, sortMaxMin> objects; - typename std::multimap<int, T, sortMaxMin>::iterator itOb; - std::multimap<int, std::vector<T>, sortMinMax> parts; - typename std::multimap<int, std::vector<T>, sortMinMax>::iterator itP; + std::multimap<int, T, sortMaxMin> objects; + typename std::multimap<int, T, sortMaxMin>::iterator itOb; + std::multimap<int, std::vector<T>, sortMinMax> parts; + typename std::multimap<int, std::vector<T>, sortMinMax>::iterator itP; }; #endif diff --git a/src/cpu/VirtualFluidsCore/Parallel/SimpleGeometricPartitioner.h b/src/cpu/VirtualFluidsCore/Parallel/SimpleGeometricPartitioner.h index b7b62c1ddfe438f3bc0a23d140880a80f7cee2dd..ee9e56af9f8578b5ea406a270de1cc1c9986f11e 100644 --- a/src/cpu/VirtualFluidsCore/Parallel/SimpleGeometricPartitioner.h +++ b/src/cpu/VirtualFluidsCore/Parallel/SimpleGeometricPartitioner.h @@ -1,97 +1,96 @@ /** -* @file SimpleGeometricPartitioner.h -* @author Kostyantyn Kucher -* @date 06/06/2011 -* -* @section DESCRIPTION -* -* This class make simple geometric partitioning. -*/ + * @file SimpleGeometricPartitioner.h + * @author Kostyantyn Kucher + * @date 06/06/2011 + * + * @section DESCRIPTION + * + * This class make simple geometric partitioning. + */ -#ifndef SIMPLEGEOMETRICPARTITIONER_H +#ifndef SIMPLEGEOMETRICPARTITIONER_H #define SIMPLEGEOMETRICPARTITIONER_H -#include "basics/utilities/UbTuple.h" -#include "basics/utilities/UbException.h" #include "MathUtil.hpp" +#include "basics/utilities/UbException.h" +#include "basics/utilities/UbTuple.h" class SimpleGeometricPartitioner { public: - static UbTupleInt3 createDimensions(const int& x, const int& y, const int& z, const int& numberOfProcess) - { - int xyz = x*y*z; + static UbTupleInt3 createDimensions(const int &x, const int &y, const int &z, const int &numberOfProcess) + { + int xyz = x * y * z; - int p = numberOfProcess; + int p = numberOfProcess; - if (p == 1) - return {1, 1, 1}; + if (p == 1) + return { 1, 1, 1 }; - double a = pow(p*pow(x,3.0)/xyz,1.0/3.0); - double b = pow(p*pow(y,3.0)/xyz,1.0/3.0); - double c = pow(p*pow(z,3.0)/xyz,1.0/3.0); + double a = pow(p * pow(x, 3.0) / xyz, 1.0 / 3.0); + double b = pow(p * pow(y, 3.0) / xyz, 1.0 / 3.0); + double c = pow(p * pow(z, 3.0) / xyz, 1.0 / 3.0); - MaxDim maxDim; - - if(c >= a && c >= b) - maxDim = cDim; - if(b >= a && b >= c) - maxDim = bDim; - if(a >= b && a >= c) - maxDim = aDim; + MaxDim maxDim; - int dim1, dim2, dim3; - dim1 = (int)Utilities::cint(a); - dim2 = (int)Utilities::cint(b); - dim3 = (int)Utilities::cint(c); - if(dim1 <= 0) dim1 = 1; - if(dim2 <= 0) dim2 = 1; - if(dim3 <= 0) dim3 = 1; + if (c >= a && c >= b) + maxDim = cDim; + if (b >= a && b >= c) + maxDim = bDim; + if (a >= b && a >= c) + maxDim = aDim; - switch (maxDim) - { - case aDim: - dim1 = p/(dim2*dim3); - if (dim1*dim2*dim3 != p) - { - dim2 = 1; - dim3 = 1; - dim1 = p; - } - break; - case bDim: - dim2 = p/(dim1*dim3); - if (dim1*dim2*dim3 != p) - { - dim1 = 1; - dim3 = 1; - dim2 = p; - } - break; - case cDim: - dim3 = p/(dim1*dim2); - if (dim1*dim2*dim3 != p) - { + int dim1, dim2, dim3; + dim1 = (int)Utilities::cint(a); + dim2 = (int)Utilities::cint(b); + dim3 = (int)Utilities::cint(c); + if (dim1 <= 0) dim1 = 1; + if (dim2 <= 0) dim2 = 1; - dim3 = p; - } - break; - } + if (dim3 <= 0) + dim3 = 1; + + switch (maxDim) { + case aDim: + dim1 = p / (dim2 * dim3); + if (dim1 * dim2 * dim3 != p) { + dim2 = 1; + dim3 = 1; + dim1 = p; + } + break; + case bDim: + dim2 = p / (dim1 * dim3); + if (dim1 * dim2 * dim3 != p) { + dim1 = 1; + dim3 = 1; + dim2 = p; + } + break; + case cDim: + dim3 = p / (dim1 * dim2); + if (dim1 * dim2 * dim3 != p) { + dim1 = 1; + dim2 = 1; + dim3 = p; + } + break; + } + + if (dim1 > x || dim2 > y || dim3 > z) { + UB_THROW(UbException( + UB_EXARGS, "SimpleGeometricPartitioner::createDimensions: Segmentation fault - bad number of prozess")); + } - if (dim1>x || dim2>y || dim3>z) - { - UB_THROW( UbException(UB_EXARGS,"SimpleGeometricPartitioner::createDimensions: Segmentation fault - bad number of prozess") ); - } + UbTupleInt3 dims(dim1, dim2, dim3); - UbTupleInt3 dims(dim1, dim2, dim3); - - return dims; - } + return dims; + } protected: private: - enum MaxDim {aDim,bDim,cDim}; + enum MaxDim { aDim, bDim, cDim }; }; #endif diff --git a/src/cpu/VirtualFluidsCore/Parallel/ZoltanPartitioner.cpp b/src/cpu/VirtualFluidsCore/Parallel/ZoltanPartitioner.cpp index 3aa51f0309dc382a16a165abe2061353a261f28e..220fe67c5d0c34ecb40e4066c68d84649ca0dfc1 100644 --- a/src/cpu/VirtualFluidsCore/Parallel/ZoltanPartitioner.cpp +++ b/src/cpu/VirtualFluidsCore/Parallel/ZoltanPartitioner.cpp @@ -9,196 +9,172 @@ using namespace std; ////////////////////////////////////////////////////////////////////////// -ZoltanPartitioner::ZoltanPartitioner(MPI_Comm comm, int rank, int numberOfLocalParts): - comm(comm), rank(rank), numberOfLocalParts(numberOfLocalParts),lb_approach("PARTITION") +ZoltanPartitioner::ZoltanPartitioner(MPI_Comm comm, int rank, int numberOfLocalParts) + : comm(comm), rank(rank), numberOfLocalParts(numberOfLocalParts), lb_approach("PARTITION") { - int rc; - float ver; - - rc = Zoltan_Initialize(0, NULL, &ver); - - if (rc != ZOLTAN_OK){ - cout<<"Sorry, Zoltan can't be initialized\n"<<endl; - MPI_Finalize(); - exit(0); - } - /****************************************************************** - ** Create a Zoltan library structure for this instance of load - ** balancing. Set the parameters and query functions that will - ** govern the library's calculation. See the Zoltan User's - ** Guide for the definition of these and many other parameters. - ******************************************************************/ - - zz = Zoltan_Create(comm); + int rc; + float ver; + + rc = Zoltan_Initialize(0, NULL, &ver); + + if (rc != ZOLTAN_OK) { + cout << "Sorry, Zoltan can't be initialized\n" << endl; + MPI_Finalize(); + exit(0); + } + /****************************************************************** + ** Create a Zoltan library structure for this instance of load + ** balancing. Set the parameters and query functions that will + ** govern the library's calculation. See the Zoltan User's + ** Guide for the definition of these and many other parameters. + ******************************************************************/ + + zz = Zoltan_Create(comm); } ////////////////////////////////////////////////////////////////////////// -ZoltanPartitioner::~ZoltanPartitioner() -{ - Zoltan_Destroy(&zz); -} +ZoltanPartitioner::~ZoltanPartitioner() { Zoltan_Destroy(&zz); } ////////////////////////////////////////////////////////////////////////// void ZoltanPartitioner::partition() { - //General parameters - Zoltan_Set_Param(zz, "DEBUG_LEVEL", "0"); - Zoltan_Set_Param(zz, "LB_METHOD", "GRAPH"); - Zoltan_Set_Param(zz, "LB_APPROACH", lb_approach.c_str()); - Zoltan_Set_Param(zz, "NUM_GID_ENTRIES", "1"); - Zoltan_Set_Param(zz, "NUM_LID_ENTRIES", "1"); - Zoltan_Set_Param(zz, "RETURN_LISTS", "ALL"); - string nparts(UbSystem::toString<int>(numberOfLocalParts)); - Zoltan_Set_Param(zz, "NUM_LOCAL_PARTS", nparts.c_str()); - - /* Query functions - defined in simpleQueries.h */ - - Zoltan_Set_Num_Obj_Fn(zz, get_number_of_vertices, &graph); - Zoltan_Set_Obj_List_Fn(zz, get_vertex_list, &graph); - Zoltan_Set_Num_Edges_Multi_Fn(zz, get_num_edges_list, &graph); - Zoltan_Set_Edge_List_Multi_Fn(zz, get_edge_list, &graph); - - /****************************************************************** - ** Zoltan can now partition the graph. - ** In this case, we assume the number of partitions is - ** equal to the number of processes. Process rank 0 will own - ** partition 0, process rank 1 will own partition 1, and so on. - ******************************************************************/ - - int rc = Zoltan_LB_Partition(zz, /* input (all remaining fields are output) */ - &changes, /* 1 if partitioning was changed, 0 otherwise */ - &numGidEntries, /* Number of integers used for a global ID */ - &numLidEntries, /* Number of integers used for a local ID */ - &numImport, /* Number of vertices to be sent to me */ - &importGlobalGids, /* Global IDs of vertices to be sent to me */ - &importLocalGids, /* Local IDs of vertices to be sent to me */ - &importProcs, /* Process rank for source of each incoming vertex */ - &importToPart, /* New partition for each incoming vertex */ - &numExport, /* Number of vertices I must send to other processes*/ - &exportGlobalGids, /* Global IDs of the vertices I must send */ - &exportLocalGids, /* Local IDs of the vertices I must send */ - &exportProcs, /* Process to which I send each of the vertices */ - &exportToPart); /* Partition to which each vertex will belong */ - - - - if (rc != ZOLTAN_OK){ - cout << "Partitioning failed on process " << rank <<"\n" << endl; - MPI_Finalize(); - Zoltan_Destroy(&zz); - exit(0); - } + // General parameters + Zoltan_Set_Param(zz, "DEBUG_LEVEL", "0"); + Zoltan_Set_Param(zz, "LB_METHOD", "GRAPH"); + Zoltan_Set_Param(zz, "LB_APPROACH", lb_approach.c_str()); + Zoltan_Set_Param(zz, "NUM_GID_ENTRIES", "1"); + Zoltan_Set_Param(zz, "NUM_LID_ENTRIES", "1"); + Zoltan_Set_Param(zz, "RETURN_LISTS", "ALL"); + string nparts(UbSystem::toString<int>(numberOfLocalParts)); + Zoltan_Set_Param(zz, "NUM_LOCAL_PARTS", nparts.c_str()); + + /* Query functions - defined in simpleQueries.h */ + + Zoltan_Set_Num_Obj_Fn(zz, get_number_of_vertices, &graph); + Zoltan_Set_Obj_List_Fn(zz, get_vertex_list, &graph); + Zoltan_Set_Num_Edges_Multi_Fn(zz, get_num_edges_list, &graph); + Zoltan_Set_Edge_List_Multi_Fn(zz, get_edge_list, &graph); + + /****************************************************************** + ** Zoltan can now partition the graph. + ** In this case, we assume the number of partitions is + ** equal to the number of processes. Process rank 0 will own + ** partition 0, process rank 1 will own partition 1, and so on. + ******************************************************************/ + + int rc = Zoltan_LB_Partition(zz, /* input (all remaining fields are output) */ + &changes, /* 1 if partitioning was changed, 0 otherwise */ + &numGidEntries, /* Number of integers used for a global ID */ + &numLidEntries, /* Number of integers used for a local ID */ + &numImport, /* Number of vertices to be sent to me */ + &importGlobalGids, /* Global IDs of vertices to be sent to me */ + &importLocalGids, /* Local IDs of vertices to be sent to me */ + &importProcs, /* Process rank for source of each incoming vertex */ + &importToPart, /* New partition for each incoming vertex */ + &numExport, /* Number of vertices I must send to other processes*/ + &exportGlobalGids, /* Global IDs of the vertices I must send */ + &exportLocalGids, /* Local IDs of the vertices I must send */ + &exportProcs, /* Process to which I send each of the vertices */ + &exportToPart); /* Partition to which each vertex will belong */ + + if (rc != ZOLTAN_OK) { + cout << "Partitioning failed on process " << rank << "\n" << endl; + MPI_Finalize(); + Zoltan_Destroy(&zz); + exit(0); + } } ////////////////////////////////////////////////////////////////////////// -void ZoltanPartitioner::setLB_APPROACH(std::string lb_approach) -{ - this->lb_approach = lb_approach; -} +void ZoltanPartitioner::setLB_APPROACH(std::string lb_approach) { this->lb_approach = lb_approach; } ////////////////////////////////////////////////////////////////////////// -void ZoltanPartitioner::setNumberOfLocalParts(int numberOfLocalParts) -{ - this->numberOfLocalParts = numberOfLocalParts; -} +void ZoltanPartitioner::setNumberOfLocalParts(int numberOfLocalParts) { this->numberOfLocalParts = numberOfLocalParts; } ////////////////////////////////////////////////////////////////////////// // Application defined query functions // ////////////////////////////////////////////////////////////////////////// int ZoltanPartitioner::get_number_of_vertices(void *data, int *ierr) { - ZoltanGraph *graph = (ZoltanGraph *)data; - *ierr = ZOLTAN_OK; - return graph->numLocalVertices; + ZoltanGraph *graph = (ZoltanGraph *)data; + *ierr = ZOLTAN_OK; + return graph->numLocalVertices; } ////////////////////////////////////////////////////////////////////////// -void ZoltanPartitioner::get_vertex_list(void *data, int sizeGID, int sizeLID, - ZOLTAN_ID_PTR globalID, ZOLTAN_ID_PTR localID, - int wgt_dim, float *obj_wgts, int *ierr) +void ZoltanPartitioner::get_vertex_list(void *data, int sizeGID, int sizeLID, ZOLTAN_ID_PTR globalID, + ZOLTAN_ID_PTR localID, int wgt_dim, float *obj_wgts, int *ierr) { - ZoltanGraph *graph = (ZoltanGraph *)data; - *ierr = ZOLTAN_OK; + ZoltanGraph *graph = (ZoltanGraph *)data; + *ierr = ZOLTAN_OK; - /* In this case, return the IDs of our vertices, but no weights. - * Zoltan will assume equally weighted vertices. - */ + /* In this case, return the IDs of our vertices, but no weights. + * Zoltan will assume equally weighted vertices. + */ - for (int i=0; i<graph->numLocalVertices; i++){ - globalID[i] = graph->vvertexGID[i]; - localID[i] = i; - } + for (int i = 0; i < graph->numLocalVertices; i++) { + globalID[i] = graph->vvertexGID[i]; + localID[i] = i; + } } ////////////////////////////////////////////////////////////////////////// -void ZoltanPartitioner::get_num_edges_list(void *data, int sizeGID, int sizeLID, - int num_obj, - ZOLTAN_ID_PTR globalID, ZOLTAN_ID_PTR localID, - int *numEdges, int *ierr) +void ZoltanPartitioner::get_num_edges_list(void *data, int sizeGID, int sizeLID, int num_obj, ZOLTAN_ID_PTR globalID, + ZOLTAN_ID_PTR localID, int *numEdges, int *ierr) { - ZoltanGraph *graph = (ZoltanGraph *)data; + ZoltanGraph *graph = (ZoltanGraph *)data; - if ( (sizeGID != 1) || (sizeLID != 1) || (num_obj != graph->numLocalVertices)){ - *ierr = ZOLTAN_FATAL; - return; - } + if ((sizeGID != 1) || (sizeLID != 1) || (num_obj != graph->numLocalVertices)) { + *ierr = ZOLTAN_FATAL; + return; + } - for (int i=0; i < num_obj ; i++){ - numEdges[i] = graph->vnumEdges[i]; - } + for (int i = 0; i < num_obj; i++) { + numEdges[i] = graph->vnumEdges[i]; + } - *ierr = ZOLTAN_OK; - return; + *ierr = ZOLTAN_OK; + return; } ////////////////////////////////////////////////////////////////////////// -void ZoltanPartitioner::get_edge_list(void *data, int sizeGID, int sizeLID, - int num_obj, ZOLTAN_ID_PTR globalID, ZOLTAN_ID_PTR localID, - int *num_edges, - ZOLTAN_ID_PTR nborGID, int *nborProc, +void ZoltanPartitioner::get_edge_list(void *data, int sizeGID, int sizeLID, int num_obj, ZOLTAN_ID_PTR globalID, + ZOLTAN_ID_PTR localID, int *num_edges, ZOLTAN_ID_PTR nborGID, int *nborProc, int wgt_dim, float *ewgts, int *ierr) { - int *nextNbor, *nextProc; - - ZoltanGraph *graph = (ZoltanGraph *)data; - *ierr = ZOLTAN_OK; - - if ( (sizeGID != 1) || (sizeLID != 1) || - (num_obj != graph->numLocalVertices)|| - (wgt_dim != 0)){ - *ierr = ZOLTAN_FATAL; - return; - } - - nextNbor = (int *)nborGID; - nextProc = nborProc; - - int n=0; - for (int i=0; i < num_obj; i++){ - - /* - * In this case, we are not setting edge weights. Zoltan will - * set each edge to weight 1.0. - */ - - for (int j=0; j < num_edges[i]; j++){ - nborGID[n] = graph->vnborGID[n]; - nborProc[n] = graph->vnborProc[n]; - n++; - } - } - return; + int *nextNbor, *nextProc; + + ZoltanGraph *graph = (ZoltanGraph *)data; + *ierr = ZOLTAN_OK; + + if ((sizeGID != 1) || (sizeLID != 1) || (num_obj != graph->numLocalVertices) || (wgt_dim != 0)) { + *ierr = ZOLTAN_FATAL; + return; + } + + nextNbor = (int *)nborGID; + nextProc = nborProc; + + int n = 0; + for (int i = 0; i < num_obj; i++) { + + /* + * In this case, we are not setting edge weights. Zoltan will + * set each edge to weight 1.0. + */ + + for (int j = 0; j < num_edges[i]; j++) { + nborGID[n] = graph->vnborGID[n]; + nborProc[n] = graph->vnborProc[n]; + n++; + } + } + return; } ////////////////////////////////////////////////////////////////////////// -ZoltanGraph* ZoltanPartitioner::getGraphData() -{ - return &graph; -} +ZoltanGraph *ZoltanPartitioner::getGraphData() { return &graph; } ////////////////////////////////////////////////////////////////////////// -void ZoltanPartitioner::getExportData(vector<int>& exportGlobalGids, vector<int>& exportToPart, vector<int>& exportProcs) +void ZoltanPartitioner::getExportData(vector<int> &exportGlobalGids, vector<int> &exportToPart, + vector<int> &exportProcs) { - for (int i = 0; i < this->numExport; i++) - { - exportGlobalGids.push_back(static_cast<int> (this->exportGlobalGids[i])); - exportToPart.push_back(this->exportToPart[i]); - exportProcs.push_back(this->exportProcs[i]); - } + for (int i = 0; i < this->numExport; i++) { + exportGlobalGids.push_back(static_cast<int>(this->exportGlobalGids[i])); + exportToPart.push_back(this->exportToPart[i]); + exportProcs.push_back(this->exportProcs[i]); + } } ////////////////////////////////////////////////////////////////////////// - bool ZoltanPartitioner::areChanges() - { - return static_cast<bool>(this->changes); - } +bool ZoltanPartitioner::areChanges() { return static_cast<bool>(this->changes); } #endif diff --git a/src/cpu/VirtualFluidsCore/Parallel/ZoltanPartitioner.h b/src/cpu/VirtualFluidsCore/Parallel/ZoltanPartitioner.h index 2bfea8877252c4aa07f33f6e771ddefdf4f48d14..402e6b9603ff38a8236579f132f74fbf0a43c9e1 100644 --- a/src/cpu/VirtualFluidsCore/Parallel/ZoltanPartitioner.h +++ b/src/cpu/VirtualFluidsCore/Parallel/ZoltanPartitioner.h @@ -1,9 +1,9 @@ /** -* @file ZoltanPartitioner.h -* @brief Class use Zoltan library for graph-based partitioning. -* @author Kostyantyn Kucher -* @date 10.06.2011 -*/ + * @file ZoltanPartitioner.h + * @brief Class use Zoltan library for graph-based partitioning. + * @author Kostyantyn Kucher + * @date 10.06.2011 + */ #ifndef ZOLTANPARTITIONER_H #define ZOLTANPARTITIONER_H @@ -11,64 +11,60 @@ #if defined VF_ZOLTAN && defined VF_MPI #include "zoltan.h" -#include <vector> #include <string> +#include <vector> /* Structure to hold graph data */ -struct ZoltanGraph{ - int numLocalVertices; // total vertices in in this partition - std::vector<int> vvertexGID; // global ID of each of my vertices - std::vector<int> vnumEdges; // number of Edges - std::vector<int> vnborGID; // global ID of neighbors - std::vector<int> vnborProc; // process owning each nbor in nborGID +struct ZoltanGraph { + int numLocalVertices; // total vertices in in this partition + std::vector<int> vvertexGID; // global ID of each of my vertices + std::vector<int> vnumEdges; // number of Edges + std::vector<int> vnborGID; // global ID of neighbors + std::vector<int> vnborProc; // process owning each nbor in nborGID }; -struct Zoltan_Output{ - ZOLTAN_ID_PTR importGlobalGids, importLocalGids, exportGlobalGids, exportLocalGids; - int *importProcs, *importToPart, *exportProcs, *exportToPart; - int changes, numGidEntries, numLidEntries, numImport, numExport; +struct Zoltan_Output { + ZOLTAN_ID_PTR importGlobalGids, importLocalGids, exportGlobalGids, exportLocalGids; + int *importProcs, *importToPart, *exportProcs, *exportToPart; + int changes, numGidEntries, numLidEntries, numImport, numExport; }; class ZoltanPartitioner { public: - ZoltanPartitioner(MPI_Comm comm , int rank, int numberOfLocalParts); - virtual ~ZoltanPartitioner(); - void partition(); - ZoltanGraph* getGraphData(); - void setLB_APPROACH(std::string lb_approach); - void setNumberOfLocalParts(int numberOfLocalParts); - void getExportData(std::vector<int>& exportGlobalGids, std::vector<int>& exportToPart, std::vector<int>& exportProcs); - bool areChanges(); + ZoltanPartitioner(MPI_Comm comm, int rank, int numberOfLocalParts); + virtual ~ZoltanPartitioner(); + void partition(); + ZoltanGraph *getGraphData(); + void setLB_APPROACH(std::string lb_approach); + void setNumberOfLocalParts(int numberOfLocalParts); + void getExportData(std::vector<int> &exportGlobalGids, std::vector<int> &exportToPart, + std::vector<int> &exportProcs); + bool areChanges(); protected: - static int get_number_of_vertices(void *data, int *ierr); - static void get_vertex_list(void *data, int sizeGID, int sizeLID, - ZOLTAN_ID_PTR globalID, ZOLTAN_ID_PTR localID, - int wgt_dim, float *obj_wgts, int *ierr); - static void get_num_edges_list(void *data, int sizeGID, int sizeLID, - int num_obj, - ZOLTAN_ID_PTR globalID, ZOLTAN_ID_PTR localID, - int *numEdges, int *ierr); - static void get_edge_list(void *data, int sizeGID, int sizeLID, - int num_obj, ZOLTAN_ID_PTR globalID, ZOLTAN_ID_PTR localID, - int *num_edges, - ZOLTAN_ID_PTR nborGID, int *nborProc, - int wgt_dim, float *ewgts, int *ierr); + static int get_number_of_vertices(void *data, int *ierr); + static void get_vertex_list(void *data, int sizeGID, int sizeLID, ZOLTAN_ID_PTR globalID, ZOLTAN_ID_PTR localID, + int wgt_dim, float *obj_wgts, int *ierr); + static void get_num_edges_list(void *data, int sizeGID, int sizeLID, int num_obj, ZOLTAN_ID_PTR globalID, + ZOLTAN_ID_PTR localID, int *numEdges, int *ierr); + static void get_edge_list(void *data, int sizeGID, int sizeLID, int num_obj, ZOLTAN_ID_PTR globalID, + ZOLTAN_ID_PTR localID, int *num_edges, ZOLTAN_ID_PTR nborGID, int *nborProc, int wgt_dim, + float *ewgts, int *ierr); private: - MPI_Comm comm; - int rank; - int numberOfLocalParts; - struct Zoltan_Struct *zz; - std::string lb_approach; - ZOLTAN_ID_PTR importGlobalGids, importLocalGids, exportGlobalGids, exportLocalGids; - int *importProcs, *importToPart, *exportProcs, *exportToPart; - int changes, numGidEntries, numLidEntries, numImport, numExport; - ZoltanGraph graph; + MPI_Comm comm; + int rank; + int numberOfLocalParts; + struct Zoltan_Struct *zz; + std::string lb_approach; + ZOLTAN_ID_PTR importGlobalGids, importLocalGids, exportGlobalGids, exportLocalGids; + int *importProcs, *importToPart, *exportProcs, *exportToPart; + int changes, numGidEntries, numLidEntries, numImport, numExport; + ZoltanGraph graph; }; #endif -#endif +#endif diff --git a/src/cpu/VirtualFluidsCore/Utilities/CheckpointConverter.cpp b/src/cpu/VirtualFluidsCore/Utilities/CheckpointConverter.cpp index fe58829b18d462d63dfd52b48ec0fe3046e2a019..914659afa685814842904e9622c31b875d6a2207 100644 --- a/src/cpu/VirtualFluidsCore/Utilities/CheckpointConverter.cpp +++ b/src/cpu/VirtualFluidsCore/Utilities/CheckpointConverter.cpp @@ -1,595 +1,650 @@ #include "CheckpointConverter.h" -#include <MemoryUtil.h> -#include "BoundaryConditions.h" #include "Block3D.h" -#include "DataSet3D.h" -#include "Grid3D.h" +#include "BoundaryConditions.h" #include "Communicator.h" #include "CoordinateTransformation3D.h" +#include "DataSet3D.h" +#include "Grid3D.h" +#include <MemoryUtil.h> #include <cstdio> #define BLOCK_SIZE 1024 using namespace MPIIODataStructures; -CheckpointConverter::CheckpointConverter(SPtr<Grid3D> grid, const std::string& path, SPtr<Communicator> comm) : - grid(grid), path(path), comm(comm) +CheckpointConverter::CheckpointConverter(SPtr<Grid3D> grid, const std::string &path, SPtr<Communicator> comm) + : grid(grid), path(path), comm(comm) { - UbSystem::makeDirectory(path + "/mpi_io_cp"); - - memset(&boundCondParamStr, 0, sizeof(boundCondParamStr)); + UbSystem::makeDirectory(path + "/mpi_io_cp"); - //------------------------- define MPI types --------------------------------- + memset(&boundCondParamStr, 0, sizeof(boundCondParamStr)); - MPI_Datatype typesGP[3] = { MPI_DOUBLE, MPI_INT, MPI_CHAR }; - int blocksGP[3] = { 34, 6, 5 }; - MPI_Aint offsetsGP[3], lbGP, extentGP; + //------------------------- define MPI types --------------------------------- - offsetsGP[0] = 0; - MPI_Type_get_extent(MPI_DOUBLE, &lbGP, &extentGP); - offsetsGP[1] = blocksGP[0] * extentGP; + MPI_Datatype typesGP[3] = { MPI_DOUBLE, MPI_INT, MPI_CHAR }; + int blocksGP[3] = { 34, 6, 5 }; + MPI_Aint offsetsGP[3], lbGP, extentGP; - MPI_Type_get_extent(MPI_INT, &lbGP, &extentGP); - offsetsGP[2] = offsetsGP[1] + blocksGP[1] * extentGP; + offsetsGP[0] = 0; + MPI_Type_get_extent(MPI_DOUBLE, &lbGP, &extentGP); + offsetsGP[1] = blocksGP[0] * extentGP; - MPI_Type_create_struct(3, blocksGP, offsetsGP, typesGP, &gridParamType); - MPI_Type_commit(&gridParamType); + MPI_Type_get_extent(MPI_INT, &lbGP, &extentGP); + offsetsGP[2] = offsetsGP[1] + blocksGP[1] * extentGP; - //----------------------------------------------------------------------- + MPI_Type_create_struct(3, blocksGP, offsetsGP, typesGP, &gridParamType); + MPI_Type_commit(&gridParamType); - MPI_Datatype typesBlock[2] = { MPI_INT, MPI_CHAR }; - int blocksBlock[2] = { 13, 1 }; - MPI_Aint offsetsBlock[2], lbBlock, extentBlock; + //----------------------------------------------------------------------- - offsetsBlock[0] = 0; - MPI_Type_get_extent(MPI_INT, &lbBlock, &extentBlock); - offsetsBlock[1] = blocksBlock[0] * extentBlock; + MPI_Datatype typesBlock[2] = { MPI_INT, MPI_CHAR }; + int blocksBlock[2] = { 13, 1 }; + MPI_Aint offsetsBlock[2], lbBlock, extentBlock; - MPI_Type_create_struct(2, blocksBlock, offsetsBlock, typesBlock, &block3dType); - MPI_Type_commit(&block3dType); + offsetsBlock[0] = 0; + MPI_Type_get_extent(MPI_INT, &lbBlock, &extentBlock); + offsetsBlock[1] = blocksBlock[0] * extentBlock; - //----------------------------------------------------------------------- + MPI_Type_create_struct(2, blocksBlock, offsetsBlock, typesBlock, &block3dType); + MPI_Type_commit(&block3dType); - MPI_Datatype typesBC[3] = { MPI_LONG_LONG_INT, MPI_FLOAT, MPI_CHAR }; - int blocksBC[3] = { 5, 38, 1 }; - MPI_Aint offsetsBC[3], lbBC, extentBC; + //----------------------------------------------------------------------- - offsetsBC[0] = 0; - MPI_Type_get_extent(MPI_LONG_LONG_INT, &lbBC, &extentBC); - offsetsBC[1] = blocksBC[0] * extentBC; + MPI_Datatype typesBC[3] = { MPI_LONG_LONG_INT, MPI_FLOAT, MPI_CHAR }; + int blocksBC[3] = { 5, 38, 1 }; + MPI_Aint offsetsBC[3], lbBC, extentBC; - MPI_Type_get_extent(MPI_FLOAT, &lbBC, &extentBC); - offsetsBC[2] = offsetsBC[1] + blocksBC[1] * extentBC; + offsetsBC[0] = 0; + MPI_Type_get_extent(MPI_LONG_LONG_INT, &lbBC, &extentBC); + offsetsBC[1] = blocksBC[0] * extentBC; - MPI_Type_create_struct(3, blocksBC, offsetsBC, typesBC, &boundCondType); - MPI_Type_commit(&boundCondType); + MPI_Type_get_extent(MPI_FLOAT, &lbBC, &extentBC); + offsetsBC[2] = offsetsBC[1] + blocksBC[1] * extentBC; - //----------------------------------------------------------------------- + MPI_Type_create_struct(3, blocksBC, offsetsBC, typesBC, &boundCondType); + MPI_Type_commit(&boundCondType); - MPI_Type_contiguous(BLOCK_SIZE, boundCondType, &boundCondType1000); - MPI_Type_commit(&boundCondType1000); + //----------------------------------------------------------------------- - //--------------------------------------- + MPI_Type_contiguous(BLOCK_SIZE, boundCondType, &boundCondType1000); + MPI_Type_commit(&boundCondType1000); - MPI_Type_contiguous(7, MPI_INT, &dataSetParamType); - MPI_Type_commit(&dataSetParamType); + //--------------------------------------- - //--------------------------------------- + MPI_Type_contiguous(7, MPI_INT, &dataSetParamType); + MPI_Type_commit(&dataSetParamType); - MPI_Datatype typesDataSetRead[3] = { MPI_DOUBLE, MPI_INT, MPI_CHAR }; - int blocksDataSetRead[3] = { 2, 5, 2 }; - MPI_Aint offsetsDataSetRead[3], lbDataSetRead, extentDataSetRead; + //--------------------------------------- - offsetsDataSetRead[0] = 0; - MPI_Type_get_extent(MPI_DOUBLE, &lbDataSetRead, &extentDataSetRead); - offsetsDataSetRead[1] = blocksDataSetRead[0] * extentDataSetRead; + MPI_Datatype typesDataSetRead[3] = { MPI_DOUBLE, MPI_INT, MPI_CHAR }; + int blocksDataSetRead[3] = { 2, 5, 2 }; + MPI_Aint offsetsDataSetRead[3], lbDataSetRead, extentDataSetRead; - MPI_Type_get_extent(MPI_INT, &lbDataSetRead, &extentDataSetRead); - offsetsDataSetRead[2] = offsetsDataSetRead[1] + blocksDataSetRead[1] * extentDataSetRead; + offsetsDataSetRead[0] = 0; + MPI_Type_get_extent(MPI_DOUBLE, &lbDataSetRead, &extentDataSetRead); + offsetsDataSetRead[1] = blocksDataSetRead[0] * extentDataSetRead; - MPI_Type_create_struct(3, blocksDataSetRead, offsetsDataSetRead, typesDataSetRead, &dataSetTypeRead); - MPI_Type_commit(&dataSetTypeRead); + MPI_Type_get_extent(MPI_INT, &lbDataSetRead, &extentDataSetRead); + offsetsDataSetRead[2] = offsetsDataSetRead[1] + blocksDataSetRead[1] * extentDataSetRead; - //----------------------------------------------------------------------- + MPI_Type_create_struct(3, blocksDataSetRead, offsetsDataSetRead, typesDataSetRead, &dataSetTypeRead); + MPI_Type_commit(&dataSetTypeRead); - MPI_Datatype typesDataSetWrite[3] = { MPI_DOUBLE, MPI_INT, MPI_CHAR }; - int blocksDataSetWrite[3] = { 2, 2, 2 }; - MPI_Aint offsetsDataSetWrite[3], lbDataSetWrite, extentDataSetWrite; + //----------------------------------------------------------------------- - offsetsDataSetWrite[0] = 0; - MPI_Type_get_extent(MPI_DOUBLE, &lbDataSetWrite, &extentDataSetWrite); - offsetsDataSetWrite[1] = blocksDataSetWrite[0] * extentDataSetWrite; + MPI_Datatype typesDataSetWrite[3] = { MPI_DOUBLE, MPI_INT, MPI_CHAR }; + int blocksDataSetWrite[3] = { 2, 2, 2 }; + MPI_Aint offsetsDataSetWrite[3], lbDataSetWrite, extentDataSetWrite; - MPI_Type_get_extent(MPI_INT, &lbDataSetWrite, &extentDataSetWrite); - offsetsDataSetWrite[2] = offsetsDataSetWrite[1] + blocksDataSetWrite[1] * extentDataSetWrite; + offsetsDataSetWrite[0] = 0; + MPI_Type_get_extent(MPI_DOUBLE, &lbDataSetWrite, &extentDataSetWrite); + offsetsDataSetWrite[1] = blocksDataSetWrite[0] * extentDataSetWrite; - MPI_Type_create_struct(3, blocksDataSetWrite, offsetsDataSetWrite, typesDataSetWrite, &dataSetTypeWrite); - MPI_Type_commit(&dataSetTypeWrite); + MPI_Type_get_extent(MPI_INT, &lbDataSetWrite, &extentDataSetWrite); + offsetsDataSetWrite[2] = offsetsDataSetWrite[1] + blocksDataSetWrite[1] * extentDataSetWrite; + MPI_Type_create_struct(3, blocksDataSetWrite, offsetsDataSetWrite, typesDataSetWrite, &dataSetTypeWrite); + MPI_Type_commit(&dataSetTypeWrite); } ////////////////////////////////////////////////////////////////////////// CheckpointConverter::~CheckpointConverter() { - MPI_Type_free(&gridParamType); - MPI_Type_free(&block3dType); - MPI_Type_free(&boundCondType); - MPI_Type_free(&dataSetParamType); - MPI_Type_free(&dataSetTypeRead); - MPI_Type_free(&dataSetTypeWrite); - MPI_Type_free(&boundCondType1000); + MPI_Type_free(&gridParamType); + MPI_Type_free(&block3dType); + MPI_Type_free(&boundCondType); + MPI_Type_free(&dataSetParamType); + MPI_Type_free(&dataSetTypeRead); + MPI_Type_free(&dataSetTypeWrite); + MPI_Type_free(&boundCondType1000); } //------------------------------------------- READ ----------------------------------------------- void CheckpointConverter::convert(int step, int procCount) { - UBLOG(logINFO, "UtilConvertor::convert start "); + UBLOG(logINFO, "UtilConvertor::convert start "); + + convertBlocks(step, procCount); + convertDataSet(step, procCount); + convertBC(step, procCount); - convertBlocks(step, procCount); - convertDataSet(step, procCount); - convertBC(step, procCount); - - UBLOG(logINFO, "UtilConvertor::convert finish "); + UBLOG(logINFO, "UtilConvertor::convert finish "); } void CheckpointConverter::convertBlocks(int step, int procCount) { - double start, finish; - start = MPI_Wtime(); - - // file to read from - MPI_File file_handlerR; - std::string filenameR = path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + "/cpBlocks.bin"; - int rcR = MPI_File_open(MPI_COMM_WORLD, filenameR.c_str(), MPI_MODE_RDONLY, MPI_INFO_NULL, &file_handlerR); - if (rcR != MPI_SUCCESS) throw UbException(UB_EXARGS, "couldn't open file " + filenameR); - - // file to write to - MPI_File file_handlerW; - UbSystem::makeDirectory(path + "/mig/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step)); - std::string filenameW = path + "/mig/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + "/cpBlocks.bin"; - int rcW = MPI_File_open(MPI_COMM_WORLD, filenameW.c_str(), MPI_MODE_CREATE | MPI_MODE_WRONLY, MPI_INFO_NULL, &file_handlerW); - if (rcW != MPI_SUCCESS) throw UbException(UB_EXARGS, "couldn't open file " + filenameW); - - // read count of blocks - int blocksCount = 0; - MPI_File_read_at(file_handlerR, 0, &blocksCount, 1, MPI_INT, MPI_STATUS_IGNORE); - Block3d* block3dArray = new Block3d[blocksCount]; - GridParam* gridParameters = new GridParam; - - // calculate the read offset - procCount = 1; // readBlocks and writeBlocks in both MPIIORestartCoProcessor and MPIIOMigrationCoProcessor have size == 1! - MPI_Offset read_offset = (MPI_Offset)(procCount * sizeof(int)); - - // read parameters of the grid and blocks - MPI_File_read_at(file_handlerR, read_offset, gridParameters, 1, gridParamType, MPI_STATUS_IGNORE); - MPI_File_read_at(file_handlerR, (MPI_Offset)(read_offset + sizeof(GridParam)), &block3dArray[0], blocksCount, block3dType, MPI_STATUS_IGNORE); - - // clear the grid - std::vector<SPtr<Block3D>> blocksVector[25]; - int minInitLevel = this->grid->getCoarsestInitializedLevel(); - if (minInitLevel > -1) - { - int maxInitLevel = this->grid->getFinestInitializedLevel(); - for (int level = minInitLevel; level <= maxInitLevel; level++) - { - grid->getBlocks(level, blocksVector[level]); - for (SPtr<Block3D> block : blocksVector[level]) // blocks of the current level - grid->deleteBlock(block); - } - } - - // restore the grid - SPtr<CoordinateTransformation3D> trafo(new CoordinateTransformation3D()); - trafo->Tx1 = gridParameters->trafoParams[0]; - trafo->Tx2 = gridParameters->trafoParams[1]; - trafo->Tx3 = gridParameters->trafoParams[2]; - trafo->Sx1 = gridParameters->trafoParams[3]; - trafo->Sx2 = gridParameters->trafoParams[4]; - trafo->Sx3 = gridParameters->trafoParams[5]; - trafo->alpha = gridParameters->trafoParams[6]; - trafo->beta = gridParameters->trafoParams[7]; - trafo->gamma = gridParameters->trafoParams[8]; - - trafo->toX1factorX1 = gridParameters->trafoParams[9]; - trafo->toX1factorX2 = gridParameters->trafoParams[10]; - trafo->toX1factorX3 = gridParameters->trafoParams[11]; - trafo->toX1delta = gridParameters->trafoParams[12]; - trafo->toX2factorX1 = gridParameters->trafoParams[13]; - trafo->toX2factorX2 = gridParameters->trafoParams[14]; - trafo->toX2factorX3 = gridParameters->trafoParams[15]; - trafo->toX2delta = gridParameters->trafoParams[16]; - trafo->toX3factorX1 = gridParameters->trafoParams[17]; - trafo->toX3factorX2 = gridParameters->trafoParams[18]; - trafo->toX3factorX3 = gridParameters->trafoParams[19]; - trafo->toX3delta = gridParameters->trafoParams[20]; - - trafo->fromX1factorX1 = gridParameters->trafoParams[21]; - trafo->fromX1factorX2 = gridParameters->trafoParams[22]; - trafo->fromX1factorX3 = gridParameters->trafoParams[23]; - trafo->fromX1delta = gridParameters->trafoParams[24]; - trafo->fromX2factorX1 = gridParameters->trafoParams[25]; - trafo->fromX2factorX2 = gridParameters->trafoParams[26]; - trafo->fromX2factorX3 = gridParameters->trafoParams[27]; - trafo->fromX2delta = gridParameters->trafoParams[28]; - trafo->fromX3factorX1 = gridParameters->trafoParams[29]; - trafo->fromX3factorX2 = gridParameters->trafoParams[30]; - trafo->fromX3factorX3 = gridParameters->trafoParams[31]; - trafo->fromX3delta = gridParameters->trafoParams[32]; - - trafo->active = gridParameters->active; - trafo->transformation = gridParameters->transformation; - - grid->setCoordinateTransformator(trafo); - - grid->setDeltaX(gridParameters->deltaX); - grid->setBlockNX(gridParameters->blockNx1, gridParameters->blockNx2, gridParameters->blockNx3); - grid->setNX1(gridParameters->nx1); - grid->setNX2(gridParameters->nx2); - grid->setNX3(gridParameters->nx3); - grid->setPeriodicX1(gridParameters->periodicX1); - grid->setPeriodicX2(gridParameters->periodicX2); - grid->setPeriodicX3(gridParameters->periodicX3); - - // regenerate blocks - for (int n = 0; n < blocksCount; n++) - { - SPtr<Block3D> block(new Block3D(block3dArray[n].x1, block3dArray[n].x2, block3dArray[n].x3, block3dArray[n].level)); - block->setActive(block3dArray[n].active); - block->setBundle(block3dArray[n].bundle); - block->setRank(block3dArray[n].rank); - block->setLocalRank(block3dArray[n].lrank); - block->setGlobalID(block3dArray[n].globalID); - block->setLocalID(block3dArray[n].localID); - block->setPart(block3dArray[n].part); - block->setLevel(block3dArray[n].level); - block->setCollectionOfInterpolationFlagCF(block3dArray[n].interpolationFlagCF); - block->setCollectionOfInterpolationFlagFC(block3dArray[n].interpolationFlagFC); - - grid->addBlock(block); - } - - // renumber blocks - grid->renumberBlockIDs(); - - // refresh globalID in all the blocks - SPtr<Block3D> block; - for (int n = 0; n < blocksCount; n++) - { - block = grid->getBlock(block3dArray[n].x1, block3dArray[n].x2, block3dArray[n].x3, block3dArray[n].level); - block3dArray[n].globalID = block->getGlobalID(); - } - - // write all data to the file - MPI_Offset write_offset = read_offset; - - MPI_File_write_at(file_handlerW, 0, &blocksCount, 1, MPI_INT, MPI_STATUS_IGNORE); - MPI_File_write_at(file_handlerW, write_offset, gridParameters, 1, gridParamType, MPI_STATUS_IGNORE); - MPI_File_write_at(file_handlerW, (MPI_Offset)(write_offset + sizeof(GridParam)), &block3dArray[0], blocksCount, block3dType, MPI_STATUS_IGNORE); - - MPI_File_close(&file_handlerR); - MPI_File_close(&file_handlerW); - - finish = MPI_Wtime(); - UBLOG(logINFO, "UtilConvertor::convertBlocks time: " << finish - start << " s"); - - delete gridParameters; - delete[] block3dArray; + double start, finish; + start = MPI_Wtime(); + + // file to read from + MPI_File file_handlerR; + std::string filenameR = path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + "/cpBlocks.bin"; + int rcR = MPI_File_open(MPI_COMM_WORLD, filenameR.c_str(), MPI_MODE_RDONLY, MPI_INFO_NULL, &file_handlerR); + if (rcR != MPI_SUCCESS) + throw UbException(UB_EXARGS, "couldn't open file " + filenameR); + + // file to write to + MPI_File file_handlerW; + UbSystem::makeDirectory(path + "/mig/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step)); + std::string filenameW = path + "/mig/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + "/cpBlocks.bin"; + int rcW = MPI_File_open(MPI_COMM_WORLD, filenameW.c_str(), MPI_MODE_CREATE | MPI_MODE_WRONLY, MPI_INFO_NULL, + &file_handlerW); + if (rcW != MPI_SUCCESS) + throw UbException(UB_EXARGS, "couldn't open file " + filenameW); + + // read count of blocks + int blocksCount = 0; + MPI_File_read_at(file_handlerR, 0, &blocksCount, 1, MPI_INT, MPI_STATUS_IGNORE); + Block3d *block3dArray = new Block3d[blocksCount]; + GridParam *gridParameters = new GridParam; + + // calculate the read offset + procCount = + 1; // readBlocks and writeBlocks in both MPIIORestartCoProcessor and MPIIOMigrationCoProcessor have size == 1! + MPI_Offset read_offset = (MPI_Offset)(procCount * sizeof(int)); + + // read parameters of the grid and blocks + MPI_File_read_at(file_handlerR, read_offset, gridParameters, 1, gridParamType, MPI_STATUS_IGNORE); + MPI_File_read_at(file_handlerR, (MPI_Offset)(read_offset + sizeof(GridParam)), &block3dArray[0], blocksCount, + block3dType, MPI_STATUS_IGNORE); + + // clear the grid + std::vector<SPtr<Block3D>> blocksVector[25]; + int minInitLevel = this->grid->getCoarsestInitializedLevel(); + if (minInitLevel > -1) { + int maxInitLevel = this->grid->getFinestInitializedLevel(); + for (int level = minInitLevel; level <= maxInitLevel; level++) { + grid->getBlocks(level, blocksVector[level]); + for (SPtr<Block3D> block : blocksVector[level]) // blocks of the current level + grid->deleteBlock(block); + } + } + + // restore the grid + SPtr<CoordinateTransformation3D> trafo(new CoordinateTransformation3D()); + trafo->Tx1 = gridParameters->trafoParams[0]; + trafo->Tx2 = gridParameters->trafoParams[1]; + trafo->Tx3 = gridParameters->trafoParams[2]; + trafo->Sx1 = gridParameters->trafoParams[3]; + trafo->Sx2 = gridParameters->trafoParams[4]; + trafo->Sx3 = gridParameters->trafoParams[5]; + trafo->alpha = gridParameters->trafoParams[6]; + trafo->beta = gridParameters->trafoParams[7]; + trafo->gamma = gridParameters->trafoParams[8]; + + trafo->toX1factorX1 = gridParameters->trafoParams[9]; + trafo->toX1factorX2 = gridParameters->trafoParams[10]; + trafo->toX1factorX3 = gridParameters->trafoParams[11]; + trafo->toX1delta = gridParameters->trafoParams[12]; + trafo->toX2factorX1 = gridParameters->trafoParams[13]; + trafo->toX2factorX2 = gridParameters->trafoParams[14]; + trafo->toX2factorX3 = gridParameters->trafoParams[15]; + trafo->toX2delta = gridParameters->trafoParams[16]; + trafo->toX3factorX1 = gridParameters->trafoParams[17]; + trafo->toX3factorX2 = gridParameters->trafoParams[18]; + trafo->toX3factorX3 = gridParameters->trafoParams[19]; + trafo->toX3delta = gridParameters->trafoParams[20]; + + trafo->fromX1factorX1 = gridParameters->trafoParams[21]; + trafo->fromX1factorX2 = gridParameters->trafoParams[22]; + trafo->fromX1factorX3 = gridParameters->trafoParams[23]; + trafo->fromX1delta = gridParameters->trafoParams[24]; + trafo->fromX2factorX1 = gridParameters->trafoParams[25]; + trafo->fromX2factorX2 = gridParameters->trafoParams[26]; + trafo->fromX2factorX3 = gridParameters->trafoParams[27]; + trafo->fromX2delta = gridParameters->trafoParams[28]; + trafo->fromX3factorX1 = gridParameters->trafoParams[29]; + trafo->fromX3factorX2 = gridParameters->trafoParams[30]; + trafo->fromX3factorX3 = gridParameters->trafoParams[31]; + trafo->fromX3delta = gridParameters->trafoParams[32]; + + trafo->active = gridParameters->active; + trafo->transformation = gridParameters->transformation; + + grid->setCoordinateTransformator(trafo); + + grid->setDeltaX(gridParameters->deltaX); + grid->setBlockNX(gridParameters->blockNx1, gridParameters->blockNx2, gridParameters->blockNx3); + grid->setNX1(gridParameters->nx1); + grid->setNX2(gridParameters->nx2); + grid->setNX3(gridParameters->nx3); + grid->setPeriodicX1(gridParameters->periodicX1); + grid->setPeriodicX2(gridParameters->periodicX2); + grid->setPeriodicX3(gridParameters->periodicX3); + + // regenerate blocks + for (int n = 0; n < blocksCount; n++) { + SPtr<Block3D> block( + new Block3D(block3dArray[n].x1, block3dArray[n].x2, block3dArray[n].x3, block3dArray[n].level)); + block->setActive(block3dArray[n].active); + block->setBundle(block3dArray[n].bundle); + block->setRank(block3dArray[n].rank); + block->setLocalRank(block3dArray[n].lrank); + block->setGlobalID(block3dArray[n].globalID); + block->setLocalID(block3dArray[n].localID); + block->setPart(block3dArray[n].part); + block->setLevel(block3dArray[n].level); + block->setCollectionOfInterpolationFlagCF(block3dArray[n].interpolationFlagCF); + block->setCollectionOfInterpolationFlagFC(block3dArray[n].interpolationFlagFC); + + grid->addBlock(block); + } + + // renumber blocks + grid->renumberBlockIDs(); + + // refresh globalID in all the blocks + SPtr<Block3D> block; + for (int n = 0; n < blocksCount; n++) { + block = grid->getBlock(block3dArray[n].x1, block3dArray[n].x2, block3dArray[n].x3, block3dArray[n].level); + block3dArray[n].globalID = block->getGlobalID(); + } + + // write all data to the file + MPI_Offset write_offset = read_offset; + + MPI_File_write_at(file_handlerW, 0, &blocksCount, 1, MPI_INT, MPI_STATUS_IGNORE); + MPI_File_write_at(file_handlerW, write_offset, gridParameters, 1, gridParamType, MPI_STATUS_IGNORE); + MPI_File_write_at(file_handlerW, (MPI_Offset)(write_offset + sizeof(GridParam)), &block3dArray[0], blocksCount, + block3dType, MPI_STATUS_IGNORE); + + MPI_File_close(&file_handlerR); + MPI_File_close(&file_handlerW); + + finish = MPI_Wtime(); + UBLOG(logINFO, "UtilConvertor::convertBlocks time: " << finish - start << " s"); + + delete gridParameters; + delete[] block3dArray; } void CheckpointConverter::convertDataSet(int step, int procCount) { - // file to read from - MPI_File file_handlerR; - std::string filenameR = path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + "/cpDataSet.bin"; - int rcR = MPI_File_open(MPI_COMM_WORLD, filenameR.c_str(), MPI_MODE_RDONLY, MPI_INFO_NULL, &file_handlerR); - if (rcR != MPI_SUCCESS) throw UbException(UB_EXARGS, "couldn't open file " + filenameR); - - // file to write to - MPI_File file_handlerW; - std::string filenameW = path + "/mig/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + "/cpDataSet.bin"; - int rcW = MPI_File_open(MPI_COMM_WORLD, filenameW.c_str(), MPI_MODE_CREATE | MPI_MODE_WRONLY, MPI_INFO_NULL, &file_handlerW); - if (rcW != MPI_SUCCESS) throw UbException(UB_EXARGS, "couldn't open file " + filenameW); - - double start, finish; - start = MPI_Wtime(); - - int blocksCount = 0; - dataSetParam dataSetParamStr1, dataSetParamStr2, dataSetParamStr3; - DataSetRestart* dataSetReadArray; - DataSetMigration* dataSetWriteArray; - size_t doubleCountInBlock; - std::vector<double> doubleValuesArray; - size_t sizeofOneDataSet; - - // calculate the read offset - MPI_Offset read_offset = (MPI_Offset)(procCount * sizeof(int)); - MPI_Offset write_offset; - - for (int pc = 0; pc < procCount; pc++) - { - // read count of blocks and parameters of data arrays - MPI_File_read_at(file_handlerR, (MPI_Offset)(pc * sizeof(int)), &blocksCount, 1, MPI_INT, MPI_STATUS_IGNORE); - MPI_File_read_at(file_handlerR, read_offset, &dataSetParamStr1, 1, dataSetParamType, MPI_STATUS_IGNORE); - MPI_File_read_at(file_handlerR, (MPI_Offset)(read_offset + sizeof(dataSetParam)), &dataSetParamStr2, 1, dataSetParamType, MPI_STATUS_IGNORE); - MPI_File_read_at(file_handlerR, (MPI_Offset)(read_offset + 2 * sizeof(dataSetParam)), &dataSetParamStr3, 1, dataSetParamType, MPI_STATUS_IGNORE); - doubleCountInBlock = dataSetParamStr1.nx[0] * dataSetParamStr1.nx[1] * dataSetParamStr1.nx[2] * dataSetParamStr1.nx[3] + - dataSetParamStr2.nx[0] * dataSetParamStr2.nx[1] * dataSetParamStr2.nx[2] * dataSetParamStr2.nx[3] + - dataSetParamStr3.nx[0] * dataSetParamStr3.nx[1] * dataSetParamStr3.nx[2] * dataSetParamStr3.nx[3]; - - dataSetReadArray = new DataSetRestart[blocksCount]; - dataSetWriteArray = new DataSetMigration[blocksCount]; - doubleValuesArray.resize(blocksCount * doubleCountInBlock); - - // read data - MPI_File_read_at(file_handlerR, (MPI_Offset)(read_offset + 3 * sizeof(dataSetParam)), dataSetReadArray, blocksCount, dataSetTypeRead, MPI_STATUS_IGNORE); - MPI_File_read_at(file_handlerR, (MPI_Offset)(read_offset + 3 * sizeof(dataSetParam) + blocksCount * sizeof(DataSetRestart)), - &doubleValuesArray[0], int(blocksCount * doubleCountInBlock), MPI_DOUBLE, MPI_STATUS_IGNORE); - - // offset to read the data of the next process - read_offset = read_offset + (MPI_Offset)(3 * sizeof(dataSetParam) + blocksCount * (sizeof(DataSetRestart) + doubleCountInBlock * sizeof(double))); - - // write parameters of data arrays - MPI_File_write_at(file_handlerW, (MPI_Offset)0, &dataSetParamStr1, 1, dataSetParamType, MPI_STATUS_IGNORE); - MPI_File_write_at(file_handlerW, (MPI_Offset)(sizeof(dataSetParam)), &dataSetParamStr2, 1, dataSetParamType, MPI_STATUS_IGNORE); - MPI_File_write_at(file_handlerW, (MPI_Offset)(2 * sizeof(dataSetParam)), &dataSetParamStr3, 1, dataSetParamType, MPI_STATUS_IGNORE); - - sizeofOneDataSet = sizeof(DataSetMigration) + doubleCountInBlock * sizeof(double); - - // write blocks and their data arrays - for (int nb = 0; nb < blocksCount; nb++) - { - SPtr<Block3D> block = grid->getBlock(dataSetReadArray[nb].x1, dataSetReadArray[nb].x2, dataSetReadArray[nb].x3, dataSetReadArray[nb].level); - dataSetWriteArray[nb].globalID = block->getGlobalID(); - dataSetWriteArray[nb].ghostLayerWidth = dataSetReadArray[nb].ghostLayerWidth; - dataSetWriteArray[nb].collFactor = dataSetReadArray[nb].collFactor; - dataSetWriteArray[nb].deltaT = dataSetReadArray[nb].deltaT; - dataSetWriteArray[nb].compressible = dataSetReadArray[nb].compressible; - dataSetWriteArray[nb].withForcing = dataSetReadArray[nb].withForcing; - - write_offset = (MPI_Offset)(3 * sizeof(dataSetParam) + dataSetWriteArray[nb].globalID * sizeofOneDataSet); - MPI_File_write_at(file_handlerW, write_offset, &dataSetWriteArray[nb], 1, dataSetTypeWrite, MPI_STATUS_IGNORE); - MPI_File_write_at(file_handlerW, (MPI_Offset)(write_offset + sizeof(DataSetMigration)), &doubleValuesArray[nb * doubleCountInBlock], - int(doubleCountInBlock), MPI_DOUBLE, MPI_STATUS_IGNORE); - } - - delete[] dataSetReadArray; - delete[] dataSetWriteArray; - } - - MPI_File_close(&file_handlerR); - - MPI_File_sync(file_handlerW); - MPI_File_close(&file_handlerW); - - DSArraysPresence arrPresence; - MPI_File file_handler1; - std::string filename1 = path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + "/cpArrays.bin"; - int rc = MPI_File_open(MPI_COMM_WORLD, filename1.c_str(), MPI_MODE_RDONLY, MPI_INFO_NULL, &file_handler1); - if (rc != MPI_SUCCESS) throw UbException(UB_EXARGS, "couldn't open file " + filename1); - MPI_File_read_at(file_handler1, (MPI_Offset)0, &arrPresence, 6, MPI_CHAR, MPI_STATUS_IGNORE); - MPI_File_close(&file_handler1); - - MPI_File file_handler2; - std::string filename2 = path + "/mig/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + "/cpArrays.bin"; - int rc2 = MPI_File_open(MPI_COMM_WORLD, filename2.c_str(), MPI_MODE_CREATE | MPI_MODE_WRONLY, MPI_INFO_NULL, &file_handler2); - if (rc2 != MPI_SUCCESS) throw UbException(UB_EXARGS, "couldn't open file " + filename2); - MPI_File_write_at(file_handler2, (MPI_Offset)0, &arrPresence, 6, MPI_CHAR, MPI_STATUS_IGNORE); - MPI_File_sync(file_handler2); - MPI_File_close(&file_handler2); - - std::string filenameRR = path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step); - std::string filenameWW = path + "/mig/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step); - - if (arrPresence.isAverageDensityArrayPresent) - convert___Array(step, procCount, filenameRR + "/cpAverageDensityArray.bin", filenameWW + "/cpAverageDensityArray.bin"); - - if (arrPresence.isAverageVelocityArrayPresent) - convert___Array(step, procCount, filenameRR + "/cpAverageVelocityArray.bin", filenameWW + "/cpAverageVelocityArray.bin"); - - if (arrPresence.isAverageFluktuationsArrayPresent) - convert___Array(step, procCount, filenameRR + "/cpAverageFluktuationsArray.bin", filenameWW + "/cpAverageFluktuationsArray.bin"); - - if (arrPresence.isAverageTripleArrayPresent) - convert___Array(step, procCount, filenameRR + "/cpAverageTripleArray.bin", filenameWW + "/cpAverageTripleArray.bin"); - - if (arrPresence.isShearStressValArrayPresent) - convert___Array(step, procCount, filenameRR + "/cpShearStressValArray.bin", filenameWW + "/cpShearStressValArray.bin"); - - if (arrPresence.isRelaxationFactorPresent) - convert___Array(step, procCount, filenameRR + "/cpRelaxationFactor.bin", filenameWW + "/cpRelaxationFactor.bin"); - - finish = MPI_Wtime(); - UBLOG(logINFO, "UtilConvertor::convertDataSet time: " << finish - start << " s"); - + // file to read from + MPI_File file_handlerR; + std::string filenameR = path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + "/cpDataSet.bin"; + int rcR = MPI_File_open(MPI_COMM_WORLD, filenameR.c_str(), MPI_MODE_RDONLY, MPI_INFO_NULL, &file_handlerR); + if (rcR != MPI_SUCCESS) + throw UbException(UB_EXARGS, "couldn't open file " + filenameR); + + // file to write to + MPI_File file_handlerW; + std::string filenameW = path + "/mig/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + "/cpDataSet.bin"; + int rcW = MPI_File_open(MPI_COMM_WORLD, filenameW.c_str(), MPI_MODE_CREATE | MPI_MODE_WRONLY, MPI_INFO_NULL, + &file_handlerW); + if (rcW != MPI_SUCCESS) + throw UbException(UB_EXARGS, "couldn't open file " + filenameW); + + double start, finish; + start = MPI_Wtime(); + + int blocksCount = 0; + dataSetParam dataSetParamStr1, dataSetParamStr2, dataSetParamStr3; + DataSetRestart *dataSetReadArray; + DataSetMigration *dataSetWriteArray; + size_t doubleCountInBlock; + std::vector<double> doubleValuesArray; + size_t sizeofOneDataSet; + + // calculate the read offset + MPI_Offset read_offset = (MPI_Offset)(procCount * sizeof(int)); + MPI_Offset write_offset; + + for (int pc = 0; pc < procCount; pc++) { + // read count of blocks and parameters of data arrays + MPI_File_read_at(file_handlerR, (MPI_Offset)(pc * sizeof(int)), &blocksCount, 1, MPI_INT, MPI_STATUS_IGNORE); + MPI_File_read_at(file_handlerR, read_offset, &dataSetParamStr1, 1, dataSetParamType, MPI_STATUS_IGNORE); + MPI_File_read_at(file_handlerR, (MPI_Offset)(read_offset + sizeof(dataSetParam)), &dataSetParamStr2, 1, + dataSetParamType, MPI_STATUS_IGNORE); + MPI_File_read_at(file_handlerR, (MPI_Offset)(read_offset + 2 * sizeof(dataSetParam)), &dataSetParamStr3, 1, + dataSetParamType, MPI_STATUS_IGNORE); + doubleCountInBlock = + dataSetParamStr1.nx[0] * dataSetParamStr1.nx[1] * dataSetParamStr1.nx[2] * dataSetParamStr1.nx[3] + + dataSetParamStr2.nx[0] * dataSetParamStr2.nx[1] * dataSetParamStr2.nx[2] * dataSetParamStr2.nx[3] + + dataSetParamStr3.nx[0] * dataSetParamStr3.nx[1] * dataSetParamStr3.nx[2] * dataSetParamStr3.nx[3]; + + dataSetReadArray = new DataSetRestart[blocksCount]; + dataSetWriteArray = new DataSetMigration[blocksCount]; + doubleValuesArray.resize(blocksCount * doubleCountInBlock); + + // read data + MPI_File_read_at(file_handlerR, (MPI_Offset)(read_offset + 3 * sizeof(dataSetParam)), dataSetReadArray, + blocksCount, dataSetTypeRead, MPI_STATUS_IGNORE); + MPI_File_read_at(file_handlerR, + (MPI_Offset)(read_offset + 3 * sizeof(dataSetParam) + blocksCount * sizeof(DataSetRestart)), + &doubleValuesArray[0], int(blocksCount * doubleCountInBlock), MPI_DOUBLE, MPI_STATUS_IGNORE); + + // offset to read the data of the next process + read_offset = + read_offset + (MPI_Offset)(3 * sizeof(dataSetParam) + + blocksCount * (sizeof(DataSetRestart) + doubleCountInBlock * sizeof(double))); + + // write parameters of data arrays + MPI_File_write_at(file_handlerW, (MPI_Offset)0, &dataSetParamStr1, 1, dataSetParamType, MPI_STATUS_IGNORE); + MPI_File_write_at(file_handlerW, (MPI_Offset)(sizeof(dataSetParam)), &dataSetParamStr2, 1, dataSetParamType, + MPI_STATUS_IGNORE); + MPI_File_write_at(file_handlerW, (MPI_Offset)(2 * sizeof(dataSetParam)), &dataSetParamStr3, 1, dataSetParamType, + MPI_STATUS_IGNORE); + + sizeofOneDataSet = sizeof(DataSetMigration) + doubleCountInBlock * sizeof(double); + + // write blocks and their data arrays + for (int nb = 0; nb < blocksCount; nb++) { + SPtr<Block3D> block = grid->getBlock(dataSetReadArray[nb].x1, dataSetReadArray[nb].x2, + dataSetReadArray[nb].x3, dataSetReadArray[nb].level); + dataSetWriteArray[nb].globalID = block->getGlobalID(); + dataSetWriteArray[nb].ghostLayerWidth = dataSetReadArray[nb].ghostLayerWidth; + dataSetWriteArray[nb].collFactor = dataSetReadArray[nb].collFactor; + dataSetWriteArray[nb].deltaT = dataSetReadArray[nb].deltaT; + dataSetWriteArray[nb].compressible = dataSetReadArray[nb].compressible; + dataSetWriteArray[nb].withForcing = dataSetReadArray[nb].withForcing; + + write_offset = (MPI_Offset)(3 * sizeof(dataSetParam) + dataSetWriteArray[nb].globalID * sizeofOneDataSet); + MPI_File_write_at(file_handlerW, write_offset, &dataSetWriteArray[nb], 1, dataSetTypeWrite, + MPI_STATUS_IGNORE); + MPI_File_write_at(file_handlerW, (MPI_Offset)(write_offset + sizeof(DataSetMigration)), + &doubleValuesArray[nb * doubleCountInBlock], int(doubleCountInBlock), MPI_DOUBLE, + MPI_STATUS_IGNORE); + } + + delete[] dataSetReadArray; + delete[] dataSetWriteArray; + } + + MPI_File_close(&file_handlerR); + + MPI_File_sync(file_handlerW); + MPI_File_close(&file_handlerW); + + DSArraysPresence arrPresence; + MPI_File file_handler1; + std::string filename1 = path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + "/cpArrays.bin"; + int rc = MPI_File_open(MPI_COMM_WORLD, filename1.c_str(), MPI_MODE_RDONLY, MPI_INFO_NULL, &file_handler1); + if (rc != MPI_SUCCESS) + throw UbException(UB_EXARGS, "couldn't open file " + filename1); + MPI_File_read_at(file_handler1, (MPI_Offset)0, &arrPresence, 6, MPI_CHAR, MPI_STATUS_IGNORE); + MPI_File_close(&file_handler1); + + MPI_File file_handler2; + std::string filename2 = path + "/mig/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + "/cpArrays.bin"; + int rc2 = MPI_File_open(MPI_COMM_WORLD, filename2.c_str(), MPI_MODE_CREATE | MPI_MODE_WRONLY, MPI_INFO_NULL, + &file_handler2); + if (rc2 != MPI_SUCCESS) + throw UbException(UB_EXARGS, "couldn't open file " + filename2); + MPI_File_write_at(file_handler2, (MPI_Offset)0, &arrPresence, 6, MPI_CHAR, MPI_STATUS_IGNORE); + MPI_File_sync(file_handler2); + MPI_File_close(&file_handler2); + + std::string filenameRR = path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step); + std::string filenameWW = path + "/mig/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step); + + if (arrPresence.isAverageDensityArrayPresent) + convert___Array(step, procCount, filenameRR + "/cpAverageDensityArray.bin", + filenameWW + "/cpAverageDensityArray.bin"); + + if (arrPresence.isAverageVelocityArrayPresent) + convert___Array(step, procCount, filenameRR + "/cpAverageVelocityArray.bin", + filenameWW + "/cpAverageVelocityArray.bin"); + + if (arrPresence.isAverageFluktuationsArrayPresent) + convert___Array(step, procCount, filenameRR + "/cpAverageFluktuationsArray.bin", + filenameWW + "/cpAverageFluktuationsArray.bin"); + + if (arrPresence.isAverageTripleArrayPresent) + convert___Array(step, procCount, filenameRR + "/cpAverageTripleArray.bin", + filenameWW + "/cpAverageTripleArray.bin"); + + if (arrPresence.isShearStressValArrayPresent) + convert___Array(step, procCount, filenameRR + "/cpShearStressValArray.bin", + filenameWW + "/cpShearStressValArray.bin"); + + if (arrPresence.isRelaxationFactorPresent) + convert___Array(step, procCount, filenameRR + "/cpRelaxationFactor.bin", + filenameWW + "/cpRelaxationFactor.bin"); + + finish = MPI_Wtime(); + UBLOG(logINFO, "UtilConvertor::convertDataSet time: " << finish - start << " s"); } -void CheckpointConverter::convert___Array(int /*step*/, int procCount, std::string filenameR, std::string filenameW) +void CheckpointConverter::convert___Array(int /*step*/, int procCount, std::string filenameR, std::string filenameW) { - double start, finish; - if (comm->isRoot()) start = MPI_Wtime(); - - MPI_File file_handlerR; - int rcR = MPI_File_open(MPI_COMM_WORLD, filenameR.c_str(), MPI_MODE_RDONLY, MPI_INFO_NULL, &file_handlerR); - if (rcR != MPI_SUCCESS) throw UbException(UB_EXARGS, "couldn't open file " + filenameR); - - MPI_File file_handlerW; - int rcW = MPI_File_open(MPI_COMM_WORLD, filenameW.c_str(), MPI_MODE_CREATE | MPI_MODE_WRONLY, MPI_INFO_NULL, &file_handlerW); - if (rcW != MPI_SUCCESS) throw UbException(UB_EXARGS, "couldn't open file " + filenameW); - - int blocksCount = 0; - dataSetParam dataSetParamStr; - memset(&dataSetParamStr, 0, sizeof(dataSetParam)); - DataSetSmallRestart* dataSetSmallReadArray; - DataSetSmallMigration* dataSetSmallWriteArray; - int doubleCountInBlock; - std::vector<double> doubleValuesArray; - - // calculate the read offset - MPI_Offset read_offset = (MPI_Offset)(procCount * sizeof(int)); - MPI_Offset write_offset; - size_t sizeofOneDataSet; - - for (int pc = 0; pc < procCount; pc++) - { - MPI_File_read_at(file_handlerR, (MPI_Offset)(pc * sizeof(int)), &blocksCount, 1, MPI_INT, MPI_STATUS_IGNORE); - MPI_File_read_at(file_handlerR, read_offset, &dataSetParamStr, 1, dataSetParamType, MPI_STATUS_IGNORE); - - dataSetSmallReadArray = new DataSetSmallRestart[blocksCount]; - dataSetSmallWriteArray = new DataSetSmallMigration[blocksCount]; - doubleCountInBlock = dataSetParamStr.nx[0] * dataSetParamStr.nx[1] * dataSetParamStr.nx[2] * dataSetParamStr.nx[3]; - doubleValuesArray.resize(blocksCount * doubleCountInBlock); - - MPI_File_read_at(file_handlerR, (MPI_Offset)(read_offset + sizeof(dataSetParam)), dataSetSmallReadArray, blocksCount * 4, MPI_INT, MPI_STATUS_IGNORE); - if (doubleCountInBlock > 0) - MPI_File_read_at(file_handlerR, (MPI_Offset)(read_offset + sizeof(dataSetParam) + blocksCount * sizeof(DataSetSmallRestart)), - &doubleValuesArray[0], blocksCount * doubleCountInBlock, MPI_DOUBLE, MPI_STATUS_IGNORE); - - read_offset = read_offset + sizeof(dataSetParam) + blocksCount * (sizeof(DataSetSmallRestart) + doubleCountInBlock * sizeof(double)); - - sizeofOneDataSet = sizeof(DataSetSmallMigration) + doubleCountInBlock * sizeof(double); - - MPI_File_write_at(file_handlerW, 0, &dataSetParamStr, 1, dataSetParamType, MPI_STATUS_IGNORE); - - for (int nb = 0; nb < blocksCount; nb++) - { - SPtr<Block3D> block = grid->getBlock(dataSetSmallReadArray[nb].x1, dataSetSmallReadArray[nb].x2, dataSetSmallReadArray[nb].x3, dataSetSmallReadArray[nb].level); - dataSetSmallWriteArray[nb].globalID = block->getGlobalID(); - - write_offset = (MPI_Offset)(sizeof(dataSetParam) + dataSetSmallWriteArray[nb].globalID * sizeofOneDataSet); - MPI_File_write_at(file_handlerW, write_offset, &dataSetSmallWriteArray[nb], 1, MPI_INT, MPI_STATUS_IGNORE); - MPI_File_write_at(file_handlerW, (MPI_Offset)(write_offset + sizeof(DataSetSmallMigration)), - &doubleValuesArray[nb * doubleCountInBlock], doubleCountInBlock, MPI_DOUBLE, MPI_STATUS_IGNORE); - } - - delete[] dataSetSmallReadArray; - delete[] dataSetSmallWriteArray; - } - MPI_File_close(&file_handlerR); - - MPI_File_sync(file_handlerW); - MPI_File_close(&file_handlerW); - - finish = MPI_Wtime(); - UBLOG(logINFO, "UtilConvertor::convert___Array time: " << finish - start << " s"); - + double start, finish; + if (comm->isRoot()) + start = MPI_Wtime(); + + MPI_File file_handlerR; + int rcR = MPI_File_open(MPI_COMM_WORLD, filenameR.c_str(), MPI_MODE_RDONLY, MPI_INFO_NULL, &file_handlerR); + if (rcR != MPI_SUCCESS) + throw UbException(UB_EXARGS, "couldn't open file " + filenameR); + + MPI_File file_handlerW; + int rcW = MPI_File_open(MPI_COMM_WORLD, filenameW.c_str(), MPI_MODE_CREATE | MPI_MODE_WRONLY, MPI_INFO_NULL, + &file_handlerW); + if (rcW != MPI_SUCCESS) + throw UbException(UB_EXARGS, "couldn't open file " + filenameW); + + int blocksCount = 0; + dataSetParam dataSetParamStr; + memset(&dataSetParamStr, 0, sizeof(dataSetParam)); + DataSetSmallRestart *dataSetSmallReadArray; + DataSetSmallMigration *dataSetSmallWriteArray; + int doubleCountInBlock; + std::vector<double> doubleValuesArray; + + // calculate the read offset + MPI_Offset read_offset = (MPI_Offset)(procCount * sizeof(int)); + MPI_Offset write_offset; + size_t sizeofOneDataSet; + + for (int pc = 0; pc < procCount; pc++) { + MPI_File_read_at(file_handlerR, (MPI_Offset)(pc * sizeof(int)), &blocksCount, 1, MPI_INT, MPI_STATUS_IGNORE); + MPI_File_read_at(file_handlerR, read_offset, &dataSetParamStr, 1, dataSetParamType, MPI_STATUS_IGNORE); + + dataSetSmallReadArray = new DataSetSmallRestart[blocksCount]; + dataSetSmallWriteArray = new DataSetSmallMigration[blocksCount]; + doubleCountInBlock = + dataSetParamStr.nx[0] * dataSetParamStr.nx[1] * dataSetParamStr.nx[2] * dataSetParamStr.nx[3]; + doubleValuesArray.resize(blocksCount * doubleCountInBlock); + + MPI_File_read_at(file_handlerR, (MPI_Offset)(read_offset + sizeof(dataSetParam)), dataSetSmallReadArray, + blocksCount * 4, MPI_INT, MPI_STATUS_IGNORE); + if (doubleCountInBlock > 0) + MPI_File_read_at( + file_handlerR, + (MPI_Offset)(read_offset + sizeof(dataSetParam) + blocksCount * sizeof(DataSetSmallRestart)), + &doubleValuesArray[0], blocksCount * doubleCountInBlock, MPI_DOUBLE, MPI_STATUS_IGNORE); + + read_offset = read_offset + sizeof(dataSetParam) + + blocksCount * (sizeof(DataSetSmallRestart) + doubleCountInBlock * sizeof(double)); + + sizeofOneDataSet = sizeof(DataSetSmallMigration) + doubleCountInBlock * sizeof(double); + + MPI_File_write_at(file_handlerW, 0, &dataSetParamStr, 1, dataSetParamType, MPI_STATUS_IGNORE); + + for (int nb = 0; nb < blocksCount; nb++) { + SPtr<Block3D> block = grid->getBlock(dataSetSmallReadArray[nb].x1, dataSetSmallReadArray[nb].x2, + dataSetSmallReadArray[nb].x3, dataSetSmallReadArray[nb].level); + dataSetSmallWriteArray[nb].globalID = block->getGlobalID(); + + write_offset = (MPI_Offset)(sizeof(dataSetParam) + dataSetSmallWriteArray[nb].globalID * sizeofOneDataSet); + MPI_File_write_at(file_handlerW, write_offset, &dataSetSmallWriteArray[nb], 1, MPI_INT, MPI_STATUS_IGNORE); + MPI_File_write_at(file_handlerW, (MPI_Offset)(write_offset + sizeof(DataSetSmallMigration)), + &doubleValuesArray[nb * doubleCountInBlock], doubleCountInBlock, MPI_DOUBLE, + MPI_STATUS_IGNORE); + } + + delete[] dataSetSmallReadArray; + delete[] dataSetSmallWriteArray; + } + MPI_File_close(&file_handlerR); + + MPI_File_sync(file_handlerW); + MPI_File_close(&file_handlerW); + + finish = MPI_Wtime(); + UBLOG(logINFO, "UtilConvertor::convert___Array time: " << finish - start << " s"); } void CheckpointConverter::convertBC(int step, int procCount) { - // file to read from - MPI_File file_handlerR; - std::string filenameR = path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + "/cpBC.bin"; - int rcR = MPI_File_open(MPI_COMM_WORLD, filenameR.c_str(), MPI_MODE_RDONLY, MPI_INFO_NULL, &file_handlerR); - if (rcR != MPI_SUCCESS) throw UbException(UB_EXARGS, "couldn't open file " + filenameR); - - // file to write to - MPI_File file_handlerW; - std::string filenameW = path + "/mig/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + "/cpBC.bin"; - int rcW = MPI_File_open(MPI_COMM_WORLD, filenameW.c_str(), MPI_MODE_CREATE | MPI_MODE_WRONLY, MPI_INFO_NULL, &file_handlerW); - if (rcW != MPI_SUCCESS) throw UbException(UB_EXARGS, "couldn't open file " + filenameW); - - double start, finish; - if (comm->isRoot()) start = MPI_Wtime(); - - int blocksCount = 0; - int dataCount1000 = 0; - int dataCount2 = 0; - size_t dataCount; - BCAddRestart* bcAddReadArray; - BCAddMigration* bcAddWriteArray; - BoundaryCondition* bcArray; - BoundaryCondition* nullBouCond = new BoundaryCondition(); - memset(nullBouCond, 0, sizeof(BoundaryCondition)); - int* intArray1; - int* intArray2; - int indexBC; - int indexC; - - MPI_Offset read_offset; - MPI_Offset read_offset1 = (MPI_Offset)(procCount * (3 * sizeof(int) + sizeof(boundCondParam))); - MPI_Offset write_offset = (MPI_Offset)(sizeof(boundCondParam) + grid->getNumberOfBlocks() * sizeof(size_t)); - MPI_Offset write_offsetIndex; - - for (int pc = 0; pc < procCount; pc++) - { - read_offset = (MPI_Offset)(pc * (3 * sizeof(int) + sizeof(boundCondParam))); - - // read count of blocks - MPI_File_read_at(file_handlerR, read_offset, &blocksCount, 1, MPI_INT, MPI_STATUS_IGNORE); - // read count of big BoundaryCondition blocks - MPI_File_read_at(file_handlerR, (MPI_Offset)(read_offset + sizeof(int)), &dataCount1000, 1, MPI_INT, MPI_STATUS_IGNORE); - // read count of indexContainer values in all blocks - MPI_File_read_at(file_handlerR, (MPI_Offset)(read_offset + 2 * sizeof(int)), &dataCount2, 1, MPI_INT, MPI_STATUS_IGNORE); - // read count of bcindexmatrix values in every block - MPI_File_read_at(file_handlerR, (MPI_Offset)(read_offset + 3 * sizeof(int)), &boundCondParamStr, 4, MPI_INT, MPI_STATUS_IGNORE); - //MPI_File_read_at(file_handlerR, (MPI_Offset)(read_offset + 3 * sizeof(int)), &boundCondParamStr, 1, boundCondParamType, MPI_STATUS_IGNORE); - - bcAddReadArray = new BCAddRestart[blocksCount]; - bcAddWriteArray = new BCAddMigration[blocksCount]; - dataCount = dataCount1000 * BLOCK_SIZE; - bcArray = new BoundaryCondition[dataCount]; - intArray1 = new int[blocksCount * boundCondParamStr.bcindexmatrixCount]; - intArray2 = new int[dataCount2]; - - // read data arrays - MPI_File_read_at(file_handlerR, read_offset1, bcAddReadArray, blocksCount * 6, MPI_INT, MPI_STATUS_IGNORE); - MPI_File_read_at(file_handlerR, (MPI_Offset)(read_offset1 + blocksCount * sizeof(BCAddRestart)), - &bcArray[0], dataCount1000, boundCondType1000, MPI_STATUS_IGNORE); - MPI_File_read_at(file_handlerR, (MPI_Offset)(read_offset1 + blocksCount * sizeof(BCAddRestart) + dataCount * sizeof(BoundaryCondition)), - &intArray1[0], blocksCount * boundCondParamStr.bcindexmatrixCount, MPI_INT, MPI_STATUS_IGNORE); - MPI_File_read_at(file_handlerR, (MPI_Offset)(read_offset1 + blocksCount * sizeof(BCAddRestart) + dataCount * sizeof(BoundaryCondition) + blocksCount * boundCondParamStr.bcindexmatrixCount * sizeof(int)), - &intArray2[0], dataCount2, MPI_INT, MPI_STATUS_IGNORE); - - // offset to read the data of the next process - read_offset1 = read_offset1 + blocksCount * sizeof(BCAddRestart) + dataCount * sizeof(BoundaryCondition) + (blocksCount * boundCondParamStr.bcindexmatrixCount + dataCount2) * sizeof(int); - - MPI_File_write_at(file_handlerW, 0, &boundCondParamStr, 4, MPI_INT, MPI_STATUS_IGNORE); - - indexBC = 0; - indexC = 0; - // write blocks and their BC data arrays - for (int nb = 0; nb < blocksCount; nb++) - { - SPtr<Block3D> block = grid->getBlock(bcAddReadArray[nb].x1, bcAddReadArray[nb].x2, bcAddReadArray[nb].x3, bcAddReadArray[nb].level); - bcAddWriteArray[nb].globalID = block->getGlobalID(); - bcAddWriteArray[nb].boundCond_count = bcAddReadArray[nb].boundCond_count; // how many BoundaryConditions in this block - bcAddWriteArray[nb].indexContainer_count = bcAddReadArray[nb].indexContainer_count; // how many indexContainer-values in this block - - write_offsetIndex = (MPI_Offset)(sizeof(boundCondParam) + bcAddWriteArray[nb].globalID * sizeof(size_t)); - MPI_File_write_at(file_handlerW, write_offsetIndex, &write_offset, 1, MPI_LONG_LONG_INT, MPI_STATUS_IGNORE); - - MPI_File_write_at(file_handlerW, write_offset, &bcAddWriteArray[nb], 3, MPI_INT, MPI_STATUS_IGNORE); - if (bcAddWriteArray[nb].boundCond_count > 0) - MPI_File_write_at(file_handlerW, (MPI_Offset)(write_offset + sizeof(BCAddMigration)), &bcArray[indexBC], bcAddWriteArray[nb].boundCond_count, boundCondType, MPI_STATUS_IGNORE); - indexBC += bcAddWriteArray[nb].boundCond_count; - - if (boundCondParamStr.bcindexmatrixCount > 0) - MPI_File_write_at(file_handlerW, (MPI_Offset)(write_offset + sizeof(BCAddMigration) + bcAddWriteArray[nb].boundCond_count * sizeof(BoundaryCondition)), - &intArray1[nb * boundCondParamStr.bcindexmatrixCount], boundCondParamStr.bcindexmatrixCount, MPI_INT, MPI_STATUS_IGNORE); - - if (bcAddWriteArray[nb].indexContainer_count > 0) - MPI_File_write_at(file_handlerW, (MPI_Offset)(write_offset + sizeof(BCAddMigration) + bcAddWriteArray[nb].boundCond_count * sizeof(BoundaryCondition) + boundCondParamStr.bcindexmatrixCount * sizeof(int)), - &intArray2[indexC], bcAddWriteArray[nb].indexContainer_count, MPI_INT, MPI_STATUS_IGNORE); - indexC += bcAddWriteArray[nb].indexContainer_count; - - write_offset += sizeof(BCAddMigration) + bcAddWriteArray[nb].boundCond_count * sizeof(BoundaryCondition) + boundCondParamStr.bcindexmatrixCount * sizeof(int) + bcAddWriteArray[nb].indexContainer_count * sizeof(int); - } - - delete[] bcAddReadArray; - delete[] bcAddWriteArray; - delete[] bcArray; - delete[] intArray1; - delete[] intArray2; - } - - delete nullBouCond; - - MPI_File_close(&file_handlerR); - - MPI_File_sync(file_handlerW); - MPI_File_close(&file_handlerW); - - finish = MPI_Wtime(); - UBLOG(logINFO, "UtilConvertor::convertBC time: " << finish - start << " s"); - + // file to read from + MPI_File file_handlerR; + std::string filenameR = path + "/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + "/cpBC.bin"; + int rcR = MPI_File_open(MPI_COMM_WORLD, filenameR.c_str(), MPI_MODE_RDONLY, MPI_INFO_NULL, &file_handlerR); + if (rcR != MPI_SUCCESS) + throw UbException(UB_EXARGS, "couldn't open file " + filenameR); + + // file to write to + MPI_File file_handlerW; + std::string filenameW = path + "/mig/mpi_io_cp/mpi_io_cp_" + UbSystem::toString(step) + "/cpBC.bin"; + int rcW = MPI_File_open(MPI_COMM_WORLD, filenameW.c_str(), MPI_MODE_CREATE | MPI_MODE_WRONLY, MPI_INFO_NULL, + &file_handlerW); + if (rcW != MPI_SUCCESS) + throw UbException(UB_EXARGS, "couldn't open file " + filenameW); + + double start, finish; + if (comm->isRoot()) + start = MPI_Wtime(); + + int blocksCount = 0; + int dataCount1000 = 0; + int dataCount2 = 0; + size_t dataCount; + BCAddRestart *bcAddReadArray; + BCAddMigration *bcAddWriteArray; + BoundaryCondition *bcArray; + BoundaryCondition *nullBouCond = new BoundaryCondition(); + memset(nullBouCond, 0, sizeof(BoundaryCondition)); + int *intArray1; + int *intArray2; + int indexBC; + int indexC; + + MPI_Offset read_offset; + MPI_Offset read_offset1 = (MPI_Offset)(procCount * (3 * sizeof(int) + sizeof(boundCondParam))); + MPI_Offset write_offset = (MPI_Offset)(sizeof(boundCondParam) + grid->getNumberOfBlocks() * sizeof(size_t)); + MPI_Offset write_offsetIndex; + + for (int pc = 0; pc < procCount; pc++) { + read_offset = (MPI_Offset)(pc * (3 * sizeof(int) + sizeof(boundCondParam))); + + // read count of blocks + MPI_File_read_at(file_handlerR, read_offset, &blocksCount, 1, MPI_INT, MPI_STATUS_IGNORE); + // read count of big BoundaryCondition blocks + MPI_File_read_at(file_handlerR, (MPI_Offset)(read_offset + sizeof(int)), &dataCount1000, 1, MPI_INT, + MPI_STATUS_IGNORE); + // read count of indexContainer values in all blocks + MPI_File_read_at(file_handlerR, (MPI_Offset)(read_offset + 2 * sizeof(int)), &dataCount2, 1, MPI_INT, + MPI_STATUS_IGNORE); + // read count of bcindexmatrix values in every block + MPI_File_read_at(file_handlerR, (MPI_Offset)(read_offset + 3 * sizeof(int)), &boundCondParamStr, 4, MPI_INT, + MPI_STATUS_IGNORE); + // MPI_File_read_at(file_handlerR, (MPI_Offset)(read_offset + 3 * sizeof(int)), &boundCondParamStr, 1, + // boundCondParamType, MPI_STATUS_IGNORE); + + bcAddReadArray = new BCAddRestart[blocksCount]; + bcAddWriteArray = new BCAddMigration[blocksCount]; + dataCount = dataCount1000 * BLOCK_SIZE; + bcArray = new BoundaryCondition[dataCount]; + intArray1 = new int[blocksCount * boundCondParamStr.bcindexmatrixCount]; + intArray2 = new int[dataCount2]; + + // read data arrays + MPI_File_read_at(file_handlerR, read_offset1, bcAddReadArray, blocksCount * 6, MPI_INT, MPI_STATUS_IGNORE); + MPI_File_read_at(file_handlerR, (MPI_Offset)(read_offset1 + blocksCount * sizeof(BCAddRestart)), &bcArray[0], + dataCount1000, boundCondType1000, MPI_STATUS_IGNORE); + MPI_File_read_at( + file_handlerR, + (MPI_Offset)(read_offset1 + blocksCount * sizeof(BCAddRestart) + dataCount * sizeof(BoundaryCondition)), + &intArray1[0], blocksCount * boundCondParamStr.bcindexmatrixCount, MPI_INT, MPI_STATUS_IGNORE); + MPI_File_read_at(file_handlerR, + (MPI_Offset)(read_offset1 + blocksCount * sizeof(BCAddRestart) + + dataCount * sizeof(BoundaryCondition) + + blocksCount * boundCondParamStr.bcindexmatrixCount * sizeof(int)), + &intArray2[0], dataCount2, MPI_INT, MPI_STATUS_IGNORE); + + // offset to read the data of the next process + read_offset1 = read_offset1 + blocksCount * sizeof(BCAddRestart) + dataCount * sizeof(BoundaryCondition) + + (blocksCount * boundCondParamStr.bcindexmatrixCount + dataCount2) * sizeof(int); + + MPI_File_write_at(file_handlerW, 0, &boundCondParamStr, 4, MPI_INT, MPI_STATUS_IGNORE); + + indexBC = 0; + indexC = 0; + // write blocks and their BC data arrays + for (int nb = 0; nb < blocksCount; nb++) { + SPtr<Block3D> block = grid->getBlock(bcAddReadArray[nb].x1, bcAddReadArray[nb].x2, bcAddReadArray[nb].x3, + bcAddReadArray[nb].level); + bcAddWriteArray[nb].globalID = block->getGlobalID(); + bcAddWriteArray[nb].boundCond_count = + bcAddReadArray[nb].boundCond_count; // how many BoundaryConditions in this block + bcAddWriteArray[nb].indexContainer_count = + bcAddReadArray[nb].indexContainer_count; // how many indexContainer-values in this block + + write_offsetIndex = (MPI_Offset)(sizeof(boundCondParam) + bcAddWriteArray[nb].globalID * sizeof(size_t)); + MPI_File_write_at(file_handlerW, write_offsetIndex, &write_offset, 1, MPI_LONG_LONG_INT, MPI_STATUS_IGNORE); + + MPI_File_write_at(file_handlerW, write_offset, &bcAddWriteArray[nb], 3, MPI_INT, MPI_STATUS_IGNORE); + if (bcAddWriteArray[nb].boundCond_count > 0) + MPI_File_write_at(file_handlerW, (MPI_Offset)(write_offset + sizeof(BCAddMigration)), &bcArray[indexBC], + bcAddWriteArray[nb].boundCond_count, boundCondType, MPI_STATUS_IGNORE); + indexBC += bcAddWriteArray[nb].boundCond_count; + + if (boundCondParamStr.bcindexmatrixCount > 0) + MPI_File_write_at(file_handlerW, + (MPI_Offset)(write_offset + sizeof(BCAddMigration) + + bcAddWriteArray[nb].boundCond_count * sizeof(BoundaryCondition)), + &intArray1[nb * boundCondParamStr.bcindexmatrixCount], + boundCondParamStr.bcindexmatrixCount, MPI_INT, MPI_STATUS_IGNORE); + + if (bcAddWriteArray[nb].indexContainer_count > 0) + MPI_File_write_at(file_handlerW, + (MPI_Offset)(write_offset + sizeof(BCAddMigration) + + bcAddWriteArray[nb].boundCond_count * sizeof(BoundaryCondition) + + boundCondParamStr.bcindexmatrixCount * sizeof(int)), + &intArray2[indexC], bcAddWriteArray[nb].indexContainer_count, MPI_INT, + MPI_STATUS_IGNORE); + indexC += bcAddWriteArray[nb].indexContainer_count; + + write_offset += sizeof(BCAddMigration) + bcAddWriteArray[nb].boundCond_count * sizeof(BoundaryCondition) + + boundCondParamStr.bcindexmatrixCount * sizeof(int) + + bcAddWriteArray[nb].indexContainer_count * sizeof(int); + } + + delete[] bcAddReadArray; + delete[] bcAddWriteArray; + delete[] bcArray; + delete[] intArray1; + delete[] intArray2; + } + + delete nullBouCond; + + MPI_File_close(&file_handlerR); + + MPI_File_sync(file_handlerW); + MPI_File_close(&file_handlerW); + + finish = MPI_Wtime(); + UBLOG(logINFO, "UtilConvertor::convertBC time: " << finish - start << " s"); } diff --git a/src/cpu/VirtualFluidsCore/Utilities/CheckpointConverter.h b/src/cpu/VirtualFluidsCore/Utilities/CheckpointConverter.h index 7a5ee2e4b950c2f0508bbd41cb6504c37ba14a9b..bad6116ccf8e1ebc32b8f7d6e12c3d36bc1b4e46 100644 --- a/src/cpu/VirtualFluidsCore/Utilities/CheckpointConverter.h +++ b/src/cpu/VirtualFluidsCore/Utilities/CheckpointConverter.h @@ -1,40 +1,40 @@ #ifndef _UTILITACONVERTOR_H_ #define _UTILITACONVERTOR_H_ -#include <mpi.h> +#include "MPIIODataStructures.h" #include <PointerDefinitions.h> +#include <mpi.h> #include <string> #include <vector> -#include "MPIIODataStructures.h" class Grid3D; class Communicator; -//! \class UtilConvertor -//! \brief Converts timestep data from MPIIORestartCoProcessor format into MPIIOMigrationCoProcessor format +//! \class UtilConvertor +//! \brief Converts timestep data from MPIIORestartCoProcessor format into MPIIOMigrationCoProcessor format class CheckpointConverter { public: - CheckpointConverter(SPtr<Grid3D> grid, const std::string& path, SPtr<Communicator> comm); - virtual ~CheckpointConverter(); + CheckpointConverter(SPtr<Grid3D> grid, const std::string &path, SPtr<Communicator> comm); + virtual ~CheckpointConverter(); - void convert(int step, int procCount); - void convertBlocks(int step, int procCount); - void convertDataSet(int step, int procCount); - void convertBC(int step, int procCount); - void convert___Array(int step, int procCount, std::string filenameR, std::string filenameW); + void convert(int step, int procCount); + void convertBlocks(int step, int procCount); + void convertDataSet(int step, int procCount); + void convertBC(int step, int procCount); + void convert___Array(int step, int procCount, std::string filenameR, std::string filenameW); protected: - std::string path; - SPtr<Communicator> comm; - SPtr<Grid3D> grid; + std::string path; + SPtr<Communicator> comm; + SPtr<Grid3D> grid; private: - MPI_Datatype gridParamType, block3dType; - MPI_Datatype dataSetParamType, dataSetTypeRead, dataSetTypeWrite; - MPI_Datatype boundCondType, boundCondType1000; + MPI_Datatype gridParamType, block3dType; + MPI_Datatype dataSetParamType, dataSetTypeRead, dataSetTypeWrite; + MPI_Datatype boundCondType, boundCondType1000; - MPIIODataStructures::boundCondParam boundCondParamStr; + MPIIODataStructures::boundCondParam boundCondParamStr; }; -#endif +#endif diff --git a/src/cpu/VirtualFluidsCore/Utilities/MemoryUtil.h b/src/cpu/VirtualFluidsCore/Utilities/MemoryUtil.h index 863b4d4f1ce0fbee66ef43a43d0edb5443e2450f..670a597cb84bd4e98450dad2743a8100f04497ea 100644 --- a/src/cpu/VirtualFluidsCore/Utilities/MemoryUtil.h +++ b/src/cpu/VirtualFluidsCore/Utilities/MemoryUtil.h @@ -1,28 +1,28 @@ //======================================================================================= -// ____ ____ __ ______ __________ __ __ __ __ -// \ \ | | | | | _ \ |___ ___| | | | | / \ | | -// \ \ | | | | | |_) | | | | | | | / \ | | -// \ \ | | | | | _ / | | | | | | / /\ \ | | -// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ -// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| -// \ \ | | ________________________________________________________________ -// \ \ | | | ______________________________________________________________| -// \ \| | | | __ __ __ __ ______ _______ -// \ | | |_____ | | | | | | | | | _ \ / _____) -// \ | | _____| | | | | | | | | | | \ \ \_______ +// ____ ____ __ ______ __________ __ __ __ __ +// \ \ | | | | | _ \ |___ ___| | | | | / \ | | +// \ \ | | | | | |_) | | | | | | | / \ | | +// \ \ | | | | | _ / | | | | | | / /\ \ | | +// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ +// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| +// \ \ | | ________________________________________________________________ +// \ \ | | | ______________________________________________________________| +// \ \| | | | __ __ __ __ ______ _______ +// \ | | |_____ | | | | | | | | | _ \ / _____) +// \ | | _____| | | | | | | | | | | \ \ \_______ // \ | | | | |_____ | \_/ | | | | |_/ / _____ | -// \ _____| |__| |________| \_______/ |__| |______/ (_______/ +// \ _____| |__| |________| \_______/ |__| |______/ (_______/ // -// This file is part of VirtualFluids. VirtualFluids is free software: you can +// This file is part of VirtualFluids. VirtualFluids is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of +// License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. -// -// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// +// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License along // with VirtualFluids (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>. // @@ -35,129 +35,130 @@ #define _MEMORYUTIL_H_ #if defined(_WIN32) || defined(_WIN64) - #define MEMORYUTIL_WINDOWS - #include "windows.h" - #include "psapi.h" - #pragma comment(lib, "psapi.lib") +#define MEMORYUTIL_WINDOWS +#include "windows.h" +#include "psapi.h" +#pragma comment(lib, "psapi.lib") #elif defined __APPLE__ #define MEMORYUTIL_APPLE - #include "sys/types.h" - #include "sys/sysctl.h" - #include <cstdlib> - #include <cstdio> - #include <cstring> +#include "sys/sysctl.h" +#include "sys/types.h" +#include <cstdio> +#include <cstdlib> +#include <cstring> #elif (defined(__amd64) || defined(__amd64__) || defined(__unix__) || defined(__CYGWIN__)) && !defined(__AIX__) - #define MEMORYUTIL_LINUX - #include "sys/types.h" - #include "sys/sysinfo.h" - #include "cstdlib" - #include "cstdio" - #include "cstring" +#define MEMORYUTIL_LINUX +#include "cstdio" +#include "cstdlib" +#include "cstring" +#include "sys/sysinfo.h" +#include "sys/types.h" #else - #error "MemoryUtil::UnknownMachine" +#error "MemoryUtil::UnknownMachine" #endif #if defined(__CYGWIN__) - #define MEMORYUTIL_CYGWIN +#define MEMORYUTIL_CYGWIN #endif ////////////////////////////////////////////////////////////////////////// -//MemoryUtil +// MemoryUtil ////////////////////////////////////////////////////////////////////////// namespace Utilities { ////////////////////////////////////////////////////////////////////////// - static long long getTotalPhysMem() - { - #if defined(MEMORYUTIL_WINDOWS) - MEMORYSTATUSEX memInfo; - memInfo.dwLength = sizeof(MEMORYSTATUSEX); - GlobalMemoryStatusEx(&memInfo); - DWORDLONG totalPhysMem = memInfo.ullTotalPhys; - #elif defined(MEMORYUTIL_LINUX) - struct sysinfo memInfo; - sysinfo (&memInfo); - long long totalPhysMem = memInfo.totalram; - //Multiply in next statement to avoid int overflow on right hand side... - totalPhysMem *= memInfo.mem_unit; - #elif defined(MEMORYUTIL_APPLE) - int mib [] = { CTL_HW, HW_MEMSIZE }; - int64_t totalPhysMem; - size_t length = sizeof(totalPhysMem); +static long long getTotalPhysMem() +{ +#if defined(MEMORYUTIL_WINDOWS) + MEMORYSTATUSEX memInfo; + memInfo.dwLength = sizeof(MEMORYSTATUSEX); + GlobalMemoryStatusEx(&memInfo); + DWORDLONG totalPhysMem = memInfo.ullTotalPhys; +#elif defined(MEMORYUTIL_LINUX) + struct sysinfo memInfo; + sysinfo(&memInfo); + long long totalPhysMem = memInfo.totalram; + // Multiply in next statement to avoid int overflow on right hand side... + totalPhysMem *= memInfo.mem_unit; +#elif defined(MEMORYUTIL_APPLE) + int mib[] = { CTL_HW, HW_MEMSIZE }; + int64_t totalPhysMem; + size_t length = sizeof(totalPhysMem); - if(sysctl(mib, 2, &totalPhysMem, &length, nullptr, 0) == -1) - return 0; - #else - #error "MemoryUtil::getTotalPhysMem - UnknownMachine" - #endif + if (sysctl(mib, 2, &totalPhysMem, &length, nullptr, 0) == -1) + return 0; +#else +#error "MemoryUtil::getTotalPhysMem - UnknownMachine" +#endif - return (long long)totalPhysMem; - } + return (long long)totalPhysMem; +} ////////////////////////////////////////////////////////////////////////// - static long long getPhysMemUsed() - { - #if defined(MEMORYUTIL_WINDOWS) - MEMORYSTATUSEX memInfo; - memInfo.dwLength = sizeof(MEMORYSTATUSEX); - GlobalMemoryStatusEx(&memInfo); - DWORDLONG physMemUsed = memInfo.ullTotalPhys - memInfo.ullAvailPhys; - #elif defined(MEMORYUTIL_LINUX) - struct sysinfo memInfo; - sysinfo (&memInfo); - long long physMemUsed = memInfo.totalram - memInfo.freeram; - //Multiply in next statement to avoid int overflow on right hand side... - physMemUsed *= memInfo.mem_unit; - #elif defined(MEMORYUTIL_APPLE) - long long physMemUsed = 0; - #else - #error "MemoryUtil::getPhysMemUsed - UnknownMachine" - #endif +static long long getPhysMemUsed() +{ +#if defined(MEMORYUTIL_WINDOWS) + MEMORYSTATUSEX memInfo; + memInfo.dwLength = sizeof(MEMORYSTATUSEX); + GlobalMemoryStatusEx(&memInfo); + DWORDLONG physMemUsed = memInfo.ullTotalPhys - memInfo.ullAvailPhys; +#elif defined(MEMORYUTIL_LINUX) + struct sysinfo memInfo; + sysinfo(&memInfo); + long long physMemUsed = memInfo.totalram - memInfo.freeram; + // Multiply in next statement to avoid int overflow on right hand side... + physMemUsed *= memInfo.mem_unit; +#elif defined(MEMORYUTIL_APPLE) + long long physMemUsed = 0; +#else +#error "MemoryUtil::getPhysMemUsed - UnknownMachine" +#endif - return (long long)physMemUsed; - } + return (long long)physMemUsed; +} ////////////////////////////////////////////////////////////////////////// #if defined(MEMORYUTIL_LINUX) || defined(MEMORYUTIL_APPLE) || defined(MEMORYUTIL_CYGWIN) - static int parseLine(char* line){ - int i = strlen(line); - while (*line < '0' || *line > '9') line++; - line[i-3] = '\0'; - i = atoi(line); - return i; - } - - static int getValue(){ //Note: this value is in KB! - FILE* file = fopen("/proc/self/status", "r"); - int result = -1; - char line[128]; +static int parseLine(char *line) +{ + int i = strlen(line); + while (*line < '0' || *line > '9') + line++; + line[i - 3] = '\0'; + i = atoi(line); + return i; +} +static int getValue() +{ // Note: this value is in KB! + FILE *file = fopen("/proc/self/status", "r"); + int result = -1; + char line[128]; - while (fgets(line, 128, file) != NULL){ - if (strncmp(line, "VmRSS:", 6) == 0){ + while (fgets(line, 128, file) != NULL) { + if (strncmp(line, "VmRSS:", 6) == 0) { result = parseLine(line); break; - } - } - fclose(file); - return result; - } + } + } + fclose(file); + return result; +} #endif ////////////////////////////////////////////////////////////////////////// - static long long getPhysMemUsedByMe() - { - #if defined(MEMORYUTIL_WINDOWS) && !defined(__CYGWIN__) - PROCESS_MEMORY_COUNTERS pmc; - GetProcessMemoryInfo(GetCurrentProcess(), &pmc, sizeof(pmc)); - SIZE_T physMemUsedByMe = pmc.WorkingSetSize; - #elif defined(MEMORYUTIL_LINUX) || defined(MEMORYUTIL_APPLE) || defined(MEMORYUTIL_CYGWIN) - long long physMemUsedByMe = (long long)getValue() * (long long)1024; - #else - #error "MemoryUtil::getPhysMemUsedByMe - UnknownMachine" - #endif +static long long getPhysMemUsedByMe() +{ +#if defined(MEMORYUTIL_WINDOWS) && !defined(__CYGWIN__) + PROCESS_MEMORY_COUNTERS pmc; + GetProcessMemoryInfo(GetCurrentProcess(), &pmc, sizeof(pmc)); + SIZE_T physMemUsedByMe = pmc.WorkingSetSize; +#elif defined(MEMORYUTIL_LINUX) || defined(MEMORYUTIL_APPLE) || defined(MEMORYUTIL_CYGWIN) + long long physMemUsedByMe = (long long)getValue() * (long long)1024; +#else +#error "MemoryUtil::getPhysMemUsedByMe - UnknownMachine" +#endif - return (long long)physMemUsedByMe; - } + return (long long)physMemUsedByMe; +} ////////////////////////////////////////////////////////////////////////// -} +} // namespace Utilities #endif - diff --git a/src/cpu/VirtualFluidsCore/Visitors/Block3DVisitor.h b/src/cpu/VirtualFluidsCore/Visitors/Block3DVisitor.h index e3ce942167e1377d0fd0172caa2fea8e7b6b4474..0c3adfb893bef12351c686e88bf907ecf6e12d99 100644 --- a/src/cpu/VirtualFluidsCore/Visitors/Block3DVisitor.h +++ b/src/cpu/VirtualFluidsCore/Visitors/Block3DVisitor.h @@ -1,28 +1,28 @@ //======================================================================================= -// ____ ____ __ ______ __________ __ __ __ __ -// \ \ | | | | | _ \ |___ ___| | | | | / \ | | -// \ \ | | | | | |_) | | | | | | | / \ | | -// \ \ | | | | | _ / | | | | | | / /\ \ | | -// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ -// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| -// \ \ | | ________________________________________________________________ -// \ \ | | | ______________________________________________________________| -// \ \| | | | __ __ __ __ ______ _______ -// \ | | |_____ | | | | | | | | | _ \ / _____) -// \ | | _____| | | | | | | | | | | \ \ \_______ +// ____ ____ __ ______ __________ __ __ __ __ +// \ \ | | | | | _ \ |___ ___| | | | | / \ | | +// \ \ | | | | | |_) | | | | | | | / \ | | +// \ \ | | | | | _ / | | | | | | / /\ \ | | +// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ +// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| +// \ \ | | ________________________________________________________________ +// \ \ | | | ______________________________________________________________| +// \ \| | | | __ __ __ __ ______ _______ +// \ | | |_____ | | | | | | | | | _ \ / _____) +// \ | | _____| | | | | | | | | | | \ \ \_______ // \ | | | | |_____ | \_/ | | | | |_/ / _____ | -// \ _____| |__| |________| \_______/ |__| |______/ (_______/ +// \ _____| |__| |________| \_______/ |__| |______/ (_______/ // -// This file is part of VirtualFluids. VirtualFluids is free software: you can +// This file is part of VirtualFluids. VirtualFluids is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of +// License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. -// -// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// +// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License along // with VirtualFluids (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>. // @@ -43,44 +43,30 @@ class Grid3D; class Block3DVisitor { public: - Block3DVisitor() = default; + Block3DVisitor() = default; + + Block3DVisitor(int startLevel, int stopLevel) : startLevel(startLevel), stopLevel(stopLevel) {} + + virtual ~Block3DVisitor() = default; - Block3DVisitor(int startLevel, int stopLevel) : startLevel(startLevel), stopLevel(stopLevel) - { - } + virtual void visit(SPtr<Grid3D> grid, SPtr<Block3D> block) = 0; - virtual ~Block3DVisitor() = default; - - virtual void visit(SPtr<Grid3D> grid, SPtr<Block3D> block) = 0; - - int getStartLevel() const; - int getStopLevel() const; - void setStartLevel(int level); - void setStopLevel(int level); + int getStartLevel() const; + int getStopLevel() const; + void setStartLevel(int level); + void setStopLevel(int level); private: - int startLevel{-1}; - int stopLevel{-1}; + int startLevel{ -1 }; + int stopLevel{ -1 }; }; ////////////////////////////////////////////////////////////////////////// -inline int Block3DVisitor::getStartLevel() const -{ - return this->startLevel; -} +inline int Block3DVisitor::getStartLevel() const { return this->startLevel; } ////////////////////////////////////////////////////////////////////////// -inline int Block3DVisitor::getStopLevel() const -{ - return this->stopLevel; -} +inline int Block3DVisitor::getStopLevel() const { return this->stopLevel; } ////////////////////////////////////////////////////////////////////////// -inline void Block3DVisitor::setStartLevel(int level) -{ - this->startLevel = level; -} +inline void Block3DVisitor::setStartLevel(int level) { this->startLevel = level; } ////////////////////////////////////////////////////////////////////////// -inline void Block3DVisitor::setStopLevel(int level) -{ - this->stopLevel = level; -} +inline void Block3DVisitor::setStopLevel(int level) { this->stopLevel = level; } -#endif +#endif diff --git a/src/cpu/VirtualFluidsCore/Visitors/BoundaryConditionsBlockVisitor.cpp b/src/cpu/VirtualFluidsCore/Visitors/BoundaryConditionsBlockVisitor.cpp index 7f1e57b2469e8aa2d051043740064f0e8c7d4bd8..49d945ceb9fca2f68960d8d0456347b34a400344 100644 --- a/src/cpu/VirtualFluidsCore/Visitors/BoundaryConditionsBlockVisitor.cpp +++ b/src/cpu/VirtualFluidsCore/Visitors/BoundaryConditionsBlockVisitor.cpp @@ -1,28 +1,28 @@ //======================================================================================= -// ____ ____ __ ______ __________ __ __ __ __ -// \ \ | | | | | _ \ |___ ___| | | | | / \ | | -// \ \ | | | | | |_) | | | | | | | / \ | | -// \ \ | | | | | _ / | | | | | | / /\ \ | | -// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ -// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| -// \ \ | | ________________________________________________________________ -// \ \ | | | ______________________________________________________________| -// \ \| | | | __ __ __ __ ______ _______ -// \ | | |_____ | | | | | | | | | _ \ / _____) -// \ | | _____| | | | | | | | | | | \ \ \_______ +// ____ ____ __ ______ __________ __ __ __ __ +// \ \ | | | | | _ \ |___ ___| | | | | / \ | | +// \ \ | | | | | |_) | | | | | | | / \ | | +// \ \ | | | | | _ / | | | | | | / /\ \ | | +// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ +// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| +// \ \ | | ________________________________________________________________ +// \ \ | | | ______________________________________________________________| +// \ \| | | | __ __ __ __ ______ _______ +// \ | | |_____ | | | | | | | | | _ \ / _____) +// \ | | _____| | | | | | | | | | | \ \ \_______ // \ | | | | |_____ | \_/ | | | | |_/ / _____ | -// \ _____| |__| |________| \_______/ |__| |______/ (_______/ +// \ _____| |__| |________| \_______/ |__| |______/ (_______/ // -// This file is part of VirtualFluids. VirtualFluids is free software: you can +// This file is part of VirtualFluids. VirtualFluids is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of +// License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. -// -// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// +// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License along // with VirtualFluids (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>. // @@ -32,96 +32,79 @@ //======================================================================================= #include "BoundaryConditionsBlockVisitor.h" -#include "LBMKernel.h" +#include "BCAdapter.h" +#include "BCArray3D.h" #include "BCProcessor.h" -#include "Grid3DSystem.h" +#include "Block3D.h" #include "D3Q27EsoTwist3DSplittedVector.h" #include "DataSet3D.h" #include "Grid3D.h" -#include "BCAdapter.h" -#include "Block3D.h" -#include "BCArray3D.h" - -BoundaryConditionsBlockVisitor::BoundaryConditionsBlockVisitor() : -Block3DVisitor(0, Grid3DSystem::MAXLEVEL) -{ +#include "Grid3DSystem.h" +#include "LBMKernel.h" -} +BoundaryConditionsBlockVisitor::BoundaryConditionsBlockVisitor() : Block3DVisitor(0, Grid3DSystem::MAXLEVEL) {} ////////////////////////////////////////////////////////////////////////// -BoundaryConditionsBlockVisitor::~BoundaryConditionsBlockVisitor() -= default; +BoundaryConditionsBlockVisitor::~BoundaryConditionsBlockVisitor() = default; ////////////////////////////////////////////////////////////////////////// void BoundaryConditionsBlockVisitor::visit(SPtr<Grid3D> grid, SPtr<Block3D> block) { - if (block->getRank() == grid->getRank()) - { - SPtr<ILBMKernel> kernel = block->getKernel(); + if (block->getRank() == grid->getRank()) { + SPtr<ILBMKernel> kernel = block->getKernel(); - if (!kernel) - { - throw UbException(UB_EXARGS, "LBMKernel in " + block->toString() + "is not exist!"); - } + if (!kernel) { + throw UbException(UB_EXARGS, "LBMKernel in " + block->toString() + "is not exist!"); + } - SPtr<BCProcessor> bcProcessor = kernel->getBCProcessor(); + SPtr<BCProcessor> bcProcessor = kernel->getBCProcessor(); - if (!bcProcessor) - { - throw UbException(UB_EXARGS,"Boundary Conditions Processor is not exist!" ); - } + if (!bcProcessor) { + throw UbException(UB_EXARGS, "Boundary Conditions Processor is not exist!"); + } - SPtr<BCArray3D> bcArray = bcProcessor->getBCArray(); + SPtr<BCArray3D> bcArray = bcProcessor->getBCArray(); - bool compressible = kernel->getCompressible(); - double collFactor = kernel->getCollisionFactor(); + bool compressible = kernel->getCompressible(); + double collFactor = kernel->getCollisionFactor(); - int minX1 = 0; - int minX2 = 0; - int minX3 = 0; - int maxX1 = (int)bcArray->getNX1(); - int maxX2 = (int)bcArray->getNX2(); - int maxX3 = (int)bcArray->getNX3(); - SPtr<BoundaryConditions> bcPtr; + int minX1 = 0; + int minX2 = 0; + int minX3 = 0; + int maxX1 = (int)bcArray->getNX1(); + int maxX2 = (int)bcArray->getNX2(); + int maxX3 = (int)bcArray->getNX3(); + SPtr<BoundaryConditions> bcPtr; - bcProcessor->clearBC(); + bcProcessor->clearBC(); - SPtr<DistributionArray3D> distributions = kernel->getDataSet()->getFdistributions(); + SPtr<DistributionArray3D> distributions = kernel->getDataSet()->getFdistributions(); - for (int x3 = minX3; x3 < maxX3; x3++) - { - for (int x2 = minX2; x2 < maxX2; x2++) - { - for (int x1 = minX1; x1 < maxX1; x1++) - { - if (!bcArray->isSolid(x1, x2, x3) && !bcArray->isUndefined(x1, x2, x3)) - { - if ((bcPtr = bcArray->getBC(x1, x2, x3)) != NULL) - { - char alg = bcPtr->getBcAlgorithmType(); - SPtr<BCAlgorithm> bca = bcMap[alg]; - - if (bca) - { - bca = bca->clone(); - bca->setNodeIndex(x1, x2, x3); - bca->setBcPointer(bcPtr); - bca->addDistributions(distributions); - bca->setCollFactor(collFactor); - bca->setCompressible(compressible); - bca->setBcArray(bcArray); - bcProcessor->addBC(bca); - } - } - } + for (int x3 = minX3; x3 < maxX3; x3++) { + for (int x2 = minX2; x2 < maxX2; x2++) { + for (int x1 = minX1; x1 < maxX1; x1++) { + if (!bcArray->isSolid(x1, x2, x3) && !bcArray->isUndefined(x1, x2, x3)) { + if ((bcPtr = bcArray->getBC(x1, x2, x3)) != NULL) { + char alg = bcPtr->getBcAlgorithmType(); + SPtr<BCAlgorithm> bca = bcMap[alg]; + + if (bca) { + bca = bca->clone(); + bca->setNodeIndex(x1, x2, x3); + bca->setBcPointer(bcPtr); + bca->addDistributions(distributions); + bca->setCollFactor(collFactor); + bca->setCompressible(compressible); + bca->setBcArray(bcArray); + bcProcessor->addBC(bca); + } + } + } + } } - } - } - } + } + } } ////////////////////////////////////////////////////////////////////////// void BoundaryConditionsBlockVisitor::addBC(SPtr<BCAdapter> bc) { - bcMap.insert(std::make_pair(bc->getBcAlgorithmType(), bc->getAlgorithm())); + bcMap.insert(std::make_pair(bc->getBcAlgorithmType(), bc->getAlgorithm())); } - - - diff --git a/src/cpu/VirtualFluidsCore/Visitors/BoundaryConditionsBlockVisitor.h b/src/cpu/VirtualFluidsCore/Visitors/BoundaryConditionsBlockVisitor.h index c7ea28e58237846b74c1cf6aa80563d4c20b6427..42eefd93077c56f12c2eec3282cb3f7a1e67c208 100644 --- a/src/cpu/VirtualFluidsCore/Visitors/BoundaryConditionsBlockVisitor.h +++ b/src/cpu/VirtualFluidsCore/Visitors/BoundaryConditionsBlockVisitor.h @@ -1,28 +1,28 @@ //======================================================================================= -// ____ ____ __ ______ __________ __ __ __ __ -// \ \ | | | | | _ \ |___ ___| | | | | / \ | | -// \ \ | | | | | |_) | | | | | | | / \ | | -// \ \ | | | | | _ / | | | | | | / /\ \ | | -// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ -// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| -// \ \ | | ________________________________________________________________ -// \ \ | | | ______________________________________________________________| -// \ \| | | | __ __ __ __ ______ _______ -// \ | | |_____ | | | | | | | | | _ \ / _____) -// \ | | _____| | | | | | | | | | | \ \ \_______ +// ____ ____ __ ______ __________ __ __ __ __ +// \ \ | | | | | _ \ |___ ___| | | | | / \ | | +// \ \ | | | | | |_) | | | | | | | / \ | | +// \ \ | | | | | _ / | | | | | | / /\ \ | | +// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ +// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| +// \ \ | | ________________________________________________________________ +// \ \ | | | ______________________________________________________________| +// \ \| | | | __ __ __ __ ______ _______ +// \ | | |_____ | | | | | | | | | _ \ / _____) +// \ | | _____| | | | | | | | | | | \ \ \_______ // \ | | | | |_____ | \_/ | | | | |_/ / _____ | -// \ _____| |__| |________| \_______/ |__| |______/ (_______/ +// \ _____| |__| |________| \_______/ |__| |______/ (_______/ // -// This file is part of VirtualFluids. VirtualFluids is free software: you can +// This file is part of VirtualFluids. VirtualFluids is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of +// License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. -// -// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// +// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License along // with VirtualFluids (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>. // @@ -34,12 +34,11 @@ #ifndef BoundaryConditionBlockVisitor_h__ #define BoundaryConditionBlockVisitor_h__ -#include <map> #include <PointerDefinitions.h> +#include <map> #include "Block3DVisitor.h" - class Grid3D; class Block3D; class BCAlgorithm; @@ -49,13 +48,14 @@ class BCAdapter; class BoundaryConditionsBlockVisitor : public Block3DVisitor { public: - BoundaryConditionsBlockVisitor(); - ~BoundaryConditionsBlockVisitor() override; - - void visit(SPtr<Grid3D> grid, SPtr<Block3D> block) override; - void addBC(SPtr<BCAdapter> bc); + BoundaryConditionsBlockVisitor(); + ~BoundaryConditionsBlockVisitor() override; + + void visit(SPtr<Grid3D> grid, SPtr<Block3D> block) override; + void addBC(SPtr<BCAdapter> bc); + protected: private: - std::map<char, SPtr<BCAlgorithm> > bcMap; + std::map<char, SPtr<BCAlgorithm>> bcMap; }; #endif // BoundaryConditionBlockVisitor_h__ diff --git a/src/cpu/VirtualFluidsCore/Visitors/ChangeBoundaryDensityBlockVisitor.cpp b/src/cpu/VirtualFluidsCore/Visitors/ChangeBoundaryDensityBlockVisitor.cpp index c0dabd959bded6b2d1657584970623549eb50248..b222d2c67af03cae39a385c91f25b29962565c39 100644 --- a/src/cpu/VirtualFluidsCore/Visitors/ChangeBoundaryDensityBlockVisitor.cpp +++ b/src/cpu/VirtualFluidsCore/Visitors/ChangeBoundaryDensityBlockVisitor.cpp @@ -1,60 +1,49 @@ #include "ChangeBoundaryDensityBlockVisitor.h" -#include "LBMKernel.h" -#include "Grid3DSystem.h" -#include "BoundaryConditions.h" +#include "BCArray3D.h" #include "BCProcessor.h" -#include "Grid3D.h" #include "Block3D.h" -#include "BCArray3D.h" +#include "BoundaryConditions.h" +#include "Grid3D.h" +#include "Grid3DSystem.h" +#include "LBMKernel.h" -ChangeBoundaryDensityBlockVisitor::ChangeBoundaryDensityBlockVisitor(float oldBoundaryDensity, float newBoundaryDensity) : -Block3DVisitor(0, Grid3DSystem::MAXLEVEL), -oldBoundaryDensity(oldBoundaryDensity), -newBoundaryDensity(newBoundaryDensity) +ChangeBoundaryDensityBlockVisitor::ChangeBoundaryDensityBlockVisitor(float oldBoundaryDensity, float newBoundaryDensity) + : Block3DVisitor(0, Grid3DSystem::MAXLEVEL), oldBoundaryDensity(oldBoundaryDensity), + newBoundaryDensity(newBoundaryDensity) { - } ////////////////////////////////////////////////////////////////////////// -ChangeBoundaryDensityBlockVisitor::~ChangeBoundaryDensityBlockVisitor() -= default; +ChangeBoundaryDensityBlockVisitor::~ChangeBoundaryDensityBlockVisitor() = default; ////////////////////////////////////////////////////////////////////////// void ChangeBoundaryDensityBlockVisitor::visit(SPtr<Grid3D> grid, SPtr<Block3D> block) { - if (block->getRank() == grid->getRank()) - { - SPtr<ILBMKernel> kernel = block->getKernel(); - SPtr<BCArray3D> bcArray = kernel->getBCProcessor()->getBCArray(); + if (block->getRank() == grid->getRank()) { + SPtr<ILBMKernel> kernel = block->getKernel(); + SPtr<BCArray3D> bcArray = kernel->getBCProcessor()->getBCArray(); - int minX1 = 0; - int minX2 = 0; - int minX3 = 0; - int maxX1 = (int)bcArray->getNX1(); - int maxX2 = (int)bcArray->getNX2(); - int maxX3 = (int)bcArray->getNX3(); + int minX1 = 0; + int minX2 = 0; + int minX3 = 0; + int maxX1 = (int)bcArray->getNX1(); + int maxX2 = (int)bcArray->getNX2(); + int maxX3 = (int)bcArray->getNX3(); - for (int x3 = minX3; x3 < maxX3; x3++) - { - for (int x2 = minX2; x2 < maxX2; x2++) - { - for (int x1 = minX1; x1 < maxX1; x1++) - { - if (!bcArray->isSolid(x1, x2, x3) && !bcArray->isUndefined(x1, x2, x3)) - { - bcPtr = bcArray->getBC(x1, x2, x3); - if (bcPtr) - { - if (bcPtr->hasDensityBoundary()) - { - float bcDensity = (float) bcPtr->getBoundaryDensity(); - if (bcDensity == oldBoundaryDensity) - { - bcPtr->setBoundaryDensity(newBoundaryDensity); + for (int x3 = minX3; x3 < maxX3; x3++) { + for (int x2 = minX2; x2 < maxX2; x2++) { + for (int x1 = minX1; x1 < maxX1; x1++) { + if (!bcArray->isSolid(x1, x2, x3) && !bcArray->isUndefined(x1, x2, x3)) { + bcPtr = bcArray->getBC(x1, x2, x3); + if (bcPtr) { + if (bcPtr->hasDensityBoundary()) { + float bcDensity = (float)bcPtr->getBoundaryDensity(); + if (bcDensity == oldBoundaryDensity) { + bcPtr->setBoundaryDensity(newBoundaryDensity); + } + } } - } - } - } + } + } } - } - } - } + } + } } diff --git a/src/cpu/VirtualFluidsCore/Visitors/ChangeBoundaryDensityBlockVisitor.h b/src/cpu/VirtualFluidsCore/Visitors/ChangeBoundaryDensityBlockVisitor.h index 1baefe7adba933891c1b0689e7798a3cd3419ca7..256448a0602bb6e5ab45fc4116aac35073795ddb 100644 --- a/src/cpu/VirtualFluidsCore/Visitors/ChangeBoundaryDensityBlockVisitor.h +++ b/src/cpu/VirtualFluidsCore/Visitors/ChangeBoundaryDensityBlockVisitor.h @@ -12,13 +12,14 @@ class BoundaryConditions; class ChangeBoundaryDensityBlockVisitor : public Block3DVisitor { public: - ChangeBoundaryDensityBlockVisitor(float oldBoundaryDensity, float newBoundaryDensity); - ~ChangeBoundaryDensityBlockVisitor() override; + ChangeBoundaryDensityBlockVisitor(float oldBoundaryDensity, float newBoundaryDensity); + ~ChangeBoundaryDensityBlockVisitor() override; + + void visit(SPtr<Grid3D> grid, SPtr<Block3D> block) override; - void visit(SPtr<Grid3D> grid, SPtr<Block3D> block) override; private: - float oldBoundaryDensity; - float newBoundaryDensity; - SPtr<BoundaryConditions> bcPtr; + float oldBoundaryDensity; + float newBoundaryDensity; + SPtr<BoundaryConditions> bcPtr; }; #endif // ChangeBoundaryDensityBlockVisitor_h__ diff --git a/src/cpu/VirtualFluidsCore/Visitors/CheckRatioBlockVisitor.cpp b/src/cpu/VirtualFluidsCore/Visitors/CheckRatioBlockVisitor.cpp index 5c18afa0a89183f1d6a8f1234d3c5d3d30668e4d..1f8a9c30e1f7a98812a06716cb461ee0e7d41aba 100644 --- a/src/cpu/VirtualFluidsCore/Visitors/CheckRatioBlockVisitor.cpp +++ b/src/cpu/VirtualFluidsCore/Visitors/CheckRatioBlockVisitor.cpp @@ -1,77 +1,58 @@ #include "CheckRatioBlockVisitor.h" -#include "Grid3DSystem.h" #include "Block3D.h" #include "Grid3D.h" +#include "Grid3DSystem.h" -CheckRatioBlockVisitor::CheckRatioBlockVisitor(int levelDepth/*shut be maxGridLevel*/, bool includeNotActiveBlocks) - : Block3DVisitor(0, Grid3DSystem::MAXLEVEL) - , levelDepth(levelDepth) - , includeNotActiveBlocks(includeNotActiveBlocks) - , state(true) +CheckRatioBlockVisitor::CheckRatioBlockVisitor(int levelDepth /*shut be maxGridLevel*/, bool includeNotActiveBlocks) + : Block3DVisitor(0, Grid3DSystem::MAXLEVEL), levelDepth(levelDepth), includeNotActiveBlocks(includeNotActiveBlocks), + state(true) { } ////////////////////////////////////////////////////////////////////////// void CheckRatioBlockVisitor::visit(SPtr<Grid3D> grid, SPtr<Block3D> block) { - int ix1, ix2, ix3, level; - ix1 = block->getX1(); - ix2 = block->getX2(); - ix3 = block->getX3(); - level = block->getLevel(); - -// int nix1, nix2, nix3; - int nlev; -// int neighix1, neighix2, neighix3, - int neighlev; - std::vector<SPtr<Block3D>> neighbors; - grid->getAllNeighbors(ix1, ix2, ix3, level, this->levelDepth, neighbors); -// bool hasAdded = false; - for (size_t i = 0; i<neighbors.size(); i++) - { - if ((neighbors[i]->isActive()||includeNotActiveBlocks) - &&neighbors[i]->getLevel()>level) - { - // neighix1 = neighbors[i]->getX1(); - // neighix2 = neighbors[i]->getX2(); - // neighix3 = neighbors[i]->getX3(); - neighlev = neighbors[i]->getLevel(); - // nix1 = neighix1>>1; - // nix2 = neighix2>>1; - // nix3 = neighix3>>1; - nlev = neighlev-1; + int ix1, ix2, ix3, level; + ix1 = block->getX1(); + ix2 = block->getX2(); + ix3 = block->getX3(); + level = block->getLevel(); - if (nlev!=level) - { - //throw UbException(UB_EXARGS, "OverlapBlockVisitor::adaptBlock - leveldifferenz passt nicht, block: "+block->toString()); - //grid->expandBlock(ix1, ix2, ix3, level); - state = state&&false; - falseBlock = block; + // int nix1, nix2, nix3; + int nlev; + // int neighix1, neighix2, neighix3, + int neighlev; + std::vector<SPtr<Block3D>> neighbors; + grid->getAllNeighbors(ix1, ix2, ix3, level, this->levelDepth, neighbors); + // bool hasAdded = false; + for (size_t i = 0; i < neighbors.size(); i++) { + if ((neighbors[i]->isActive() || includeNotActiveBlocks) && neighbors[i]->getLevel() > level) { + // neighix1 = neighbors[i]->getX1(); + // neighix2 = neighbors[i]->getX2(); + // neighix3 = neighbors[i]->getX3(); + neighlev = neighbors[i]->getLevel(); + // nix1 = neighix1>>1; + // nix2 = neighix2>>1; + // nix3 = neighix3>>1; + nlev = neighlev - 1; - } - else - { - state = state&&true; - } + if (nlev != level) { + // throw UbException(UB_EXARGS, "OverlapBlockVisitor::adaptBlock - leveldifferenz passt nicht, block: + // "+block->toString()); grid->expandBlock(ix1, ix2, ix3, level); + state = state && false; + falseBlock = block; - //UBLOG(logINFO, "OverlapBlockVisitor::state= "<<state); + } else { + state = state && true; + } - - } - } + // UBLOG(logINFO, "OverlapBlockVisitor::state= "<<state); + } + } } ////////////////////////////////////////////////////////////////////////// -bool CheckRatioBlockVisitor::getState() -{ - return state; -} +bool CheckRatioBlockVisitor::getState() { return state; } ////////////////////////////////////////////////////////////////////////// -void CheckRatioBlockVisitor::resetState() -{ - state = true; -} +void CheckRatioBlockVisitor::resetState() { state = true; } ////////////////////////////////////////////////////////////////////////// -std::string CheckRatioBlockVisitor::getStateString() -{ - return falseBlock->toString(); -} +std::string CheckRatioBlockVisitor::getStateString() { return falseBlock->toString(); } ////////////////////////////////////////////////////////////////////////// diff --git a/src/cpu/VirtualFluidsCore/Visitors/CheckRatioBlockVisitor.h b/src/cpu/VirtualFluidsCore/Visitors/CheckRatioBlockVisitor.h index da666fe47ad2fdea78ee512a37f3bcba4ffc0f3c..c727447ff6395c050119b211b019540d980e67d8 100644 --- a/src/cpu/VirtualFluidsCore/Visitors/CheckRatioBlockVisitor.h +++ b/src/cpu/VirtualFluidsCore/Visitors/CheckRatioBlockVisitor.h @@ -1,8 +1,8 @@ #ifndef CheckRatioBlockVisitor_H #define CheckRatioBlockVisitor_H -#include <string> #include <PointerDefinitions.h> +#include <string> #include "Block3DVisitor.h" @@ -12,22 +12,21 @@ class Block3D; class CheckRatioBlockVisitor : public Block3DVisitor { public: - CheckRatioBlockVisitor(int levelDepth, bool includeNotActiveBlocks = true); + CheckRatioBlockVisitor(int levelDepth, bool includeNotActiveBlocks = true); - ~CheckRatioBlockVisitor() override = default; + ~CheckRatioBlockVisitor() override = default; - bool getState(); - void resetState(); - std::string getStateString(); + bool getState(); + void resetState(); + std::string getStateString(); - void visit(SPtr<Grid3D> grid, SPtr<Block3D> block) override; + void visit(SPtr<Grid3D> grid, SPtr<Block3D> block) override; private: - int levelDepth; - bool includeNotActiveBlocks; - bool state; - SPtr<Block3D> falseBlock; + int levelDepth; + bool includeNotActiveBlocks; + bool state; + SPtr<Block3D> falseBlock; }; -#endif //OverlapBlockVisitor_H - +#endif // OverlapBlockVisitor_H diff --git a/src/cpu/VirtualFluidsCore/Visitors/CoarsenCrossAndInsideGbObjectBlockVisitor.cpp b/src/cpu/VirtualFluidsCore/Visitors/CoarsenCrossAndInsideGbObjectBlockVisitor.cpp index 85047e2588259a5764f0c8193aaf68352c06b1c9..384983726353455e8c497fb26e9283b0bda0a2b3 100644 --- a/src/cpu/VirtualFluidsCore/Visitors/CoarsenCrossAndInsideGbObjectBlockVisitor.cpp +++ b/src/cpu/VirtualFluidsCore/Visitors/CoarsenCrossAndInsideGbObjectBlockVisitor.cpp @@ -3,38 +3,32 @@ #include "Grid3D.h" #include <geometry3d/GbObject3D.h> -CoarsenCrossAndInsideGbObjectBlockVisitor::CoarsenCrossAndInsideGbObjectBlockVisitor() - : Block3DVisitor() -{ -} +CoarsenCrossAndInsideGbObjectBlockVisitor::CoarsenCrossAndInsideGbObjectBlockVisitor() : Block3DVisitor() {} ////////////////////////////////////////////////////////////////////////// -CoarsenCrossAndInsideGbObjectBlockVisitor::CoarsenCrossAndInsideGbObjectBlockVisitor(SPtr<GbObject3D> geoObject, int fineLevel, int coarseLevel) - : Block3DVisitor(fineLevel, fineLevel), geoObject(geoObject), coarseLevel(coarseLevel) +CoarsenCrossAndInsideGbObjectBlockVisitor::CoarsenCrossAndInsideGbObjectBlockVisitor(SPtr<GbObject3D> geoObject, + int fineLevel, int coarseLevel) + : Block3DVisitor(fineLevel, fineLevel), geoObject(geoObject), coarseLevel(coarseLevel) { - } ////////////////////////////////////////////////////////////////////////// -CoarsenCrossAndInsideGbObjectBlockVisitor::~CoarsenCrossAndInsideGbObjectBlockVisitor() -= default; +CoarsenCrossAndInsideGbObjectBlockVisitor::~CoarsenCrossAndInsideGbObjectBlockVisitor() = default; ////////////////////////////////////////////////////////////////////////// void CoarsenCrossAndInsideGbObjectBlockVisitor::visit(const SPtr<Grid3D> grid, SPtr<Block3D> block) { - int fineLevel = block->getLevel(); - if (notActive && block->isNotActive()) return; - if (fineLevel>this->getStopLevel()) return; + int fineLevel = block->getLevel(); + if (notActive && block->isNotActive()) + return; + if (fineLevel > this->getStopLevel()) + return; - UbTupleDouble3 coords = grid->getBlockWorldCoordinates(block); - UbTupleDouble3 deltas = grid->getBlockLengths(block); - if (geoObject->isCellInsideOrCuttingGbObject3D(val<1>(coords) - , val<2>(coords) - , val<3>(coords) - , val<1>(coords)+val<1>(deltas) - , val<2>(coords)+val<2>(deltas) - , val<3>(coords)+val<3>(deltas))) - { - grid->collapseBlock(block->getX1(), block->getX2(), block->getX3(), fineLevel, coarseLevel); - } + UbTupleDouble3 coords = grid->getBlockWorldCoordinates(block); + UbTupleDouble3 deltas = grid->getBlockLengths(block); + if (geoObject->isCellInsideOrCuttingGbObject3D(val<1>(coords), val<2>(coords), val<3>(coords), + val<1>(coords) + val<1>(deltas), val<2>(coords) + val<2>(deltas), + val<3>(coords) + val<3>(deltas))) { + grid->collapseBlock(block->getX1(), block->getX2(), block->getX3(), fineLevel, coarseLevel); + } - return; + return; } ////////////////////////////////////////////////////////////////////////// diff --git a/src/cpu/VirtualFluidsCore/Visitors/CoarsenCrossAndInsideGbObjectBlockVisitor.h b/src/cpu/VirtualFluidsCore/Visitors/CoarsenCrossAndInsideGbObjectBlockVisitor.h index a62e6dc8dac71e4e1ad4d7c6f1beebdde53823dd..0c234358dbadeb6a1b48de8ae98a19dcd6722c1f 100644 --- a/src/cpu/VirtualFluidsCore/Visitors/CoarsenCrossAndInsideGbObjectBlockVisitor.h +++ b/src/cpu/VirtualFluidsCore/Visitors/CoarsenCrossAndInsideGbObjectBlockVisitor.h @@ -10,24 +10,24 @@ class Block3D; class Grid3D; //! \brief Refine blocks on base of bounding box which is defined with <i>geoObject</i> -//! \details The class uses a geometry object for define a bounding box. Inside and across this bounding box will be grid on block basis refinement. -//! \author K. Kutscher +//! \details The class uses a geometry object for define a bounding box. Inside and across this bounding box will be +//! grid on block basis refinement. \author K. Kutscher class CoarsenCrossAndInsideGbObjectBlockVisitor : public Block3DVisitor { public: - //! A default constructor - CoarsenCrossAndInsideGbObjectBlockVisitor(); - //! A constructor - //! \param geoObject a smart pointer to bounding box - //! \param refineLevel an integer for refine on this level - CoarsenCrossAndInsideGbObjectBlockVisitor(SPtr<GbObject3D> geoObject, int fineLevel, int coarseLevel); - ~CoarsenCrossAndInsideGbObjectBlockVisitor() override; - void visit(SPtr<Grid3D> grid, SPtr<Block3D> block) override; - ////////////////////////////////////////////////////////////////////////// + //! A default constructor + CoarsenCrossAndInsideGbObjectBlockVisitor(); + //! A constructor + //! \param geoObject a smart pointer to bounding box + //! \param refineLevel an integer for refine on this level + CoarsenCrossAndInsideGbObjectBlockVisitor(SPtr<GbObject3D> geoObject, int fineLevel, int coarseLevel); + ~CoarsenCrossAndInsideGbObjectBlockVisitor() override; + void visit(SPtr<Grid3D> grid, SPtr<Block3D> block) override; + ////////////////////////////////////////////////////////////////////////// protected: SPtr<GbObject3D> geoObject; - bool notActive{true}; - int coarseLevel; + bool notActive{ true }; + int coarseLevel; }; -#endif +#endif diff --git a/src/cpu/VirtualFluidsCore/Visitors/ConnectorBlockVisitor.cpp b/src/cpu/VirtualFluidsCore/Visitors/ConnectorBlockVisitor.cpp index 01256a40c3f54e8931312a29fac24d0ad0efafd5..df20a2de7eb9327ad732211cfa9023e892d29e8c 100644 --- a/src/cpu/VirtualFluidsCore/Visitors/ConnectorBlockVisitor.cpp +++ b/src/cpu/VirtualFluidsCore/Visitors/ConnectorBlockVisitor.cpp @@ -1,471 +1,464 @@ #include "ConnectorBlockVisitor.h" -#include "Grid3DSystem.h" -#include "ConnectorFactory.h" -#include "InterpolationProcessor.h" #include "Communicator.h" +#include "ConnectorFactory.h" #include "Grid3D.h" +#include "Grid3DSystem.h" +#include "InterpolationProcessor.h" -ConnectorBlockVisitor::ConnectorBlockVisitor(SPtr<Communicator> comm, LBMReal nu, InterpolationProcessorPtr iProcessor, SPtr<ConnectorFactory> cFactory) : - Block3DVisitor(0, Grid3DSystem::MAXLEVEL), - comm(comm), - nu(nu), - iProcessor(iProcessor), - cFactory(cFactory) +ConnectorBlockVisitor::ConnectorBlockVisitor(SPtr<Communicator> comm, LBMReal nu, InterpolationProcessorPtr iProcessor, + SPtr<ConnectorFactory> cFactory) + : Block3DVisitor(0, Grid3DSystem::MAXLEVEL), comm(comm), nu(nu), iProcessor(iProcessor), cFactory(cFactory) { } ////////////////////////////////////////////////////////////////////////// -ConnectorBlockVisitor::~ConnectorBlockVisitor(void) -= default; +ConnectorBlockVisitor::~ConnectorBlockVisitor(void) = default; ////////////////////////////////////////////////////////////////////////// void ConnectorBlockVisitor::visit(SPtr<Grid3D> grid, SPtr<Block3D> block) { - if (!block) return; + if (!block) + return; - UBLOG(logDEBUG5, "ConnectorBlockVisitor::visit() - start"); - UBLOG(logDEBUG5, block->toString()); + UBLOG(logDEBUG5, "ConnectorBlockVisitor::visit() - start"); + UBLOG(logDEBUG5, block->toString()); - gridRank = comm->getProcessID(); - grid->setRank(gridRank); + gridRank = comm->getProcessID(); + grid->setRank(gridRank); - setSameLevelConnectors(grid, block); + setSameLevelConnectors(grid, block); - if (grid->getFinestInitializedLevel() > grid->getCoarsestInitializedLevel()) - setInterpolationConnectors(grid, block); + if (grid->getFinestInitializedLevel() > grid->getCoarsestInitializedLevel()) + setInterpolationConnectors(grid, block); - if (block->getGlobalID()==2234) - { - UBLOG(logINFO, block->toString()); - } + if (block->getGlobalID() == 2234) { + UBLOG(logINFO, block->toString()); + } - UBLOG(logDEBUG5, "ConnectorBlockVisitor::visit() - end"); + UBLOG(logDEBUG5, "ConnectorBlockVisitor::visit() - end"); } ////////////////////////////////////////////////////////////////////////// void ConnectorBlockVisitor::setSameLevelConnectors(SPtr<Grid3D> grid, SPtr<Block3D> block) { - if (block->getGlobalID()==2234) - { - UBLOG(logINFO, block->toString()); - } - UBLOG(logDEBUG5, "ConnectorBlockVisitor::setSameLevelConnectors() - start"); - int blockRank = block->getRank(); - if (gridRank == blockRank && block->isActive()) - { - block->clearWeight(); - std::vector<SPtr<Block3D>> neighbors; - int ix1 = block->getX1(); - int ix2 = block->getX2(); - int ix3 = block->getX3(); - int level = block->getLevel(); - - for (int dir = 0; dir < D3Q27System::ENDDIR; dir++) - { - SPtr<Block3D> neighBlock = grid->getNeighborBlock(dir, ix1, ix2, ix3, level); - - if (neighBlock) - { - int neighBlockRank = neighBlock->getRank(); - if (blockRank == neighBlockRank && neighBlock->isActive()) - { - SPtr<Block3DConnector> connector; - connector = cFactory->createSameLevelDirectConnector(block, neighBlock, dir); - block->setConnector(connector); - } - else if (blockRank != neighBlockRank && neighBlock->isActive()) - { - setRemoteConnectors(block, neighBlock, dir); + if (block->getGlobalID() == 2234) { + UBLOG(logINFO, block->toString()); + } + UBLOG(logDEBUG5, "ConnectorBlockVisitor::setSameLevelConnectors() - start"); + int blockRank = block->getRank(); + if (gridRank == blockRank && block->isActive()) { + block->clearWeight(); + std::vector<SPtr<Block3D>> neighbors; + int ix1 = block->getX1(); + int ix2 = block->getX2(); + int ix3 = block->getX3(); + int level = block->getLevel(); + + for (int dir = 0; dir < D3Q27System::ENDDIR; dir++) { + SPtr<Block3D> neighBlock = grid->getNeighborBlock(dir, ix1, ix2, ix3, level); + + if (neighBlock) { + int neighBlockRank = neighBlock->getRank(); + if (blockRank == neighBlockRank && neighBlock->isActive()) { + SPtr<Block3DConnector> connector; + connector = cFactory->createSameLevelDirectConnector(block, neighBlock, dir); + block->setConnector(connector); + } else if (blockRank != neighBlockRank && neighBlock->isActive()) { + setRemoteConnectors(block, neighBlock, dir); + } } - } - } - } - UBLOG(logDEBUG5, "ConnectorBlockVisitor::setSameLevelConnectors() - end"); - if (block->getGlobalID()==2234) - { - UBLOG(logINFO, block->toString()); - } + } + } + UBLOG(logDEBUG5, "ConnectorBlockVisitor::setSameLevelConnectors() - end"); + if (block->getGlobalID() == 2234) { + UBLOG(logINFO, block->toString()); + } } ////////////////////////////////////////////////////////////////////////// void ConnectorBlockVisitor::setRemoteConnectors(SPtr<Block3D> sblock, SPtr<Block3D> tblock, int dir) { - UBLOG(logDEBUG5, "ConnectorBlockVisitor::setRemoteConnectors() - start"); - CreateTransmittersHelper helper; - CreateTransmittersHelper::TransmitterPtr sender, receiver; - helper.createTransmitters(sblock, tblock, dir, CreateTransmittersHelper::NONE, sender, receiver, comm, CreateTransmittersHelper::MPI); - - - SPtr<Block3DConnector> connector; - connector = cFactory->createSameLevelVectorConnector(sblock, sender, receiver, dir); - sblock->setConnector(connector); - UBLOG(logDEBUG5, "ConnectorBlockVisitor::setRemoteConnectors() - end"); + UBLOG(logDEBUG5, "ConnectorBlockVisitor::setRemoteConnectors() - start"); + CreateTransmittersHelper helper; + CreateTransmittersHelper::TransmitterPtr sender, receiver; + helper.createTransmitters(sblock, tblock, dir, CreateTransmittersHelper::NONE, sender, receiver, comm, + CreateTransmittersHelper::MPI); + + SPtr<Block3DConnector> connector; + connector = cFactory->createSameLevelVectorConnector(sblock, sender, receiver, dir); + sblock->setConnector(connector); + UBLOG(logDEBUG5, "ConnectorBlockVisitor::setRemoteConnectors() - end"); } ////////////////////////////////////////////////////////////////////////// void ConnectorBlockVisitor::setInterpolationConnectors(SPtr<Grid3D> grid, SPtr<Block3D> block) { - if (block->getGlobalID()==2234) - { - UBLOG(logINFO, block->toString()); - } - UBLOG(logDEBUG5, "ConnectorBlockVisitor::setInterpolationConnectors() - start"); -// int blockRank = block->getRank(); - - //search for all blocks with different ranks - if (block->hasInterpolationFlagCF() && block->isActive()) - { - int fbx1 = block->getX1() << 1; - int fbx2 = block->getX2() << 1; - int fbx3 = block->getX3() << 1; - int level = block->getLevel() + 1; - - if (block->hasInterpolationFlagCF(D3Q27System::E)) - { - SPtr<Block3D> fblock00 = grid->getBlock(fbx1+1, fbx2, fbx3, level); - SPtr<Block3D> fblock10 = grid->getBlock(fbx1+1, fbx2+1, fbx3, level); - SPtr<Block3D> fblock01 = grid->getBlock(fbx1+1, fbx2, fbx3+1, level); - SPtr<Block3D> fblock11 = grid->getBlock(fbx1+1, fbx2+1, fbx3+1, level); - - setInterpolationConnectors(fblock00, fblock10, fblock01, fblock11, block, D3Q27System::E); - } - if (block->hasInterpolationFlagCF(D3Q27System::W)) - { - SPtr<Block3D> fblock00 = grid->getBlock(fbx1, fbx2, fbx3, level); - SPtr<Block3D> fblock10 = grid->getBlock(fbx1, fbx2+1, fbx3, level); - SPtr<Block3D> fblock01 = grid->getBlock(fbx1, fbx2, fbx3+1, level); - SPtr<Block3D> fblock11 = grid->getBlock(fbx1, fbx2+1, fbx3+1, level); - - setInterpolationConnectors(fblock00, fblock10, fblock01, fblock11, block, D3Q27System::W); - } - if (block->hasInterpolationFlagCF(D3Q27System::N)) - { - SPtr<Block3D> fblock00 = grid->getBlock(fbx1, fbx2+1, fbx3, level); - SPtr<Block3D> fblock10 = grid->getBlock(fbx1+1, fbx2+1, fbx3, level); - SPtr<Block3D> fblock01 = grid->getBlock(fbx1, fbx2+1, fbx3+1, level); - SPtr<Block3D> fblock11 = grid->getBlock(fbx1+1, fbx2+1, fbx3+1, level); - - setInterpolationConnectors(fblock00, fblock10, fblock01, fblock11, block, D3Q27System::N); - } - if (block->hasInterpolationFlagCF(D3Q27System::S)) - { - SPtr<Block3D> fblock00 = grid->getBlock(fbx1, fbx2, fbx3, level); - SPtr<Block3D> fblock10 = grid->getBlock(fbx1+1, fbx2, fbx3, level); - SPtr<Block3D> fblock01 = grid->getBlock(fbx1, fbx2, fbx3+1, level); - SPtr<Block3D> fblock11 = grid->getBlock(fbx1+1, fbx2, fbx3+1, level); - - setInterpolationConnectors(fblock00, fblock10, fblock01, fblock11, block, D3Q27System::S); - } - if (block->hasInterpolationFlagCF(D3Q27System::T)) - { - SPtr<Block3D> fblock00 = grid->getBlock(fbx1, fbx2, fbx3+1, level); - SPtr<Block3D> fblock10 = grid->getBlock(fbx1+1, fbx2, fbx3+1, level); - SPtr<Block3D> fblock01 = grid->getBlock(fbx1, fbx2+1, fbx3+1, level); - SPtr<Block3D> fblock11 = grid->getBlock(fbx1+1, fbx2+1, fbx3+1, level); - - setInterpolationConnectors(fblock00, fblock10, fblock01, fblock11, block, D3Q27System::T); - } - if (block->hasInterpolationFlagCF(D3Q27System::B)) - { - SPtr<Block3D> fblock00 = grid->getBlock(fbx1, fbx2, fbx3, level); - SPtr<Block3D> fblock10 = grid->getBlock(fbx1+1, fbx2, fbx3, level); - SPtr<Block3D> fblock01 = grid->getBlock(fbx1, fbx2+1, fbx3, level); - SPtr<Block3D> fblock11 = grid->getBlock(fbx1+1, fbx2+1, fbx3, level); - - setInterpolationConnectors(fblock00, fblock10, fblock01, fblock11, block, D3Q27System::B); - } - - //////NE-NW-SE-SW - if (block->hasInterpolationFlagCF(D3Q27System::NE)&&!block->hasInterpolationFlagCF(D3Q27System::N) && !block->hasInterpolationFlagCF(D3Q27System::E)) - { - SPtr<Block3D> fblock00 = grid->getBlock(fbx1+1, fbx2+1, fbx3+0, level); - SPtr<Block3D> fblock10 = grid->getBlock(fbx1+1, fbx2+1, fbx3+1, level); - SPtr<Block3D> fblock01; - SPtr<Block3D> fblock11; - - setInterpolationConnectors(fblock00, fblock10, fblock01, fblock11, block, D3Q27System::NE); - } - if (block->hasInterpolationFlagCF(D3Q27System::SW)&& !block->hasInterpolationFlagCF(D3Q27System::W) && !block->hasInterpolationFlagCF(D3Q27System::S)) - { - SPtr<Block3D> fblock00 = grid->getBlock(fbx1, fbx2, fbx3, level); - SPtr<Block3D> fblock10 = grid->getBlock(fbx1, fbx2, fbx3+1, level); - SPtr<Block3D> fblock01; - SPtr<Block3D> fblock11; - - setInterpolationConnectors(fblock00, fblock10, fblock01, fblock11, block, D3Q27System::SW); - } - if (block->hasInterpolationFlagCF(D3Q27System::SE)&& !block->hasInterpolationFlagCF(D3Q27System::E) && !block->hasInterpolationFlagCF(D3Q27System::S)) - { - SPtr<Block3D> fblock00 = grid->getBlock(fbx1+1, fbx2, fbx3+0, level); - SPtr<Block3D> fblock10 = grid->getBlock(fbx1+1, fbx2, fbx3+1, level); - SPtr<Block3D> fblock01; - SPtr<Block3D> fblock11; - - setInterpolationConnectors(fblock00, fblock10, fblock01, fblock11, block, D3Q27System::SE); - } - if (block->hasInterpolationFlagCF(D3Q27System::NW)&& !block->hasInterpolationFlagCF(D3Q27System::N) && !block->hasInterpolationFlagCF(D3Q27System::W)) - { - SPtr<Block3D> fblock00 = grid->getBlock(fbx1, fbx2+1, fbx3, level); - SPtr<Block3D> fblock10 = grid->getBlock(fbx1, fbx2+1, fbx3+1, level); - SPtr<Block3D> fblock01; - SPtr<Block3D> fblock11; - - setInterpolationConnectors(fblock00, fblock10, fblock01, fblock11, block, D3Q27System::NW); - } - - /////////TE-BW-BE-TW 1-0 - if (block->hasInterpolationFlagCF(D3Q27System::TE)&& !block->hasInterpolationFlagCF(D3Q27System::E) && !block->hasInterpolationFlagCF(D3Q27System::T)) - { - SPtr<Block3D> fblock00 = grid->getBlock(fbx1+1, fbx2+0, fbx3+1, level); - SPtr<Block3D> fblock10 = grid->getBlock(fbx1+1, fbx2+1, fbx3+1, level); - SPtr<Block3D> fblock01; - SPtr<Block3D> fblock11; - - setInterpolationConnectors(fblock00, fblock10, fblock01, fblock11, block, D3Q27System::TE); - } - if (block->hasInterpolationFlagCF(D3Q27System::BW)&& !block->hasInterpolationFlagCF(D3Q27System::W) && !block->hasInterpolationFlagCF(D3Q27System::B)) - { - - SPtr<Block3D> fblock00 = grid->getBlock(fbx1, fbx2+0, fbx3, level); - SPtr<Block3D> fblock10 = grid->getBlock(fbx1, fbx2+1, fbx3, level); - SPtr<Block3D> fblock01; - SPtr<Block3D> fblock11; - - setInterpolationConnectors(fblock00, fblock10, fblock01, fblock11, block, D3Q27System::BW); - } - if (block->hasInterpolationFlagCF(D3Q27System::BE)&& !block->hasInterpolationFlagCF(D3Q27System::E) && !block->hasInterpolationFlagCF(D3Q27System::B)) - { - SPtr<Block3D> fblock00 = grid->getBlock(fbx1+1, fbx2+0, fbx3, level); - SPtr<Block3D> fblock10 = grid->getBlock(fbx1+1, fbx2+1, fbx3, level); - SPtr<Block3D> fblock01; - SPtr<Block3D> fblock11; - - setInterpolationConnectors(fblock00, fblock10, fblock01, fblock11, block, D3Q27System::BE); - } - if (block->hasInterpolationFlagCF(D3Q27System::TW)&& !block->hasInterpolationFlagCF(D3Q27System::W) && !block->hasInterpolationFlagCF(D3Q27System::T)) - { - SPtr<Block3D> fblock00 = grid->getBlock(fbx1, fbx2+0, fbx3+1, level); - SPtr<Block3D> fblock10 = grid->getBlock(fbx1, fbx2+1, fbx3+1, level); - SPtr<Block3D> fblock01; - SPtr<Block3D> fblock11; - - setInterpolationConnectors(fblock00, fblock10, fblock01, fblock11, block, D3Q27System::TW); - } - - //////TN-BS-BN-TS - if (block->hasInterpolationFlagCF(D3Q27System::TN)&& !block->hasInterpolationFlagCF(D3Q27System::N) && !block->hasInterpolationFlagCF(D3Q27System::T)) - { - SPtr<Block3D> fblock00 = grid->getBlock(fbx1+0, fbx2+1, fbx3+1, level); - SPtr<Block3D> fblock10 = grid->getBlock(fbx1+1, fbx2+1, fbx3+1, level); - SPtr<Block3D> fblock01; - SPtr<Block3D> fblock11; - - setInterpolationConnectors(fblock00, fblock10, fblock01, fblock11, block, D3Q27System::TN); - } - if (block->hasInterpolationFlagCF(D3Q27System::BS)&& !block->hasInterpolationFlagCF(D3Q27System::S) && !block->hasInterpolationFlagCF(D3Q27System::B)) - { - SPtr<Block3D> fblock00 = grid->getBlock(fbx1+0, fbx2, fbx3, level); - SPtr<Block3D> fblock10 = grid->getBlock(fbx1+1, fbx2, fbx3, level); - SPtr<Block3D> fblock01; - SPtr<Block3D> fblock11; - - setInterpolationConnectors(fblock00, fblock10, fblock01, fblock11, block, D3Q27System::BS); - } - if (block->hasInterpolationFlagCF(D3Q27System::BN)&& !block->hasInterpolationFlagCF(D3Q27System::N) && !block->hasInterpolationFlagCF(D3Q27System::B)) - { - SPtr<Block3D> fblock00 = grid->getBlock(fbx1+0, fbx2+1, fbx3, level); - SPtr<Block3D> fblock10 = grid->getBlock(fbx1+1, fbx2+1, fbx3, level); - SPtr<Block3D> fblock01; - SPtr<Block3D> fblock11; - - setInterpolationConnectors(fblock00, fblock10, fblock01, fblock11, block, D3Q27System::BN); - } - if (block->hasInterpolationFlagCF(D3Q27System::TS)&& !block->hasInterpolationFlagCF(D3Q27System::S) && !block->hasInterpolationFlagCF(D3Q27System::T)) - { - SPtr<Block3D> fblock00 = grid->getBlock(fbx1+0, fbx2, fbx3+1, level); - SPtr<Block3D> fblock10 = grid->getBlock(fbx1+1, fbx2, fbx3+1, level); - SPtr<Block3D> fblock01; - SPtr<Block3D> fblock11; - - setInterpolationConnectors(fblock00, fblock10, fblock01, fblock11, block, D3Q27System::TS); - } - - - - - //////corners - if (block->hasInterpolationFlagCF(D3Q27System::TNE)&&!block->hasInterpolationFlagCF(D3Q27System::TE)&&!block->hasInterpolationFlagCF(D3Q27System::TN)&&!block->hasInterpolationFlagCF(D3Q27System::NE)&&!block->hasInterpolationFlagCF(D3Q27System::T)&&!block->hasInterpolationFlagCF(D3Q27System::N) && !block->hasInterpolationFlagCF(D3Q27System::E)) - { - SPtr<Block3D> fblock00 = grid->getBlock(fbx1+1, fbx2+1, fbx3+1, level); - SPtr<Block3D> fblock10;// = grid->getBlock(fbx1+1, fbx2+1, fbx3+0, level); - SPtr<Block3D> fblock01;// = grid->getBlock(fbx1+1, fbx2+1, fbx3+1, level); - SPtr<Block3D> fblock11;// = grid->getBlock(fbx1+1, fbx2+1, fbx3+1, level); - - setInterpolationConnectors(fblock00, fblock10, fblock01, fblock11, block, D3Q27System::TNE); - } - if (block->hasInterpolationFlagCF(D3Q27System::TSW)&&!block->hasInterpolationFlagCF(D3Q27System::TW)&&!block->hasInterpolationFlagCF(D3Q27System::TS)&& !block->hasInterpolationFlagCF(D3Q27System::SW)&& !block->hasInterpolationFlagCF(D3Q27System::T)&& !block->hasInterpolationFlagCF(D3Q27System::W) && !block->hasInterpolationFlagCF(D3Q27System::S)) - { - SPtr<Block3D> fblock00 = grid->getBlock(fbx1, fbx2, fbx3+1, level); - SPtr<Block3D> fblock10;// = grid->getBlock(fbx1, fbx2, fbx3, level); - SPtr<Block3D> fblock01;// = grid->getBlock(fbx1, fbx2, fbx3+1, level); - SPtr<Block3D> fblock11;// = grid->getBlock(fbx1, fbx2, fbx3+1, level); - - setInterpolationConnectors(fblock00, fblock10, fblock01, fblock11, block, D3Q27System::TSW); - } - if (block->hasInterpolationFlagCF(D3Q27System::TSE)&&!block->hasInterpolationFlagCF(D3Q27System::TE)&&!block->hasInterpolationFlagCF(D3Q27System::TS)&& !block->hasInterpolationFlagCF(D3Q27System::SE)&& !block->hasInterpolationFlagCF(D3Q27System::T)&& !block->hasInterpolationFlagCF(D3Q27System::E) && !block->hasInterpolationFlagCF(D3Q27System::S)) - { - SPtr<Block3D> fblock00 = grid->getBlock(fbx1+1, fbx2, fbx3+1, level); - SPtr<Block3D> fblock10;// = grid->getBlock(fbx1+1, fbx2, fbx3+0, level); - SPtr<Block3D> fblock01;// = grid->getBlock(fbx1+1, fbx2, fbx3+1, level); - SPtr<Block3D> fblock11;// = grid->getBlock(fbx1+1, fbx2, fbx3+1, level); - - setInterpolationConnectors(fblock00, fblock10, fblock01, fblock11, block, D3Q27System::TSE); - } - if (block->hasInterpolationFlagCF(D3Q27System::TNW)&&!block->hasInterpolationFlagCF(D3Q27System::TW)&&!block->hasInterpolationFlagCF(D3Q27System::TN)&& !block->hasInterpolationFlagCF(D3Q27System::NW)&& !block->hasInterpolationFlagCF(D3Q27System::T)&& !block->hasInterpolationFlagCF(D3Q27System::N) && !block->hasInterpolationFlagCF(D3Q27System::W)) - { - SPtr<Block3D> fblock00 = grid->getBlock(fbx1, fbx2+1, fbx3+1, level); - SPtr<Block3D> fblock10;// = grid->getBlock(fbx1, fbx2+1, fbx3, level); - SPtr<Block3D> fblock01;// = grid->getBlock(fbx1, fbx2+1, fbx3+1, level); - SPtr<Block3D> fblock11;// = grid->getBlock(fbx1, fbx2+1, fbx3+1, level); - - setInterpolationConnectors(fblock00, fblock10, fblock01, fblock11, block, D3Q27System::TNW); - } - if (block->hasInterpolationFlagCF(D3Q27System::BNE)&&!block->hasInterpolationFlagCF(D3Q27System::BE)&&!block->hasInterpolationFlagCF(D3Q27System::BN)&& !block->hasInterpolationFlagCF(D3Q27System::NE)&&!block->hasInterpolationFlagCF(D3Q27System::B)&&!block->hasInterpolationFlagCF(D3Q27System::N) && !block->hasInterpolationFlagCF(D3Q27System::E)) - { - SPtr<Block3D> fblock00 = grid->getBlock(fbx1+1, fbx2+1, fbx3+0, level); - SPtr<Block3D> fblock10;// = grid->getBlock(fbx1+1, fbx2+1, fbx3+0, level); - SPtr<Block3D> fblock01;// = grid->getBlock(fbx1+1, fbx2+1, fbx3+1, level); - SPtr<Block3D> fblock11;// = grid->getBlock(fbx1+1, fbx2+1, fbx3+1, level); - - setInterpolationConnectors(fblock00, fblock10, fblock01, fblock11, block, D3Q27System::BNE); - } - if (block->hasInterpolationFlagCF(D3Q27System::BSW)&& !block->hasInterpolationFlagCF(D3Q27System::BS)&& !block->hasInterpolationFlagCF(D3Q27System::BW)&& !block->hasInterpolationFlagCF(D3Q27System::SW)&& !block->hasInterpolationFlagCF(D3Q27System::B)&& !block->hasInterpolationFlagCF(D3Q27System::W) && !block->hasInterpolationFlagCF(D3Q27System::S)) - { - SPtr<Block3D> fblock00 = grid->getBlock(fbx1, fbx2, fbx3+0, level); - SPtr<Block3D> fblock10;// = grid->getBlock(fbx1, fbx2, fbx3, level); - SPtr<Block3D> fblock01;// = grid->getBlock(fbx1, fbx2, fbx3+1, level); - SPtr<Block3D> fblock11;// = grid->getBlock(fbx1, fbx2, fbx3+1, level); - - setInterpolationConnectors(fblock00, fblock10, fblock01, fblock11, block, D3Q27System::BSW); - } - if (block->hasInterpolationFlagCF(D3Q27System::BSE)&& !block->hasInterpolationFlagCF(D3Q27System::BS)&& !block->hasInterpolationFlagCF(D3Q27System::BE)&& !block->hasInterpolationFlagCF(D3Q27System::SE)&& !block->hasInterpolationFlagCF(D3Q27System::B)&& !block->hasInterpolationFlagCF(D3Q27System::E) && !block->hasInterpolationFlagCF(D3Q27System::S)) - { - SPtr<Block3D> fblock00 = grid->getBlock(fbx1+1, fbx2, fbx3, level); - SPtr<Block3D> fblock10;// = grid->getBlock(fbx1+1, fbx2, fbx3+0, level); - SPtr<Block3D> fblock01;// = grid->getBlock(fbx1+1, fbx2, fbx3+1, level); - SPtr<Block3D> fblock11;// = grid->getBlock(fbx1+1, fbx2, fbx3+1, level); - - setInterpolationConnectors(fblock00, fblock10, fblock01, fblock11, block, D3Q27System::BSE); - } - if (block->hasInterpolationFlagCF(D3Q27System::BNW)&& !block->hasInterpolationFlagCF(D3Q27System::BN)&& !block->hasInterpolationFlagCF(D3Q27System::BW)&& !block->hasInterpolationFlagCF(D3Q27System::NW)&& !block->hasInterpolationFlagCF(D3Q27System::B)&& !block->hasInterpolationFlagCF(D3Q27System::N) && !block->hasInterpolationFlagCF(D3Q27System::W)) - { - SPtr<Block3D> fblock00 = grid->getBlock(fbx1, fbx2+1, fbx3+0, level); - SPtr<Block3D> fblock10;// = grid->getBlock(fbx1, fbx2+1, fbx3, level); - SPtr<Block3D> fblock01;// = grid->getBlock(fbx1, fbx2+1, fbx3+1, level); - SPtr<Block3D> fblock11;// = grid->getBlock(fbx1, fbx2+1, fbx3+1, level); - - setInterpolationConnectors(fblock00, fblock10, fblock01, fblock11, block, D3Q27System::BNW); - } - - } - UBLOG(logDEBUG5, "ConnectorBlockVisitor::setInterpolationConnectors() - end"); + if (block->getGlobalID() == 2234) { + UBLOG(logINFO, block->toString()); + } + UBLOG(logDEBUG5, "ConnectorBlockVisitor::setInterpolationConnectors() - start"); + // int blockRank = block->getRank(); + + // search for all blocks with different ranks + if (block->hasInterpolationFlagCF() && block->isActive()) { + int fbx1 = block->getX1() << 1; + int fbx2 = block->getX2() << 1; + int fbx3 = block->getX3() << 1; + int level = block->getLevel() + 1; + + if (block->hasInterpolationFlagCF(D3Q27System::E)) { + SPtr<Block3D> fblock00 = grid->getBlock(fbx1 + 1, fbx2, fbx3, level); + SPtr<Block3D> fblock10 = grid->getBlock(fbx1 + 1, fbx2 + 1, fbx3, level); + SPtr<Block3D> fblock01 = grid->getBlock(fbx1 + 1, fbx2, fbx3 + 1, level); + SPtr<Block3D> fblock11 = grid->getBlock(fbx1 + 1, fbx2 + 1, fbx3 + 1, level); + + setInterpolationConnectors(fblock00, fblock10, fblock01, fblock11, block, D3Q27System::E); + } + if (block->hasInterpolationFlagCF(D3Q27System::W)) { + SPtr<Block3D> fblock00 = grid->getBlock(fbx1, fbx2, fbx3, level); + SPtr<Block3D> fblock10 = grid->getBlock(fbx1, fbx2 + 1, fbx3, level); + SPtr<Block3D> fblock01 = grid->getBlock(fbx1, fbx2, fbx3 + 1, level); + SPtr<Block3D> fblock11 = grid->getBlock(fbx1, fbx2 + 1, fbx3 + 1, level); + + setInterpolationConnectors(fblock00, fblock10, fblock01, fblock11, block, D3Q27System::W); + } + if (block->hasInterpolationFlagCF(D3Q27System::N)) { + SPtr<Block3D> fblock00 = grid->getBlock(fbx1, fbx2 + 1, fbx3, level); + SPtr<Block3D> fblock10 = grid->getBlock(fbx1 + 1, fbx2 + 1, fbx3, level); + SPtr<Block3D> fblock01 = grid->getBlock(fbx1, fbx2 + 1, fbx3 + 1, level); + SPtr<Block3D> fblock11 = grid->getBlock(fbx1 + 1, fbx2 + 1, fbx3 + 1, level); + + setInterpolationConnectors(fblock00, fblock10, fblock01, fblock11, block, D3Q27System::N); + } + if (block->hasInterpolationFlagCF(D3Q27System::S)) { + SPtr<Block3D> fblock00 = grid->getBlock(fbx1, fbx2, fbx3, level); + SPtr<Block3D> fblock10 = grid->getBlock(fbx1 + 1, fbx2, fbx3, level); + SPtr<Block3D> fblock01 = grid->getBlock(fbx1, fbx2, fbx3 + 1, level); + SPtr<Block3D> fblock11 = grid->getBlock(fbx1 + 1, fbx2, fbx3 + 1, level); + + setInterpolationConnectors(fblock00, fblock10, fblock01, fblock11, block, D3Q27System::S); + } + if (block->hasInterpolationFlagCF(D3Q27System::T)) { + SPtr<Block3D> fblock00 = grid->getBlock(fbx1, fbx2, fbx3 + 1, level); + SPtr<Block3D> fblock10 = grid->getBlock(fbx1 + 1, fbx2, fbx3 + 1, level); + SPtr<Block3D> fblock01 = grid->getBlock(fbx1, fbx2 + 1, fbx3 + 1, level); + SPtr<Block3D> fblock11 = grid->getBlock(fbx1 + 1, fbx2 + 1, fbx3 + 1, level); + + setInterpolationConnectors(fblock00, fblock10, fblock01, fblock11, block, D3Q27System::T); + } + if (block->hasInterpolationFlagCF(D3Q27System::B)) { + SPtr<Block3D> fblock00 = grid->getBlock(fbx1, fbx2, fbx3, level); + SPtr<Block3D> fblock10 = grid->getBlock(fbx1 + 1, fbx2, fbx3, level); + SPtr<Block3D> fblock01 = grid->getBlock(fbx1, fbx2 + 1, fbx3, level); + SPtr<Block3D> fblock11 = grid->getBlock(fbx1 + 1, fbx2 + 1, fbx3, level); + + setInterpolationConnectors(fblock00, fblock10, fblock01, fblock11, block, D3Q27System::B); + } + + //////NE-NW-SE-SW + if (block->hasInterpolationFlagCF(D3Q27System::NE) && !block->hasInterpolationFlagCF(D3Q27System::N) && + !block->hasInterpolationFlagCF(D3Q27System::E)) { + SPtr<Block3D> fblock00 = grid->getBlock(fbx1 + 1, fbx2 + 1, fbx3 + 0, level); + SPtr<Block3D> fblock10 = grid->getBlock(fbx1 + 1, fbx2 + 1, fbx3 + 1, level); + SPtr<Block3D> fblock01; + SPtr<Block3D> fblock11; + + setInterpolationConnectors(fblock00, fblock10, fblock01, fblock11, block, D3Q27System::NE); + } + if (block->hasInterpolationFlagCF(D3Q27System::SW) && !block->hasInterpolationFlagCF(D3Q27System::W) && + !block->hasInterpolationFlagCF(D3Q27System::S)) { + SPtr<Block3D> fblock00 = grid->getBlock(fbx1, fbx2, fbx3, level); + SPtr<Block3D> fblock10 = grid->getBlock(fbx1, fbx2, fbx3 + 1, level); + SPtr<Block3D> fblock01; + SPtr<Block3D> fblock11; + + setInterpolationConnectors(fblock00, fblock10, fblock01, fblock11, block, D3Q27System::SW); + } + if (block->hasInterpolationFlagCF(D3Q27System::SE) && !block->hasInterpolationFlagCF(D3Q27System::E) && + !block->hasInterpolationFlagCF(D3Q27System::S)) { + SPtr<Block3D> fblock00 = grid->getBlock(fbx1 + 1, fbx2, fbx3 + 0, level); + SPtr<Block3D> fblock10 = grid->getBlock(fbx1 + 1, fbx2, fbx3 + 1, level); + SPtr<Block3D> fblock01; + SPtr<Block3D> fblock11; + + setInterpolationConnectors(fblock00, fblock10, fblock01, fblock11, block, D3Q27System::SE); + } + if (block->hasInterpolationFlagCF(D3Q27System::NW) && !block->hasInterpolationFlagCF(D3Q27System::N) && + !block->hasInterpolationFlagCF(D3Q27System::W)) { + SPtr<Block3D> fblock00 = grid->getBlock(fbx1, fbx2 + 1, fbx3, level); + SPtr<Block3D> fblock10 = grid->getBlock(fbx1, fbx2 + 1, fbx3 + 1, level); + SPtr<Block3D> fblock01; + SPtr<Block3D> fblock11; + + setInterpolationConnectors(fblock00, fblock10, fblock01, fblock11, block, D3Q27System::NW); + } + + /////////TE-BW-BE-TW 1-0 + if (block->hasInterpolationFlagCF(D3Q27System::TE) && !block->hasInterpolationFlagCF(D3Q27System::E) && + !block->hasInterpolationFlagCF(D3Q27System::T)) { + SPtr<Block3D> fblock00 = grid->getBlock(fbx1 + 1, fbx2 + 0, fbx3 + 1, level); + SPtr<Block3D> fblock10 = grid->getBlock(fbx1 + 1, fbx2 + 1, fbx3 + 1, level); + SPtr<Block3D> fblock01; + SPtr<Block3D> fblock11; + + setInterpolationConnectors(fblock00, fblock10, fblock01, fblock11, block, D3Q27System::TE); + } + if (block->hasInterpolationFlagCF(D3Q27System::BW) && !block->hasInterpolationFlagCF(D3Q27System::W) && + !block->hasInterpolationFlagCF(D3Q27System::B)) { + + SPtr<Block3D> fblock00 = grid->getBlock(fbx1, fbx2 + 0, fbx3, level); + SPtr<Block3D> fblock10 = grid->getBlock(fbx1, fbx2 + 1, fbx3, level); + SPtr<Block3D> fblock01; + SPtr<Block3D> fblock11; + + setInterpolationConnectors(fblock00, fblock10, fblock01, fblock11, block, D3Q27System::BW); + } + if (block->hasInterpolationFlagCF(D3Q27System::BE) && !block->hasInterpolationFlagCF(D3Q27System::E) && + !block->hasInterpolationFlagCF(D3Q27System::B)) { + SPtr<Block3D> fblock00 = grid->getBlock(fbx1 + 1, fbx2 + 0, fbx3, level); + SPtr<Block3D> fblock10 = grid->getBlock(fbx1 + 1, fbx2 + 1, fbx3, level); + SPtr<Block3D> fblock01; + SPtr<Block3D> fblock11; + + setInterpolationConnectors(fblock00, fblock10, fblock01, fblock11, block, D3Q27System::BE); + } + if (block->hasInterpolationFlagCF(D3Q27System::TW) && !block->hasInterpolationFlagCF(D3Q27System::W) && + !block->hasInterpolationFlagCF(D3Q27System::T)) { + SPtr<Block3D> fblock00 = grid->getBlock(fbx1, fbx2 + 0, fbx3 + 1, level); + SPtr<Block3D> fblock10 = grid->getBlock(fbx1, fbx2 + 1, fbx3 + 1, level); + SPtr<Block3D> fblock01; + SPtr<Block3D> fblock11; + + setInterpolationConnectors(fblock00, fblock10, fblock01, fblock11, block, D3Q27System::TW); + } + + //////TN-BS-BN-TS + if (block->hasInterpolationFlagCF(D3Q27System::TN) && !block->hasInterpolationFlagCF(D3Q27System::N) && + !block->hasInterpolationFlagCF(D3Q27System::T)) { + SPtr<Block3D> fblock00 = grid->getBlock(fbx1 + 0, fbx2 + 1, fbx3 + 1, level); + SPtr<Block3D> fblock10 = grid->getBlock(fbx1 + 1, fbx2 + 1, fbx3 + 1, level); + SPtr<Block3D> fblock01; + SPtr<Block3D> fblock11; + + setInterpolationConnectors(fblock00, fblock10, fblock01, fblock11, block, D3Q27System::TN); + } + if (block->hasInterpolationFlagCF(D3Q27System::BS) && !block->hasInterpolationFlagCF(D3Q27System::S) && + !block->hasInterpolationFlagCF(D3Q27System::B)) { + SPtr<Block3D> fblock00 = grid->getBlock(fbx1 + 0, fbx2, fbx3, level); + SPtr<Block3D> fblock10 = grid->getBlock(fbx1 + 1, fbx2, fbx3, level); + SPtr<Block3D> fblock01; + SPtr<Block3D> fblock11; + + setInterpolationConnectors(fblock00, fblock10, fblock01, fblock11, block, D3Q27System::BS); + } + if (block->hasInterpolationFlagCF(D3Q27System::BN) && !block->hasInterpolationFlagCF(D3Q27System::N) && + !block->hasInterpolationFlagCF(D3Q27System::B)) { + SPtr<Block3D> fblock00 = grid->getBlock(fbx1 + 0, fbx2 + 1, fbx3, level); + SPtr<Block3D> fblock10 = grid->getBlock(fbx1 + 1, fbx2 + 1, fbx3, level); + SPtr<Block3D> fblock01; + SPtr<Block3D> fblock11; + + setInterpolationConnectors(fblock00, fblock10, fblock01, fblock11, block, D3Q27System::BN); + } + if (block->hasInterpolationFlagCF(D3Q27System::TS) && !block->hasInterpolationFlagCF(D3Q27System::S) && + !block->hasInterpolationFlagCF(D3Q27System::T)) { + SPtr<Block3D> fblock00 = grid->getBlock(fbx1 + 0, fbx2, fbx3 + 1, level); + SPtr<Block3D> fblock10 = grid->getBlock(fbx1 + 1, fbx2, fbx3 + 1, level); + SPtr<Block3D> fblock01; + SPtr<Block3D> fblock11; + + setInterpolationConnectors(fblock00, fblock10, fblock01, fblock11, block, D3Q27System::TS); + } + + //////corners + if (block->hasInterpolationFlagCF(D3Q27System::TNE) && !block->hasInterpolationFlagCF(D3Q27System::TE) && + !block->hasInterpolationFlagCF(D3Q27System::TN) && !block->hasInterpolationFlagCF(D3Q27System::NE) && + !block->hasInterpolationFlagCF(D3Q27System::T) && !block->hasInterpolationFlagCF(D3Q27System::N) && + !block->hasInterpolationFlagCF(D3Q27System::E)) { + SPtr<Block3D> fblock00 = grid->getBlock(fbx1 + 1, fbx2 + 1, fbx3 + 1, level); + SPtr<Block3D> fblock10; // = grid->getBlock(fbx1+1, fbx2+1, fbx3+0, level); + SPtr<Block3D> fblock01; // = grid->getBlock(fbx1+1, fbx2+1, fbx3+1, level); + SPtr<Block3D> fblock11; // = grid->getBlock(fbx1+1, fbx2+1, fbx3+1, level); + + setInterpolationConnectors(fblock00, fblock10, fblock01, fblock11, block, D3Q27System::TNE); + } + if (block->hasInterpolationFlagCF(D3Q27System::TSW) && !block->hasInterpolationFlagCF(D3Q27System::TW) && + !block->hasInterpolationFlagCF(D3Q27System::TS) && !block->hasInterpolationFlagCF(D3Q27System::SW) && + !block->hasInterpolationFlagCF(D3Q27System::T) && !block->hasInterpolationFlagCF(D3Q27System::W) && + !block->hasInterpolationFlagCF(D3Q27System::S)) { + SPtr<Block3D> fblock00 = grid->getBlock(fbx1, fbx2, fbx3 + 1, level); + SPtr<Block3D> fblock10; // = grid->getBlock(fbx1, fbx2, fbx3, level); + SPtr<Block3D> fblock01; // = grid->getBlock(fbx1, fbx2, fbx3+1, level); + SPtr<Block3D> fblock11; // = grid->getBlock(fbx1, fbx2, fbx3+1, level); + + setInterpolationConnectors(fblock00, fblock10, fblock01, fblock11, block, D3Q27System::TSW); + } + if (block->hasInterpolationFlagCF(D3Q27System::TSE) && !block->hasInterpolationFlagCF(D3Q27System::TE) && + !block->hasInterpolationFlagCF(D3Q27System::TS) && !block->hasInterpolationFlagCF(D3Q27System::SE) && + !block->hasInterpolationFlagCF(D3Q27System::T) && !block->hasInterpolationFlagCF(D3Q27System::E) && + !block->hasInterpolationFlagCF(D3Q27System::S)) { + SPtr<Block3D> fblock00 = grid->getBlock(fbx1 + 1, fbx2, fbx3 + 1, level); + SPtr<Block3D> fblock10; // = grid->getBlock(fbx1+1, fbx2, fbx3+0, level); + SPtr<Block3D> fblock01; // = grid->getBlock(fbx1+1, fbx2, fbx3+1, level); + SPtr<Block3D> fblock11; // = grid->getBlock(fbx1+1, fbx2, fbx3+1, level); + + setInterpolationConnectors(fblock00, fblock10, fblock01, fblock11, block, D3Q27System::TSE); + } + if (block->hasInterpolationFlagCF(D3Q27System::TNW) && !block->hasInterpolationFlagCF(D3Q27System::TW) && + !block->hasInterpolationFlagCF(D3Q27System::TN) && !block->hasInterpolationFlagCF(D3Q27System::NW) && + !block->hasInterpolationFlagCF(D3Q27System::T) && !block->hasInterpolationFlagCF(D3Q27System::N) && + !block->hasInterpolationFlagCF(D3Q27System::W)) { + SPtr<Block3D> fblock00 = grid->getBlock(fbx1, fbx2 + 1, fbx3 + 1, level); + SPtr<Block3D> fblock10; // = grid->getBlock(fbx1, fbx2+1, fbx3, level); + SPtr<Block3D> fblock01; // = grid->getBlock(fbx1, fbx2+1, fbx3+1, level); + SPtr<Block3D> fblock11; // = grid->getBlock(fbx1, fbx2+1, fbx3+1, level); + + setInterpolationConnectors(fblock00, fblock10, fblock01, fblock11, block, D3Q27System::TNW); + } + if (block->hasInterpolationFlagCF(D3Q27System::BNE) && !block->hasInterpolationFlagCF(D3Q27System::BE) && + !block->hasInterpolationFlagCF(D3Q27System::BN) && !block->hasInterpolationFlagCF(D3Q27System::NE) && + !block->hasInterpolationFlagCF(D3Q27System::B) && !block->hasInterpolationFlagCF(D3Q27System::N) && + !block->hasInterpolationFlagCF(D3Q27System::E)) { + SPtr<Block3D> fblock00 = grid->getBlock(fbx1 + 1, fbx2 + 1, fbx3 + 0, level); + SPtr<Block3D> fblock10; // = grid->getBlock(fbx1+1, fbx2+1, fbx3+0, level); + SPtr<Block3D> fblock01; // = grid->getBlock(fbx1+1, fbx2+1, fbx3+1, level); + SPtr<Block3D> fblock11; // = grid->getBlock(fbx1+1, fbx2+1, fbx3+1, level); + + setInterpolationConnectors(fblock00, fblock10, fblock01, fblock11, block, D3Q27System::BNE); + } + if (block->hasInterpolationFlagCF(D3Q27System::BSW) && !block->hasInterpolationFlagCF(D3Q27System::BS) && + !block->hasInterpolationFlagCF(D3Q27System::BW) && !block->hasInterpolationFlagCF(D3Q27System::SW) && + !block->hasInterpolationFlagCF(D3Q27System::B) && !block->hasInterpolationFlagCF(D3Q27System::W) && + !block->hasInterpolationFlagCF(D3Q27System::S)) { + SPtr<Block3D> fblock00 = grid->getBlock(fbx1, fbx2, fbx3 + 0, level); + SPtr<Block3D> fblock10; // = grid->getBlock(fbx1, fbx2, fbx3, level); + SPtr<Block3D> fblock01; // = grid->getBlock(fbx1, fbx2, fbx3+1, level); + SPtr<Block3D> fblock11; // = grid->getBlock(fbx1, fbx2, fbx3+1, level); + + setInterpolationConnectors(fblock00, fblock10, fblock01, fblock11, block, D3Q27System::BSW); + } + if (block->hasInterpolationFlagCF(D3Q27System::BSE) && !block->hasInterpolationFlagCF(D3Q27System::BS) && + !block->hasInterpolationFlagCF(D3Q27System::BE) && !block->hasInterpolationFlagCF(D3Q27System::SE) && + !block->hasInterpolationFlagCF(D3Q27System::B) && !block->hasInterpolationFlagCF(D3Q27System::E) && + !block->hasInterpolationFlagCF(D3Q27System::S)) { + SPtr<Block3D> fblock00 = grid->getBlock(fbx1 + 1, fbx2, fbx3, level); + SPtr<Block3D> fblock10; // = grid->getBlock(fbx1+1, fbx2, fbx3+0, level); + SPtr<Block3D> fblock01; // = grid->getBlock(fbx1+1, fbx2, fbx3+1, level); + SPtr<Block3D> fblock11; // = grid->getBlock(fbx1+1, fbx2, fbx3+1, level); + + setInterpolationConnectors(fblock00, fblock10, fblock01, fblock11, block, D3Q27System::BSE); + } + if (block->hasInterpolationFlagCF(D3Q27System::BNW) && !block->hasInterpolationFlagCF(D3Q27System::BN) && + !block->hasInterpolationFlagCF(D3Q27System::BW) && !block->hasInterpolationFlagCF(D3Q27System::NW) && + !block->hasInterpolationFlagCF(D3Q27System::B) && !block->hasInterpolationFlagCF(D3Q27System::N) && + !block->hasInterpolationFlagCF(D3Q27System::W)) { + SPtr<Block3D> fblock00 = grid->getBlock(fbx1, fbx2 + 1, fbx3 + 0, level); + SPtr<Block3D> fblock10; // = grid->getBlock(fbx1, fbx2+1, fbx3, level); + SPtr<Block3D> fblock01; // = grid->getBlock(fbx1, fbx2+1, fbx3+1, level); + SPtr<Block3D> fblock11; // = grid->getBlock(fbx1, fbx2+1, fbx3+1, level); + + setInterpolationConnectors(fblock00, fblock10, fblock01, fblock11, block, D3Q27System::BNW); + } + } + UBLOG(logDEBUG5, "ConnectorBlockVisitor::setInterpolationConnectors() - end"); } ////////////////////////////////////////////////////////////////////////// -void ConnectorBlockVisitor::setInterpolationConnectors(SPtr<Block3D> fblock00, SPtr<Block3D> fblock10, SPtr<Block3D> fblock01, SPtr<Block3D> fblock11, SPtr<Block3D> cBlock, int dir) +void ConnectorBlockVisitor::setInterpolationConnectors(SPtr<Block3D> fblock00, SPtr<Block3D> fblock10, + SPtr<Block3D> fblock01, SPtr<Block3D> fblock11, + SPtr<Block3D> cBlock, int dir) { - UBLOG(logDEBUG5, "ConnectorBlockVisitor::setInterpolationConnectors(...) - start"); - int fblock00Rank = -999, fblock10Rank = -999, fblock01Rank = -999, fblock11Rank = -999; - if (fblock00) fblock00Rank = fblock00->getRank(); - if (fblock01) fblock01Rank = fblock01->getRank(); - if (fblock10) fblock10Rank = fblock10->getRank(); - if (fblock11) fblock11Rank = fblock11->getRank(); - int cBlockRank = cBlock->getRank(); - - LBMReal omegaF; - if (fblock00) omegaF = LBMSystem::calcCollisionFactor(nu, fblock00->getLevel()); - if (fblock01) omegaF = LBMSystem::calcCollisionFactor(nu, fblock01->getLevel()); - if (fblock10) omegaF = LBMSystem::calcCollisionFactor(nu, fblock10->getLevel()); - if (fblock11) omegaF = LBMSystem::calcCollisionFactor(nu, fblock11->getLevel()); - LBMReal omegaC = LBMSystem::calcCollisionFactor(nu, cBlock->getLevel()); - iProcessor->setOmegas(omegaC, omegaF); - - InterpolationProcessorPtr cIProcessor(iProcessor->clone()); - InterpolationProcessorPtr fIProcessor00(iProcessor->clone()); - InterpolationProcessorPtr fIProcessor10(iProcessor->clone()); - InterpolationProcessorPtr fIProcessor01(iProcessor->clone()); - InterpolationProcessorPtr fIProcessor11(iProcessor->clone()); - - CreateTransmittersHelper::TransmitterPtr senderCF00, receiverCF00, - senderCF01, receiverCF01, - senderCF10, receiverCF10, - senderCF11, receiverCF11, - senderFC00, receiverFC00, - senderFC01, receiverFC01, - senderFC10, receiverFC10, - senderFC11, receiverFC11; - - if (fblock00) createTransmitters(cBlock, fblock00, dir, CreateTransmittersHelper::SW, senderCF00, receiverCF00, senderFC00, receiverFC00); - if (fblock01) createTransmitters(cBlock, fblock01, dir, CreateTransmittersHelper::NW, senderCF01, receiverCF01, senderFC01, receiverFC01); - if (fblock10) createTransmitters(cBlock, fblock10, dir, CreateTransmittersHelper::SE, senderCF10, receiverCF10, senderFC10, receiverFC10); - if (fblock11) createTransmitters(cBlock, fblock11, dir, CreateTransmittersHelper::NE, senderCF11, receiverCF11, senderFC11, receiverFC11); - - if (cBlockRank == gridRank) - { - SPtr<Block3DConnector> connector = cFactory->createCoarseToFineConnector(cBlock, - senderCF00, receiverCF00, senderCF01, receiverCF01, - senderCF10, receiverCF10, senderCF11, receiverCF11, - dir, cIProcessor); - cBlock->setConnector(connector); - } - if (fblock00 && fblock00Rank == gridRank) - { - SPtr<Block3DConnector> connector = cFactory->createFineToCoarseConnector(fblock00, - senderFC00, receiverFC00, dir, fIProcessor00, FineToCoarseBlock3DConnector::Type00); - fblock00->setConnector(connector); - } - if (fblock01 && fblock01Rank == gridRank) - { - SPtr<Block3DConnector> connector = cFactory->createFineToCoarseConnector(fblock01, - senderFC01, receiverFC01, dir, fIProcessor01, FineToCoarseBlock3DConnector::Type01); - fblock01->setConnector(connector); - } - if (fblock10 && fblock10Rank == gridRank) - { - SPtr<Block3DConnector> connector = cFactory->createFineToCoarseConnector(fblock10, - senderFC10, receiverFC10, dir, fIProcessor10, FineToCoarseBlock3DConnector::Type10); - fblock10->setConnector(connector); - } - if (fblock11 && fblock11Rank == gridRank) - { - SPtr<Block3DConnector> connector = cFactory->createFineToCoarseConnector(fblock11, - senderFC11, receiverFC11, dir, fIProcessor11, FineToCoarseBlock3DConnector::Type11); - fblock11->setConnector(connector); - } - UBLOG(logDEBUG5, "ConnectorBlockVisitor::setInterpolationConnectors(...) - end"); + UBLOG(logDEBUG5, "ConnectorBlockVisitor::setInterpolationConnectors(...) - start"); + int fblock00Rank = -999, fblock10Rank = -999, fblock01Rank = -999, fblock11Rank = -999; + if (fblock00) + fblock00Rank = fblock00->getRank(); + if (fblock01) + fblock01Rank = fblock01->getRank(); + if (fblock10) + fblock10Rank = fblock10->getRank(); + if (fblock11) + fblock11Rank = fblock11->getRank(); + int cBlockRank = cBlock->getRank(); + + LBMReal omegaF; + if (fblock00) + omegaF = LBMSystem::calcCollisionFactor(nu, fblock00->getLevel()); + if (fblock01) + omegaF = LBMSystem::calcCollisionFactor(nu, fblock01->getLevel()); + if (fblock10) + omegaF = LBMSystem::calcCollisionFactor(nu, fblock10->getLevel()); + if (fblock11) + omegaF = LBMSystem::calcCollisionFactor(nu, fblock11->getLevel()); + LBMReal omegaC = LBMSystem::calcCollisionFactor(nu, cBlock->getLevel()); + iProcessor->setOmegas(omegaC, omegaF); + + InterpolationProcessorPtr cIProcessor(iProcessor->clone()); + InterpolationProcessorPtr fIProcessor00(iProcessor->clone()); + InterpolationProcessorPtr fIProcessor10(iProcessor->clone()); + InterpolationProcessorPtr fIProcessor01(iProcessor->clone()); + InterpolationProcessorPtr fIProcessor11(iProcessor->clone()); + + CreateTransmittersHelper::TransmitterPtr senderCF00, receiverCF00, senderCF01, receiverCF01, senderCF10, + receiverCF10, senderCF11, receiverCF11, senderFC00, receiverFC00, senderFC01, receiverFC01, senderFC10, + receiverFC10, senderFC11, receiverFC11; + + if (fblock00) + createTransmitters(cBlock, fblock00, dir, CreateTransmittersHelper::SW, senderCF00, receiverCF00, senderFC00, + receiverFC00); + if (fblock01) + createTransmitters(cBlock, fblock01, dir, CreateTransmittersHelper::NW, senderCF01, receiverCF01, senderFC01, + receiverFC01); + if (fblock10) + createTransmitters(cBlock, fblock10, dir, CreateTransmittersHelper::SE, senderCF10, receiverCF10, senderFC10, + receiverFC10); + if (fblock11) + createTransmitters(cBlock, fblock11, dir, CreateTransmittersHelper::NE, senderCF11, receiverCF11, senderFC11, + receiverFC11); + + if (cBlockRank == gridRank) { + SPtr<Block3DConnector> connector = + cFactory->createCoarseToFineConnector(cBlock, senderCF00, receiverCF00, senderCF01, receiverCF01, + senderCF10, receiverCF10, senderCF11, receiverCF11, dir, cIProcessor); + cBlock->setConnector(connector); + } + if (fblock00 && fblock00Rank == gridRank) { + SPtr<Block3DConnector> connector = cFactory->createFineToCoarseConnector( + fblock00, senderFC00, receiverFC00, dir, fIProcessor00, FineToCoarseBlock3DConnector::Type00); + fblock00->setConnector(connector); + } + if (fblock01 && fblock01Rank == gridRank) { + SPtr<Block3DConnector> connector = cFactory->createFineToCoarseConnector( + fblock01, senderFC01, receiverFC01, dir, fIProcessor01, FineToCoarseBlock3DConnector::Type01); + fblock01->setConnector(connector); + } + if (fblock10 && fblock10Rank == gridRank) { + SPtr<Block3DConnector> connector = cFactory->createFineToCoarseConnector( + fblock10, senderFC10, receiverFC10, dir, fIProcessor10, FineToCoarseBlock3DConnector::Type10); + fblock10->setConnector(connector); + } + if (fblock11 && fblock11Rank == gridRank) { + SPtr<Block3DConnector> connector = cFactory->createFineToCoarseConnector( + fblock11, senderFC11, receiverFC11, dir, fIProcessor11, FineToCoarseBlock3DConnector::Type11); + fblock11->setConnector(connector); + } + UBLOG(logDEBUG5, "ConnectorBlockVisitor::setInterpolationConnectors(...) - end"); } ////////////////////////////////////////////////////////////////////////// void ConnectorBlockVisitor::createTransmitters(SPtr<Block3D> cBlock, SPtr<Block3D> fBlock, int dir, - CreateTransmittersHelper::IBlock ib, - CreateTransmittersHelper::TransmitterPtr& senderCF, - CreateTransmittersHelper::TransmitterPtr& receiverCF, - CreateTransmittersHelper::TransmitterPtr& senderFC, - CreateTransmittersHelper::TransmitterPtr& receiverFC) + CreateTransmittersHelper::IBlock ib, + CreateTransmittersHelper::TransmitterPtr &senderCF, + CreateTransmittersHelper::TransmitterPtr &receiverCF, + CreateTransmittersHelper::TransmitterPtr &senderFC, + CreateTransmittersHelper::TransmitterPtr &receiverFC) { - UBLOG(logDEBUG5, "ConnectorBlockVisitor::createTransmitters(...) - start"); - CreateTransmittersHelper helper; -// bool MPIpool = true; -// bool orthogonal = false; - int fBlockRank = fBlock->getRank(); - int cBlockRank = cBlock->getRank(); - if (fBlockRank == cBlockRank && fBlockRank == gridRank) - { - senderCF = receiverFC = CreateTransmittersHelper::TransmitterPtr(new TbLocalTransmitter< CbVector< LBMReal > >()); - senderFC = receiverCF = CreateTransmittersHelper::TransmitterPtr(new TbLocalTransmitter< CbVector< LBMReal > >()); - } - else if (cBlockRank == gridRank) - { - helper.createTransmitters(cBlock, fBlock, dir, ib, senderCF, receiverCF, comm, CreateTransmittersHelper::MPI); - } - else if (fBlockRank == gridRank) - { - helper.createTransmitters(fBlock, cBlock, dir, ib, senderFC, receiverFC, comm, CreateTransmittersHelper::MPI); - } - UBLOG(logDEBUG5, "ConnectorBlockVisitor::createTransmitters(...) - end"); + UBLOG(logDEBUG5, "ConnectorBlockVisitor::createTransmitters(...) - start"); + CreateTransmittersHelper helper; + // bool MPIpool = true; + // bool orthogonal = false; + int fBlockRank = fBlock->getRank(); + int cBlockRank = cBlock->getRank(); + if (fBlockRank == cBlockRank && fBlockRank == gridRank) { + senderCF = receiverFC = CreateTransmittersHelper::TransmitterPtr(new TbLocalTransmitter<CbVector<LBMReal>>()); + senderFC = receiverCF = CreateTransmittersHelper::TransmitterPtr(new TbLocalTransmitter<CbVector<LBMReal>>()); + } else if (cBlockRank == gridRank) { + helper.createTransmitters(cBlock, fBlock, dir, ib, senderCF, receiverCF, comm, CreateTransmittersHelper::MPI); + } else if (fBlockRank == gridRank) { + helper.createTransmitters(fBlock, cBlock, dir, ib, senderFC, receiverFC, comm, CreateTransmittersHelper::MPI); + } + UBLOG(logDEBUG5, "ConnectorBlockVisitor::createTransmitters(...) - end"); } - diff --git a/src/cpu/VirtualFluidsCore/Visitors/ConnectorBlockVisitor.h b/src/cpu/VirtualFluidsCore/Visitors/ConnectorBlockVisitor.h index f40083001d78d74b9b2b8d173a3059a8a4469433..97371655556b96917ee4dae1c80fac626c6aaba5 100644 --- a/src/cpu/VirtualFluidsCore/Visitors/ConnectorBlockVisitor.h +++ b/src/cpu/VirtualFluidsCore/Visitors/ConnectorBlockVisitor.h @@ -4,8 +4,8 @@ #include <PointerDefinitions.h> #include "Block3DVisitor.h" -#include "D3Q27System.h" #include "CreateTransmittersHelper.h" +#include "D3Q27System.h" class Grid3D; class Block3D; @@ -15,27 +15,27 @@ class ConnectorFactory; class ConnectorBlockVisitor : public Block3DVisitor { public: - ConnectorBlockVisitor(SPtr<Communicator> comm, LBMReal nu, SPtr<InterpolationProcessor> iProcessor, SPtr<ConnectorFactory> cFactory); - ~ConnectorBlockVisitor() override; - void visit(SPtr<Grid3D> grid, SPtr<Block3D> block) override; - ////////////////////////////////////////////////////////////////////////// + ConnectorBlockVisitor(SPtr<Communicator> comm, LBMReal nu, SPtr<InterpolationProcessor> iProcessor, + SPtr<ConnectorFactory> cFactory); + ~ConnectorBlockVisitor() override; + void visit(SPtr<Grid3D> grid, SPtr<Block3D> block) override; + ////////////////////////////////////////////////////////////////////////// protected: - void setSameLevelConnectors(SPtr<Grid3D> grid, SPtr<Block3D> block); - void setRemoteConnectors(SPtr<Block3D> sblock, SPtr<Block3D> tblock, int dir); - void setInterpolationConnectors(SPtr<Grid3D> grid, SPtr<Block3D> block); - void setInterpolationConnectors(SPtr<Block3D> fBlockSW, SPtr<Block3D> fBlockSE, SPtr<Block3D> fBlockNW, SPtr<Block3D> fBlockNE, SPtr<Block3D> cBlock, int dir); - void createTransmitters(SPtr<Block3D> cBlock, SPtr<Block3D> fBlock, int dir, - CreateTransmittersHelper::IBlock ib, - CreateTransmittersHelper::TransmitterPtr& senderCF, - CreateTransmittersHelper::TransmitterPtr& receiverCF, - CreateTransmittersHelper::TransmitterPtr& senderFC, - CreateTransmittersHelper::TransmitterPtr& receiverFC); - SPtr<Communicator> comm; - int gridRank; - LBMReal nu; - SPtr<InterpolationProcessor> iProcessor; - SPtr<ConnectorFactory> cFactory; + void setSameLevelConnectors(SPtr<Grid3D> grid, SPtr<Block3D> block); + void setRemoteConnectors(SPtr<Block3D> sblock, SPtr<Block3D> tblock, int dir); + void setInterpolationConnectors(SPtr<Grid3D> grid, SPtr<Block3D> block); + void setInterpolationConnectors(SPtr<Block3D> fBlockSW, SPtr<Block3D> fBlockSE, SPtr<Block3D> fBlockNW, + SPtr<Block3D> fBlockNE, SPtr<Block3D> cBlock, int dir); + void createTransmitters(SPtr<Block3D> cBlock, SPtr<Block3D> fBlock, int dir, CreateTransmittersHelper::IBlock ib, + CreateTransmittersHelper::TransmitterPtr &senderCF, + CreateTransmittersHelper::TransmitterPtr &receiverCF, + CreateTransmittersHelper::TransmitterPtr &senderFC, + CreateTransmittersHelper::TransmitterPtr &receiverFC); + SPtr<Communicator> comm; + int gridRank; + LBMReal nu; + SPtr<InterpolationProcessor> iProcessor; + SPtr<ConnectorFactory> cFactory; }; -#endif //ConnectorBlockVisitor_H - +#endif // ConnectorBlockVisitor_H diff --git a/src/cpu/VirtualFluidsCore/Visitors/CreateTransmittersHelper.cpp b/src/cpu/VirtualFluidsCore/Visitors/CreateTransmittersHelper.cpp index 24177504ce65eb2cc34c621077a8e6108fc171f4..6a5cdbf82b2ec37ce11224a6416beeaab5e9d558 100644 --- a/src/cpu/VirtualFluidsCore/Visitors/CreateTransmittersHelper.cpp +++ b/src/cpu/VirtualFluidsCore/Visitors/CreateTransmittersHelper.cpp @@ -1,10 +1,10 @@ #include "CreateTransmittersHelper.h" -#include <D3Q27System.h> #include <Communicator.h> +#include <D3Q27System.h> #include <string> #ifdef VF_FETOL - #include <FETOLTransmitterBondPool.h> +#include <FETOLTransmitterBondPool.h> #endif #include <MathUtil.hpp> @@ -13,146 +13,152 @@ unsigned CreateTransmittersHelper::vKey = 0; using namespace std; ////////////////////////////////////////////////////////////////////////// -CreateTransmittersHelper::CreateTransmittersHelper() -= default; +CreateTransmittersHelper::CreateTransmittersHelper() = default; ////////////////////////////////////////////////////////////////////////// void CreateTransmittersHelper::createTransmitters(SPtr<Block3D> sblock, SPtr<Block3D> tblock, int dir, IBlock ib, - TransmitterPtr& sender, TransmitterPtr& receiver, SPtr<Communicator> comm, TransmitterType tType) + TransmitterPtr &sender, TransmitterPtr &receiver, + SPtr<Communicator> comm, TransmitterType tType) { - //SourceBlock - int srcLevel = sblock->getLevel(); -// int srcID = sblock->getGlobalID(); - - //TargetBlock - int tgtLevel = tblock->getLevel(); -// int tgtID = tblock->getGlobalID(); - - int invDir = D3Q27System::INVDIR[dir]; - - if( srcLevel != tgtLevel ) invDir = dir; - - int srcRank = 0; - int tgtRank = 0; - - if (tType == MPI) - { - srcRank = sblock->getRank(); - tgtRank = tblock->getRank(); - } -#ifdef VF_FETOL - else if (tType == MPI2BOND) - { - srcRank = sblock->getLocalRank(); - tgtRank = tblock->getLocalRank(); - } -#endif + // SourceBlock + int srcLevel = sblock->getLevel(); + // int srcID = sblock->getGlobalID(); - if (tType == MPI -#ifdef VF_FETOL - || tType == MPI2BOND -#endif - ) - { - string sendPoolKey = generatePoolKey(srcRank, srcLevel, tgtRank, tgtLevel); - string receivePoolKey = generatePoolKey(tgtRank, tgtLevel, srcRank, srcLevel); - - TbCbVectorMpiPool <LBMReal>::MpiPoolPtr sendPool = TbCbVectorMpiPool <LBMReal>::getTbCbVectorMpiPool(sendPoolKey ); - TbCbVectorMpiPool <LBMReal>::MpiPoolPtr recvPool = TbCbVectorMpiPool <LBMReal>::getTbCbVectorMpiPool(receivePoolKey); - - MPI_Comm mpi_comm = *((MPI_Comm*) comm->getNativeCommunicator()); - - if( !sendPool ) sendPool = TbCbVectorMpiPool <LBMReal>::createTbCbVectorMpiPool(sendPoolKey ,tgtRank, generateMPITag(srcLevel, tgtLevel), mpi_comm); - if( !recvPool ) recvPool = TbCbVectorMpiPool <LBMReal>::createTbCbVectorMpiPool(receivePoolKey,tgtRank, generateMPITag(tgtLevel, srcLevel), mpi_comm); - - TbCbVectorMpiPool <LBMReal>::CbVectorKey keyOfSendCbVectorKey = generateVectorKey(sblock->getX1(), sblock->getX2(), sblock->getX3()/*tgtID*/, dir, ib); - TbCbVectorMpiPool <LBMReal>::CbVectorKey keyOfRecvCbVectorKey = generateVectorKey(tblock->getX1(), tblock->getX2(), tblock->getX3()/*srcID*/, invDir, ib); - - //////////////////////////////////////////////////////// - //DEBUG - //int myid = comm->getProcessID(); - //FILE * file; - ////char * name = "d:/temp/sendPoolKey.csv"; - //std::string name = "d:/temp/VectorKey" + UbSystem::toString(myid) + ".csv"; - //file = fopen(name.c_str(), "a"); - //fprintf(file, "%d;%d%;%d;%d;%d;%u;%d;%d%;%d;%d;%d;%u\n", sblock->getX1(), sblock->getX2(), sblock->getX3()/*tgtID*/, dir, ib, keyOfSendCbVectorKey, tblock->getX1(), tblock->getX2(), tblock->getX3()/*srcID*/, invDir, ib, keyOfRecvCbVectorKey); - //fclose(file); - //////////////////////////////////////////////////////// - - //create sender-/receiver - sender = TransmitterPtr( new TbCbVectorSenderMpiPool< LBMReal >(keyOfSendCbVectorKey,sendPool.get()) ); - receiver = TransmitterPtr( new TbCbVectorReceiverMpiPool< LBMReal >(keyOfRecvCbVectorKey,recvPool.get()) ); - } -#ifdef VF_FETOL - if (tType == BOND) - { - int srcBondRank = sblock->getRank(); - int tgtBondRank = tblock->getRank(); + // TargetBlock + int tgtLevel = tblock->getLevel(); + // int tgtID = tblock->getGlobalID(); - int sendBondPoolKey = generatePoolKey(srcBondRank,srcLevel,tgtBondRank,tgtLevel); - int receiveBondPoolKey = generatePoolKey(tgtBondRank,tgtLevel,srcBondRank,srcLevel); + int invDir = D3Q27System::INVDIR[dir]; - TbCbVectorBondPool <LBMReal>::BondPoolPtr sendPool = TbCbVectorBondPool <LBMReal>::getTbCbVectorBondPool(sendBondPoolKey ); - TbCbVectorBondPool <LBMReal>::BondPoolPtr recvPool = TbCbVectorBondPool <LBMReal>::getTbCbVectorBondPool(receiveBondPoolKey); + if (srcLevel != tgtLevel) + invDir = dir; - if( !sendPool ) sendPool = TbCbVectorBondPool <LBMReal>::createTbCbVectorBondPool(sendBondPoolKey ,tgtBondRank, generateMPITag(srcLevel, tgtLevel)); - if( !recvPool ) recvPool = TbCbVectorBondPool <LBMReal>::createTbCbVectorBondPool(receiveBondPoolKey,tgtBondRank, generateMPITag(tgtLevel, srcLevel)); + int srcRank = 0; + int tgtRank = 0; - TbCbVectorBondPool <LBMReal>::CbVectorKey keyOfSendCbVectorKey = generateVectorKey(tgtID, dir, ib); - TbCbVectorBondPool <LBMReal>::CbVectorKey keyOfRecvCbVectorKey = generateVectorKey(srcID, invDir, ib); + if (tType == MPI) { + srcRank = sblock->getRank(); + tgtRank = tblock->getRank(); + } +#ifdef VF_FETOL + else if (tType == MPI2BOND) { + srcRank = sblock->getLocalRank(); + tgtRank = tblock->getLocalRank(); + } +#endif - //create sender-/receiver - sender = TransmitterPtr( new TbCbVectorSenderBondPool< LBMReal >(keyOfSendCbVectorKey,sendPool.get()) ); - receiver = TransmitterPtr( new TbCbVectorReceiverBondPool< LBMReal >(keyOfRecvCbVectorKey,recvPool.get()) ); - } + if (tType == MPI +#ifdef VF_FETOL + || tType == MPI2BOND +#endif + ) { + string sendPoolKey = generatePoolKey(srcRank, srcLevel, tgtRank, tgtLevel); + string receivePoolKey = generatePoolKey(tgtRank, tgtLevel, srcRank, srcLevel); + + TbCbVectorMpiPool<LBMReal>::MpiPoolPtr sendPool = TbCbVectorMpiPool<LBMReal>::getTbCbVectorMpiPool(sendPoolKey); + TbCbVectorMpiPool<LBMReal>::MpiPoolPtr recvPool = + TbCbVectorMpiPool<LBMReal>::getTbCbVectorMpiPool(receivePoolKey); + + MPI_Comm mpi_comm = *((MPI_Comm *)comm->getNativeCommunicator()); + + if (!sendPool) + sendPool = TbCbVectorMpiPool<LBMReal>::createTbCbVectorMpiPool( + sendPoolKey, tgtRank, generateMPITag(srcLevel, tgtLevel), mpi_comm); + if (!recvPool) + recvPool = TbCbVectorMpiPool<LBMReal>::createTbCbVectorMpiPool( + receivePoolKey, tgtRank, generateMPITag(tgtLevel, srcLevel), mpi_comm); + + TbCbVectorMpiPool<LBMReal>::CbVectorKey keyOfSendCbVectorKey = + generateVectorKey(sblock->getX1(), sblock->getX2(), sblock->getX3() /*tgtID*/, dir, ib); + TbCbVectorMpiPool<LBMReal>::CbVectorKey keyOfRecvCbVectorKey = + generateVectorKey(tblock->getX1(), tblock->getX2(), tblock->getX3() /*srcID*/, invDir, ib); + + //////////////////////////////////////////////////////// + // DEBUG + // int myid = comm->getProcessID(); + // FILE * file; + ////char * name = "d:/temp/sendPoolKey.csv"; + // std::string name = "d:/temp/VectorKey" + UbSystem::toString(myid) + ".csv"; + // file = fopen(name.c_str(), "a"); + // fprintf(file, "%d;%d%;%d;%d;%d;%u;%d;%d%;%d;%d;%d;%u\n", sblock->getX1(), sblock->getX2(), + // sblock->getX3()/*tgtID*/, dir, ib, keyOfSendCbVectorKey, tblock->getX1(), tblock->getX2(), + // tblock->getX3()/*srcID*/, invDir, ib, keyOfRecvCbVectorKey); fclose(file); + //////////////////////////////////////////////////////// + + // create sender-/receiver + sender = TransmitterPtr(new TbCbVectorSenderMpiPool<LBMReal>(keyOfSendCbVectorKey, sendPool.get())); + receiver = TransmitterPtr(new TbCbVectorReceiverMpiPool<LBMReal>(keyOfRecvCbVectorKey, recvPool.get())); + } +#ifdef VF_FETOL + if (tType == BOND) { + int srcBondRank = sblock->getRank(); + int tgtBondRank = tblock->getRank(); + + int sendBondPoolKey = generatePoolKey(srcBondRank, srcLevel, tgtBondRank, tgtLevel); + int receiveBondPoolKey = generatePoolKey(tgtBondRank, tgtLevel, srcBondRank, srcLevel); + + TbCbVectorBondPool<LBMReal>::BondPoolPtr sendPool = + TbCbVectorBondPool<LBMReal>::getTbCbVectorBondPool(sendBondPoolKey); + TbCbVectorBondPool<LBMReal>::BondPoolPtr recvPool = + TbCbVectorBondPool<LBMReal>::getTbCbVectorBondPool(receiveBondPoolKey); + + if (!sendPool) + sendPool = TbCbVectorBondPool<LBMReal>::createTbCbVectorBondPool(sendBondPoolKey, tgtBondRank, + generateMPITag(srcLevel, tgtLevel)); + if (!recvPool) + recvPool = TbCbVectorBondPool<LBMReal>::createTbCbVectorBondPool(receiveBondPoolKey, tgtBondRank, + generateMPITag(tgtLevel, srcLevel)); + + TbCbVectorBondPool<LBMReal>::CbVectorKey keyOfSendCbVectorKey = generateVectorKey(tgtID, dir, ib); + TbCbVectorBondPool<LBMReal>::CbVectorKey keyOfRecvCbVectorKey = generateVectorKey(srcID, invDir, ib); + + // create sender-/receiver + sender = TransmitterPtr(new TbCbVectorSenderBondPool<LBMReal>(keyOfSendCbVectorKey, sendPool.get())); + receiver = TransmitterPtr(new TbCbVectorReceiverBondPool<LBMReal>(keyOfRecvCbVectorKey, recvPool.get())); + } #endif } ////////////////////////////////////////////////////////////////////////// int CreateTransmittersHelper::generateMPITag(int srcLevel, int tgtLevel) { - //The MPI standard guarantees that integers 0-32767 can be used as tags - if (srcLevel == tgtLevel) - { - return srcLevel; - } - else - { - srcLevel++; - tgtLevel++; - std::string str = UbSystem::toString<int>(srcLevel) + UbSystem::toString<int>(tgtLevel); - int r = UbSystem::stringTo<int>(str); - return r; - } + // The MPI standard guarantees that integers 0-32767 can be used as tags + if (srcLevel == tgtLevel) { + return srcLevel; + } else { + srcLevel++; + tgtLevel++; + std::string str = UbSystem::toString<int>(srcLevel) + UbSystem::toString<int>(tgtLevel); + int r = UbSystem::stringTo<int>(str); + return r; + } } ////////////////////////////////////////////////////////////////////////// string CreateTransmittersHelper::generatePoolKey(int srcRank, int srcLevel, int tgtRank, int tgtLevel) { - std::string str; - str = UbSystem::toString<int>(srcLevel); - str += "#"; - str += UbSystem::toString<int>(tgtLevel); - str += "#"; - str += UbSystem::toString<int>(srcRank); - str += "#"; - str += UbSystem::toString<int>(tgtRank); - - return str; + std::string str; + str = UbSystem::toString<int>(srcLevel); + str += "#"; + str += UbSystem::toString<int>(tgtLevel); + str += "#"; + str += UbSystem::toString<int>(srcRank); + str += "#"; + str += UbSystem::toString<int>(tgtRank); + + return str; } ////////////////////////////////////////////////////////////////////////// string CreateTransmittersHelper::generateVectorKey(int x1, int x2, int x3, int dir, IBlock ib) { - std::string str; - - str += UbSystem::toString<int>(x1); - str += "#"; - str += UbSystem::toString<int>(x2); - str += "#"; - str += UbSystem::toString<int>(x3); - str += "#"; - str += UbSystem::toString<int>(dir); - str += "#"; - str += UbSystem::toString<int>(ib); - - return str; + std::string str; + + str += UbSystem::toString<int>(x1); + str += "#"; + str += UbSystem::toString<int>(x2); + str += "#"; + str += UbSystem::toString<int>(x3); + str += "#"; + str += UbSystem::toString<int>(dir); + str += "#"; + str += UbSystem::toString<int>(ib); + + return str; } - - diff --git a/src/cpu/VirtualFluidsCore/Visitors/CreateTransmittersHelper.h b/src/cpu/VirtualFluidsCore/Visitors/CreateTransmittersHelper.h index d339bdfb41e43ee3ae159b3141e4e2f67c1bcc1d..f34adb32658db0214b8247788a2570e7dbac0761 100644 --- a/src/cpu/VirtualFluidsCore/Visitors/CreateTransmittersHelper.h +++ b/src/cpu/VirtualFluidsCore/Visitors/CreateTransmittersHelper.h @@ -1,4 +1,4 @@ -#ifndef CREATETRANSMITTERSHELPER_H +#ifndef CREATETRANSMITTERSHELPER_H #define CREATETRANSMITTERSHELPER_H #include "Block3D.h" @@ -6,33 +6,38 @@ #include "LBMSystem.h" +#include <basics/container/CbVector.h> #include <basics/transmitter/TbTransmitter.h> #include <basics/transmitter/TbTransmitterMpiPool.h> -#include <basics/container/CbVector.h> -//! \brief The class helps to create Transmitters. +//! \brief The class helps to create Transmitters. //! \details It is created two types of Transmitters: MPI and BOND //! \author K. Kucher class CreateTransmittersHelper { public: - //! Switch between same level and interpolation Connectors. NONE - for same level Connectors; SW, NW, NE, SE - source/target fine blocks in grid interface - enum IBlock {NONE, SW, NW, NE, SE}; - //! Switch between MPI and BOND Transmitters - enum TransmitterType {MPI, BOND, MPI2BOND}; + //! Switch between same level and interpolation Connectors. NONE - for same level Connectors; SW, NW, NE, SE - + //! source/target fine blocks in grid interface + enum IBlock { NONE, SW, NW, NE, SE }; + //! Switch between MPI and BOND Transmitters + enum TransmitterType { MPI, BOND, MPI2BOND }; + public: - using DataType = CbVector<LBMReal>; - using TransmitterPtr = SPtr<TbTransmitter<DataType> >; + using DataType = CbVector<LBMReal>; + using TransmitterPtr = SPtr<TbTransmitter<DataType>>; + public: - CreateTransmittersHelper(); - void createTransmitters(const SPtr<Block3D> sblock, const SPtr<Block3D> tblock, int dir, IBlock ib, - TransmitterPtr& sender, TransmitterPtr& receiver, SPtr<Communicator> comm, TransmitterType tType); + CreateTransmittersHelper(); + void createTransmitters(const SPtr<Block3D> sblock, const SPtr<Block3D> tblock, int dir, IBlock ib, + TransmitterPtr &sender, TransmitterPtr &receiver, SPtr<Communicator> comm, + TransmitterType tType); + protected: private: - std::string generatePoolKey(int srcRank, int srcLevel, int tgtRank, int tgtLevel); - std::string generateVectorKey(int x1, int x2, int x3,/*int id,*/ int dir, IBlock ib); - int generateMPITag(int srcLevel, int tgtLevel); - static unsigned int vKey; + std::string generatePoolKey(int srcRank, int srcLevel, int tgtRank, int tgtLevel); + std::string generateVectorKey(int x1, int x2, int x3, /*int id,*/ int dir, IBlock ib); + int generateMPITag(int srcLevel, int tgtLevel); + static unsigned int vKey; }; #endif diff --git a/src/cpu/VirtualFluidsCore/Visitors/GenBlocksGridVisitor.cpp b/src/cpu/VirtualFluidsCore/Visitors/GenBlocksGridVisitor.cpp index df8ce92ea6b0084ccf23ca370f4e18a532cc73e6..a8270d40d7b2e193024056551591f6b0f3464b5e 100644 --- a/src/cpu/VirtualFluidsCore/Visitors/GenBlocksGridVisitor.cpp +++ b/src/cpu/VirtualFluidsCore/Visitors/GenBlocksGridVisitor.cpp @@ -1,28 +1,28 @@ //======================================================================================= -// ____ ____ __ ______ __________ __ __ __ __ -// \ \ | | | | | _ \ |___ ___| | | | | / \ | | -// \ \ | | | | | |_) | | | | | | | / \ | | -// \ \ | | | | | _ / | | | | | | / /\ \ | | -// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ -// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| -// \ \ | | ________________________________________________________________ -// \ \ | | | ______________________________________________________________| -// \ \| | | | __ __ __ __ ______ _______ -// \ | | |_____ | | | | | | | | | _ \ / _____) -// \ | | _____| | | | | | | | | | | \ \ \_______ +// ____ ____ __ ______ __________ __ __ __ __ +// \ \ | | | | | _ \ |___ ___| | | | | / \ | | +// \ \ | | | | | |_) | | | | | | | / \ | | +// \ \ | | | | | _ / | | | | | | / /\ \ | | +// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ +// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| +// \ \ | | ________________________________________________________________ +// \ \ | | | ______________________________________________________________| +// \ \| | | | __ __ __ __ ______ _______ +// \ | | |_____ | | | | | | | | | _ \ / _____) +// \ | | _____| | | | | | | | | | | \ \ \_______ // \ | | | | |_____ | \_/ | | | | |_/ / _____ | -// \ _____| |__| |________| \_______/ |__| |______/ (_______/ +// \ _____| |__| |________| \_______/ |__| |______/ (_______/ // -// This file is part of VirtualFluids. VirtualFluids is free software: you can +// This file is part of VirtualFluids. VirtualFluids is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of +// License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. -// -// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// +// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License along // with VirtualFluids (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>. // @@ -32,18 +32,14 @@ //======================================================================================= #include "GenBlocksGridVisitor.h" -#include "Grid3DSystem.h" -#include "CoordinateTransformation3D.h" #include "Block3D.h" +#include "CoordinateTransformation3D.h" #include "Grid3D.h" +#include "Grid3DSystem.h" #include <geometry3d/GbObject3D.h> -GenBlocksGridVisitor::GenBlocksGridVisitor(SPtr<GbObject3D> boundingBox) : - boundingBox(boundingBox) -{ - -} +GenBlocksGridVisitor::GenBlocksGridVisitor(SPtr<GbObject3D> boundingBox) : boundingBox(boundingBox) {} ////////////////////////////////////////////////////////////////////////// void GenBlocksGridVisitor::visit(const SPtr<Grid3D> grid) { @@ -55,53 +51,53 @@ void GenBlocksGridVisitor::visit(const SPtr<Grid3D> grid) UbTupleInt3 blockNX = grid->getBlockNX(); - double blockLentghX1 = (double)val<1>(blockNX)*dx; - double blockLentghX2 = (double)val<2>(blockNX)*dx; - double blockLentghX3 = (double)val<3>(blockNX)*dx; + double blockLentghX1 = (double)val<1>(blockNX) * dx; + double blockLentghX2 = (double)val<2>(blockNX) * dx; + double blockLentghX3 = (double)val<3>(blockNX) * dx; - SPtr<CoordinateTransformation3D> trafo(new CoordinateTransformation3D(orgX1, orgX2, orgX3, blockLentghX1, blockLentghX2, blockLentghX3)); + SPtr<CoordinateTransformation3D> trafo( + new CoordinateTransformation3D(orgX1, orgX2, orgX3, blockLentghX1, blockLentghX2, blockLentghX3)); grid->setCoordinateTransformator(trafo); genBlocks(grid); } ////////////////////////////////////////////////////////////////////////// -void GenBlocksGridVisitor::fillExtentWithBlocks( SPtr<Grid3D> grid ) +void GenBlocksGridVisitor::fillExtentWithBlocks(SPtr<Grid3D> grid) { - for(int x3 = val<3>(minInd); x3 < val<3>(maxInd); x3++) - { - for(int x2 = val<2>(minInd); x2 < val<2>(maxInd); x2++) - { - for(int x1 = val<1>(minInd); x1 < val<1>(maxInd); x1++) - { - SPtr<Block3D> block( new Block3D(x1,x2,x3,0) ); - grid->addBlock(block); - } - } - } + for (int x3 = val<3>(minInd); x3 < val<3>(maxInd); x3++) { + for (int x2 = val<2>(minInd); x2 < val<2>(maxInd); x2++) { + for (int x1 = val<1>(minInd); x1 < val<1>(maxInd); x1++) { + SPtr<Block3D> block(new Block3D(x1, x2, x3, 0)); + grid->addBlock(block); + } + } + } } ////////////////////////////////////////////////////////////////////////// void GenBlocksGridVisitor::genBlocks(SPtr<Grid3D> grid) { - minInd = grid->getBlockIndexes(boundingBox->getX1Minimum(), boundingBox->getX2Minimum(), boundingBox->getX3Minimum()); - double geoMaxX1 = boundingBox->getX1Maximum(); - double geoMaxX2 = boundingBox->getX2Maximum(); - double geoMaxX3 = boundingBox->getX3Maximum(); - maxInd = grid->getBlockIndexes(geoMaxX1, geoMaxX2, geoMaxX3); - UbTupleDouble3 blockCoord = grid->getBlockWorldCoordinates(static_cast<int>(val<1>(maxInd)), static_cast<int>(val<2>(maxInd)), static_cast<int>(val<3>(maxInd)), 0); - //if (geoMaxX1 > val<1>(blockCoord)) + minInd = + grid->getBlockIndexes(boundingBox->getX1Minimum(), boundingBox->getX2Minimum(), boundingBox->getX3Minimum()); + double geoMaxX1 = boundingBox->getX1Maximum(); + double geoMaxX2 = boundingBox->getX2Maximum(); + double geoMaxX3 = boundingBox->getX3Maximum(); + maxInd = grid->getBlockIndexes(geoMaxX1, geoMaxX2, geoMaxX3); + UbTupleDouble3 blockCoord = grid->getBlockWorldCoordinates( + static_cast<int>(val<1>(maxInd)), static_cast<int>(val<2>(maxInd)), static_cast<int>(val<3>(maxInd)), 0); + // if (geoMaxX1 > val<1>(blockCoord)) // val<1>(maxInd) += 1; - //if (geoMaxX2 > val<2>(blockCoord)) + // if (geoMaxX2 > val<2>(blockCoord)) // val<2>(maxInd) += 1; - //if (geoMaxX3 > val<3>(blockCoord)) + // if (geoMaxX3 > val<3>(blockCoord)) // val<3>(maxInd) += 1; double dx = grid->getDeltaX(0); - if (fabs(geoMaxX1-val<1>(blockCoord)) > dx) - val<1>(maxInd) += 1; - if (fabs(geoMaxX2-val<2>(blockCoord)) > dx) - val<2>(maxInd) += 1; - if (fabs(geoMaxX3-val<3>(blockCoord)) > dx) - val<3>(maxInd) += 1; + if (fabs(geoMaxX1 - val<1>(blockCoord)) > dx) + val<1>(maxInd) += 1; + if (fabs(geoMaxX2 - val<2>(blockCoord)) > dx) + val<2>(maxInd) += 1; + if (fabs(geoMaxX3 - val<3>(blockCoord)) > dx) + val<3>(maxInd) += 1; this->fillExtentWithBlocks(grid); diff --git a/src/cpu/VirtualFluidsCore/Visitors/GenBlocksGridVisitor.h b/src/cpu/VirtualFluidsCore/Visitors/GenBlocksGridVisitor.h index 65db6fa109087b7121358f0c3227846dbb246326..ddfdf4b16bb55ce94eb91308e8b1fde36d3bacf0 100644 --- a/src/cpu/VirtualFluidsCore/Visitors/GenBlocksGridVisitor.h +++ b/src/cpu/VirtualFluidsCore/Visitors/GenBlocksGridVisitor.h @@ -1,28 +1,28 @@ //======================================================================================= -// ____ ____ __ ______ __________ __ __ __ __ -// \ \ | | | | | _ \ |___ ___| | | | | / \ | | -// \ \ | | | | | |_) | | | | | | | / \ | | -// \ \ | | | | | _ / | | | | | | / /\ \ | | -// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ -// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| -// \ \ | | ________________________________________________________________ -// \ \ | | | ______________________________________________________________| -// \ \| | | | __ __ __ __ ______ _______ -// \ | | |_____ | | | | | | | | | _ \ / _____) -// \ | | _____| | | | | | | | | | | \ \ \_______ +// ____ ____ __ ______ __________ __ __ __ __ +// \ \ | | | | | _ \ |___ ___| | | | | / \ | | +// \ \ | | | | | |_) | | | | | | | / \ | | +// \ \ | | | | | _ / | | | | | | / /\ \ | | +// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ +// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| +// \ \ | | ________________________________________________________________ +// \ \ | | | ______________________________________________________________| +// \ \| | | | __ __ __ __ ______ _______ +// \ | | |_____ | | | | | | | | | _ \ / _____) +// \ | | _____| | | | | | | | | | | \ \ \_______ // \ | | | | |_____ | \_/ | | | | |_/ / _____ | -// \ _____| |__| |________| \_______/ |__| |______/ (_______/ +// \ _____| |__| |________| \_______/ |__| |______/ (_______/ // -// This file is part of VirtualFluids. VirtualFluids is free software: you can +// This file is part of VirtualFluids. VirtualFluids is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of +// License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. -// -// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// +// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License along // with VirtualFluids (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>. // @@ -38,7 +38,7 @@ #include <basics/utilities/UbTuple.h> -#include "Grid3DVisitor.h" +#include "Grid3DVisitor.h" class GbObject3D; class Grid3D; @@ -47,16 +47,16 @@ class Grid3D; class GenBlocksGridVisitor : public Grid3DVisitor { public: - GenBlocksGridVisitor(SPtr<GbObject3D> boundingBox); - ~GenBlocksGridVisitor() override= default; + GenBlocksGridVisitor(SPtr<GbObject3D> boundingBox); + ~GenBlocksGridVisitor() override = default; - void visit(SPtr<Grid3D> grid) override; + void visit(SPtr<Grid3D> grid) override; private: - UbTupleInt3 minInd, maxInd; - SPtr<GbObject3D> boundingBox; - void fillExtentWithBlocks(SPtr<Grid3D> grid); - void genBlocks(SPtr<Grid3D> grid); + UbTupleInt3 minInd, maxInd; + SPtr<GbObject3D> boundingBox; + void fillExtentWithBlocks(SPtr<Grid3D> grid); + void genBlocks(SPtr<Grid3D> grid); }; -#endif +#endif diff --git a/src/cpu/VirtualFluidsCore/Visitors/Grid3DVisitor.h b/src/cpu/VirtualFluidsCore/Visitors/Grid3DVisitor.h index 5484ac44202930eaeacde3e64ac20c2d6bccaabd..80c39e66c1a41c202d347efbccdbdbb00fb3700a 100644 --- a/src/cpu/VirtualFluidsCore/Visitors/Grid3DVisitor.h +++ b/src/cpu/VirtualFluidsCore/Visitors/Grid3DVisitor.h @@ -1,28 +1,28 @@ //======================================================================================= -// ____ ____ __ ______ __________ __ __ __ __ -// \ \ | | | | | _ \ |___ ___| | | | | / \ | | -// \ \ | | | | | |_) | | | | | | | / \ | | -// \ \ | | | | | _ / | | | | | | / /\ \ | | -// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ -// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| -// \ \ | | ________________________________________________________________ -// \ \ | | | ______________________________________________________________| -// \ \| | | | __ __ __ __ ______ _______ -// \ | | |_____ | | | | | | | | | _ \ / _____) -// \ | | _____| | | | | | | | | | | \ \ \_______ +// ____ ____ __ ______ __________ __ __ __ __ +// \ \ | | | | | _ \ |___ ___| | | | | / \ | | +// \ \ | | | | | |_) | | | | | | | / \ | | +// \ \ | | | | | _ / | | | | | | / /\ \ | | +// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ +// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| +// \ \ | | ________________________________________________________________ +// \ \ | | | ______________________________________________________________| +// \ \| | | | __ __ __ __ ______ _______ +// \ | | |_____ | | | | | | | | | _ \ / _____) +// \ | | _____| | | | | | | | | | | \ \ \_______ // \ | | | | |_____ | \_/ | | | | |_/ / _____ | -// \ _____| |__| |________| \_______/ |__| |______/ (_______/ +// \ _____| |__| |________| \_______/ |__| |______/ (_______/ // -// This file is part of VirtualFluids. VirtualFluids is free software: you can +// This file is part of VirtualFluids. VirtualFluids is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of +// License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. -// -// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// +// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License along // with VirtualFluids (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>. // @@ -36,17 +36,16 @@ #include <PointerDefinitions.h> - class Grid3D; //! Abstract class provides interface for visitor design pettern class Grid3DVisitor { public: - Grid3DVisitor() = default; - virtual ~Grid3DVisitor() = default; + Grid3DVisitor() = default; + virtual ~Grid3DVisitor() = default; - virtual void visit(SPtr<Grid3D> grid) = 0; + virtual void visit(SPtr<Grid3D> grid) = 0; }; -#endif +#endif diff --git a/src/cpu/VirtualFluidsCore/Visitors/InitDistributionsBlockVisitor.cpp b/src/cpu/VirtualFluidsCore/Visitors/InitDistributionsBlockVisitor.cpp index 055cf6a2ba68dce48c3bb49e3c1a94dc9a3c9748..c424a6376a62159da2e4b9f73ccf01858fbde521 100644 --- a/src/cpu/VirtualFluidsCore/Visitors/InitDistributionsBlockVisitor.cpp +++ b/src/cpu/VirtualFluidsCore/Visitors/InitDistributionsBlockVisitor.cpp @@ -1,28 +1,28 @@ //======================================================================================= -// ____ ____ __ ______ __________ __ __ __ __ -// \ \ | | | | | _ \ |___ ___| | | | | / \ | | -// \ \ | | | | | |_) | | | | | | | / \ | | -// \ \ | | | | | _ / | | | | | | / /\ \ | | -// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ -// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| -// \ \ | | ________________________________________________________________ -// \ \ | | | ______________________________________________________________| -// \ \| | | | __ __ __ __ ______ _______ -// \ | | |_____ | | | | | | | | | _ \ / _____) -// \ | | _____| | | | | | | | | | | \ \ \_______ +// ____ ____ __ ______ __________ __ __ __ __ +// \ \ | | | | | _ \ |___ ___| | | | | / \ | | +// \ \ | | | | | |_) | | | | | | | / \ | | +// \ \ | | | | | _ / | | | | | | / /\ \ | | +// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ +// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| +// \ \ | | ________________________________________________________________ +// \ \ | | | ______________________________________________________________| +// \ \| | | | __ __ __ __ ______ _______ +// \ | | |_____ | | | | | | | | | _ \ / _____) +// \ | | _____| | | | | | | | | | | \ \ \_______ // \ | | | | |_____ | \_/ | | | | |_/ / _____ | -// \ _____| |__| |________| \_______/ |__| |______/ (_______/ +// \ _____| |__| |________| \_______/ |__| |______/ (_______/ // -// This file is part of VirtualFluids. VirtualFluids is free software: you can +// This file is part of VirtualFluids. VirtualFluids is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of +// License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. -// -// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// +// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License along // with VirtualFluids (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>. // @@ -32,292 +32,301 @@ //======================================================================================= #include "InitDistributionsBlockVisitor.h" -#include "LBMKernel.h" +#include "BCArray3D.h" #include "BCProcessor.h" -#include "Grid3DSystem.h" +#include "Block3D.h" #include "DataSet3D.h" #include "EsoTwist3D.h" #include "Grid3D.h" -#include "Block3D.h" -#include "BCArray3D.h" +#include "Grid3DSystem.h" +#include "LBMKernel.h" -InitDistributionsBlockVisitor::InitDistributionsBlockVisitor() - : Block3DVisitor(0, Grid3DSystem::MAXLEVEL) +InitDistributionsBlockVisitor::InitDistributionsBlockVisitor() : Block3DVisitor(0, Grid3DSystem::MAXLEVEL) { - this->setVx1(0.0); - this->setVx2(0.0); - this->setVx3(0.0); - this->setRho(0.0); + this->setVx1(0.0); + this->setVx2(0.0); + this->setVx3(0.0); + this->setRho(0.0); } ////////////////////////////////////////////////////////////////////////// -void InitDistributionsBlockVisitor::setVx1( const mu::Parser& parser) -{ - this->checkFunction(parser); - this->muVx1 = parser; +void InitDistributionsBlockVisitor::setVx1(const mu::Parser &parser) +{ + this->checkFunction(parser); + this->muVx1 = parser; } ////////////////////////////////////////////////////////////////////////// -void InitDistributionsBlockVisitor::setVx2( const mu::Parser& parser) -{ - this->checkFunction(parser); - this->muVx2 = parser; +void InitDistributionsBlockVisitor::setVx2(const mu::Parser &parser) +{ + this->checkFunction(parser); + this->muVx2 = parser; } ////////////////////////////////////////////////////////////////////////// -void InitDistributionsBlockVisitor::setVx3( const mu::Parser& parser) -{ - this->checkFunction(parser); - this->muVx3 = parser; +void InitDistributionsBlockVisitor::setVx3(const mu::Parser &parser) +{ + this->checkFunction(parser); + this->muVx3 = parser; } ////////////////////////////////////////////////////////////////////////// -void InitDistributionsBlockVisitor::setRho( const mu::Parser& parser) -{ - this->checkFunction(parser); - this->muRho = parser; +void InitDistributionsBlockVisitor::setRho(const mu::Parser &parser) +{ + this->checkFunction(parser); + this->muRho = parser; } ////////////////////////////////////////////////////////////////////////// -void InitDistributionsBlockVisitor::setVx1( const std::string& muParserString) -{ - this->muVx1.SetExpr(muParserString); - this->checkFunction(muVx1); +void InitDistributionsBlockVisitor::setVx1(const std::string &muParserString) +{ + this->muVx1.SetExpr(muParserString); + this->checkFunction(muVx1); } ////////////////////////////////////////////////////////////////////////// -void InitDistributionsBlockVisitor::setVx2( const std::string& muParserString) -{ - this->muVx2.SetExpr(muParserString); - this->checkFunction(muVx2); +void InitDistributionsBlockVisitor::setVx2(const std::string &muParserString) +{ + this->muVx2.SetExpr(muParserString); + this->checkFunction(muVx2); } ////////////////////////////////////////////////////////////////////////// -void InitDistributionsBlockVisitor::setVx3( const std::string& muParserString) -{ - this->muVx3.SetExpr(muParserString); - this->checkFunction(muVx3); +void InitDistributionsBlockVisitor::setVx3(const std::string &muParserString) +{ + this->muVx3.SetExpr(muParserString); + this->checkFunction(muVx3); } ////////////////////////////////////////////////////////////////////////// -void InitDistributionsBlockVisitor::setRho( const std::string& muParserString) -{ - this->muRho.SetExpr(muParserString); - this->checkFunction(muRho); +void InitDistributionsBlockVisitor::setRho(const std::string &muParserString) +{ + this->muRho.SetExpr(muParserString); + this->checkFunction(muRho); } ////////////////////////////////////////////////////////////////////////// -void InitDistributionsBlockVisitor::setVx1( LBMReal vx1 ) -{ - this->muVx1.SetExpr( UbSystem::toString(vx1,D3Q27RealLim::digits10) ); - this->checkFunction(muVx1); +void InitDistributionsBlockVisitor::setVx1(LBMReal vx1) +{ + this->muVx1.SetExpr(UbSystem::toString(vx1, D3Q27RealLim::digits10)); + this->checkFunction(muVx1); } ////////////////////////////////////////////////////////////////////////// -void InitDistributionsBlockVisitor::setVx2( LBMReal vx2 ) -{ - this->muVx2.SetExpr( UbSystem::toString(vx2,D3Q27RealLim::digits10) ); - this->checkFunction(muVx2); +void InitDistributionsBlockVisitor::setVx2(LBMReal vx2) +{ + this->muVx2.SetExpr(UbSystem::toString(vx2, D3Q27RealLim::digits10)); + this->checkFunction(muVx2); } ////////////////////////////////////////////////////////////////////////// -void InitDistributionsBlockVisitor::setVx3( LBMReal vx3 ) -{ - this->muVx3.SetExpr( UbSystem::toString(vx3,D3Q27RealLim::digits10) ); - this->checkFunction(muVx3); +void InitDistributionsBlockVisitor::setVx3(LBMReal vx3) +{ + this->muVx3.SetExpr(UbSystem::toString(vx3, D3Q27RealLim::digits10)); + this->checkFunction(muVx3); } ////////////////////////////////////////////////////////////////////////// -void InitDistributionsBlockVisitor::setRho( LBMReal rho ) -{ - this->muRho.SetExpr( UbSystem::toString(rho,D3Q27RealLim::digits10) ); - this->checkFunction(muRho); +void InitDistributionsBlockVisitor::setRho(LBMReal rho) +{ + this->muRho.SetExpr(UbSystem::toString(rho, D3Q27RealLim::digits10)); + this->checkFunction(muRho); } ////////////////////////////////////////////////////////////////////////// -void InitDistributionsBlockVisitor::visit(const SPtr<Grid3D> grid, SPtr<Block3D> block) +void InitDistributionsBlockVisitor::visit(const SPtr<Grid3D> grid, SPtr<Block3D> block) { - using namespace D3Q27System; - - if(!block) UB_THROW( UbException(UB_EXARGS,"block is not exist") ); - - //UbTupleDouble3 blockLengths = grid->getBlockLengths(block); - //UbTupleDouble3 nodeOffset = grid->getNodeOffset(block); - double dx = grid->getDeltaX(block); - - //define vars for functions - mu::value_type x1,x2,x3; - this->muVx1.DefineVar("x1",&x1); this->muVx1.DefineVar("x2",&x2); this->muVx1.DefineVar("x3",&x3); - this->muVx2.DefineVar("x1",&x1); this->muVx2.DefineVar("x2",&x2); this->muVx2.DefineVar("x3",&x3); - this->muVx3.DefineVar("x1",&x1); this->muVx3.DefineVar("x2",&x2); this->muVx3.DefineVar("x3",&x3); - this->muRho.DefineVar("x1",&x1); this->muRho.DefineVar("x2",&x2); this->muRho.DefineVar("x3",&x3); - - using CalcFeqsFct = void (*)(LBMReal* const& /*feq[27]*/,const LBMReal& /*(d)rho*/,const LBMReal& /*vx1*/,const LBMReal& /*vx2*/,const LBMReal& /*vx3*/); - CalcFeqsFct calcFeqsFct = NULL; - - LBMReal vx1,vx2,vx3,rho; - - int gridRank = grid->getRank(); - int blockRank = block->getRank(); - - if (blockRank == gridRank && block->isActive()) - { - SPtr<ILBMKernel> kernel = block->getKernel(); - if (!kernel) - throw UbException(UB_EXARGS, "The LBM kernel isn't exist in block: "+block->toString()); - - if(kernel->getCompressible()) - calcFeqsFct = &D3Q27System::calcCompFeq; - else - calcFeqsFct = &D3Q27System::calcIncompFeq; - - //UbTupleDouble3 org = grid->getBlockWorldCoordinates(block); - - SPtr<BCArray3D> bcArray = kernel->getBCProcessor()->getBCArray(); - SPtr<DistributionArray3D> distributions = kernel->getDataSet()->getFdistributions(); - - LBMReal o = kernel->getCollisionFactor(); - - LBMReal f[D3Q27System::ENDF+1]; - - for(size_t ix3=0; ix3<bcArray->getNX3(); ix3++) - for(size_t ix2=0; ix2<bcArray->getNX2(); ix2++) - for(size_t ix1=0; ix1<bcArray->getNX1(); ix1++) - { - Vector3D coords = grid->getNodeCoordinates(block, ix1, ix2, ix3); - x1 = coords[0]; - x2 = coords[1]; - x3 = coords[2]; - - vx1 = muVx1.Eval(); - vx2 = muVx2.Eval(); - vx3 = muVx3.Eval(); - rho = muRho.Eval(); - - //x-derivative - double deltaX=dx*0.5; - x1 = coords[0]+deltaX; - double vx1Plusx1 = muVx1.Eval(); - double vx2Plusx1 = muVx2.Eval(); - double vx3Plusx1 = muVx3.Eval(); - - x1 = coords[0]-deltaX; - double vx1Minusx1 = muVx1.Eval(); - double vx2Minusx1 = muVx2.Eval(); - double vx3Minusx1 = muVx3.Eval(); - - //y-derivative - x1 = coords[0]; - x2 = coords[1]+deltaX; - double vx1Plusx2 = muVx1.Eval(); - double vx2Plusx2 = muVx2.Eval(); - double vx3Plusx2 = muVx3.Eval(); - - x2 = coords[1]-deltaX; - double vx1Minusx2 = muVx1.Eval(); - double vx2Minusx2 = muVx2.Eval(); - double vx3Minusx2 = muVx3.Eval(); - - //z-derivative - x2 = coords[1]; - x3 = coords[2]+deltaX; - double vx1Plusx3 = muVx1.Eval(); - double vx2Plusx3 = muVx2.Eval(); - double vx3Plusx3 = muVx3.Eval(); - - x3 = coords[2]-deltaX; - double vx1Minusx3 = muVx1.Eval(); - double vx2Minusx3 = muVx2.Eval(); - double vx3Minusx3 = muVx3.Eval(); - - double ax=(vx1Plusx1-vx1Minusx1)/(2.0*deltaX)*dx; - double bx=(vx2Plusx1-vx2Minusx1)/(2.0*deltaX)*dx; - double cx=(vx3Plusx1-vx3Minusx1)/(2.0*deltaX)*dx; - - double ay=(vx1Plusx2-vx1Minusx2)/(2.0*deltaX)*dx; - double by=(vx2Plusx2-vx2Minusx2)/(2.0*deltaX)*dx; - double cy=(vx3Plusx2-vx3Minusx2)/(2.0*deltaX)*dx; - - double az=(vx1Plusx3-vx1Minusx3)/(2.0*deltaX)*dx; - double bz=(vx2Plusx3-vx2Minusx3)/(2.0*deltaX)*dx; - double cz=(vx3Plusx3-vx3Minusx3)/(2.0*deltaX)*dx; - double eps_new=1.0; - LBMReal op = 1.; - - LBMReal feq[27]; - - calcFeqsFct(feq,rho,vx1,vx2,vx3); - - double f_E = eps_new *((5.*ax*o + 5.*by*o + 5.*cz*o - 8.*ax*op + 4.*by*op + 4.*cz*op)/(54.*o*op)); - double f_N = f_E + eps_new *((2.*(ax - by))/(9.*o)); - double f_T = f_E + eps_new *((2.*(ax - cz))/(9.*o)); - double f_NE = eps_new *(-(5.*cz*o + 3.*(ay + bx)*op - 2.*cz*op + ax*(5.*o + op) + by*(5.*o + op))/(54.*o*op)); - double f_SE = f_NE + eps_new *(( ay + bx )/(9.*o)); - double f_TE = eps_new *(-(5.*cz*o + by*(5.*o - 2.*op) + 3.*(az + cx)*op + cz*op + ax*(5.*o + op))/(54.*o*op)); - double f_BE = f_TE + eps_new *(( az + cx )/(9.*o)); - double f_TN = eps_new *(-(5.*ax*o + 5.*by*o + 5.*cz*o - 2.*ax*op + by*op + 3.*bz*op + 3.*cy*op + cz*op)/(54.*o*op)); - double f_BN = f_TN + eps_new *(( bz + cy )/(9.*o)); - double f_ZERO = eps_new *((5.*(ax + by + cz))/(9.*op)); - double f_TNE = eps_new *(-(ay + az + bx + bz + cx + cy)/(72.*o)); - double f_TSW = - eps_new *((ay + bx)/(36.*o)) - f_TNE; - double f_TSE = - eps_new *((az + cx)/(36.*o)) - f_TNE; - double f_TNW = - eps_new *((bz + cy)/(36.*o)) - f_TNE; - - - f[E] = f_E + feq[E]; - f[W] = f_E + feq[W]; - f[N] = f_N + feq[N]; - f[S] = f_N + feq[S]; - f[T] = f_T + feq[T]; - f[B] = f_T + feq[B]; - f[NE] = f_NE + feq[NE]; - f[SW] = f_NE + feq[SW]; - f[SE] = f_SE + feq[SE]; - f[NW] = f_SE + feq[NW]; - f[TE] = f_TE + feq[TE]; - f[BW] = f_TE + feq[BW]; - f[BE] = f_BE + feq[BE]; - f[TW] = f_BE + feq[TW]; - f[TN] = f_TN + feq[TN]; - f[BS] = f_TN + feq[BS]; - f[BN] = f_BN + feq[BN]; - f[TS] = f_BN + feq[TS]; - f[TNE] = f_TNE + feq[TNE]; - f[TNW] = f_TNW + feq[TNW]; - f[TSE] = f_TSE + feq[TSE]; - f[TSW] = f_TSW + feq[TSW]; - f[BNE] = f_TSW + feq[BNE]; - f[BNW] = f_TSE + feq[BNW]; - f[BSE] = f_TNW + feq[BSE]; - f[BSW] = f_TNE + feq[BSW]; - f[ZERO] = f_ZERO + feq[ZERO]; - - //calcFeqsFct(f,rho,vx1,vx2,vx3); - //distributions->setDistribution(f, ix1, ix2, ix3); - distributions->setDistributionInv(f, ix1, ix2, ix3); - - //distributions->swap(); - //distributions->setDistribution(f, ix1, ix2, ix3); - //distributions->setDistributionInv(f, ix1, ix2, ix3); - //distributions->swap(); - - } - } - - //variablen der functions loeschen, da die verwiesenen Objecte nach dem verlassen des scopes ungueltig sind! - this->muVx1.ClearVar(); - this->muVx2.ClearVar(); - this->muVx3.ClearVar(); - this->muRho.ClearVar(); - + using namespace D3Q27System; + + if (!block) + UB_THROW(UbException(UB_EXARGS, "block is not exist")); + + // UbTupleDouble3 blockLengths = grid->getBlockLengths(block); + // UbTupleDouble3 nodeOffset = grid->getNodeOffset(block); + double dx = grid->getDeltaX(block); + + // define vars for functions + mu::value_type x1, x2, x3; + this->muVx1.DefineVar("x1", &x1); + this->muVx1.DefineVar("x2", &x2); + this->muVx1.DefineVar("x3", &x3); + this->muVx2.DefineVar("x1", &x1); + this->muVx2.DefineVar("x2", &x2); + this->muVx2.DefineVar("x3", &x3); + this->muVx3.DefineVar("x1", &x1); + this->muVx3.DefineVar("x2", &x2); + this->muVx3.DefineVar("x3", &x3); + this->muRho.DefineVar("x1", &x1); + this->muRho.DefineVar("x2", &x2); + this->muRho.DefineVar("x3", &x3); + + using CalcFeqsFct = void (*)(LBMReal *const & /*feq[27]*/, const LBMReal & /*(d)rho*/, const LBMReal & /*vx1*/, + const LBMReal & /*vx2*/, const LBMReal & /*vx3*/); + CalcFeqsFct calcFeqsFct = NULL; + + LBMReal vx1, vx2, vx3, rho; + + int gridRank = grid->getRank(); + int blockRank = block->getRank(); + + if (blockRank == gridRank && block->isActive()) { + SPtr<ILBMKernel> kernel = block->getKernel(); + if (!kernel) + throw UbException(UB_EXARGS, "The LBM kernel isn't exist in block: " + block->toString()); + + if (kernel->getCompressible()) + calcFeqsFct = &D3Q27System::calcCompFeq; + else + calcFeqsFct = &D3Q27System::calcIncompFeq; + + // UbTupleDouble3 org = grid->getBlockWorldCoordinates(block); + + SPtr<BCArray3D> bcArray = kernel->getBCProcessor()->getBCArray(); + SPtr<DistributionArray3D> distributions = kernel->getDataSet()->getFdistributions(); + + LBMReal o = kernel->getCollisionFactor(); + + LBMReal f[D3Q27System::ENDF + 1]; + + for (size_t ix3 = 0; ix3 < bcArray->getNX3(); ix3++) + for (size_t ix2 = 0; ix2 < bcArray->getNX2(); ix2++) + for (size_t ix1 = 0; ix1 < bcArray->getNX1(); ix1++) { + Vector3D coords = grid->getNodeCoordinates(block, ix1, ix2, ix3); + x1 = coords[0]; + x2 = coords[1]; + x3 = coords[2]; + + vx1 = muVx1.Eval(); + vx2 = muVx2.Eval(); + vx3 = muVx3.Eval(); + rho = muRho.Eval(); + + // x-derivative + double deltaX = dx * 0.5; + x1 = coords[0] + deltaX; + double vx1Plusx1 = muVx1.Eval(); + double vx2Plusx1 = muVx2.Eval(); + double vx3Plusx1 = muVx3.Eval(); + + x1 = coords[0] - deltaX; + double vx1Minusx1 = muVx1.Eval(); + double vx2Minusx1 = muVx2.Eval(); + double vx3Minusx1 = muVx3.Eval(); + + // y-derivative + x1 = coords[0]; + x2 = coords[1] + deltaX; + double vx1Plusx2 = muVx1.Eval(); + double vx2Plusx2 = muVx2.Eval(); + double vx3Plusx2 = muVx3.Eval(); + + x2 = coords[1] - deltaX; + double vx1Minusx2 = muVx1.Eval(); + double vx2Minusx2 = muVx2.Eval(); + double vx3Minusx2 = muVx3.Eval(); + + // z-derivative + x2 = coords[1]; + x3 = coords[2] + deltaX; + double vx1Plusx3 = muVx1.Eval(); + double vx2Plusx3 = muVx2.Eval(); + double vx3Plusx3 = muVx3.Eval(); + + x3 = coords[2] - deltaX; + double vx1Minusx3 = muVx1.Eval(); + double vx2Minusx3 = muVx2.Eval(); + double vx3Minusx3 = muVx3.Eval(); + + double ax = (vx1Plusx1 - vx1Minusx1) / (2.0 * deltaX) * dx; + double bx = (vx2Plusx1 - vx2Minusx1) / (2.0 * deltaX) * dx; + double cx = (vx3Plusx1 - vx3Minusx1) / (2.0 * deltaX) * dx; + + double ay = (vx1Plusx2 - vx1Minusx2) / (2.0 * deltaX) * dx; + double by = (vx2Plusx2 - vx2Minusx2) / (2.0 * deltaX) * dx; + double cy = (vx3Plusx2 - vx3Minusx2) / (2.0 * deltaX) * dx; + + double az = (vx1Plusx3 - vx1Minusx3) / (2.0 * deltaX) * dx; + double bz = (vx2Plusx3 - vx2Minusx3) / (2.0 * deltaX) * dx; + double cz = (vx3Plusx3 - vx3Minusx3) / (2.0 * deltaX) * dx; + double eps_new = 1.0; + LBMReal op = 1.; + + LBMReal feq[27]; + + calcFeqsFct(feq, rho, vx1, vx2, vx3); + + double f_E = + eps_new * + ((5. * ax * o + 5. * by * o + 5. * cz * o - 8. * ax * op + 4. * by * op + 4. * cz * op) / + (54. * o * op)); + double f_N = f_E + eps_new * ((2. * (ax - by)) / (9. * o)); + double f_T = f_E + eps_new * ((2. * (ax - cz)) / (9. * o)); + double f_NE = + eps_new * + (-(5. * cz * o + 3. * (ay + bx) * op - 2. * cz * op + ax * (5. * o + op) + by * (5. * o + op)) / + (54. * o * op)); + double f_SE = f_NE + eps_new * ((ay + bx) / (9. * o)); + double f_TE = + eps_new * + (-(5. * cz * o + by * (5. * o - 2. * op) + 3. * (az + cx) * op + cz * op + ax * (5. * o + op)) / + (54. * o * op)); + double f_BE = f_TE + eps_new * ((az + cx) / (9. * o)); + double f_TN = eps_new * (-(5. * ax * o + 5. * by * o + 5. * cz * o - 2. * ax * op + by * op + + 3. * bz * op + 3. * cy * op + cz * op) / + (54. * o * op)); + double f_BN = f_TN + eps_new * ((bz + cy) / (9. * o)); + double f_ZERO = eps_new * ((5. * (ax + by + cz)) / (9. * op)); + double f_TNE = eps_new * (-(ay + az + bx + bz + cx + cy) / (72. * o)); + double f_TSW = -eps_new * ((ay + bx) / (36. * o)) - f_TNE; + double f_TSE = -eps_new * ((az + cx) / (36. * o)) - f_TNE; + double f_TNW = -eps_new * ((bz + cy) / (36. * o)) - f_TNE; + + f[E] = f_E + feq[E]; + f[W] = f_E + feq[W]; + f[N] = f_N + feq[N]; + f[S] = f_N + feq[S]; + f[T] = f_T + feq[T]; + f[B] = f_T + feq[B]; + f[NE] = f_NE + feq[NE]; + f[SW] = f_NE + feq[SW]; + f[SE] = f_SE + feq[SE]; + f[NW] = f_SE + feq[NW]; + f[TE] = f_TE + feq[TE]; + f[BW] = f_TE + feq[BW]; + f[BE] = f_BE + feq[BE]; + f[TW] = f_BE + feq[TW]; + f[TN] = f_TN + feq[TN]; + f[BS] = f_TN + feq[BS]; + f[BN] = f_BN + feq[BN]; + f[TS] = f_BN + feq[TS]; + f[TNE] = f_TNE + feq[TNE]; + f[TNW] = f_TNW + feq[TNW]; + f[TSE] = f_TSE + feq[TSE]; + f[TSW] = f_TSW + feq[TSW]; + f[BNE] = f_TSW + feq[BNE]; + f[BNW] = f_TSE + feq[BNW]; + f[BSE] = f_TNW + feq[BSE]; + f[BSW] = f_TNE + feq[BSW]; + f[ZERO] = f_ZERO + feq[ZERO]; + + // calcFeqsFct(f,rho,vx1,vx2,vx3); + // distributions->setDistribution(f, ix1, ix2, ix3); + distributions->setDistributionInv(f, ix1, ix2, ix3); + + // distributions->swap(); + // distributions->setDistribution(f, ix1, ix2, ix3); + // distributions->setDistributionInv(f, ix1, ix2, ix3); + // distributions->swap(); + } + } + + // variablen der functions loeschen, da die verwiesenen Objecte nach dem verlassen des scopes ungueltig sind! + this->muVx1.ClearVar(); + this->muVx2.ClearVar(); + this->muVx3.ClearVar(); + this->muRho.ClearVar(); } ////////////////////////////////////////////////////////////////////////// void InitDistributionsBlockVisitor::checkFunction(mu::Parser fct) { - double x1=1.0,x2=1.0,x3=1.0; - fct.DefineVar("x1",&x1); - fct.DefineVar("x2",&x2); - fct.DefineVar("x3",&x3); - - try - { - fct.Eval(); - fct.ClearVar(); - } - catch(mu::ParserError& e) - { - throw UbException(UB_EXARGS,"function: "+e.GetExpr() + (std::string)"error: "+e.GetMsg() - +(std::string)", only x1,x2,x3 are allowed as variables" ); - } + double x1 = 1.0, x2 = 1.0, x3 = 1.0; + fct.DefineVar("x1", &x1); + fct.DefineVar("x2", &x2); + fct.DefineVar("x3", &x3); + + try { + fct.Eval(); + fct.ClearVar(); + } catch (mu::ParserError &e) { + throw UbException(UB_EXARGS, "function: " + e.GetExpr() + (std::string) "error: " + e.GetMsg() + + (std::string) ", only x1,x2,x3 are allowed as variables"); + } } ////////////////////////////////////////////////////////////////////////// - - - diff --git a/src/cpu/VirtualFluidsCore/Visitors/InitDistributionsBlockVisitor.h b/src/cpu/VirtualFluidsCore/Visitors/InitDistributionsBlockVisitor.h index bddda7901b29995d6c38de764b737c1d6636b2d8..c64f0ed936c9d9f527ec49f31e9646d5fa3150e9 100644 --- a/src/cpu/VirtualFluidsCore/Visitors/InitDistributionsBlockVisitor.h +++ b/src/cpu/VirtualFluidsCore/Visitors/InitDistributionsBlockVisitor.h @@ -1,28 +1,28 @@ //======================================================================================= -// ____ ____ __ ______ __________ __ __ __ __ -// \ \ | | | | | _ \ |___ ___| | | | | / \ | | -// \ \ | | | | | |_) | | | | | | | / \ | | -// \ \ | | | | | _ / | | | | | | / /\ \ | | -// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ -// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| -// \ \ | | ________________________________________________________________ -// \ \ | | | ______________________________________________________________| -// \ \| | | | __ __ __ __ ______ _______ -// \ | | |_____ | | | | | | | | | _ \ / _____) -// \ | | _____| | | | | | | | | | | \ \ \_______ +// ____ ____ __ ______ __________ __ __ __ __ +// \ \ | | | | | _ \ |___ ___| | | | | / \ | | +// \ \ | | | | | |_) | | | | | | | / \ | | +// \ \ | | | | | _ / | | | | | | / /\ \ | | +// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ +// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| +// \ \ | | ________________________________________________________________ +// \ \ | | | ______________________________________________________________| +// \ \| | | | __ __ __ __ ______ _______ +// \ | | |_____ | | | | | | | | | _ \ / _____) +// \ | | _____| | | | | | | | | | | \ \ \_______ // \ | | | | |_____ | \_/ | | | | |_/ / _____ | -// \ _____| |__| |________| \_______/ |__| |______/ (_______/ +// \ _____| |__| |________| \_______/ |__| |______/ (_______/ // -// This file is part of VirtualFluids. VirtualFluids is free software: you can +// This file is part of VirtualFluids. VirtualFluids is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of +// License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. -// -// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// +// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License along // with VirtualFluids (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>. // @@ -45,13 +45,13 @@ class Grid3D; class Block3D; //! \brief A class implements an initialization of the flow area. -//! \details +//! \details //! It is more flexible way to initialize flow area. -//! You can define functions to calculate macroscopic values for feq. +//! You can define functions to calculate macroscopic values for feq. //! x1,x2,x3 are automatically defined via this adapter and are the real world //! vertex coordinates. //! -//!if function is invalid an UbException with detailed information is thrown +//! if function is invalid an UbException with detailed information is thrown //! //! Example: //! \code @@ -63,39 +63,39 @@ class Block3D; class InitDistributionsBlockVisitor : public Block3DVisitor { public: - using D3Q27RealLim = std::numeric_limits<LBMReal>; + using D3Q27RealLim = std::numeric_limits<LBMReal>; public: - InitDistributionsBlockVisitor(); - ////////////////////////////////////////////////////////////////////////// - //automatic vars are: x1,x2, x3 - //ussage example: setVx1("x1*0.01+x2*0.003") - ////////////////////////////////////////////////////////////////////////// - void setVx1( const mu::Parser& parser); - void setVx2( const mu::Parser& parser); - void setVx3( const mu::Parser& parser); - void setRho( const mu::Parser& parser); + InitDistributionsBlockVisitor(); + ////////////////////////////////////////////////////////////////////////// + // automatic vars are: x1,x2, x3 + // ussage example: setVx1("x1*0.01+x2*0.003") + ////////////////////////////////////////////////////////////////////////// + void setVx1(const mu::Parser &parser); + void setVx2(const mu::Parser &parser); + void setVx3(const mu::Parser &parser); + void setRho(const mu::Parser &parser); - void setVx1( const std::string& muParserString); - void setVx2( const std::string& muParserString); - void setVx3( const std::string& muParserString); - void setRho( const std::string& muParserString); - ////////////////////////////////////////////////////////////////////////// - void setVx1( LBMReal vx1 ); - void setVx2( LBMReal vx2 ); - void setVx3( LBMReal vx3 ); - void setRho( LBMReal rho ); + void setVx1(const std::string &muParserString); + void setVx2(const std::string &muParserString); + void setVx3(const std::string &muParserString); + void setRho(const std::string &muParserString); + ////////////////////////////////////////////////////////////////////////// + void setVx1(LBMReal vx1); + void setVx2(LBMReal vx2); + void setVx3(LBMReal vx3); + void setRho(LBMReal rho); - void visit(SPtr<Grid3D> grid, SPtr<Block3D> block) override; + void visit(SPtr<Grid3D> grid, SPtr<Block3D> block) override; protected: - void checkFunction(mu::Parser fct); + void checkFunction(mu::Parser fct); private: - mu::Parser muVx1; - mu::Parser muVx2; - mu::Parser muVx3; - mu::Parser muRho; + mu::Parser muVx1; + mu::Parser muVx2; + mu::Parser muVx3; + mu::Parser muRho; }; -#endif //D3Q27INITDISTRIBUTIONSPATCHVISITOR_H +#endif // D3Q27INITDISTRIBUTIONSPATCHVISITOR_H diff --git a/src/cpu/VirtualFluidsCore/Visitors/InitDistributionsFromFileBlockVisitor.cpp b/src/cpu/VirtualFluidsCore/Visitors/InitDistributionsFromFileBlockVisitor.cpp index c03e8231085519a5eea67631ab120b2c1e05b718..73431d92876a10b207740ca17212a30dc84a7b98 100644 --- a/src/cpu/VirtualFluidsCore/Visitors/InitDistributionsFromFileBlockVisitor.cpp +++ b/src/cpu/VirtualFluidsCore/Visitors/InitDistributionsFromFileBlockVisitor.cpp @@ -1,255 +1,241 @@ #include "InitDistributionsFromFileBlockVisitor.h" -#include <basics/utilities/UbFileInputASCII.h> -#include "LBMKernel.h" +#include "BCArray3D.h" #include "BCProcessor.h" -#include "Grid3DSystem.h" -#include "InitDensityLBMKernel.h" +#include "Block3D.h" #include "DataSet3D.h" #include "EsoTwist3D.h" #include "Grid3D.h" -#include "Block3D.h" -#include "BCArray3D.h" - +#include "Grid3DSystem.h" +#include "InitDensityLBMKernel.h" +#include "LBMKernel.h" +#include <basics/utilities/UbFileInputASCII.h> -InitDistributionsFromFileBlockVisitor::InitDistributionsFromFileBlockVisitor(/*LBMReal nu, */LBMReal rho, std::string filename) - : Block3DVisitor(0, Grid3DSystem::MAXLEVEL), /*nu(nu),*/ rho(rho) +InitDistributionsFromFileBlockVisitor::InitDistributionsFromFileBlockVisitor(/*LBMReal nu, */ LBMReal rho, + std::string filename) + : Block3DVisitor(0, Grid3DSystem::MAXLEVEL), /*nu(nu),*/ rho(rho) { - UbFileInputASCII in(filename); - if (!in) - { - throw UbException(UB_EXARGS, "could not open file "+filename); - } - - int nodesX1 = in.readInteger(); - int nodesX2 = in.readInteger(); - int nodesX3 = in.readInteger(); - - matrix = CbArray4D<LBMReal, IndexerX4X3X2X1>(3, nodesX1, nodesX2, nodesX3, 0); - - for (int x3 = 0; x3<nodesX3; x3++) - for (int x2 = 0; x2<nodesX2; x2++) - for (int x1 = 0; x1<nodesX1; x1++) - { - //for (int x1 = 0; x1<nodesX1; x1++) - // for (int x2 = 0; x2<nodesX2; x2++) - // for (int x3 = 0; x3<nodesX3; x3++) - // { - matrix(Vx1, x1, x2, x3) = in.readDouble(); - matrix(Vx2, x1, x2, x3) = in.readDouble(); - matrix(Vx3, x1, x2, x3) = in.readDouble(); - } + UbFileInputASCII in(filename); + if (!in) { + throw UbException(UB_EXARGS, "could not open file " + filename); + } + + int nodesX1 = in.readInteger(); + int nodesX2 = in.readInteger(); + int nodesX3 = in.readInteger(); + + matrix = CbArray4D<LBMReal, IndexerX4X3X2X1>(3, nodesX1, nodesX2, nodesX3, 0); + + for (int x3 = 0; x3 < nodesX3; x3++) + for (int x2 = 0; x2 < nodesX2; x2++) + for (int x1 = 0; x1 < nodesX1; x1++) { + // for (int x1 = 0; x1<nodesX1; x1++) + // for (int x2 = 0; x2<nodesX2; x2++) + // for (int x3 = 0; x3<nodesX3; x3++) + // { + matrix(Vx1, x1, x2, x3) = in.readDouble(); + matrix(Vx2, x1, x2, x3) = in.readDouble(); + matrix(Vx3, x1, x2, x3) = in.readDouble(); + } } ////////////////////////////////////////////////////////////////////////// void InitDistributionsFromFileBlockVisitor::visit(const SPtr<Grid3D> grid, SPtr<Block3D> block) { - using namespace D3Q27System; - - if (!block) UB_THROW(UbException(UB_EXARGS, "block is not exist")); - -// UbTupleDouble3 blockLengths = grid->getBlockLengths(block); -// UbTupleDouble3 nodeOffset = grid->getNodeOffset(block); -// double dx = grid->getDeltaX(block); -// LBMReal o = LBMSystem::calcCollisionFactor(nu, block->getLevel()); - - - //Funktionszeiger - typedef void(*CalcFeqsFct)(LBMReal* const& /*feq[27]*/, const LBMReal& /*(d)rho*/, const LBMReal& /*vx1*/, const LBMReal& /*vx2*/, const LBMReal& /*vx3*/); - CalcFeqsFct calcFeqsFct = NULL; - - LBMReal vx1, vx2, vx3; - - int gridRank = grid->getRank(); - int blockRank = block->getRank(); - - if (blockRank==gridRank && block->isActive()) - { - SPtr<ILBMKernel> kernel = block->getKernel(); - if (!kernel) - throw UbException(UB_EXARGS, "The LBM kernel isn't exist in block: "+block->toString()); - - if (kernel->getCompressible()) - calcFeqsFct = &D3Q27System::calcCompFeq; - else - calcFeqsFct = &D3Q27System::calcIncompFeq; - -// UbTupleDouble3 org = grid->getBlockWorldCoordinates(block); - - SPtr<BCArray3D> bcArray = kernel->getBCProcessor()->getBCArray(); - SPtr<EsoTwist3D> distributions = dynamicPointerCast<EsoTwist3D>(kernel->getDataSet()->getFdistributions()); - - LBMReal f[D3Q27System::ENDF+1]; - -// size_t nx1 = distributions->getNX1(); -// size_t nx2 = distributions->getNX2(); -// size_t nx3 = distributions->getNX3(); - - int minX1 = 0; - int minX2 = 0; -// int minX3 = 0; - - int maxX1 = (int)bcArray->getNX1(); - int maxX2 = (int)bcArray->getNX2(); - int maxX3 = (int)bcArray->getNX3(); - - int maxMX1 = (int)matrix.getNX2(); - int maxMX2 = (int)matrix.getNX3(); - int maxMX3 = (int)matrix.getNX4(); - - int blockix1 = block->getX1(); - int blockix2 = block->getX2(); - int blockix3 = block->getX3(); - - UbTupleInt3 blockNx = grid->getBlockNX(); - - for (int ix3 = minX1; ix3<maxX3; ix3++) - for (int ix2 = minX2; ix2<maxX2; ix2++) - for (int ix1 = minX1; ix1<maxX1; ix1++) - { - int x1 = blockix1*val<1>(blockNx)+ix1-1; - int x2 = blockix2*val<2>(blockNx)+ix2-1; - int x3 = blockix3*val<3>(blockNx)+ix3-1; - - if (x1==-1) - { - x1 = maxMX1-1; - } - if (x2==-1) - { - x2 = maxMX2-1; - } - if (x3==-1) - { - x3 = maxMX3-1; - } - - if (x1==maxMX1) - { - x1 = 1; - } - if (x2==maxMX2) - { - x2 = 1; - } - if (x3==maxMX3) - { - x3 = 1; - } - - vx1 = matrix(Vx1, x1, x2, x3); - vx2 = matrix(Vx2, x1, x2, x3); - vx3 = matrix(Vx3, x1, x2, x3); - - //int x1p, x2p, x3p; - - ////x-derivative - //if (x1+1 >= maxMX1) x1p = x1; - //else x1p = x1+1; - //double vx1Plusx1 = matrix(Vx1, x1p, x2, x3); - //double vx2Plusx1 = matrix(Vx2, x1p, x2, x3); - //double vx3Plusx1 = matrix(Vx3, x1p, x2, x3); - - //if (x1-1 < minX1) x1p = x1; - //else x1p = x1-1; - //double vx1Minusx1 = matrix(Vx1, x1p, x2, x3); - //double vx2Minusx1 = matrix(Vx2, x1p, x2, x3); - //double vx3Minusx1 = matrix(Vx3, x1p, x2, x3); - - ////y-derivative - //if (x2+1 >= maxMX2) x2p = x2; - //else x2p = x2+1; - //double vx1Plusx2 = matrix(Vx1, x1, x2p, x3); - //double vx2Plusx2 = matrix(Vx2, x1, x2p, x3); - //double vx3Plusx2 = matrix(Vx3, x1, x2p, x3); - - //if (x2-1 < minX2) x2p = x2; - //else x2p = x2-1; - //double vx1Minusx2 = matrix(Vx1, x1, x2p, x3); - //double vx2Minusx2 = matrix(Vx2, x1, x2p, x3); - //double vx3Minusx2 = matrix(Vx3, x1, x2p, x3); - - ////z-derivative - //if (x3+1 >= maxMX3) x3p = x3; - //else x3p = x3+1; - //double vx1Plusx3 = matrix(Vx1, x1, x2, x3p); - //double vx2Plusx3 = matrix(Vx2, x1, x2, x3p); - //double vx3Plusx3 = matrix(Vx3, x1, x2, x3p); - - //if (x3-1 < minX3) x3p = x3; - //else x3p = x3-1; - //double vx1Minusx3 = matrix(Vx1, x1, x2, x3); - //double vx2Minusx3 = matrix(Vx2, x1, x2, x3); - //double vx3Minusx3 = matrix(Vx3, x1, x2, x3); - - //double ax = (vx1Plusx1 - vx1Minusx1) / (2.0); - //double bx = (vx2Plusx1 - vx2Minusx1) / (2.0); - //double cx = (vx3Plusx1 - vx3Minusx1) / (2.0); - - //double ay = (vx1Plusx2 - vx1Minusx2) / (2.0); - //double by = (vx2Plusx2 - vx2Minusx2) / (2.0); - //double cy = (vx3Plusx2 - vx3Minusx2) / (2.0); - - //double az = (vx1Plusx3 - vx1Minusx3) / (2.0); - //double bz = (vx2Plusx3 - vx2Minusx3) / (2.0); - //double cz = (vx3Plusx3 - vx3Minusx3) / (2.0); - //double eps_new = 1.0; - //LBMReal op = 1.; - - //LBMReal feq[27]; - - //calcFeqsFct(feq, rho, vx1, vx2, vx3); - - //double f_E = eps_new *((5.*ax*o + 5.*by*o + 5.*cz*o - 8.*ax*op + 4.*by*op + 4.*cz*op) / (54.*o*op)); - //double f_N = f_E + eps_new *((2.*(ax - by)) / (9.*o)); - //double f_T = f_E + eps_new *((2.*(ax - cz)) / (9.*o)); - //double f_NE = eps_new *(-(5.*cz*o + 3.*(ay + bx)*op - 2.*cz*op + ax*(5.*o + op) + by*(5.*o + op)) / (54.*o*op)); - //double f_SE = f_NE + eps_new *((ay + bx) / (9.*o)); - //double f_TE = eps_new *(-(5.*cz*o + by*(5.*o - 2.*op) + 3.*(az + cx)*op + cz*op + ax*(5.*o + op)) / (54.*o*op)); - //double f_BE = f_TE + eps_new *((az + cx) / (9.*o)); - //double f_TN = eps_new *(-(5.*ax*o + 5.*by*o + 5.*cz*o - 2.*ax*op + by*op + 3.*bz*op + 3.*cy*op + cz*op) / (54.*o*op)); - //double f_BN = f_TN + eps_new *((bz + cy) / (9.*o)); - //double f_ZERO = eps_new *((5.*(ax + by + cz)) / (9.*op)); - //double f_TNE = eps_new *(-(ay + az + bx + bz + cx + cy) / (72.*o)); - //double f_TSW = -eps_new *((ay + bx) / (36.*o)) - f_TNE; - //double f_TSE = -eps_new *((az + cx) / (36.*o)) - f_TNE; - //double f_TNW = -eps_new *((bz + cy) / (36.*o)) - f_TNE; - - - //f[E] = f_E + feq[E]; - //f[W] = f_E + feq[W]; - //f[N] = f_N + feq[N]; - //f[S] = f_N + feq[S]; - //f[T] = f_T + feq[T]; - //f[B] = f_T + feq[B]; - //f[NE] = f_NE + feq[NE]; - //f[SW] = f_NE + feq[SW]; - //f[SE] = f_SE + feq[SE]; - //f[NW] = f_SE + feq[NW]; - //f[TE] = f_TE + feq[TE]; - //f[BW] = f_TE + feq[BW]; - //f[BE] = f_BE + feq[BE]; - //f[TW] = f_BE + feq[TW]; - //f[TN] = f_TN + feq[TN]; - //f[BS] = f_TN + feq[BS]; - //f[BN] = f_BN + feq[BN]; - //f[TS] = f_BN + feq[TS]; - //f[TNE] = f_TNE + feq[TNE]; - //f[TNW] = f_TNW + feq[TNW]; - //f[TSE] = f_TSE + feq[TSE]; - //f[TSW] = f_TSW + feq[TSW]; - //f[BNE] = f_TSW + feq[BNE]; - //f[BNW] = f_TSE + feq[BNW]; - //f[BSE] = f_TNW + feq[BSE]; - //f[BSW] = f_TNE + feq[BSW]; - //f[ZERO] = f_ZERO + feq[ZERO]; - - calcFeqsFct(f, rho, vx1, vx2, vx3); - - distributions->setDistribution(f, ix1, ix2, ix3); - distributions->setDistributionInv(f, ix1, ix2, ix3); - dynamicPointerCast<InitDensityLBMKernel>(kernel)->setVelocity(ix1, ix2, ix3, vx1, vx2, vx3); - } - - } + using namespace D3Q27System; + + if (!block) + UB_THROW(UbException(UB_EXARGS, "block is not exist")); + + // UbTupleDouble3 blockLengths = grid->getBlockLengths(block); + // UbTupleDouble3 nodeOffset = grid->getNodeOffset(block); + // double dx = grid->getDeltaX(block); + // LBMReal o = LBMSystem::calcCollisionFactor(nu, block->getLevel()); + + // Funktionszeiger + typedef void (*CalcFeqsFct)(LBMReal *const & /*feq[27]*/, const LBMReal & /*(d)rho*/, const LBMReal & /*vx1*/, + const LBMReal & /*vx2*/, const LBMReal & /*vx3*/); + CalcFeqsFct calcFeqsFct = NULL; + + LBMReal vx1, vx2, vx3; + + int gridRank = grid->getRank(); + int blockRank = block->getRank(); + + if (blockRank == gridRank && block->isActive()) { + SPtr<ILBMKernel> kernel = block->getKernel(); + if (!kernel) + throw UbException(UB_EXARGS, "The LBM kernel isn't exist in block: " + block->toString()); + + if (kernel->getCompressible()) + calcFeqsFct = &D3Q27System::calcCompFeq; + else + calcFeqsFct = &D3Q27System::calcIncompFeq; + + // UbTupleDouble3 org = grid->getBlockWorldCoordinates(block); + + SPtr<BCArray3D> bcArray = kernel->getBCProcessor()->getBCArray(); + SPtr<EsoTwist3D> distributions = dynamicPointerCast<EsoTwist3D>(kernel->getDataSet()->getFdistributions()); + + LBMReal f[D3Q27System::ENDF + 1]; + + // size_t nx1 = distributions->getNX1(); + // size_t nx2 = distributions->getNX2(); + // size_t nx3 = distributions->getNX3(); + + int minX1 = 0; + int minX2 = 0; + // int minX3 = 0; + + int maxX1 = (int)bcArray->getNX1(); + int maxX2 = (int)bcArray->getNX2(); + int maxX3 = (int)bcArray->getNX3(); + + int maxMX1 = (int)matrix.getNX2(); + int maxMX2 = (int)matrix.getNX3(); + int maxMX3 = (int)matrix.getNX4(); + + int blockix1 = block->getX1(); + int blockix2 = block->getX2(); + int blockix3 = block->getX3(); + + UbTupleInt3 blockNx = grid->getBlockNX(); + + for (int ix3 = minX1; ix3 < maxX3; ix3++) + for (int ix2 = minX2; ix2 < maxX2; ix2++) + for (int ix1 = minX1; ix1 < maxX1; ix1++) { + int x1 = blockix1 * val<1>(blockNx) + ix1 - 1; + int x2 = blockix2 * val<2>(blockNx) + ix2 - 1; + int x3 = blockix3 * val<3>(blockNx) + ix3 - 1; + + if (x1 == -1) { + x1 = maxMX1 - 1; + } + if (x2 == -1) { + x2 = maxMX2 - 1; + } + if (x3 == -1) { + x3 = maxMX3 - 1; + } + + if (x1 == maxMX1) { + x1 = 1; + } + if (x2 == maxMX2) { + x2 = 1; + } + if (x3 == maxMX3) { + x3 = 1; + } + + vx1 = matrix(Vx1, x1, x2, x3); + vx2 = matrix(Vx2, x1, x2, x3); + vx3 = matrix(Vx3, x1, x2, x3); + + // int x1p, x2p, x3p; + + ////x-derivative + // if (x1+1 >= maxMX1) x1p = x1; + // else x1p = x1+1; + // double vx1Plusx1 = matrix(Vx1, x1p, x2, x3); + // double vx2Plusx1 = matrix(Vx2, x1p, x2, x3); + // double vx3Plusx1 = matrix(Vx3, x1p, x2, x3); + + // if (x1-1 < minX1) x1p = x1; + // else x1p = x1-1; + // double vx1Minusx1 = matrix(Vx1, x1p, x2, x3); + // double vx2Minusx1 = matrix(Vx2, x1p, x2, x3); + // double vx3Minusx1 = matrix(Vx3, x1p, x2, x3); + + ////y-derivative + // if (x2+1 >= maxMX2) x2p = x2; + // else x2p = x2+1; + // double vx1Plusx2 = matrix(Vx1, x1, x2p, x3); + // double vx2Plusx2 = matrix(Vx2, x1, x2p, x3); + // double vx3Plusx2 = matrix(Vx3, x1, x2p, x3); + + // if (x2-1 < minX2) x2p = x2; + // else x2p = x2-1; + // double vx1Minusx2 = matrix(Vx1, x1, x2p, x3); + // double vx2Minusx2 = matrix(Vx2, x1, x2p, x3); + // double vx3Minusx2 = matrix(Vx3, x1, x2p, x3); + + ////z-derivative + // if (x3+1 >= maxMX3) x3p = x3; + // else x3p = x3+1; + // double vx1Plusx3 = matrix(Vx1, x1, x2, x3p); + // double vx2Plusx3 = matrix(Vx2, x1, x2, x3p); + // double vx3Plusx3 = matrix(Vx3, x1, x2, x3p); + + // if (x3-1 < minX3) x3p = x3; + // else x3p = x3-1; + // double vx1Minusx3 = matrix(Vx1, x1, x2, x3); + // double vx2Minusx3 = matrix(Vx2, x1, x2, x3); + // double vx3Minusx3 = matrix(Vx3, x1, x2, x3); + + // double ax = (vx1Plusx1 - vx1Minusx1) / (2.0); + // double bx = (vx2Plusx1 - vx2Minusx1) / (2.0); + // double cx = (vx3Plusx1 - vx3Minusx1) / (2.0); + + // double ay = (vx1Plusx2 - vx1Minusx2) / (2.0); + // double by = (vx2Plusx2 - vx2Minusx2) / (2.0); + // double cy = (vx3Plusx2 - vx3Minusx2) / (2.0); + + // double az = (vx1Plusx3 - vx1Minusx3) / (2.0); + // double bz = (vx2Plusx3 - vx2Minusx3) / (2.0); + // double cz = (vx3Plusx3 - vx3Minusx3) / (2.0); + // double eps_new = 1.0; + // LBMReal op = 1.; + + // LBMReal feq[27]; + + // calcFeqsFct(feq, rho, vx1, vx2, vx3); + + // double f_E = eps_new *((5.*ax*o + 5.*by*o + 5.*cz*o - 8.*ax*op + 4.*by*op + 4.*cz*op) / + // (54.*o*op)); double f_N = f_E + eps_new *((2.*(ax - by)) / (9.*o)); double f_T = f_E + eps_new + // *((2.*(ax - cz)) / (9.*o)); double f_NE = eps_new *(-(5.*cz*o + 3.*(ay + bx)*op - 2.*cz*op + + // ax*(5.*o + op) + by*(5.*o + op)) / (54.*o*op)); double f_SE = f_NE + eps_new *((ay + bx) / + // (9.*o)); double f_TE = eps_new *(-(5.*cz*o + by*(5.*o - 2.*op) + 3.*(az + cx)*op + cz*op + + // ax*(5.*o + op)) / (54.*o*op)); double f_BE = f_TE + eps_new *((az + cx) / (9.*o)); double f_TN = + // eps_new *(-(5.*ax*o + 5.*by*o + 5.*cz*o - 2.*ax*op + by*op + 3.*bz*op + 3.*cy*op + cz*op) / + // (54.*o*op)); double f_BN = f_TN + eps_new *((bz + cy) / (9.*o)); double f_ZERO = eps_new *((5.*(ax + // + by + cz)) / (9.*op)); double f_TNE = eps_new *(-(ay + az + bx + bz + cx + cy) / (72.*o)); double + // f_TSW = -eps_new *((ay + bx) / (36.*o)) - f_TNE; double f_TSE = -eps_new *((az + cx) / (36.*o)) - + // f_TNE; double f_TNW = -eps_new *((bz + cy) / (36.*o)) - f_TNE; + + // f[E] = f_E + feq[E]; + // f[W] = f_E + feq[W]; + // f[N] = f_N + feq[N]; + // f[S] = f_N + feq[S]; + // f[T] = f_T + feq[T]; + // f[B] = f_T + feq[B]; + // f[NE] = f_NE + feq[NE]; + // f[SW] = f_NE + feq[SW]; + // f[SE] = f_SE + feq[SE]; + // f[NW] = f_SE + feq[NW]; + // f[TE] = f_TE + feq[TE]; + // f[BW] = f_TE + feq[BW]; + // f[BE] = f_BE + feq[BE]; + // f[TW] = f_BE + feq[TW]; + // f[TN] = f_TN + feq[TN]; + // f[BS] = f_TN + feq[BS]; + // f[BN] = f_BN + feq[BN]; + // f[TS] = f_BN + feq[TS]; + // f[TNE] = f_TNE + feq[TNE]; + // f[TNW] = f_TNW + feq[TNW]; + // f[TSE] = f_TSE + feq[TSE]; + // f[TSW] = f_TSW + feq[TSW]; + // f[BNE] = f_TSW + feq[BNE]; + // f[BNW] = f_TSE + feq[BNW]; + // f[BSE] = f_TNW + feq[BSE]; + // f[BSW] = f_TNE + feq[BSW]; + // f[ZERO] = f_ZERO + feq[ZERO]; + + calcFeqsFct(f, rho, vx1, vx2, vx3); + + distributions->setDistribution(f, ix1, ix2, ix3); + distributions->setDistributionInv(f, ix1, ix2, ix3); + dynamicPointerCast<InitDensityLBMKernel>(kernel)->setVelocity(ix1, ix2, ix3, vx1, vx2, vx3); + } + } } ////////////////////////////////////////////////////////////////////////// diff --git a/src/cpu/VirtualFluidsCore/Visitors/InitDistributionsFromFileBlockVisitor.h b/src/cpu/VirtualFluidsCore/Visitors/InitDistributionsFromFileBlockVisitor.h index bb059fc1129bef7968104b15845167bf81512f02..1f40abadeef750da38e03d3db30ba752d4ae9da0 100644 --- a/src/cpu/VirtualFluidsCore/Visitors/InitDistributionsFromFileBlockVisitor.h +++ b/src/cpu/VirtualFluidsCore/Visitors/InitDistributionsFromFileBlockVisitor.h @@ -12,16 +12,14 @@ class Block3D; class InitDistributionsFromFileBlockVisitor : public Block3DVisitor { public: - InitDistributionsFromFileBlockVisitor(/*LBMReal nu, */LBMReal rho, std::string file); + InitDistributionsFromFileBlockVisitor(/*LBMReal nu, */ LBMReal rho, std::string file); - void visit(SPtr<Grid3D> grid, SPtr<Block3D> block) override; + void visit(SPtr<Grid3D> grid, SPtr<Block3D> block) override; private: - CbArray4D<LBMReal, IndexerX4X3X2X1> matrix; - enum Velocity { Vx1, Vx2, Vx3 }; -// LBMReal nu; - LBMReal rho; + CbArray4D<LBMReal, IndexerX4X3X2X1> matrix; + enum Velocity { Vx1, Vx2, Vx3 }; + // LBMReal nu; + LBMReal rho; }; #endif // InitDistributionsFromFileBlockVisitor_h__ - - diff --git a/src/cpu/VirtualFluidsCore/Visitors/InitDistributionsWithInterpolationGridVisitor.cpp b/src/cpu/VirtualFluidsCore/Visitors/InitDistributionsWithInterpolationGridVisitor.cpp index 279714e35fba8e812b56e01b3fc5929e9285cc45..343353c7b7caf58269e1b25799dbbc730fc227b5 100644 --- a/src/cpu/VirtualFluidsCore/Visitors/InitDistributionsWithInterpolationGridVisitor.cpp +++ b/src/cpu/VirtualFluidsCore/Visitors/InitDistributionsWithInterpolationGridVisitor.cpp @@ -2,608 +2,623 @@ #include "mpi.h" -#include <basics/utilities/UbFileInputASCII.h> -#include "LBMKernel.h" #include "BCProcessor.h" -#include "Grid3DSystem.h" -#include <CbArray2D.h> +#include "Block3D.h" #include "D3Q27EsoTwist3DSplittedVector.h" -#include "InterpolationProcessor.h" #include "DataSet3D.h" #include "Grid3D.h" -#include "Block3D.h" +#include "Grid3DSystem.h" +#include "InterpolationProcessor.h" +#include "LBMKernel.h" +#include <CbArray2D.h> +#include <basics/utilities/UbFileInputASCII.h> using namespace std; -InitDistributionsWithInterpolationGridVisitor::InitDistributionsWithInterpolationGridVisitor(SPtr<Grid3D> oldGrid, InterpolationProcessorPtr iProcessor, LBMReal nu) - : oldGrid(oldGrid), iProcessor(iProcessor), nu(nu) +InitDistributionsWithInterpolationGridVisitor::InitDistributionsWithInterpolationGridVisitor( + SPtr<Grid3D> oldGrid, InterpolationProcessorPtr iProcessor, LBMReal nu) + : oldGrid(oldGrid), iProcessor(iProcessor), nu(nu) { - } ////////////////////////////////////////////////////////////////////////// -InitDistributionsWithInterpolationGridVisitor::~InitDistributionsWithInterpolationGridVisitor() -= default; +InitDistributionsWithInterpolationGridVisitor::~InitDistributionsWithInterpolationGridVisitor() = default; ////////////////////////////////////////////////////////////////////////// void InitDistributionsWithInterpolationGridVisitor::visit(SPtr<Grid3D> grid) { - newGrid = grid; - int minInitLevel = newGrid->getCoarsestInitializedLevel(); - int maxInitLevel = newGrid->getFinestInitializedLevel(); - int newGridRank = newGrid->getRank(); - - for (int l = minInitLevel; l<=maxInitLevel; l++) - { -// int n = 0; - vector<SPtr<Block3D>> blockVector; - newGrid->getBlocks(l, blockVector); - vector<SPtr<Block3D>> tBlockID; - - for(SPtr<Block3D> newBlock : blockVector) - { - if (!newBlock) - UB_THROW(UbException(UB_EXARGS, "block is not exist")); - - int newBlockRank = newBlock->getRank(); -// int newBlockLevel = newBlock->getLevel(); - - SPtr<Block3D> oldBlock = oldGrid->getBlock(newBlock->getX1(), newBlock->getX2(), newBlock->getX3(), newBlock->getLevel()); - if (oldBlock) - { - int oldBlockRank = oldBlock->getRank(); - if (oldBlockRank == newBlockRank && oldBlock->isActive() && newBlockRank == newGridRank && newBlock->isActive()) - { - copyLocalBlock(oldBlock, newBlock); - } - else - { - copyRemoteBlock(oldBlock, newBlock); - } - } - else - { - int newlevel = newBlock->getLevel(); - Vector3D coords = newGrid->getNodeCoordinates(newBlock, 1, 1, 1); - - UbTupleInt3 oldGridBlockIndexes = oldGrid->getBlockIndexes(coords[0], coords[1], coords[2], newlevel-1); - oldBlock = oldGrid->getBlock(val<1>(oldGridBlockIndexes), val<2>(oldGridBlockIndexes), val<3>(oldGridBlockIndexes), newlevel-1); - - if (oldBlock) - { - int oldBlockRank = oldBlock->getRank(); -// int oldBlockLevel = oldBlock->getLevel(); - - if (oldBlockRank == newBlockRank && oldBlock->isActive() && newBlockRank == newGridRank && newBlock->isActive()) - { - interpolateLocalBlockCoarseToFine(oldBlock, newBlock); - } - else - { - interpolateRemoteBlockCoarseToFine(oldBlock, newBlock); - } + newGrid = grid; + int minInitLevel = newGrid->getCoarsestInitializedLevel(); + int maxInitLevel = newGrid->getFinestInitializedLevel(); + int newGridRank = newGrid->getRank(); + + for (int l = minInitLevel; l <= maxInitLevel; l++) { + // int n = 0; + vector<SPtr<Block3D>> blockVector; + newGrid->getBlocks(l, blockVector); + vector<SPtr<Block3D>> tBlockID; + + for (SPtr<Block3D> newBlock : blockVector) { + if (!newBlock) + UB_THROW(UbException(UB_EXARGS, "block is not exist")); + + int newBlockRank = newBlock->getRank(); + // int newBlockLevel = newBlock->getLevel(); + + SPtr<Block3D> oldBlock = + oldGrid->getBlock(newBlock->getX1(), newBlock->getX2(), newBlock->getX3(), newBlock->getLevel()); + if (oldBlock) { + int oldBlockRank = oldBlock->getRank(); + if (oldBlockRank == newBlockRank && oldBlock->isActive() && newBlockRank == newGridRank && + newBlock->isActive()) { + copyLocalBlock(oldBlock, newBlock); + } else { + copyRemoteBlock(oldBlock, newBlock); + } + } else { + int newlevel = newBlock->getLevel(); + Vector3D coords = newGrid->getNodeCoordinates(newBlock, 1, 1, 1); + + UbTupleInt3 oldGridBlockIndexes = + oldGrid->getBlockIndexes(coords[0], coords[1], coords[2], newlevel - 1); + oldBlock = oldGrid->getBlock(val<1>(oldGridBlockIndexes), val<2>(oldGridBlockIndexes), + val<3>(oldGridBlockIndexes), newlevel - 1); + + if (oldBlock) { + int oldBlockRank = oldBlock->getRank(); + // int oldBlockLevel = oldBlock->getLevel(); + + if (oldBlockRank == newBlockRank && oldBlock->isActive() && newBlockRank == newGridRank && + newBlock->isActive()) { + interpolateLocalBlockCoarseToFine(oldBlock, newBlock); + } else { + interpolateRemoteBlockCoarseToFine(oldBlock, newBlock); + } + } else { + oldGridBlockIndexes = oldGrid->getBlockIndexes(coords[0], coords[1], coords[2], newlevel + 1); + oldBlock = oldGrid->getBlock(val<1>(oldGridBlockIndexes), val<2>(oldGridBlockIndexes), + val<3>(oldGridBlockIndexes), newlevel + 1); + if (oldBlock) { + int oldBlockRank = oldBlock->getRank(); + // int oldBlockLevel = oldBlock->getLevel(); + + if (oldBlockRank == newBlockRank && oldBlock->isActive() && newBlockRank == newGridRank && + newBlock->isActive()) { + interpolateLocalBlockFineToCoarse(oldBlock, newBlock); + } else { + interpolateRemoteBlockFineToCoarse(oldBlock, newBlock); + } + } + } } - else - { - oldGridBlockIndexes = oldGrid->getBlockIndexes(coords[0], coords[1], coords[2], newlevel+1); - oldBlock = oldGrid->getBlock(val<1>(oldGridBlockIndexes), val<2>(oldGridBlockIndexes), val<3>(oldGridBlockIndexes), newlevel+1); - if (oldBlock) - { - int oldBlockRank = oldBlock->getRank(); -// int oldBlockLevel = oldBlock->getLevel(); - - if (oldBlockRank == newBlockRank && oldBlock->isActive() && newBlockRank == newGridRank && newBlock->isActive()) - { - interpolateLocalBlockFineToCoarse(oldBlock, newBlock); - } - else - { - interpolateRemoteBlockFineToCoarse(oldBlock, newBlock); - } - } - } - } - } - } + } + } } ////////////////////////////////////////////////////////////////////////// void InitDistributionsWithInterpolationGridVisitor::copyLocalBlock(SPtr<Block3D> oldBlock, SPtr<Block3D> newBlock) { - SPtr<ILBMKernel> oldKernel = oldBlock->getKernel(); - if (!oldKernel) - throw UbException(UB_EXARGS, "The LBM kernel isn't exist in block: "+oldBlock->toString()); - SPtr<EsoTwist3D> oldDistributions = dynamicPointerCast<EsoTwist3D>(oldKernel->getDataSet()->getFdistributions()); - - SPtr<ILBMKernel> kernel = newBlock->getKernel(); - if (!kernel) - throw UbException(UB_EXARGS, "The LBM kernel isn't exist in new block: "+newBlock->toString()); - kernel->getDataSet()->setFdistributions(oldDistributions); + SPtr<ILBMKernel> oldKernel = oldBlock->getKernel(); + if (!oldKernel) + throw UbException(UB_EXARGS, "The LBM kernel isn't exist in block: " + oldBlock->toString()); + SPtr<EsoTwist3D> oldDistributions = dynamicPointerCast<EsoTwist3D>(oldKernel->getDataSet()->getFdistributions()); + + SPtr<ILBMKernel> kernel = newBlock->getKernel(); + if (!kernel) + throw UbException(UB_EXARGS, "The LBM kernel isn't exist in new block: " + newBlock->toString()); + kernel->getDataSet()->setFdistributions(oldDistributions); } ////////////////////////////////////////////////////////////////////////// void InitDistributionsWithInterpolationGridVisitor::copyRemoteBlock(SPtr<Block3D> oldBlock, SPtr<Block3D> newBlock) { - int newGridRank = newGrid->getRank(); - int oldBlockRank = oldBlock->getRank(); - int newBlockRank = newBlock->getRank(); - - if (oldBlockRank == newGridRank && oldBlock->isActive()) - { - SPtr<ILBMKernel> oldKernel = oldBlock->getKernel(); - if (!oldKernel) - throw UbException(UB_EXARGS, "The LBM kernel isn't exist in block: "+oldBlock->toString()); - SPtr<EsoTwist3D> oldDistributions = dynamicPointerCast<EsoTwist3D>(oldKernel->getDataSet()->getFdistributions()); - - CbArray4D<LBMReal, IndexerX4X3X2X1>::CbArray4DPtr localDistributions = dynamicPointerCast<D3Q27EsoTwist3DSplittedVector>(oldDistributions)->getLocalDistributions(); - CbArray4D<LBMReal, IndexerX4X3X2X1>::CbArray4DPtr nonLocalDistributions = dynamicPointerCast<D3Q27EsoTwist3DSplittedVector>(oldDistributions)->getNonLocalDistributions(); - CbArray3D<LBMReal, IndexerX3X2X1>::CbArray3DPtr zeroDistributions = dynamicPointerCast<D3Q27EsoTwist3DSplittedVector>(oldDistributions)->getZeroDistributions(); - - MPI_Send(localDistributions->getStartAdressOfSortedArray(0, 0, 0, 0), (int)localDistributions->getDataVector().size(), MPI_DOUBLE, newBlockRank, 0, MPI_COMM_WORLD); - MPI_Send(nonLocalDistributions->getStartAdressOfSortedArray(0, 0, 0, 0), (int)nonLocalDistributions->getDataVector().size(), MPI_DOUBLE, newBlockRank, 0, MPI_COMM_WORLD); - MPI_Send(zeroDistributions->getStartAdressOfSortedArray(0, 0, 0), (int)zeroDistributions->getDataVector().size(), MPI_DOUBLE, newBlockRank, 0, MPI_COMM_WORLD); - } - else if (newBlockRank == newGridRank && newBlock->isActive()) - { - SPtr<ILBMKernel> newKernel = newBlock->getKernel(); - if (!newKernel) - throw UbException(UB_EXARGS, "The LBM kernel isn't exist in new block: "+newBlock->toString()+UbSystem::toString(newGridRank)); - - SPtr<EsoTwist3D> newDistributions = dynamicPointerCast<EsoTwist3D>(newKernel->getDataSet()->getFdistributions()); - - CbArray4D<LBMReal, IndexerX4X3X2X1>::CbArray4DPtr localDistributions = dynamicPointerCast<D3Q27EsoTwist3DSplittedVector>(newDistributions)->getLocalDistributions(); - CbArray4D<LBMReal, IndexerX4X3X2X1>::CbArray4DPtr nonLocalDistributions = dynamicPointerCast<D3Q27EsoTwist3DSplittedVector>(newDistributions)->getNonLocalDistributions(); - CbArray3D<LBMReal, IndexerX3X2X1>::CbArray3DPtr zeroDistributions = dynamicPointerCast<D3Q27EsoTwist3DSplittedVector>(newDistributions)->getZeroDistributions(); - - MPI_Recv(localDistributions->getStartAdressOfSortedArray(0, 0, 0, 0), (int)localDistributions->getDataVector().size(), MPI_DOUBLE, oldBlockRank, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); - MPI_Recv(nonLocalDistributions->getStartAdressOfSortedArray(0, 0, 0, 0), (int)nonLocalDistributions->getDataVector().size(), MPI_DOUBLE, oldBlockRank, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); - MPI_Recv(zeroDistributions->getStartAdressOfSortedArray(0, 0, 0), (int)zeroDistributions->getDataVector().size(), MPI_DOUBLE, oldBlockRank, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); - } + int newGridRank = newGrid->getRank(); + int oldBlockRank = oldBlock->getRank(); + int newBlockRank = newBlock->getRank(); + + if (oldBlockRank == newGridRank && oldBlock->isActive()) { + SPtr<ILBMKernel> oldKernel = oldBlock->getKernel(); + if (!oldKernel) + throw UbException(UB_EXARGS, "The LBM kernel isn't exist in block: " + oldBlock->toString()); + SPtr<EsoTwist3D> oldDistributions = + dynamicPointerCast<EsoTwist3D>(oldKernel->getDataSet()->getFdistributions()); + + CbArray4D<LBMReal, IndexerX4X3X2X1>::CbArray4DPtr localDistributions = + dynamicPointerCast<D3Q27EsoTwist3DSplittedVector>(oldDistributions)->getLocalDistributions(); + CbArray4D<LBMReal, IndexerX4X3X2X1>::CbArray4DPtr nonLocalDistributions = + dynamicPointerCast<D3Q27EsoTwist3DSplittedVector>(oldDistributions)->getNonLocalDistributions(); + CbArray3D<LBMReal, IndexerX3X2X1>::CbArray3DPtr zeroDistributions = + dynamicPointerCast<D3Q27EsoTwist3DSplittedVector>(oldDistributions)->getZeroDistributions(); + + MPI_Send(localDistributions->getStartAdressOfSortedArray(0, 0, 0, 0), + (int)localDistributions->getDataVector().size(), MPI_DOUBLE, newBlockRank, 0, MPI_COMM_WORLD); + MPI_Send(nonLocalDistributions->getStartAdressOfSortedArray(0, 0, 0, 0), + (int)nonLocalDistributions->getDataVector().size(), MPI_DOUBLE, newBlockRank, 0, MPI_COMM_WORLD); + MPI_Send(zeroDistributions->getStartAdressOfSortedArray(0, 0, 0), + (int)zeroDistributions->getDataVector().size(), MPI_DOUBLE, newBlockRank, 0, MPI_COMM_WORLD); + } else if (newBlockRank == newGridRank && newBlock->isActive()) { + SPtr<ILBMKernel> newKernel = newBlock->getKernel(); + if (!newKernel) + throw UbException(UB_EXARGS, "The LBM kernel isn't exist in new block: " + newBlock->toString() + + UbSystem::toString(newGridRank)); + + SPtr<EsoTwist3D> newDistributions = + dynamicPointerCast<EsoTwist3D>(newKernel->getDataSet()->getFdistributions()); + + CbArray4D<LBMReal, IndexerX4X3X2X1>::CbArray4DPtr localDistributions = + dynamicPointerCast<D3Q27EsoTwist3DSplittedVector>(newDistributions)->getLocalDistributions(); + CbArray4D<LBMReal, IndexerX4X3X2X1>::CbArray4DPtr nonLocalDistributions = + dynamicPointerCast<D3Q27EsoTwist3DSplittedVector>(newDistributions)->getNonLocalDistributions(); + CbArray3D<LBMReal, IndexerX3X2X1>::CbArray3DPtr zeroDistributions = + dynamicPointerCast<D3Q27EsoTwist3DSplittedVector>(newDistributions)->getZeroDistributions(); + + MPI_Recv(localDistributions->getStartAdressOfSortedArray(0, 0, 0, 0), + (int)localDistributions->getDataVector().size(), MPI_DOUBLE, oldBlockRank, 0, MPI_COMM_WORLD, + MPI_STATUS_IGNORE); + MPI_Recv(nonLocalDistributions->getStartAdressOfSortedArray(0, 0, 0, 0), + (int)nonLocalDistributions->getDataVector().size(), MPI_DOUBLE, oldBlockRank, 0, MPI_COMM_WORLD, + MPI_STATUS_IGNORE); + MPI_Recv(zeroDistributions->getStartAdressOfSortedArray(0, 0, 0), + (int)zeroDistributions->getDataVector().size(), MPI_DOUBLE, oldBlockRank, 0, MPI_COMM_WORLD, + MPI_STATUS_IGNORE); + } } ////////////////////////////////////////////////////////////////////////// -void InitDistributionsWithInterpolationGridVisitor::interpolateLocalBlockCoarseToFine(SPtr<Block3D> oldBlock, SPtr<Block3D> newBlock) +void InitDistributionsWithInterpolationGridVisitor::interpolateLocalBlockCoarseToFine(SPtr<Block3D> oldBlock, + SPtr<Block3D> newBlock) { - D3Q27ICell icellC; - D3Q27ICell icellF; - LBMReal xoff, yoff, zoff; - - LBMReal omegaC = LBMSystem::calcCollisionFactor(nu, oldBlock->getLevel()); - LBMReal omegaF =LBMSystem::calcCollisionFactor(nu, newBlock->getLevel()); - - iProcessor->setOmegas(omegaC, omegaF); - - SPtr<ILBMKernel> oldKernel = oldBlock->getKernel(); - if (!oldKernel) - throw UbException(UB_EXARGS, "The LBM kernel isn't exist in old block: "+oldBlock->toString()); - - SPtr<EsoTwist3D> oldDistributions = dynamicPointerCast<EsoTwist3D>(oldKernel->getDataSet()->getFdistributions()); - - SPtr<BCArray3D> bcArrayOldBlock = oldBlock->getKernel()->getBCProcessor()->getBCArray(); - - SPtr<ILBMKernel> newKernel = newBlock->getKernel(); - if (!newKernel) - throw UbException(UB_EXARGS, "The LBM kernel isn't exist in new block: "+newBlock->toString()); - - SPtr<EsoTwist3D> newDistributions = dynamicPointerCast<EsoTwist3D>(newKernel->getDataSet()->getFdistributions()); - - int minX1 = 0; - int minX2 = 0; - int minX3 = 0; - - int maxX1 = (int)newDistributions->getNX1()-1; - int maxX2 = (int)newDistributions->getNX2()-1; - int maxX3 = (int)newDistributions->getNX3()-1; - - int bMaxX1 = (int)newDistributions->getNX1(); - int bMaxX2 = (int)newDistributions->getNX2(); - int bMaxX3 = (int)newDistributions->getNX3(); - - for (int ix3 = minX3; ix3 < maxX3; ix3+=2) - for (int ix2 = minX2; ix2 < maxX2; ix2+=2) - for (int ix1 = minX1; ix1 < maxX1; ix1+=2) - { - Vector3D coords = newGrid->getNodeCoordinates(newBlock, ix1, ix2, ix3); - UbTupleInt3 oldGridIndexMin = oldGrid->getNodeIndexes(oldBlock, coords[0], coords[1], coords[2]); - int howManySolids= iProcessor->iCellHowManySolids(bcArrayOldBlock, val<1>(oldGridIndexMin), val<2>(oldGridIndexMin), val<3>(oldGridIndexMin)); - - if (howManySolids == 0 || howManySolids == 8) - { - iProcessor->readICell(oldDistributions, icellC, val<1>(oldGridIndexMin), val<2>(oldGridIndexMin), val<3>(oldGridIndexMin)); - iProcessor->interpolateCoarseToFine(icellC, icellF); - } - else - { - if (iProcessor->findNeighborICell(bcArrayOldBlock, oldDistributions, icellC, bMaxX1, bMaxX2, bMaxX3, - val<1>(oldGridIndexMin), val<2>(oldGridIndexMin), val<3>(oldGridIndexMin), xoff, yoff, zoff)) - { - //std::string err = "For "+oldBlock->toString()+ - // " x1="+UbSystem::toString(val<1>(oldGridIndexMin))+ - // ", x2=" + UbSystem::toString(val<2>(oldGridIndexMin))+ - // ", x3=" + UbSystem::toString(val<3>(oldGridIndexMin))+ - // " interpolation is not implemented for other direction"+ - // " by using in: "+(std::string)typeid(*this).name()+ - // " or maybe you have a solid on the block boundary"; - //UB_THROW(UbException(UB_EXARGS, err)); - iProcessor->interpolateCoarseToFine(icellC, icellF, xoff, yoff, zoff); - } - else - { - for (int i=0; i<27; i++) - { - icellF.BSW[i]=0.0; - icellF.BSE[i]=0.0; - icellF.BNW[i]=0.0; - icellF.BNE[i]=0.0; - icellF.TSW[i]=0.0; - icellF.TSE[i]=0.0; - icellF.TNW[i]=0.0; - icellF.TNE[i]=0.0; - } - // std::string err = "For "+oldBlock->toString()+ - // " x1="+UbSystem::toString(val<1>(oldGridIndexMin))+ - // ", x2=" + UbSystem::toString(val<2>(oldGridIndexMin))+ - // ", x3=" + UbSystem::toString(val<3>(oldGridIndexMin))+ - // " interpolation is not implemented for other direction"+ - // " by using in: "+(std::string)typeid(*this).name()+ - // " or maybe you have a solid on the block boundary"; - ////UB_THROW(UbException(UB_EXARGS, err)); - // UBLOG(logINFO, err); - } + D3Q27ICell icellC; + D3Q27ICell icellF; + LBMReal xoff, yoff, zoff; + + LBMReal omegaC = LBMSystem::calcCollisionFactor(nu, oldBlock->getLevel()); + LBMReal omegaF = LBMSystem::calcCollisionFactor(nu, newBlock->getLevel()); + + iProcessor->setOmegas(omegaC, omegaF); + + SPtr<ILBMKernel> oldKernel = oldBlock->getKernel(); + if (!oldKernel) + throw UbException(UB_EXARGS, "The LBM kernel isn't exist in old block: " + oldBlock->toString()); + + SPtr<EsoTwist3D> oldDistributions = dynamicPointerCast<EsoTwist3D>(oldKernel->getDataSet()->getFdistributions()); + + SPtr<BCArray3D> bcArrayOldBlock = oldBlock->getKernel()->getBCProcessor()->getBCArray(); + + SPtr<ILBMKernel> newKernel = newBlock->getKernel(); + if (!newKernel) + throw UbException(UB_EXARGS, "The LBM kernel isn't exist in new block: " + newBlock->toString()); + + SPtr<EsoTwist3D> newDistributions = dynamicPointerCast<EsoTwist3D>(newKernel->getDataSet()->getFdistributions()); + + int minX1 = 0; + int minX2 = 0; + int minX3 = 0; + + int maxX1 = (int)newDistributions->getNX1() - 1; + int maxX2 = (int)newDistributions->getNX2() - 1; + int maxX3 = (int)newDistributions->getNX3() - 1; + + int bMaxX1 = (int)newDistributions->getNX1(); + int bMaxX2 = (int)newDistributions->getNX2(); + int bMaxX3 = (int)newDistributions->getNX3(); + + for (int ix3 = minX3; ix3 < maxX3; ix3 += 2) + for (int ix2 = minX2; ix2 < maxX2; ix2 += 2) + for (int ix1 = minX1; ix1 < maxX1; ix1 += 2) { + Vector3D coords = newGrid->getNodeCoordinates(newBlock, ix1, ix2, ix3); + UbTupleInt3 oldGridIndexMin = oldGrid->getNodeIndexes(oldBlock, coords[0], coords[1], coords[2]); + int howManySolids = iProcessor->iCellHowManySolids(bcArrayOldBlock, val<1>(oldGridIndexMin), + val<2>(oldGridIndexMin), val<3>(oldGridIndexMin)); + + if (howManySolids == 0 || howManySolids == 8) { + iProcessor->readICell(oldDistributions, icellC, val<1>(oldGridIndexMin), val<2>(oldGridIndexMin), + val<3>(oldGridIndexMin)); + iProcessor->interpolateCoarseToFine(icellC, icellF); + } else { + if (iProcessor->findNeighborICell(bcArrayOldBlock, oldDistributions, icellC, bMaxX1, bMaxX2, bMaxX3, + val<1>(oldGridIndexMin), val<2>(oldGridIndexMin), + val<3>(oldGridIndexMin), xoff, yoff, zoff)) { + // std::string err = "For "+oldBlock->toString()+ + // " x1="+UbSystem::toString(val<1>(oldGridIndexMin))+ + // ", x2=" + UbSystem::toString(val<2>(oldGridIndexMin))+ + // ", x3=" + UbSystem::toString(val<3>(oldGridIndexMin))+ + // " interpolation is not implemented for other direction"+ + // " by using in: "+(std::string)typeid(*this).name()+ + // " or maybe you have a solid on the block boundary"; + // UB_THROW(UbException(UB_EXARGS, err)); + iProcessor->interpolateCoarseToFine(icellC, icellF, xoff, yoff, zoff); + } else { + for (int i = 0; i < 27; i++) { + icellF.BSW[i] = 0.0; + icellF.BSE[i] = 0.0; + icellF.BNW[i] = 0.0; + icellF.BNE[i] = 0.0; + icellF.TSW[i] = 0.0; + icellF.TSE[i] = 0.0; + icellF.TNW[i] = 0.0; + icellF.TNE[i] = 0.0; + } + // std::string err = "For "+oldBlock->toString()+ + // " x1="+UbSystem::toString(val<1>(oldGridIndexMin))+ + // ", x2=" + UbSystem::toString(val<2>(oldGridIndexMin))+ + // ", x3=" + UbSystem::toString(val<3>(oldGridIndexMin))+ + // " interpolation is not implemented for other direction"+ + // " by using in: "+(std::string)typeid(*this).name()+ + // " or maybe you have a solid on the block boundary"; + ////UB_THROW(UbException(UB_EXARGS, err)); + // UBLOG(logINFO, err); + } + } + + iProcessor->writeICell(newDistributions, icellF, ix1, ix2, ix3); + iProcessor->writeICellInv(newDistributions, icellF, ix1, ix2, ix3); } - - iProcessor->writeICell(newDistributions, icellF, ix1, ix2, ix3); - iProcessor->writeICellInv(newDistributions, icellF, ix1, ix2, ix3); - } } ////////////////////////////////////////////////////////////////////////// -void InitDistributionsWithInterpolationGridVisitor::interpolateRemoteBlockCoarseToFine(SPtr<Block3D> oldBlock, SPtr<Block3D> newBlock) +void InitDistributionsWithInterpolationGridVisitor::interpolateRemoteBlockCoarseToFine(SPtr<Block3D> oldBlock, + SPtr<Block3D> newBlock) { - int newGridRank = newGrid->getRank(); - int oldBlockRank = oldBlock->getRank(); - int newBlockRank = newBlock->getRank(); - - if (oldBlockRank == newGridRank) - { - SPtr<ILBMKernel> oldKernel = oldBlock->getKernel(); - if (!oldKernel) - throw UbException(UB_EXARGS, "The LBM kernel isn't exist in block: "+oldBlock->toString()); - SPtr<EsoTwist3D> oldDistributions = dynamicPointerCast<EsoTwist3D>(oldKernel->getDataSet()->getFdistributions()); - - CbArray4D<LBMReal, IndexerX4X3X2X1>::CbArray4DPtr localDistributions = dynamicPointerCast<D3Q27EsoTwist3DSplittedVector>(oldDistributions)->getLocalDistributions(); - CbArray4D<LBMReal, IndexerX4X3X2X1>::CbArray4DPtr nonLocalDistributions = dynamicPointerCast<D3Q27EsoTwist3DSplittedVector>(oldDistributions)->getNonLocalDistributions(); - CbArray3D<LBMReal, IndexerX3X2X1>::CbArray3DPtr zeroDistributions = dynamicPointerCast<D3Q27EsoTwist3DSplittedVector>(oldDistributions)->getZeroDistributions(); - - MPI_Send(localDistributions->getStartAdressOfSortedArray(0, 0, 0, 0), (int)localDistributions->getDataVector().size(), MPI_DOUBLE, newBlockRank, 0, MPI_COMM_WORLD); - MPI_Send(nonLocalDistributions->getStartAdressOfSortedArray(0, 0, 0, 0), (int)nonLocalDistributions->getDataVector().size(), MPI_DOUBLE, newBlockRank, 0, MPI_COMM_WORLD); - MPI_Send(zeroDistributions->getStartAdressOfSortedArray(0, 0, 0), (int)zeroDistributions->getDataVector().size(), MPI_DOUBLE, newBlockRank, 0, MPI_COMM_WORLD); - - SPtr<BCArray3D> bcArrayOldBlock = oldBlock->getKernel()->getBCProcessor()->getBCArray(); - std::vector< int >& bcDataVector = bcArrayOldBlock->getBcindexmatrixDataVector(); - MPI_Send(&bcDataVector[0], (int)bcDataVector.size(), MPI_INT, newBlockRank, 0, MPI_COMM_WORLD); - } - else if (newBlockRank == newGridRank && newBlock->isActive()) - { - D3Q27ICell icellC; - D3Q27ICell icellF; - LBMReal xoff, yoff, zoff; - - LBMReal omegaC = LBMSystem::calcCollisionFactor(nu, oldBlock->getLevel()); - LBMReal omegaF =LBMSystem::calcCollisionFactor(nu, newBlock->getLevel()); - - iProcessor->setOmegas(omegaC, omegaF); - - SPtr<ILBMKernel> newKernel = newBlock->getKernel(); - if (!newKernel) - throw UbException(UB_EXARGS, "The LBM kernel isn't exist in new block: "+newBlock->toString()); - - SPtr<EsoTwist3D> newDistributions = dynamicPointerCast<EsoTwist3D>(newKernel->getDataSet()->getFdistributions()); - - int minX1 = 0; - int minX2 = 0; - int minX3 = 0; - - int maxX1 = (int)newDistributions->getNX1()-1; - int maxX2 = (int)newDistributions->getNX2()-1; - int maxX3 = (int)newDistributions->getNX3()-1; - - int bMaxX1 = (int)newDistributions->getNX1(); - int bMaxX2 = (int)newDistributions->getNX2(); - int bMaxX3 = (int)newDistributions->getNX3(); - - SPtr<EsoTwist3D> oldDistributions(new D3Q27EsoTwist3DSplittedVector(bMaxX1, bMaxX2, bMaxX3, 0)); - - CbArray4D<LBMReal, IndexerX4X3X2X1>::CbArray4DPtr localDistributions = dynamicPointerCast<D3Q27EsoTwist3DSplittedVector>(oldDistributions)->getLocalDistributions(); - CbArray4D<LBMReal, IndexerX4X3X2X1>::CbArray4DPtr nonLocalDistributions = dynamicPointerCast<D3Q27EsoTwist3DSplittedVector>(oldDistributions)->getNonLocalDistributions(); - CbArray3D<LBMReal, IndexerX3X2X1>::CbArray3DPtr zeroDistributions = dynamicPointerCast<D3Q27EsoTwist3DSplittedVector>(oldDistributions)->getZeroDistributions(); - - MPI_Recv(localDistributions->getStartAdressOfSortedArray(0, 0, 0, 0), (int)localDistributions->getDataVector().size(), MPI_DOUBLE, oldBlockRank, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); - MPI_Recv(nonLocalDistributions->getStartAdressOfSortedArray(0, 0, 0, 0), (int)nonLocalDistributions->getDataVector().size(), MPI_DOUBLE, oldBlockRank, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); - MPI_Recv(zeroDistributions->getStartAdressOfSortedArray(0, 0, 0), (int)zeroDistributions->getDataVector().size(), MPI_DOUBLE, oldBlockRank, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); - - SPtr<BCArray3D> bcArrayOldBlock(new BCArray3D(bMaxX1, bMaxX2, bMaxX3, BCArray3D::FLUID)); - std::vector< int >& bcDataVector = bcArrayOldBlock->getBcindexmatrixDataVector(); - MPI_Recv(&bcDataVector[0], (int)bcDataVector.size(), MPI_INT, oldBlockRank, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); - - for (int ix3 = minX3; ix3 < maxX3; ix3+=2) - for (int ix2 = minX2; ix2 < maxX2; ix2+=2) - for (int ix1 = minX1; ix1 < maxX1; ix1+=2) - { - Vector3D coords = newGrid->getNodeCoordinates(newBlock, ix1, ix2, ix3); - UbTupleInt3 oldGridIndexMin = oldGrid->getNodeIndexes(oldBlock, coords[0], coords[1], coords[2]); - - int howManySolids= iProcessor->iCellHowManySolids(bcArrayOldBlock, val<1>(oldGridIndexMin), val<2>(oldGridIndexMin), val<3>(oldGridIndexMin)); - - if (howManySolids == 0 || howManySolids == 8) - { - iProcessor->readICell(oldDistributions, icellC, val<1>(oldGridIndexMin), val<2>(oldGridIndexMin), val<3>(oldGridIndexMin)); - iProcessor->interpolateCoarseToFine(icellC, icellF); - } - else - { - if (iProcessor->findNeighborICell(bcArrayOldBlock, oldDistributions, icellC, bMaxX1, bMaxX2, bMaxX3, - val<1>(oldGridIndexMin), val<2>(oldGridIndexMin), val<3>(oldGridIndexMin), xoff, yoff, zoff)) - { - //std::string err = "For "+oldBlock->toString()+ - // " x1="+UbSystem::toString(val<1>(oldGridIndexMin))+ - // ", x2=" + UbSystem::toString(val<2>(oldGridIndexMin))+ - // ", x3=" + UbSystem::toString(val<3>(oldGridIndexMin))+ - // " interpolation is not implemented for other direction"+ - // " by using in: "+(std::string)typeid(*this).name()+ - // " or maybe you have a solid on the block boundary"; - //UB_THROW(UbException(UB_EXARGS, err)); - iProcessor->interpolateCoarseToFine(icellC, icellF, xoff, yoff, zoff); - } - else - { - for (int i=0; i<27; i++) - { - icellF.BSW[i]=0.0; - icellF.BSE[i]=0.0; - icellF.BNW[i]=0.0; - icellF.BNE[i]=0.0; - icellF.TSW[i]=0.0; - icellF.TSE[i]=0.0; - icellF.TNW[i]=0.0; - icellF.TNE[i]=0.0; - } - // std::string err = "For "+oldBlock->toString()+ - // " x1="+UbSystem::toString(val<1>(oldGridIndexMin))+ - // ", x2=" + UbSystem::toString(val<2>(oldGridIndexMin))+ - // ", x3=" + UbSystem::toString(val<3>(oldGridIndexMin))+ - // " interpolation is not implemented for other direction"+ - // " by using in: "+(std::string)typeid(*this).name()+ - // " or maybe you have a solid on the block boundary"; - ////UB_THROW(UbException(UB_EXARGS, err)); - // UBLOG(logINFO, err); - } - } - - - - iProcessor->writeICell(newDistributions, icellF, ix1, ix2, ix3); - iProcessor->writeICellInv(newDistributions, icellF, ix1, ix2, ix3); - } - } + int newGridRank = newGrid->getRank(); + int oldBlockRank = oldBlock->getRank(); + int newBlockRank = newBlock->getRank(); + + if (oldBlockRank == newGridRank) { + SPtr<ILBMKernel> oldKernel = oldBlock->getKernel(); + if (!oldKernel) + throw UbException(UB_EXARGS, "The LBM kernel isn't exist in block: " + oldBlock->toString()); + SPtr<EsoTwist3D> oldDistributions = + dynamicPointerCast<EsoTwist3D>(oldKernel->getDataSet()->getFdistributions()); + + CbArray4D<LBMReal, IndexerX4X3X2X1>::CbArray4DPtr localDistributions = + dynamicPointerCast<D3Q27EsoTwist3DSplittedVector>(oldDistributions)->getLocalDistributions(); + CbArray4D<LBMReal, IndexerX4X3X2X1>::CbArray4DPtr nonLocalDistributions = + dynamicPointerCast<D3Q27EsoTwist3DSplittedVector>(oldDistributions)->getNonLocalDistributions(); + CbArray3D<LBMReal, IndexerX3X2X1>::CbArray3DPtr zeroDistributions = + dynamicPointerCast<D3Q27EsoTwist3DSplittedVector>(oldDistributions)->getZeroDistributions(); + + MPI_Send(localDistributions->getStartAdressOfSortedArray(0, 0, 0, 0), + (int)localDistributions->getDataVector().size(), MPI_DOUBLE, newBlockRank, 0, MPI_COMM_WORLD); + MPI_Send(nonLocalDistributions->getStartAdressOfSortedArray(0, 0, 0, 0), + (int)nonLocalDistributions->getDataVector().size(), MPI_DOUBLE, newBlockRank, 0, MPI_COMM_WORLD); + MPI_Send(zeroDistributions->getStartAdressOfSortedArray(0, 0, 0), + (int)zeroDistributions->getDataVector().size(), MPI_DOUBLE, newBlockRank, 0, MPI_COMM_WORLD); + + SPtr<BCArray3D> bcArrayOldBlock = oldBlock->getKernel()->getBCProcessor()->getBCArray(); + std::vector<int> &bcDataVector = bcArrayOldBlock->getBcindexmatrixDataVector(); + MPI_Send(&bcDataVector[0], (int)bcDataVector.size(), MPI_INT, newBlockRank, 0, MPI_COMM_WORLD); + } else if (newBlockRank == newGridRank && newBlock->isActive()) { + D3Q27ICell icellC; + D3Q27ICell icellF; + LBMReal xoff, yoff, zoff; + + LBMReal omegaC = LBMSystem::calcCollisionFactor(nu, oldBlock->getLevel()); + LBMReal omegaF = LBMSystem::calcCollisionFactor(nu, newBlock->getLevel()); + + iProcessor->setOmegas(omegaC, omegaF); + + SPtr<ILBMKernel> newKernel = newBlock->getKernel(); + if (!newKernel) + throw UbException(UB_EXARGS, "The LBM kernel isn't exist in new block: " + newBlock->toString()); + + SPtr<EsoTwist3D> newDistributions = + dynamicPointerCast<EsoTwist3D>(newKernel->getDataSet()->getFdistributions()); + + int minX1 = 0; + int minX2 = 0; + int minX3 = 0; + + int maxX1 = (int)newDistributions->getNX1() - 1; + int maxX2 = (int)newDistributions->getNX2() - 1; + int maxX3 = (int)newDistributions->getNX3() - 1; + + int bMaxX1 = (int)newDistributions->getNX1(); + int bMaxX2 = (int)newDistributions->getNX2(); + int bMaxX3 = (int)newDistributions->getNX3(); + + SPtr<EsoTwist3D> oldDistributions(new D3Q27EsoTwist3DSplittedVector(bMaxX1, bMaxX2, bMaxX3, 0)); + + CbArray4D<LBMReal, IndexerX4X3X2X1>::CbArray4DPtr localDistributions = + dynamicPointerCast<D3Q27EsoTwist3DSplittedVector>(oldDistributions)->getLocalDistributions(); + CbArray4D<LBMReal, IndexerX4X3X2X1>::CbArray4DPtr nonLocalDistributions = + dynamicPointerCast<D3Q27EsoTwist3DSplittedVector>(oldDistributions)->getNonLocalDistributions(); + CbArray3D<LBMReal, IndexerX3X2X1>::CbArray3DPtr zeroDistributions = + dynamicPointerCast<D3Q27EsoTwist3DSplittedVector>(oldDistributions)->getZeroDistributions(); + + MPI_Recv(localDistributions->getStartAdressOfSortedArray(0, 0, 0, 0), + (int)localDistributions->getDataVector().size(), MPI_DOUBLE, oldBlockRank, 0, MPI_COMM_WORLD, + MPI_STATUS_IGNORE); + MPI_Recv(nonLocalDistributions->getStartAdressOfSortedArray(0, 0, 0, 0), + (int)nonLocalDistributions->getDataVector().size(), MPI_DOUBLE, oldBlockRank, 0, MPI_COMM_WORLD, + MPI_STATUS_IGNORE); + MPI_Recv(zeroDistributions->getStartAdressOfSortedArray(0, 0, 0), + (int)zeroDistributions->getDataVector().size(), MPI_DOUBLE, oldBlockRank, 0, MPI_COMM_WORLD, + MPI_STATUS_IGNORE); + + SPtr<BCArray3D> bcArrayOldBlock(new BCArray3D(bMaxX1, bMaxX2, bMaxX3, BCArray3D::FLUID)); + std::vector<int> &bcDataVector = bcArrayOldBlock->getBcindexmatrixDataVector(); + MPI_Recv(&bcDataVector[0], (int)bcDataVector.size(), MPI_INT, oldBlockRank, 0, MPI_COMM_WORLD, + MPI_STATUS_IGNORE); + + for (int ix3 = minX3; ix3 < maxX3; ix3 += 2) + for (int ix2 = minX2; ix2 < maxX2; ix2 += 2) + for (int ix1 = minX1; ix1 < maxX1; ix1 += 2) { + Vector3D coords = newGrid->getNodeCoordinates(newBlock, ix1, ix2, ix3); + UbTupleInt3 oldGridIndexMin = oldGrid->getNodeIndexes(oldBlock, coords[0], coords[1], coords[2]); + + int howManySolids = iProcessor->iCellHowManySolids( + bcArrayOldBlock, val<1>(oldGridIndexMin), val<2>(oldGridIndexMin), val<3>(oldGridIndexMin)); + + if (howManySolids == 0 || howManySolids == 8) { + iProcessor->readICell(oldDistributions, icellC, val<1>(oldGridIndexMin), + val<2>(oldGridIndexMin), val<3>(oldGridIndexMin)); + iProcessor->interpolateCoarseToFine(icellC, icellF); + } else { + if (iProcessor->findNeighborICell(bcArrayOldBlock, oldDistributions, icellC, bMaxX1, bMaxX2, + bMaxX3, val<1>(oldGridIndexMin), val<2>(oldGridIndexMin), + val<3>(oldGridIndexMin), xoff, yoff, zoff)) { + // std::string err = "For "+oldBlock->toString()+ + // " x1="+UbSystem::toString(val<1>(oldGridIndexMin))+ + // ", x2=" + UbSystem::toString(val<2>(oldGridIndexMin))+ + // ", x3=" + UbSystem::toString(val<3>(oldGridIndexMin))+ + // " interpolation is not implemented for other direction"+ + // " by using in: "+(std::string)typeid(*this).name()+ + // " or maybe you have a solid on the block boundary"; + // UB_THROW(UbException(UB_EXARGS, err)); + iProcessor->interpolateCoarseToFine(icellC, icellF, xoff, yoff, zoff); + } else { + for (int i = 0; i < 27; i++) { + icellF.BSW[i] = 0.0; + icellF.BSE[i] = 0.0; + icellF.BNW[i] = 0.0; + icellF.BNE[i] = 0.0; + icellF.TSW[i] = 0.0; + icellF.TSE[i] = 0.0; + icellF.TNW[i] = 0.0; + icellF.TNE[i] = 0.0; + } + // std::string err = "For "+oldBlock->toString()+ + // " x1="+UbSystem::toString(val<1>(oldGridIndexMin))+ + // ", x2=" + UbSystem::toString(val<2>(oldGridIndexMin))+ + // ", x3=" + UbSystem::toString(val<3>(oldGridIndexMin))+ + // " interpolation is not implemented for other direction"+ + // " by using in: "+(std::string)typeid(*this).name()+ + // " or maybe you have a solid on the block boundary"; + ////UB_THROW(UbException(UB_EXARGS, err)); + // UBLOG(logINFO, err); + } + } + + iProcessor->writeICell(newDistributions, icellF, ix1, ix2, ix3); + iProcessor->writeICellInv(newDistributions, icellF, ix1, ix2, ix3); + } + } } ////////////////////////////////////////////////////////////////////////// -void InitDistributionsWithInterpolationGridVisitor::interpolateLocalBlockFineToCoarse(SPtr<Block3D> oldBlock, SPtr<Block3D> newBlock) +void InitDistributionsWithInterpolationGridVisitor::interpolateLocalBlockFineToCoarse(SPtr<Block3D> oldBlock, + SPtr<Block3D> newBlock) { - LBMReal icellC[27]; - D3Q27ICell icellF; - LBMReal xoff, yoff, zoff; - - LBMReal omegaF = LBMSystem::calcCollisionFactor(nu, oldBlock->getLevel()); - LBMReal omegaC =LBMSystem::calcCollisionFactor(nu, newBlock->getLevel()); - - iProcessor->setOmegas(omegaC, omegaF); - - SPtr<ILBMKernel> oldKernel = oldBlock->getKernel(); - if (!oldKernel) - throw UbException(UB_EXARGS, "The LBM kernel isn't exist in old block: "+oldBlock->toString()); - - SPtr<EsoTwist3D> oldDistributions = dynamicPointerCast<EsoTwist3D>(oldKernel->getDataSet()->getFdistributions()); - - SPtr<BCArray3D> bcArrayOldBlock = oldBlock->getKernel()->getBCProcessor()->getBCArray(); - - SPtr<ILBMKernel> newKernel = newBlock->getKernel(); - if (!newKernel) - throw UbException(UB_EXARGS, "The LBM kernel isn't exist in new block: "+newBlock->toString()); - - SPtr<EsoTwist3D> newDistributions = dynamicPointerCast<EsoTwist3D>(newKernel->getDataSet()->getFdistributions()); - - int minX1 = 0; - int minX2 = 0; - int minX3 = 0; - - int maxX1 = (int)newDistributions->getNX1()-1; - int maxX2 = (int)newDistributions->getNX2()-1; - int maxX3 = (int)newDistributions->getNX3()-1; - - int bMaxX1 = (int)newDistributions->getNX1(); - int bMaxX2 = (int)newDistributions->getNX2(); - int bMaxX3 = (int)newDistributions->getNX3(); - - for (int ix3 = minX3; ix3 < maxX3; ix3+=2) - for (int ix2 = minX2; ix2 < maxX2; ix2+=2) - for (int ix1 = minX1; ix1 < maxX1; ix1+=2) - { - Vector3D coords = newGrid->getNodeCoordinates(newBlock, ix1, ix2, ix3); - UbTupleInt3 oldGridIndexMin = oldGrid->getNodeIndexes(oldBlock, coords[0], coords[1], coords[2]); - - int howManySolids= iProcessor->iCellHowManySolids(bcArrayOldBlock, val<1>(oldGridIndexMin), val<2>(oldGridIndexMin), val<3>(oldGridIndexMin)); - - if (howManySolids == 0 || howManySolids == 8) - { - iProcessor->readICell(oldDistributions, icellF, val<1>(oldGridIndexMin), val<2>(oldGridIndexMin), val<3>(oldGridIndexMin)); - iProcessor->interpolateFineToCoarse(icellF, icellC); - } - else - { - if (iProcessor->findNeighborICell(bcArrayOldBlock, oldDistributions, icellF, bMaxX1, bMaxX2, bMaxX3, - val<1>(oldGridIndexMin), val<2>(oldGridIndexMin), val<3>(oldGridIndexMin), xoff, yoff, zoff)) - { - //std::string err = "For "+oldBlock->toString()+ - // " x1="+UbSystem::toString(val<1>(oldGridIndexMin))+ - // ", x2=" + UbSystem::toString(val<2>(oldGridIndexMin))+ - // ", x3=" + UbSystem::toString(val<3>(oldGridIndexMin))+ - // " interpolation is not implemented for other direction"+ - // " by using in: "+(std::string)typeid(*this).name()+ - // " or maybe you have a solid on the block boundary"; - //UB_THROW(UbException(UB_EXARGS, err)); - iProcessor->interpolateFineToCoarse(icellF, icellC, xoff, yoff, zoff); - } - else - { - for (int i=0; i<27; i++) - { - icellF.BSW[i]=0.0; - icellF.BSE[i]=0.0; - icellF.BNW[i]=0.0; - icellF.BNE[i]=0.0; - icellF.TSW[i]=0.0; - icellF.TSE[i]=0.0; - icellF.TNW[i]=0.0; - icellF.TNE[i]=0.0; - } - // std::string err = "For "+oldBlock->toString()+ - // " x1="+UbSystem::toString(val<1>(oldGridIndexMin))+ - // ", x2=" + UbSystem::toString(val<2>(oldGridIndexMin))+ - // ", x3=" + UbSystem::toString(val<3>(oldGridIndexMin))+ - // " interpolation is not implemented for other direction"+ - // " by using in: "+(std::string)typeid(*this).name()+ - // " or maybe you have a solid on the block boundary"; - ////UB_THROW(UbException(UB_EXARGS, err)); - // UBLOG(logINFO, err); - } + LBMReal icellC[27]; + D3Q27ICell icellF; + LBMReal xoff, yoff, zoff; + + LBMReal omegaF = LBMSystem::calcCollisionFactor(nu, oldBlock->getLevel()); + LBMReal omegaC = LBMSystem::calcCollisionFactor(nu, newBlock->getLevel()); + + iProcessor->setOmegas(omegaC, omegaF); + + SPtr<ILBMKernel> oldKernel = oldBlock->getKernel(); + if (!oldKernel) + throw UbException(UB_EXARGS, "The LBM kernel isn't exist in old block: " + oldBlock->toString()); + + SPtr<EsoTwist3D> oldDistributions = dynamicPointerCast<EsoTwist3D>(oldKernel->getDataSet()->getFdistributions()); + + SPtr<BCArray3D> bcArrayOldBlock = oldBlock->getKernel()->getBCProcessor()->getBCArray(); + + SPtr<ILBMKernel> newKernel = newBlock->getKernel(); + if (!newKernel) + throw UbException(UB_EXARGS, "The LBM kernel isn't exist in new block: " + newBlock->toString()); + + SPtr<EsoTwist3D> newDistributions = dynamicPointerCast<EsoTwist3D>(newKernel->getDataSet()->getFdistributions()); + + int minX1 = 0; + int minX2 = 0; + int minX3 = 0; + + int maxX1 = (int)newDistributions->getNX1() - 1; + int maxX2 = (int)newDistributions->getNX2() - 1; + int maxX3 = (int)newDistributions->getNX3() - 1; + + int bMaxX1 = (int)newDistributions->getNX1(); + int bMaxX2 = (int)newDistributions->getNX2(); + int bMaxX3 = (int)newDistributions->getNX3(); + + for (int ix3 = minX3; ix3 < maxX3; ix3 += 2) + for (int ix2 = minX2; ix2 < maxX2; ix2 += 2) + for (int ix1 = minX1; ix1 < maxX1; ix1 += 2) { + Vector3D coords = newGrid->getNodeCoordinates(newBlock, ix1, ix2, ix3); + UbTupleInt3 oldGridIndexMin = oldGrid->getNodeIndexes(oldBlock, coords[0], coords[1], coords[2]); + + int howManySolids = iProcessor->iCellHowManySolids(bcArrayOldBlock, val<1>(oldGridIndexMin), + val<2>(oldGridIndexMin), val<3>(oldGridIndexMin)); + + if (howManySolids == 0 || howManySolids == 8) { + iProcessor->readICell(oldDistributions, icellF, val<1>(oldGridIndexMin), val<2>(oldGridIndexMin), + val<3>(oldGridIndexMin)); + iProcessor->interpolateFineToCoarse(icellF, icellC); + } else { + if (iProcessor->findNeighborICell(bcArrayOldBlock, oldDistributions, icellF, bMaxX1, bMaxX2, bMaxX3, + val<1>(oldGridIndexMin), val<2>(oldGridIndexMin), + val<3>(oldGridIndexMin), xoff, yoff, zoff)) { + // std::string err = "For "+oldBlock->toString()+ + // " x1="+UbSystem::toString(val<1>(oldGridIndexMin))+ + // ", x2=" + UbSystem::toString(val<2>(oldGridIndexMin))+ + // ", x3=" + UbSystem::toString(val<3>(oldGridIndexMin))+ + // " interpolation is not implemented for other direction"+ + // " by using in: "+(std::string)typeid(*this).name()+ + // " or maybe you have a solid on the block boundary"; + // UB_THROW(UbException(UB_EXARGS, err)); + iProcessor->interpolateFineToCoarse(icellF, icellC, xoff, yoff, zoff); + } else { + for (int i = 0; i < 27; i++) { + icellF.BSW[i] = 0.0; + icellF.BSE[i] = 0.0; + icellF.BNW[i] = 0.0; + icellF.BNE[i] = 0.0; + icellF.TSW[i] = 0.0; + icellF.TSE[i] = 0.0; + icellF.TNW[i] = 0.0; + icellF.TNE[i] = 0.0; + } + // std::string err = "For "+oldBlock->toString()+ + // " x1="+UbSystem::toString(val<1>(oldGridIndexMin))+ + // ", x2=" + UbSystem::toString(val<2>(oldGridIndexMin))+ + // ", x3=" + UbSystem::toString(val<3>(oldGridIndexMin))+ + // " interpolation is not implemented for other direction"+ + // " by using in: "+(std::string)typeid(*this).name()+ + // " or maybe you have a solid on the block boundary"; + ////UB_THROW(UbException(UB_EXARGS, err)); + // UBLOG(logINFO, err); + } + } + + iProcessor->writeINode(newDistributions, icellC, ix1, ix2, ix3); + // iProcessor->writeINodeInv(newDistributions, icellC, ix1, ix2, ix3); } - - iProcessor->writeINode(newDistributions, icellC, ix1, ix2, ix3); - //iProcessor->writeINodeInv(newDistributions, icellC, ix1, ix2, ix3); - } } ////////////////////////////////////////////////////////////////////////// -void InitDistributionsWithInterpolationGridVisitor::interpolateRemoteBlockFineToCoarse(SPtr<Block3D> oldBlock, SPtr<Block3D> newBlock) +void InitDistributionsWithInterpolationGridVisitor::interpolateRemoteBlockFineToCoarse(SPtr<Block3D> oldBlock, + SPtr<Block3D> newBlock) { - int newGridRank = newGrid->getRank(); - int oldBlockRank = oldBlock->getRank(); - int newBlockRank = newBlock->getRank(); - - if (oldBlockRank == newGridRank) - { - SPtr<ILBMKernel> oldKernel = oldBlock->getKernel(); - if (!oldKernel) - throw UbException(UB_EXARGS, "The LBM kernel isn't exist in block: "+oldBlock->toString()); - SPtr<EsoTwist3D> oldDistributions = dynamicPointerCast<EsoTwist3D>(oldKernel->getDataSet()->getFdistributions()); - - CbArray4D<LBMReal, IndexerX4X3X2X1>::CbArray4DPtr localDistributions = dynamicPointerCast<D3Q27EsoTwist3DSplittedVector>(oldDistributions)->getLocalDistributions(); - CbArray4D<LBMReal, IndexerX4X3X2X1>::CbArray4DPtr nonLocalDistributions = dynamicPointerCast<D3Q27EsoTwist3DSplittedVector>(oldDistributions)->getNonLocalDistributions(); - CbArray3D<LBMReal, IndexerX3X2X1>::CbArray3DPtr zeroDistributions = dynamicPointerCast<D3Q27EsoTwist3DSplittedVector>(oldDistributions)->getZeroDistributions(); - - MPI_Send(localDistributions->getStartAdressOfSortedArray(0, 0, 0, 0), (int)localDistributions->getDataVector().size(), MPI_DOUBLE, newBlockRank, 0, MPI_COMM_WORLD); - MPI_Send(nonLocalDistributions->getStartAdressOfSortedArray(0, 0, 0, 0), (int)nonLocalDistributions->getDataVector().size(), MPI_DOUBLE, newBlockRank, 0, MPI_COMM_WORLD); - MPI_Send(zeroDistributions->getStartAdressOfSortedArray(0, 0, 0), (int)zeroDistributions->getDataVector().size(), MPI_DOUBLE, newBlockRank, 0, MPI_COMM_WORLD); - - SPtr<BCArray3D> bcArrayOldBlock = oldBlock->getKernel()->getBCProcessor()->getBCArray(); - std::vector< int >& bcDataVector = bcArrayOldBlock->getBcindexmatrixDataVector(); - MPI_Send(&bcDataVector[0], (int)bcDataVector.size(), MPI_INT, newBlockRank, 0, MPI_COMM_WORLD); - } - else if (newBlockRank == newGridRank && newBlock->isActive()) - { - LBMReal icellC[27]; - D3Q27ICell icellF; - LBMReal xoff, yoff, zoff; - - LBMReal omegaF = LBMSystem::calcCollisionFactor(nu, oldBlock->getLevel()); - LBMReal omegaC =LBMSystem::calcCollisionFactor(nu, newBlock->getLevel()); - - iProcessor->setOmegas(omegaC, omegaF); - - SPtr<ILBMKernel> newKernel = newBlock->getKernel(); - if (!newKernel) - throw UbException(UB_EXARGS, "The LBM kernel isn't exist in new block: "+newBlock->toString()); - - SPtr<EsoTwist3D> newDistributions = dynamicPointerCast<EsoTwist3D>(newKernel->getDataSet()->getFdistributions()); - - int minX1 = 0; - int minX2 = 0; - int minX3 = 0; - - int maxX1 = (int)newDistributions->getNX1()-1; - int maxX2 = (int)newDistributions->getNX2()-1; - int maxX3 = (int)newDistributions->getNX3()-1; - - int bMaxX1 = (int)newDistributions->getNX1(); - int bMaxX2 = (int)newDistributions->getNX2(); - int bMaxX3 = (int)newDistributions->getNX3(); - - SPtr<EsoTwist3D> oldDistributions(new D3Q27EsoTwist3DSplittedVector(bMaxX1, bMaxX2, bMaxX3, 0)); - - CbArray4D<LBMReal, IndexerX4X3X2X1>::CbArray4DPtr localDistributions = dynamicPointerCast<D3Q27EsoTwist3DSplittedVector>(oldDistributions)->getLocalDistributions(); - CbArray4D<LBMReal, IndexerX4X3X2X1>::CbArray4DPtr nonLocalDistributions = dynamicPointerCast<D3Q27EsoTwist3DSplittedVector>(oldDistributions)->getNonLocalDistributions(); - CbArray3D<LBMReal, IndexerX3X2X1>::CbArray3DPtr zeroDistributions = dynamicPointerCast<D3Q27EsoTwist3DSplittedVector>(oldDistributions)->getZeroDistributions(); - - MPI_Recv(localDistributions->getStartAdressOfSortedArray(0, 0, 0, 0), (int)localDistributions->getDataVector().size(), MPI_DOUBLE, oldBlockRank, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); - MPI_Recv(nonLocalDistributions->getStartAdressOfSortedArray(0, 0, 0, 0), (int)nonLocalDistributions->getDataVector().size(), MPI_DOUBLE, oldBlockRank, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); - MPI_Recv(zeroDistributions->getStartAdressOfSortedArray(0, 0, 0), (int)zeroDistributions->getDataVector().size(), MPI_DOUBLE, oldBlockRank, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); - - SPtr<BCArray3D> bcArrayOldBlock(new BCArray3D(bMaxX1, bMaxX2, bMaxX3, BCArray3D::FLUID)); - std::vector< int >& bcDataVector = bcArrayOldBlock->getBcindexmatrixDataVector(); - MPI_Recv(&bcDataVector[0], (int)bcDataVector.size(), MPI_INT, oldBlockRank, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); - - for (int ix3 = minX3; ix3 < maxX3; ix3+=2) - for (int ix2 = minX2; ix2 < maxX2; ix2+=2) - for (int ix1 = minX1; ix1 < maxX1; ix1+=2) - { - Vector3D coords = newGrid->getNodeCoordinates(newBlock, ix1, ix2, ix3); - UbTupleInt3 oldGridIndexMin = oldGrid->getNodeIndexes(oldBlock, coords[0], coords[1], coords[2]); - - int howManySolids= iProcessor->iCellHowManySolids(bcArrayOldBlock, val<1>(oldGridIndexMin), val<2>(oldGridIndexMin), val<3>(oldGridIndexMin)); - - if (howManySolids == 0 || howManySolids == 8) - { - iProcessor->readICell(oldDistributions, icellF, val<1>(oldGridIndexMin), val<2>(oldGridIndexMin), val<3>(oldGridIndexMin)); - iProcessor->interpolateFineToCoarse(icellF, icellC); - } - else - { - if (iProcessor->findNeighborICell(bcArrayOldBlock, oldDistributions, icellF, bMaxX1, bMaxX2, bMaxX3, - val<1>(oldGridIndexMin), val<2>(oldGridIndexMin), val<3>(oldGridIndexMin), xoff, yoff, zoff)) - { - //std::string err = "For "+oldBlock->toString()+ - // " x1="+UbSystem::toString(val<1>(oldGridIndexMin))+ - // ", x2=" + UbSystem::toString(val<2>(oldGridIndexMin))+ - // ", x3=" + UbSystem::toString(val<3>(oldGridIndexMin))+ - // " interpolation is not implemented for other direction"+ - // " by using in: "+(std::string)typeid(*this).name()+ - // " or maybe you have a solid on the block boundary"; - //UB_THROW(UbException(UB_EXARGS, err)); - iProcessor->interpolateFineToCoarse(icellF, icellC, xoff, yoff, zoff); - } - else - { - for (int i=0; i<27; i++) - { - icellF.BSW[i]=0.0; - icellF.BSE[i]=0.0; - icellF.BNW[i]=0.0; - icellF.BNE[i]=0.0; - icellF.TSW[i]=0.0; - icellF.TSE[i]=0.0; - icellF.TNW[i]=0.0; - icellF.TNE[i]=0.0; - } - // std::string err = "For "+oldBlock->toString()+ - // " x1="+UbSystem::toString(val<1>(oldGridIndexMin))+ - // ", x2=" + UbSystem::toString(val<2>(oldGridIndexMin))+ - // ", x3=" + UbSystem::toString(val<3>(oldGridIndexMin))+ - // " interpolation is not implemented for other direction"+ - // " by using in: "+(std::string)typeid(*this).name()+ - // " or maybe you have a solid on the block boundary"; - ////UB_THROW(UbException(UB_EXARGS, err)); - // UBLOG(logINFO, err); - } - } - - iProcessor->writeINode(newDistributions, icellC, ix1, ix2, ix3); - //iProcessor->writeINodeInv(newDistributions, icellC, ix1, ix2, ix3); - } - } + int newGridRank = newGrid->getRank(); + int oldBlockRank = oldBlock->getRank(); + int newBlockRank = newBlock->getRank(); + + if (oldBlockRank == newGridRank) { + SPtr<ILBMKernel> oldKernel = oldBlock->getKernel(); + if (!oldKernel) + throw UbException(UB_EXARGS, "The LBM kernel isn't exist in block: " + oldBlock->toString()); + SPtr<EsoTwist3D> oldDistributions = + dynamicPointerCast<EsoTwist3D>(oldKernel->getDataSet()->getFdistributions()); + + CbArray4D<LBMReal, IndexerX4X3X2X1>::CbArray4DPtr localDistributions = + dynamicPointerCast<D3Q27EsoTwist3DSplittedVector>(oldDistributions)->getLocalDistributions(); + CbArray4D<LBMReal, IndexerX4X3X2X1>::CbArray4DPtr nonLocalDistributions = + dynamicPointerCast<D3Q27EsoTwist3DSplittedVector>(oldDistributions)->getNonLocalDistributions(); + CbArray3D<LBMReal, IndexerX3X2X1>::CbArray3DPtr zeroDistributions = + dynamicPointerCast<D3Q27EsoTwist3DSplittedVector>(oldDistributions)->getZeroDistributions(); + + MPI_Send(localDistributions->getStartAdressOfSortedArray(0, 0, 0, 0), + (int)localDistributions->getDataVector().size(), MPI_DOUBLE, newBlockRank, 0, MPI_COMM_WORLD); + MPI_Send(nonLocalDistributions->getStartAdressOfSortedArray(0, 0, 0, 0), + (int)nonLocalDistributions->getDataVector().size(), MPI_DOUBLE, newBlockRank, 0, MPI_COMM_WORLD); + MPI_Send(zeroDistributions->getStartAdressOfSortedArray(0, 0, 0), + (int)zeroDistributions->getDataVector().size(), MPI_DOUBLE, newBlockRank, 0, MPI_COMM_WORLD); + + SPtr<BCArray3D> bcArrayOldBlock = oldBlock->getKernel()->getBCProcessor()->getBCArray(); + std::vector<int> &bcDataVector = bcArrayOldBlock->getBcindexmatrixDataVector(); + MPI_Send(&bcDataVector[0], (int)bcDataVector.size(), MPI_INT, newBlockRank, 0, MPI_COMM_WORLD); + } else if (newBlockRank == newGridRank && newBlock->isActive()) { + LBMReal icellC[27]; + D3Q27ICell icellF; + LBMReal xoff, yoff, zoff; + + LBMReal omegaF = LBMSystem::calcCollisionFactor(nu, oldBlock->getLevel()); + LBMReal omegaC = LBMSystem::calcCollisionFactor(nu, newBlock->getLevel()); + + iProcessor->setOmegas(omegaC, omegaF); + + SPtr<ILBMKernel> newKernel = newBlock->getKernel(); + if (!newKernel) + throw UbException(UB_EXARGS, "The LBM kernel isn't exist in new block: " + newBlock->toString()); + + SPtr<EsoTwist3D> newDistributions = + dynamicPointerCast<EsoTwist3D>(newKernel->getDataSet()->getFdistributions()); + + int minX1 = 0; + int minX2 = 0; + int minX3 = 0; + + int maxX1 = (int)newDistributions->getNX1() - 1; + int maxX2 = (int)newDistributions->getNX2() - 1; + int maxX3 = (int)newDistributions->getNX3() - 1; + + int bMaxX1 = (int)newDistributions->getNX1(); + int bMaxX2 = (int)newDistributions->getNX2(); + int bMaxX3 = (int)newDistributions->getNX3(); + + SPtr<EsoTwist3D> oldDistributions(new D3Q27EsoTwist3DSplittedVector(bMaxX1, bMaxX2, bMaxX3, 0)); + + CbArray4D<LBMReal, IndexerX4X3X2X1>::CbArray4DPtr localDistributions = + dynamicPointerCast<D3Q27EsoTwist3DSplittedVector>(oldDistributions)->getLocalDistributions(); + CbArray4D<LBMReal, IndexerX4X3X2X1>::CbArray4DPtr nonLocalDistributions = + dynamicPointerCast<D3Q27EsoTwist3DSplittedVector>(oldDistributions)->getNonLocalDistributions(); + CbArray3D<LBMReal, IndexerX3X2X1>::CbArray3DPtr zeroDistributions = + dynamicPointerCast<D3Q27EsoTwist3DSplittedVector>(oldDistributions)->getZeroDistributions(); + + MPI_Recv(localDistributions->getStartAdressOfSortedArray(0, 0, 0, 0), + (int)localDistributions->getDataVector().size(), MPI_DOUBLE, oldBlockRank, 0, MPI_COMM_WORLD, + MPI_STATUS_IGNORE); + MPI_Recv(nonLocalDistributions->getStartAdressOfSortedArray(0, 0, 0, 0), + (int)nonLocalDistributions->getDataVector().size(), MPI_DOUBLE, oldBlockRank, 0, MPI_COMM_WORLD, + MPI_STATUS_IGNORE); + MPI_Recv(zeroDistributions->getStartAdressOfSortedArray(0, 0, 0), + (int)zeroDistributions->getDataVector().size(), MPI_DOUBLE, oldBlockRank, 0, MPI_COMM_WORLD, + MPI_STATUS_IGNORE); + + SPtr<BCArray3D> bcArrayOldBlock(new BCArray3D(bMaxX1, bMaxX2, bMaxX3, BCArray3D::FLUID)); + std::vector<int> &bcDataVector = bcArrayOldBlock->getBcindexmatrixDataVector(); + MPI_Recv(&bcDataVector[0], (int)bcDataVector.size(), MPI_INT, oldBlockRank, 0, MPI_COMM_WORLD, + MPI_STATUS_IGNORE); + + for (int ix3 = minX3; ix3 < maxX3; ix3 += 2) + for (int ix2 = minX2; ix2 < maxX2; ix2 += 2) + for (int ix1 = minX1; ix1 < maxX1; ix1 += 2) { + Vector3D coords = newGrid->getNodeCoordinates(newBlock, ix1, ix2, ix3); + UbTupleInt3 oldGridIndexMin = oldGrid->getNodeIndexes(oldBlock, coords[0], coords[1], coords[2]); + + int howManySolids = iProcessor->iCellHowManySolids( + bcArrayOldBlock, val<1>(oldGridIndexMin), val<2>(oldGridIndexMin), val<3>(oldGridIndexMin)); + + if (howManySolids == 0 || howManySolids == 8) { + iProcessor->readICell(oldDistributions, icellF, val<1>(oldGridIndexMin), + val<2>(oldGridIndexMin), val<3>(oldGridIndexMin)); + iProcessor->interpolateFineToCoarse(icellF, icellC); + } else { + if (iProcessor->findNeighborICell(bcArrayOldBlock, oldDistributions, icellF, bMaxX1, bMaxX2, + bMaxX3, val<1>(oldGridIndexMin), val<2>(oldGridIndexMin), + val<3>(oldGridIndexMin), xoff, yoff, zoff)) { + // std::string err = "For "+oldBlock->toString()+ + // " x1="+UbSystem::toString(val<1>(oldGridIndexMin))+ + // ", x2=" + UbSystem::toString(val<2>(oldGridIndexMin))+ + // ", x3=" + UbSystem::toString(val<3>(oldGridIndexMin))+ + // " interpolation is not implemented for other direction"+ + // " by using in: "+(std::string)typeid(*this).name()+ + // " or maybe you have a solid on the block boundary"; + // UB_THROW(UbException(UB_EXARGS, err)); + iProcessor->interpolateFineToCoarse(icellF, icellC, xoff, yoff, zoff); + } else { + for (int i = 0; i < 27; i++) { + icellF.BSW[i] = 0.0; + icellF.BSE[i] = 0.0; + icellF.BNW[i] = 0.0; + icellF.BNE[i] = 0.0; + icellF.TSW[i] = 0.0; + icellF.TSE[i] = 0.0; + icellF.TNW[i] = 0.0; + icellF.TNE[i] = 0.0; + } + // std::string err = "For "+oldBlock->toString()+ + // " x1="+UbSystem::toString(val<1>(oldGridIndexMin))+ + // ", x2=" + UbSystem::toString(val<2>(oldGridIndexMin))+ + // ", x3=" + UbSystem::toString(val<3>(oldGridIndexMin))+ + // " interpolation is not implemented for other direction"+ + // " by using in: "+(std::string)typeid(*this).name()+ + // " or maybe you have a solid on the block boundary"; + ////UB_THROW(UbException(UB_EXARGS, err)); + // UBLOG(logINFO, err); + } + } + + iProcessor->writeINode(newDistributions, icellC, ix1, ix2, ix3); + // iProcessor->writeINodeInv(newDistributions, icellC, ix1, ix2, ix3); + } + } } ////////////////////////////////////////////////////////////////////////// diff --git a/src/cpu/VirtualFluidsCore/Visitors/InitDistributionsWithInterpolationGridVisitor.h b/src/cpu/VirtualFluidsCore/Visitors/InitDistributionsWithInterpolationGridVisitor.h index bdc373e14d02f947c9a9a60249b6a617e6d0069c..207656e1f3bfb287cf8cc1bd1270daf510ce9aa3 100644 --- a/src/cpu/VirtualFluidsCore/Visitors/InitDistributionsWithInterpolationGridVisitor.h +++ b/src/cpu/VirtualFluidsCore/Visitors/InitDistributionsWithInterpolationGridVisitor.h @@ -13,22 +13,24 @@ class InterpolationProcessor; class InitDistributionsWithInterpolationGridVisitor : public Grid3DVisitor { public: - InitDistributionsWithInterpolationGridVisitor(SPtr<Grid3D> oldGrid, SPtr<InterpolationProcessor> iProcessor, LBMReal nu); - ~InitDistributionsWithInterpolationGridVisitor() override; - void visit(SPtr<Grid3D> grid) override; + InitDistributionsWithInterpolationGridVisitor(SPtr<Grid3D> oldGrid, SPtr<InterpolationProcessor> iProcessor, + LBMReal nu); + ~InitDistributionsWithInterpolationGridVisitor() override; + void visit(SPtr<Grid3D> grid) override; + private: - void copyLocalBlock(SPtr<Block3D> oldBlock, SPtr<Block3D> newBlock); - void copyRemoteBlock(SPtr<Block3D> oldBlock, SPtr<Block3D> newBlock); - void interpolateLocalBlockCoarseToFine(SPtr<Block3D> oldBlock, SPtr<Block3D> newBlock); - void interpolateRemoteBlockCoarseToFine(SPtr<Block3D> oldBlock, SPtr<Block3D> newBlock); - void interpolateLocalBlockFineToCoarse(SPtr<Block3D> oldBlock, SPtr<Block3D> newBlock); - void interpolateRemoteBlockFineToCoarse(SPtr<Block3D> oldBlock, SPtr<Block3D> newBlock); - - SPtr<Grid3D> newGrid; - SPtr<Grid3D> oldGrid; - LBMReal nu; - - SPtr<InterpolationProcessor> iProcessor; + void copyLocalBlock(SPtr<Block3D> oldBlock, SPtr<Block3D> newBlock); + void copyRemoteBlock(SPtr<Block3D> oldBlock, SPtr<Block3D> newBlock); + void interpolateLocalBlockCoarseToFine(SPtr<Block3D> oldBlock, SPtr<Block3D> newBlock); + void interpolateRemoteBlockCoarseToFine(SPtr<Block3D> oldBlock, SPtr<Block3D> newBlock); + void interpolateLocalBlockFineToCoarse(SPtr<Block3D> oldBlock, SPtr<Block3D> newBlock); + void interpolateRemoteBlockFineToCoarse(SPtr<Block3D> oldBlock, SPtr<Block3D> newBlock); + + SPtr<Grid3D> newGrid; + SPtr<Grid3D> oldGrid; + LBMReal nu; + + SPtr<InterpolationProcessor> iProcessor; }; #endif // InitDistributionsWithVelocityProfileBlockVisitor_h__ diff --git a/src/cpu/VirtualFluidsCore/Visitors/MetisPartitioningGridVisitor.cpp b/src/cpu/VirtualFluidsCore/Visitors/MetisPartitioningGridVisitor.cpp index 23f3260e9e4efbcbf516bbd58cbb03fa12d5ab5b..7b516fc75c608a1627edc9b75264d32bc660c59a 100644 --- a/src/cpu/VirtualFluidsCore/Visitors/MetisPartitioningGridVisitor.cpp +++ b/src/cpu/VirtualFluidsCore/Visitors/MetisPartitioningGridVisitor.cpp @@ -1,28 +1,24 @@ #if defined VF_METIS && defined VF_MPI #include "MetisPartitioningGridVisitor.h" -#include <cmath> #include "Block3D.h" -#include "Grid3D.h" #include "Communicator.h" #include "D3Q27System.h" +#include "Grid3D.h" +#include <cmath> using namespace std; -MetisPartitioningGridVisitor::MetisPartitioningGridVisitor(SPtr<Communicator> comm, GraphType graphType, int numOfDirs, MetisPartitioner::PartType partType, bool threads, int numberOfThreads) - : Grid3DVisitor(), - numberOfThreads(numberOfThreads), - numOfDirs(numOfDirs), - comm(comm), - threads(threads), - graphType(graphType), - partType(partType) -{ - numberOfProcesses = comm->getNumberOfProcesses(); +MetisPartitioningGridVisitor::MetisPartitioningGridVisitor(SPtr<Communicator> comm, GraphType graphType, int numOfDirs, + MetisPartitioner::PartType partType, bool threads, + int numberOfThreads) + : Grid3DVisitor(), numberOfThreads(numberOfThreads), numOfDirs(numOfDirs), comm(comm), threads(threads), + graphType(graphType), partType(partType) +{ + numberOfProcesses = comm->getNumberOfProcesses(); } ////////////////////////////////////////////////////////////////////////// -MetisPartitioningGridVisitor::~MetisPartitioningGridVisitor() -= default; +MetisPartitioningGridVisitor::~MetisPartitioningGridVisitor() = default; ////////////////////////////////////////////////////////////////////////// void MetisPartitioningGridVisitor::visit(SPtr<Grid3D> grid) { @@ -30,11 +26,10 @@ void MetisPartitioningGridVisitor::visit(SPtr<Grid3D> grid) this->clear(); - bundleRoot = comm->getBundleRoot(); - bundleID = comm->getBundleID(); + bundleRoot = comm->getBundleRoot(); + bundleID = comm->getBundleID(); numberOfBundles = comm->getNumberOfBundles(); - if (numberOfBundles > 1) - { + if (numberOfBundles > 1) { if (bundleRoot == bundleID && processRoot == processID) collectData(grid, numberOfBundles, BUNDLE); comm->broadcast(blockID); @@ -44,32 +39,27 @@ void MetisPartitioningGridVisitor::visit(SPtr<Grid3D> grid) } processRoot = comm->getProcessRoot(); - processID = comm->getProcessID(); + processID = comm->getProcessID(); /*int numberOfProcesses = comm->getNumberOfProcesses();*/ - if (numberOfProcesses > 1) - { - int temp = bundleID; - for (int i = 0; i < numberOfBundles; i++) - { - if (bundleRoot == bundleID && processRoot == processID) - { - bundleID = i; - //numberOfProcesses = comm->getNumberOfProcessesInBundle(i); - collectData(grid, numberOfProcesses, PROCESS); - bundleID = temp; - } - comm->broadcast(blockID); - //UBLOG(logINFO, "blockID="<<blockID.size()); - comm->broadcast(parts); - //UBLOG(logINFO, "parts="<<parts.size()); - distributePartitionData(grid, PROCESS); - } + if (numberOfProcesses > 1) { + int temp = bundleID; + for (int i = 0; i < numberOfBundles; i++) { + if (bundleRoot == bundleID && processRoot == processID) { + bundleID = i; + // numberOfProcesses = comm->getNumberOfProcessesInBundle(i); + collectData(grid, numberOfProcesses, PROCESS); + bundleID = temp; + } + comm->broadcast(blockID); + // UBLOG(logINFO, "blockID="<<blockID.size()); + comm->broadcast(parts); + // UBLOG(logINFO, "parts="<<parts.size()); + distributePartitionData(grid, PROCESS); + } } - if (threads) - { - if (numberOfThreads > 1) - { + if (threads) { + if (numberOfThreads > 1) { collectData(grid, numberOfThreads, THREAD); distributePartitionData(grid, THREAD); } @@ -81,14 +71,13 @@ void MetisPartitioningGridVisitor::collectData(SPtr<Grid3D> grid, int nofSegment { clear(); - switch (graphType) - { - case LevelIntersected: - buildMetisGraphLevelIntersected(grid, nofSegments, level); - break; - case LevelBased: - buildMetisGraphLevelBased(grid, nofSegments, level); - break; + switch (graphType) { + case LevelIntersected: + buildMetisGraphLevelIntersected(grid, nofSegments, level); + break; + case LevelBased: + buildMetisGraphLevelBased(grid, nofSegments, level); + break; } } ////////////////////////////////////////////////////////////////////////// @@ -96,30 +85,24 @@ void MetisPartitioningGridVisitor::distributePartitionData(SPtr<Grid3D> grid, Pa { SPtr<Block3D> block; - for(size_t p=0; p<parts.size(); p++) - { + for (size_t p = 0; p < parts.size(); p++) { block = grid->getBlock(blockID[p]); - if (block) - { - switch (level) - { - case BUNDLE: - block->setBundle(parts[p]); - break; - case PROCESS: - if (numberOfBundles == 1) - { - block->setRank(parts[p]); - } - else - { - block->setLocalRank(parts[p]); - block->setRank(comm->getProcessID(block->getBundle(),parts[p])); - } - break; - case THREAD: - block->setPart(parts[p]); - break; + if (block) { + switch (level) { + case BUNDLE: + block->setBundle(parts[p]); + break; + case PROCESS: + if (numberOfBundles == 1) { + block->setRank(parts[p]); + } else { + block->setLocalRank(parts[p]); + block->setRank(comm->getProcessID(block->getBundle(), parts[p])); + } + break; + case THREAD: + block->setPart(parts[p]); + break; } } } @@ -127,16 +110,14 @@ void MetisPartitioningGridVisitor::distributePartitionData(SPtr<Grid3D> grid, Pa ////////////////////////////////////////////////////////////////////////// void MetisPartitioningGridVisitor::buildMetisGraphLevelIntersected(SPtr<Grid3D> grid, int nofSegments, PartLevel level) { - int edges = 0; - const int edgeWeight= 1; + int edges = 0; + const int edgeWeight = 1; const int edgeWeightChildFactor = 8; - int n = 0; + int n = 0; - for(Grid3D::BlockIDMap::value_type b : grid->getBlockIDs()) - { + for (Grid3D::BlockIDMap::value_type b : grid->getBlockIDs()) { SPtr<Block3D> block = b.second; - if (this->getPartitionCondition(block, level)) - { + if (this->getPartitionCondition(block, level)) { block->setLocalID(n); blockID.push_back(block->getGlobalID()); n++; @@ -145,22 +126,17 @@ void MetisPartitioningGridVisitor::buildMetisGraphLevelIntersected(SPtr<Grid3D> MetisPartitioner metis; - for(Grid3D::BlockIDMap::value_type b : grid->getBlockIDs()) - { + for (Grid3D::BlockIDMap::value_type b : grid->getBlockIDs()) { const SPtr<Block3D> block = b.second; - if (this->getPartitionCondition(block, level)) - { - metis.xadj.push_back(edges); - //the weights of the vertices are 2^level of grid (1, 2, 4, 8 .....) 1<<level - metis.vwgt.push_back((idx_t)(1<<block->getLevel())); + if (this->getPartitionCondition(block, level)) { + metis.xadj.push_back(edges); + // the weights of the vertices are 2^level of grid (1, 2, 4, 8 .....) 1<<level + metis.vwgt.push_back((idx_t)(1 << block->getLevel())); - for( int dir = 0; dir <= numOfDirs; dir++) - { + for (int dir = 0; dir <= numOfDirs; dir++) { SPtr<Block3D> neighBlock = grid->getNeighborBlock(dir, block); - if(neighBlock) - { - if (this->getPartitionCondition(neighBlock, level)) - { + if (neighBlock) { + if (this->getPartitionCondition(neighBlock, level)) { edges++; metis.adjwgt.push_back(edgeWeight); metis.adjncy.push_back(neighBlock->getLocalID()); @@ -169,14 +145,11 @@ void MetisPartitioningGridVisitor::buildMetisGraphLevelIntersected(SPtr<Grid3D> } vector<SPtr<Block3D>> subBlocks; grid->getSubBlocks(block, 1, subBlocks); - for(SPtr<Block3D> subBlock : subBlocks) - { - if (subBlock) - { - if (this->getPartitionCondition(subBlock, level)) - { + for (SPtr<Block3D> subBlock : subBlocks) { + if (subBlock) { + if (this->getPartitionCondition(subBlock, level)) { edges++; - metis.adjwgt.push_back(edgeWeight*edgeWeightChildFactor); + metis.adjwgt.push_back(edgeWeight * edgeWeightChildFactor); metis.adjncy.push_back(subBlock->getLocalID()); } } @@ -185,10 +158,11 @@ void MetisPartitioningGridVisitor::buildMetisGraphLevelIntersected(SPtr<Grid3D> } metis.xadj.push_back(static_cast<idx_t>(metis.adjncy.size())); - if ((metis.adjncy.size()%2)!=0) - throw UbException(UB_EXARGS,"number of edges is odd - probable adjncy-vector doesn't contain all pairs (A->B) and (B->A)!!!" ); + if ((metis.adjncy.size() % 2) != 0) + throw UbException( + UB_EXARGS, + "number of edges is odd - probable adjncy-vector doesn't contain all pairs (A->B) and (B->A)!!!"); - metis.partition(nofSegments, partType); parts = metis.part; } @@ -198,17 +172,14 @@ void MetisPartitioningGridVisitor::buildMetisGraphLevelBased(SPtr<Grid3D> grid, int minInitLevel = grid->getCoarsestInitializedLevel(); int maxInitLevel = grid->getFinestInitializedLevel(); - for(int l = minInitLevel; l<=maxInitLevel;l++) - { + for (int l = minInitLevel; l <= maxInitLevel; l++) { int n = 0; vector<SPtr<Block3D>> blockVector; grid->getBlocks(l, blockVector); vector<SPtr<Block3D>> tBlockID; - for(SPtr<Block3D> block : blockVector) - { - if (this->getPartitionCondition(block, level)) - { + for (SPtr<Block3D> block : blockVector) { + if (this->getPartitionCondition(block, level)) { block->setLocalID(n); blockID.push_back(block->getGlobalID()); tBlockID.push_back(block); @@ -216,28 +187,23 @@ void MetisPartitioningGridVisitor::buildMetisGraphLevelBased(SPtr<Grid3D> grid, } } - if (tBlockID.size() == 0) - { - UB_THROW(UbException(UB_EXARGS,"Blocks for decomposition don't exist!")); + if (tBlockID.size() == 0) { + UB_THROW(UbException(UB_EXARGS, "Blocks for decomposition don't exist!")); } MetisPartitioner metis; const int vertexWeight = 1; - int edges = 0; + int edges = 0; - for(SPtr<Block3D> block : tBlockID) - { + for (SPtr<Block3D> block : tBlockID) { metis.xadj.push_back(edges); metis.vwgt.push_back(vertexWeight); - for( int dir = 0; dir <= numOfDirs; dir++) - { + for (int dir = 0; dir <= numOfDirs; dir++) { SPtr<Block3D> neighBlock = grid->getNeighborBlock(dir, block); - if(neighBlock) - { - if (this->getPartitionCondition(neighBlock, level)) - { + if (neighBlock) { + if (this->getPartitionCondition(neighBlock, level)) { edges++; metis.adjwgt.push_back(getEdgeWeight(dir)); metis.adjncy.push_back(neighBlock->getLocalID()); @@ -246,19 +212,19 @@ void MetisPartitioningGridVisitor::buildMetisGraphLevelBased(SPtr<Grid3D> grid, } } metis.xadj.push_back(static_cast<idx_t>(metis.adjncy.size())); - if ((metis.adjncy.size()%2)!=0) - throw UbException(UB_EXARGS,"number of edges is odd - probable adjncy-vector doesn't contain all pairs (A->B) and (B->A)!!!" ); + if ((metis.adjncy.size() % 2) != 0) + throw UbException( + UB_EXARGS, + "number of edges is odd - probable adjncy-vector doesn't contain all pairs (A->B) and (B->A)!!!"); - int nofBlocks = grid->getNumberOfBlocks(l); + int nofBlocks = grid->getNumberOfBlocks(l); int tnofSegments = nofSegments; - if (nofBlocks < nofSegments) - { - tnofSegments = nofBlocks; + if (nofBlocks < nofSegments) { + tnofSegments = nofBlocks; } metis.partition(tnofSegments, partType); - for(idx_t p : metis.part) - { + for (idx_t p : metis.part) { parts.push_back(p); } } @@ -266,23 +232,16 @@ void MetisPartitioningGridVisitor::buildMetisGraphLevelBased(SPtr<Grid3D> grid, ////////////////////////////////////////////////////////////////////////// bool MetisPartitioningGridVisitor::getPartitionCondition(SPtr<Block3D> block, PartLevel level) { - if (level == BUNDLE) - { - return true; - } - else if(level == PROCESS) - { - if (block->getBundle() == bundleID) - { - return true; - } - } - else if(level == THREAD) - { - if (block->getBundle() == bundleID && block->getRank() == processID) - { - return true; - } + if (level == BUNDLE) { + return true; + } else if (level == PROCESS) { + if (block->getBundle() == bundleID) { + return true; + } + } else if (level == THREAD) { + if (block->getBundle() == bundleID && block->getRank() == processID) { + return true; + } } return false; @@ -296,28 +255,19 @@ void MetisPartitioningGridVisitor::clear() ////////////////////////////////////////////////////////////////////////// int MetisPartitioningGridVisitor::getEdgeWeight(int dir) { - using namespace D3Q27System; - if (dir <= B) - { - return 100; - } - else if (dir >= NE && dir <= TS) - { - return 10; - } - else if (dir >= TNE) - { - return 1; - } + using namespace D3Q27System; + if (dir <= B) { + return 100; + } else if (dir >= NE && dir <= TS) { + return 10; + } else if (dir >= TNE) { + return 1; + } -// FIXME: non-void function does not return a value in all control paths + // FIXME: non-void function does not return a value in all control paths return 0; } ////////////////////////////////////////////////////////////////////////// -void MetisPartitioningGridVisitor::setNumberOfProcesses(int np) -{ - numberOfProcesses = np; -} - +void MetisPartitioningGridVisitor::setNumberOfProcesses(int np) { numberOfProcesses = np; } -#endif //VF_METIS +#endif // VF_METIS diff --git a/src/cpu/VirtualFluidsCore/Visitors/MetisPartitioningGridVisitor.h b/src/cpu/VirtualFluidsCore/Visitors/MetisPartitioningGridVisitor.h index 2d241359c9ad7058ec995a863c854fb52cb5c6be..d1bc5ba308ff798c21cc27cae02367f31b35fbac 100644 --- a/src/cpu/VirtualFluidsCore/Visitors/MetisPartitioningGridVisitor.h +++ b/src/cpu/VirtualFluidsCore/Visitors/MetisPartitioningGridVisitor.h @@ -1,15 +1,14 @@ -#ifndef MetisPartitioningGridVisitor_h +#ifndef MetisPartitioningGridVisitor_h #define MetisPartitioningGridVisitor_h #if defined VF_METIS && defined VF_MPI -#include <vector> #include <PointerDefinitions.h> +#include <vector> #include "Grid3DVisitor.h" #include "MetisPartitioner.h" - class Communicator; //////////////////////////////////////////////////////////////////////// @@ -21,48 +20,50 @@ class Grid3D; class Block3D; class MetisPartitioningGridVisitor : public Grid3DVisitor -{ +{ public: - //! This describe different types of decomposition - enum GraphType{LevelIntersected, LevelBased}; + //! This describe different types of decomposition + enum GraphType { LevelIntersected, LevelBased }; public: - //! Constructor - //! \param comm - communicator - //! \param graphType - type of decomposition - //! \param numOfDirs - maximum number of neighbors for each process - //! \param threads - on/off decomposition for threads - //! \param numberOfThreads - number of threads - MetisPartitioningGridVisitor(SPtr<Communicator> comm, GraphType graphType, int numOfDirs, MetisPartitioner::PartType partType = MetisPartitioner::KWAY, bool threads = false, int numberOfThreads = 0); - ~MetisPartitioningGridVisitor() override; - void visit(SPtr<Grid3D> grid) override; - void setNumberOfProcesses(int np); + //! Constructor + //! \param comm - communicator + //! \param graphType - type of decomposition + //! \param numOfDirs - maximum number of neighbors for each process + //! \param threads - on/off decomposition for threads + //! \param numberOfThreads - number of threads + MetisPartitioningGridVisitor(SPtr<Communicator> comm, GraphType graphType, int numOfDirs, + MetisPartitioner::PartType partType = MetisPartitioner::KWAY, bool threads = false, + int numberOfThreads = 0); + ~MetisPartitioningGridVisitor() override; + void visit(SPtr<Grid3D> grid) override; + void setNumberOfProcesses(int np); protected: - enum PartLevel {BUNDLE, PROCESS, THREAD}; - void collectData(SPtr<Grid3D> grid, int nofSegments, PartLevel level); - void buildMetisGraphLevelIntersected(SPtr<Grid3D> grid, int nofSegments, PartLevel level); - void buildMetisGraphLevelBased(SPtr<Grid3D> grid, int nofSegments, PartLevel level); - bool getPartitionCondition(SPtr<Block3D> block, PartLevel level); - void distributePartitionData(SPtr<Grid3D> grid, PartLevel level); - void clear(); - int getEdgeWeight(int dir); - int nofSegments; - int numOfDirs; - std::vector<int> blockID; - std::vector<idx_t> parts; - SPtr<Communicator> comm; - int bundleRoot; - int processRoot; - int bundleID; - int processID; - int numberOfBundles; - int numberOfThreads; - bool threads; - GraphType graphType; - MetisPartitioner::PartType partType; - int numberOfProcesses; + enum PartLevel { BUNDLE, PROCESS, THREAD }; + void collectData(SPtr<Grid3D> grid, int nofSegments, PartLevel level); + void buildMetisGraphLevelIntersected(SPtr<Grid3D> grid, int nofSegments, PartLevel level); + void buildMetisGraphLevelBased(SPtr<Grid3D> grid, int nofSegments, PartLevel level); + bool getPartitionCondition(SPtr<Block3D> block, PartLevel level); + void distributePartitionData(SPtr<Grid3D> grid, PartLevel level); + void clear(); + int getEdgeWeight(int dir); + int nofSegments; + int numOfDirs; + std::vector<int> blockID; + std::vector<idx_t> parts; + SPtr<Communicator> comm; + int bundleRoot; + int processRoot; + int bundleID; + int processID; + int numberOfBundles; + int numberOfThreads; + bool threads; + GraphType graphType; + MetisPartitioner::PartType partType; + int numberOfProcesses; }; -#endif //VF_MPI -#endif +#endif // VF_MPI +#endif diff --git a/src/cpu/VirtualFluidsCore/Visitors/OverlapBlockVisitor.cpp b/src/cpu/VirtualFluidsCore/Visitors/OverlapBlockVisitor.cpp index 5a1c2442392ea3500a0a95c3e8cc3364586c5354..338c6de90499db39836910c47a7b60f00ee7c675 100644 --- a/src/cpu/VirtualFluidsCore/Visitors/OverlapBlockVisitor.cpp +++ b/src/cpu/VirtualFluidsCore/Visitors/OverlapBlockVisitor.cpp @@ -1,60 +1,54 @@ #include "OverlapBlockVisitor.h" -#include "Grid3DSystem.h" #include "Block3D.h" #include "Grid3D.h" +#include "Grid3DSystem.h" -OverlapBlockVisitor::OverlapBlockVisitor(int levelDepth/*shut be maxGridLevel*/, bool includeNotActiveBlocks) - : Block3DVisitor(0, Grid3DSystem::MAXLEVEL) - , levelDepth(levelDepth) - , includeNotActiveBlocks(includeNotActiveBlocks) +OverlapBlockVisitor::OverlapBlockVisitor(int levelDepth /*shut be maxGridLevel*/, bool includeNotActiveBlocks) + : Block3DVisitor(0, Grid3DSystem::MAXLEVEL), levelDepth(levelDepth), includeNotActiveBlocks(includeNotActiveBlocks) { } ////////////////////////////////////////////////////////////////////////// void OverlapBlockVisitor::visit(SPtr<Grid3D> grid, SPtr<Block3D> block) { - int ix1, ix2, ix3, level; - ix1 = block->getX1(); - ix2 = block->getX2(); - ix3 = block->getX3(); - level = block->getLevel(); + int ix1, ix2, ix3, level; + ix1 = block->getX1(); + ix2 = block->getX2(); + ix3 = block->getX3(); + level = block->getLevel(); - int nix1, nix2,nix3, nlev; - int neighix1, neighix2, neighix3, neighlev; - std::vector<SPtr<Block3D>> neighbors; - grid->getAllNeighbors(ix1, ix2, ix3, level, this->levelDepth, neighbors); -// bool hasAdded = false; - for(size_t i=0; i<neighbors.size(); i++) - { - if( ( neighbors[i]->isActive() || includeNotActiveBlocks ) - && neighbors[i]->getLevel() > level) - { - neighix1 = neighbors[i]->getX1(); - neighix2 = neighbors[i]->getX2(); - neighix3 = neighbors[i]->getX3(); - neighlev = neighbors[i]->getLevel(); - nix1 = neighix1>>1; - nix2 = neighix2>>1; - nix3 = neighix3>>1; - nlev = neighlev-1; + int nix1, nix2, nix3, nlev; + int neighix1, neighix2, neighix3, neighlev; + std::vector<SPtr<Block3D>> neighbors; + grid->getAllNeighbors(ix1, ix2, ix3, level, this->levelDepth, neighbors); + // bool hasAdded = false; + for (size_t i = 0; i < neighbors.size(); i++) { + if ((neighbors[i]->isActive() || includeNotActiveBlocks) && neighbors[i]->getLevel() > level) { + neighix1 = neighbors[i]->getX1(); + neighix2 = neighbors[i]->getX2(); + neighix3 = neighbors[i]->getX3(); + neighlev = neighbors[i]->getLevel(); + nix1 = neighix1 >> 1; + nix2 = neighix2 >> 1; + nix3 = neighix3 >> 1; + nlev = neighlev - 1; - if(nlev != level) - { - throw UbException(UB_EXARGS, "OverlapBlockVisitor::adaptBlock - leveldifferenz passt nicht, block: " + block->toString()); - } + if (nlev != level) { + throw UbException(UB_EXARGS, "OverlapBlockVisitor::adaptBlock - leveldifferenz passt nicht, block: " + + block->toString()); + } - SPtr<Block3D> newBlock = grid->getBlock(nix1,nix2,nix3,nlev); - if(!newBlock) - { - newBlock = SPtr<Block3D>(new Block3D(nix1,nix2,nix3,nlev)); - grid->addBlock(newBlock); - // hasAdded=true; - } - } - } + SPtr<Block3D> newBlock = grid->getBlock(nix1, nix2, nix3, nlev); + if (!newBlock) { + newBlock = SPtr<Block3D>(new Block3D(nix1, nix2, nix3, nlev)); + grid->addBlock(newBlock); + // hasAdded=true; + } + } + } } ////////////////////////////////////////////////////////////////////////// std::string OverlapBlockVisitor::getSpecificDescription() { - std::string str("Overlap:"); - return str; + std::string str("Overlap:"); + return str; } diff --git a/src/cpu/VirtualFluidsCore/Visitors/OverlapBlockVisitor.h b/src/cpu/VirtualFluidsCore/Visitors/OverlapBlockVisitor.h index 49f34438c1db40126f7915ee3080d7352dad9337..d839d80418a29897e5da0951d71d47f12372134c 100644 --- a/src/cpu/VirtualFluidsCore/Visitors/OverlapBlockVisitor.h +++ b/src/cpu/VirtualFluidsCore/Visitors/OverlapBlockVisitor.h @@ -1,8 +1,8 @@ #ifndef OverlapBlockVisitor_H #define OverlapBlockVisitor_H -#include <string> #include <PointerDefinitions.h> +#include <string> #include "Block3DVisitor.h" @@ -12,20 +12,19 @@ class Block3D; class OverlapBlockVisitor : public Block3DVisitor { public: - OverlapBlockVisitor(int levelDepth, bool includeNotActiveBlocks = true); - - ~OverlapBlockVisitor() override= default; + OverlapBlockVisitor(int levelDepth, bool includeNotActiveBlocks = true); - bool isIterative() { return false; } + ~OverlapBlockVisitor() override = default; - std::string getSpecificDescription(); + bool isIterative() { return false; } - void visit(SPtr<Grid3D> grid, SPtr<Block3D> block) override; + std::string getSpecificDescription(); + void visit(SPtr<Grid3D> grid, SPtr<Block3D> block) override; private: - int levelDepth; - bool includeNotActiveBlocks; + int levelDepth; + bool includeNotActiveBlocks; }; -#endif //OverlapBlockVisitor_H +#endif // OverlapBlockVisitor_H diff --git a/src/cpu/VirtualFluidsCore/Visitors/PQueuePartitioningGridVisitor.cpp b/src/cpu/VirtualFluidsCore/Visitors/PQueuePartitioningGridVisitor.cpp index 51fe5e8c8b117b7d198084e10b608136f2f9c1e8..f4b0136c91bc24f862879ed98a662e25eb9c6847 100644 --- a/src/cpu/VirtualFluidsCore/Visitors/PQueuePartitioningGridVisitor.cpp +++ b/src/cpu/VirtualFluidsCore/Visitors/PQueuePartitioningGridVisitor.cpp @@ -2,53 +2,44 @@ #include <vector> -#include "PriorityQueueDecompositor.h" -#include "Grid3D.h" #include "Block3D.h" +#include "Grid3D.h" +#include "PriorityQueueDecompositor.h" #include "UbLogger.h" - -PQueuePartitioningGridVisitor::PQueuePartitioningGridVisitor(int numOfParts) : numOfParts(numOfParts) -{ - -} +PQueuePartitioningGridVisitor::PQueuePartitioningGridVisitor(int numOfParts) : numOfParts(numOfParts) {} ////////////////////////////////////////////////////////////////////////// void PQueuePartitioningGridVisitor::visit(SPtr<Grid3D> grid) { - UBLOG(logDEBUG5, "PQueuePartitioningGridVisitor::visit() - start"); - std::vector<SPtr<Block3D>> blocks; - std::vector<int> weights; - std::vector< std::vector <SPtr<Block3D>> > parts; - int gridRank = grid->getRank(); - - int minInitLevel = grid->getCoarsestInitializedLevel(); - int maxInitLevel = grid->getFinestInitializedLevel(); - - for(int level = minInitLevel; level<=maxInitLevel; level++) - { - std::vector<SPtr<Block3D>> blockVector; - grid->getBlocks(level, gridRank, true, blockVector); - for(SPtr<Block3D> block : blockVector) - { - if (block) - { - blocks.push_back(block); - weights.push_back(block->getNumberOfLocalConnectors()*(1<<block->getLevel())); - } - } - } - PriorityQueueDecompositor <SPtr<Block3D>> dec = PriorityQueueDecompositor <SPtr<Block3D>> (blocks, weights, numOfParts); - dec.getDecomposition(parts); - - int i = 0; - for(std::vector<SPtr<Block3D>> p : parts) - { - for(SPtr<Block3D> block : p) - { - block->setPart(i); - } - i++; - - } - UBLOG(logDEBUG5, "PQueuePartitioningGridVisitor::visit() - end"); + UBLOG(logDEBUG5, "PQueuePartitioningGridVisitor::visit() - start"); + std::vector<SPtr<Block3D>> blocks; + std::vector<int> weights; + std::vector<std::vector<SPtr<Block3D>>> parts; + int gridRank = grid->getRank(); + + int minInitLevel = grid->getCoarsestInitializedLevel(); + int maxInitLevel = grid->getFinestInitializedLevel(); + + for (int level = minInitLevel; level <= maxInitLevel; level++) { + std::vector<SPtr<Block3D>> blockVector; + grid->getBlocks(level, gridRank, true, blockVector); + for (SPtr<Block3D> block : blockVector) { + if (block) { + blocks.push_back(block); + weights.push_back(block->getNumberOfLocalConnectors() * (1 << block->getLevel())); + } + } + } + PriorityQueueDecompositor<SPtr<Block3D>> dec = + PriorityQueueDecompositor<SPtr<Block3D>>(blocks, weights, numOfParts); + dec.getDecomposition(parts); + + int i = 0; + for (std::vector<SPtr<Block3D>> p : parts) { + for (SPtr<Block3D> block : p) { + block->setPart(i); + } + i++; + } + UBLOG(logDEBUG5, "PQueuePartitioningGridVisitor::visit() - end"); } diff --git a/src/cpu/VirtualFluidsCore/Visitors/PQueuePartitioningGridVisitor.h b/src/cpu/VirtualFluidsCore/Visitors/PQueuePartitioningGridVisitor.h index d1fdbeda7ee59ae3c85cb5c428249f08edd31395..e31fdb4b5fa2b8763e29851b09eebe83cccf980b 100644 --- a/src/cpu/VirtualFluidsCore/Visitors/PQueuePartitioningGridVisitor.h +++ b/src/cpu/VirtualFluidsCore/Visitors/PQueuePartitioningGridVisitor.h @@ -1,10 +1,10 @@ /** -* @file PQueuePartitioningPatchVisitor.h -* @brief Visitor class which apply Priority Queue for threads decomposition. -* @author Kostyantyn Kucher -* @date 06.06.2011 -*/ -#ifndef PQUEUEPARTITIONINGPATCHVISITOR_H + * @file PQueuePartitioningPatchVisitor.h + * @brief Visitor class which apply Priority Queue for threads decomposition. + * @author Kostyantyn Kucher + * @date 06.06.2011 + */ +#ifndef PQUEUEPARTITIONINGPATCHVISITOR_H #define PQUEUEPARTITIONINGPATCHVISITOR_H #include <PointerDefinitions.h> @@ -16,12 +16,12 @@ class Grid3D; class PQueuePartitioningGridVisitor : public Grid3DVisitor { public: - PQueuePartitioningGridVisitor(int numOfParts); + PQueuePartitioningGridVisitor(int numOfParts); - void visit(SPtr<Grid3D> grid) override; + void visit(SPtr<Grid3D> grid) override; private: - int numOfParts; + int numOfParts; }; #endif diff --git a/src/cpu/VirtualFluidsCore/Visitors/RatioBlockVisitor.cpp b/src/cpu/VirtualFluidsCore/Visitors/RatioBlockVisitor.cpp index 9fd72e75b6f54e3e304bf7b5625c5e2277635415..bf25b8876f540c6ff5f678b32ad67ddd736c145d 100644 --- a/src/cpu/VirtualFluidsCore/Visitors/RatioBlockVisitor.cpp +++ b/src/cpu/VirtualFluidsCore/Visitors/RatioBlockVisitor.cpp @@ -1,129 +1,154 @@ #include "RatioBlockVisitor.h" -#include "Grid3DSystem.h" -#include "Grid3D.h" #include "Block3D.h" +#include "Grid3D.h" +#include "Grid3DSystem.h" RatioBlockVisitor::RatioBlockVisitor(int levelDepth, bool includeNotActiveBlocks) - : Block3DVisitor(0, Grid3DSystem::MAXLEVEL) - , maxLevelRatio(1) - , expandBlocks(true) - , levelDepth(levelDepth) - , includeNotActiveBlocks(includeNotActiveBlocks) + : Block3DVisitor(0, Grid3DSystem::MAXLEVEL), maxLevelRatio(1), expandBlocks(true), levelDepth(levelDepth), + includeNotActiveBlocks(includeNotActiveBlocks) { - } ////////////////////////////////////////////////////////////////////////// void RatioBlockVisitor::visit(SPtr<Grid3D> grid, SPtr<Block3D> block) { - int ix1, ix2, ix3, level; - ix1 = block->getX1(); - ix2 = block->getX2(); - ix3 = block->getX3(); - level = block->getLevel(); + int ix1, ix2, ix3, level; + ix1 = block->getX1(); + ix2 = block->getX2(); + ix3 = block->getX3(); + level = block->getLevel(); - if( block->isActive() || includeNotActiveBlocks ) - { - if(this->expandBlocks) - { - if(this->lookForExpand(grid,ix1, ix2, ix3, level)) - { - grid->expandBlock(ix1, ix2, ix3, level); - } - } - else - { - if(this->lookForCollapse(grid,ix1, ix2, ix3, level)) - { - grid->collapseBlock(ix1, ix2, ix3, level, levelDepth); - } - } - } + if (block->isActive() || includeNotActiveBlocks) { + if (this->expandBlocks) { + if (this->lookForExpand(grid, ix1, ix2, ix3, level)) { + grid->expandBlock(ix1, ix2, ix3, level); + } + } else { + if (this->lookForCollapse(grid, ix1, ix2, ix3, level)) { + grid->collapseBlock(ix1, ix2, ix3, level, levelDepth); + } + } + } } ////////////////////////////////////////////////////////////////////////// -bool RatioBlockVisitor::lookForExpand(SPtr<Grid3D> grid, const int& ix1, const int& ix2, const int& ix3, const int& level) +bool RatioBlockVisitor::lookForExpand(SPtr<Grid3D> grid, const int &ix1, const int &ix2, const int &ix3, + const int &level) { - std::vector<SPtr<Block3D>> neighbors; - grid->getAllNeighbors(ix1, ix2, ix3, level, this->levelDepth, neighbors); - for(size_t i=0; i<neighbors.size(); i++) - { - if( ( neighbors[i]->isActive() || includeNotActiveBlocks ) - && neighbors[i]->getLevel() > level+this->maxLevelRatio) - { - return true; - } - } + std::vector<SPtr<Block3D>> neighbors; + grid->getAllNeighbors(ix1, ix2, ix3, level, this->levelDepth, neighbors); + for (size_t i = 0; i < neighbors.size(); i++) { + if ((neighbors[i]->isActive() || includeNotActiveBlocks) && + neighbors[i]->getLevel() > level + this->maxLevelRatio) { + return true; + } + } - return false; + return false; } ////////////////////////////////////////////////////////////////////////// -bool RatioBlockVisitor::lookForCollapse(SPtr<Grid3D> grid, const int& ix1, const int& ix2, const int& ix3, const int& level) +bool RatioBlockVisitor::lookForCollapse(SPtr<Grid3D> grid, const int &ix1, const int &ix2, const int &ix3, + const int &level) { - std::vector<SPtr<Block3D>> neighbors; - grid->getAllNeighbors(ix1, ix2,ix3, level, this->levelDepth, neighbors); - for(size_t i=0; i<neighbors.size(); i++) - { - if( ( neighbors[i]->isActive() || includeNotActiveBlocks ) - && neighbors[i]->getLevel() < level-this->maxLevelRatio) - { - return true; - } - } + std::vector<SPtr<Block3D>> neighbors; + grid->getAllNeighbors(ix1, ix2, ix3, level, this->levelDepth, neighbors); + for (size_t i = 0; i < neighbors.size(); i++) { + if ((neighbors[i]->isActive() || includeNotActiveBlocks) && + neighbors[i]->getLevel() < level - this->maxLevelRatio) { + return true; + } + } - return false; + return false; } ////////////////////////////////////////////////////////////////////////// void RatioBlockVisitor::setExpandByAdaptation(bool expandBlocks) { - if(this->expandBlocks != expandBlocks) - { - this->expandBlocks = expandBlocks; + if (this->expandBlocks != expandBlocks) { + this->expandBlocks = expandBlocks; - int l1 = Block3DVisitor::getStartLevel(); - int l2 = Block3DVisitor::getStopLevel(); + int l1 = Block3DVisitor::getStartLevel(); + int l2 = Block3DVisitor::getStopLevel(); - if(expandBlocks) { if(l1 < l2) { Block3DVisitor::setStartLevel(l2); Block3DVisitor::setStopLevel(l1); } } - else { if(l2 < l1) { Block3DVisitor::setStartLevel(l2); Block3DVisitor::setStopLevel(l1); } } - } + if (expandBlocks) { + if (l1 < l2) { + Block3DVisitor::setStartLevel(l2); + Block3DVisitor::setStopLevel(l1); + } + } else { + if (l2 < l1) { + Block3DVisitor::setStartLevel(l2); + Block3DVisitor::setStopLevel(l1); + } + } + } } ////////////////////////////////////////////////////////////////////////// void RatioBlockVisitor::setLevelRatio(int ratio) { - if(ratio < 1) throw UbException(UB_EXARGS,"illegal ratio specified"); - this->maxLevelRatio = ratio; + if (ratio < 1) + throw UbException(UB_EXARGS, "illegal ratio specified"); + this->maxLevelRatio = ratio; } ////////////////////////////////////////////////////////////////////////// std::string RatioBlockVisitor::getSpecificDescription() { - std::string str("Ratio:"); - return str; + std::string str("Ratio:"); + return str; } ////////////////////////////////////////////////////////////////////////// int RatioBlockVisitor::getStartLevel() { - int l1 = Block3DVisitor::getStartLevel(); - int l2 = Block3DVisitor::getStopLevel(); + int l1 = Block3DVisitor::getStartLevel(); + int l2 = Block3DVisitor::getStopLevel(); - if(this->expandBlocks) { if(l2 < l1) return(l1); else return(l2); } - else { if(l2 < l1) return(l2); else return(l1); } + if (this->expandBlocks) { + if (l2 < l1) + return (l1); + else + return (l2); + } else { + if (l2 < l1) + return (l2); + else + return (l1); + } } ////////////////////////////////////////////////////////////////////////// int RatioBlockVisitor::getStopLevel() { - int l1 = Block3DVisitor::getStartLevel(); - int l2 = Block3DVisitor::getStopLevel(); + int l1 = Block3DVisitor::getStartLevel(); + int l2 = Block3DVisitor::getStopLevel(); - if(this->expandBlocks) { if(l2 < l1) return(l2); else return(l1); } - else { if(l2 < l1) return(l1); else return(l2); } + if (this->expandBlocks) { + if (l2 < l1) + return (l2); + else + return (l1); + } else { + if (l2 < l1) + return (l1); + else + return (l2); + } } ////////////////////////////////////////////////////////////////////////// void RatioBlockVisitor::setStartLevel(int level) { - if(this->expandBlocks) { if(level >= Block3DVisitor::getStopLevel()) Block3DVisitor::setStartLevel(level); } - else { if(level <= Block3DVisitor::getStopLevel()) Block3DVisitor::setStartLevel(level); } + if (this->expandBlocks) { + if (level >= Block3DVisitor::getStopLevel()) + Block3DVisitor::setStartLevel(level); + } else { + if (level <= Block3DVisitor::getStopLevel()) + Block3DVisitor::setStartLevel(level); + } } ////////////////////////////////////////////////////////////////////////// void RatioBlockVisitor::setStopLevel(int level) { - if(this->expandBlocks) { if(level <= Block3DVisitor::getStartLevel()) Block3DVisitor::setStopLevel(level); } - else { if(level >= Block3DVisitor::getStartLevel()) Block3DVisitor::setStopLevel(level); } + if (this->expandBlocks) { + if (level <= Block3DVisitor::getStartLevel()) + Block3DVisitor::setStopLevel(level); + } else { + if (level >= Block3DVisitor::getStartLevel()) + Block3DVisitor::setStopLevel(level); + } } diff --git a/src/cpu/VirtualFluidsCore/Visitors/RatioBlockVisitor.h b/src/cpu/VirtualFluidsCore/Visitors/RatioBlockVisitor.h index f3f42d9cfa0613747645783f3939c1be8e3630ce..037d06dbfea92062dc957fe996c02cefdf46af9f 100644 --- a/src/cpu/VirtualFluidsCore/Visitors/RatioBlockVisitor.h +++ b/src/cpu/VirtualFluidsCore/Visitors/RatioBlockVisitor.h @@ -1,8 +1,8 @@ #ifndef RatioBlockVisitor_H #define RatioBlockVisitor_H -#include <string> #include <PointerDefinitions.h> +#include <string> #include "Block3DVisitor.h" @@ -12,38 +12,38 @@ class Block3D; class RatioBlockVisitor : public Block3DVisitor { public: - RatioBlockVisitor(int levelDepth, bool includeNotActiveBlocks = false); + RatioBlockVisitor(int levelDepth, bool includeNotActiveBlocks = false); - ~RatioBlockVisitor() override = default; + ~RatioBlockVisitor() override = default; - bool expandsByAdaptation() { return this->expandBlocks; } + bool expandsByAdaptation() { return this->expandBlocks; } - void setExpandByAdaptation(bool expandBlocks); + void setExpandByAdaptation(bool expandBlocks); - int getLevelRatio() { return this->maxLevelRatio; } - bool isIterative() { return true; } + int getLevelRatio() { return this->maxLevelRatio; } + bool isIterative() { return true; } - void setLevelRatio(int ratio); + void setLevelRatio(int ratio); - int getStartLevel(); - int getStopLevel(); + int getStartLevel(); + int getStopLevel(); - void setStartLevel(int level); - void setStopLevel(int level); + void setStartLevel(int level); + void setStopLevel(int level); - std::string getSpecificDescription(); + std::string getSpecificDescription(); - void visit(SPtr<Grid3D> grid, SPtr<Block3D> block) override; + void visit(SPtr<Grid3D> grid, SPtr<Block3D> block) override; protected: - bool lookForExpand(SPtr<Grid3D> grid, const int& ix1, const int& ix2, const int& ix3, const int& level); - bool lookForCollapse(SPtr<Grid3D> grid, const int& ix1, const int& ix2, const int& ix3, const int& level); + bool lookForExpand(SPtr<Grid3D> grid, const int &ix1, const int &ix2, const int &ix3, const int &level); + bool lookForCollapse(SPtr<Grid3D> grid, const int &ix1, const int &ix2, const int &ix3, const int &level); private: - int maxLevelRatio; - bool expandBlocks; - int levelDepth; - bool includeNotActiveBlocks; + int maxLevelRatio; + bool expandBlocks; + int levelDepth; + bool includeNotActiveBlocks; }; #endif diff --git a/src/cpu/VirtualFluidsCore/Visitors/RatioSmoothBlockVisitor.cpp b/src/cpu/VirtualFluidsCore/Visitors/RatioSmoothBlockVisitor.cpp index b067fcad45a1ed1b231c4e7e7d97303172df376a..3bcdd29299a8183a2cda60253101df89b681a51a 100644 --- a/src/cpu/VirtualFluidsCore/Visitors/RatioSmoothBlockVisitor.cpp +++ b/src/cpu/VirtualFluidsCore/Visitors/RatioSmoothBlockVisitor.cpp @@ -1,145 +1,167 @@ #include "RatioSmoothBlockVisitor.h" -#include "Grid3DSystem.h" #include "Block3D.h" #include "Grid3D.h" +#include "Grid3DSystem.h" RatioSmoothBlockVisitor::RatioSmoothBlockVisitor(int levelDepth, bool includeNotActiveBlocks) - : Block3DVisitor(Grid3DSystem::MAXLEVEL, 0) - , maxLevelRatio(1) - , expandBlocks(true) - , levelDepth(levelDepth) - , includeNotActiveBlocks(includeNotActiveBlocks) + : Block3DVisitor(Grid3DSystem::MAXLEVEL, 0), maxLevelRatio(1), expandBlocks(true), levelDepth(levelDepth), + includeNotActiveBlocks(includeNotActiveBlocks) { } ////////////////////////////////////////////////////////////////////////// void RatioSmoothBlockVisitor::visit(SPtr<Grid3D> grid, SPtr<Block3D> block) { - int ix1, ix2, ix3, level; - ix1 = block->getX1(); - ix2 = block->getX2(); - ix3 = block->getX3(); - level = block->getLevel(); + int ix1, ix2, ix3, level; + ix1 = block->getX1(); + ix2 = block->getX2(); + ix3 = block->getX3(); + level = block->getLevel(); - if( block->isActive() || includeNotActiveBlocks ) - { - if(this->expandBlocks) - { - if(this->lookForExpand(grid,ix1, ix2, ix3, level)) - { - grid->expandBlock(ix1, ix2, ix3, level); - } - } - else - { - if(this->lookForCollapse(grid,ix1, ix2, ix3, level)) - { - grid->collapseBlock(ix1, ix2, ix3, level, levelDepth); - } - } - } + if (block->isActive() || includeNotActiveBlocks) { + if (this->expandBlocks) { + if (this->lookForExpand(grid, ix1, ix2, ix3, level)) { + grid->expandBlock(ix1, ix2, ix3, level); + } + } else { + if (this->lookForCollapse(grid, ix1, ix2, ix3, level)) { + grid->collapseBlock(ix1, ix2, ix3, level, levelDepth); + } + } + } } ////////////////////////////////////////////////////////////////////////// -bool RatioSmoothBlockVisitor::lookForExpand(SPtr<Grid3D> grid, const int& ix1, const int& ix2, const int& ix3, const int& level) +bool RatioSmoothBlockVisitor::lookForExpand(SPtr<Grid3D> grid, const int &ix1, const int &ix2, const int &ix3, + const int &level) { - std::vector<SPtr<Block3D>> neighbors; - grid->getAllNeighbors(ix1, ix2, ix3, level, this->levelDepth, neighbors); - int nix1, nix2,nix3, nlev; - for(size_t i=0; i<neighbors.size(); i++) - { - if( ( neighbors[i]->isActive() || includeNotActiveBlocks ) - && neighbors[i]->getLevel() > level) - { - nix1 = (neighbors)[i]->getX1(); - nix2 = (neighbors)[i]->getX2(); - nix3 = (neighbors)[i]->getX3(); - nlev = (neighbors)[i]->getLevel(); + std::vector<SPtr<Block3D>> neighbors; + grid->getAllNeighbors(ix1, ix2, ix3, level, this->levelDepth, neighbors); + int nix1, nix2, nix3, nlev; + for (size_t i = 0; i < neighbors.size(); i++) { + if ((neighbors[i]->isActive() || includeNotActiveBlocks) && neighbors[i]->getLevel() > level) { + nix1 = (neighbors)[i]->getX1(); + nix2 = (neighbors)[i]->getX2(); + nix3 = (neighbors)[i]->getX3(); + nlev = (neighbors)[i]->getLevel(); - std::vector<SPtr<Block3D>> neighbors1; - grid->getAllNeighbors(nix1, nix2, nix3, nlev, nlev+1, neighbors1); - for(size_t j=0; j<neighbors1.size(); j++) - { - if( ( neighbors1[j]->isActive() || includeNotActiveBlocks ) - && neighbors1[j]->getLevel() > level+this->maxLevelRatio) - { - return true; + std::vector<SPtr<Block3D>> neighbors1; + grid->getAllNeighbors(nix1, nix2, nix3, nlev, nlev + 1, neighbors1); + for (size_t j = 0; j < neighbors1.size(); j++) { + if ((neighbors1[j]->isActive() || includeNotActiveBlocks) && + neighbors1[j]->getLevel() > level + this->maxLevelRatio) { + return true; + } } - } - } - } - return false; + } + } + return false; } ////////////////////////////////////////////////////////////////////////// -bool RatioSmoothBlockVisitor::lookForCollapse(SPtr<Grid3D> grid, const int& ix1, const int& ix2, const int& ix3, const int& level) +bool RatioSmoothBlockVisitor::lookForCollapse(SPtr<Grid3D> grid, const int &ix1, const int &ix2, const int &ix3, + const int &level) { - std::vector<SPtr<Block3D>> neighbors; - grid->getAllNeighbors(ix1, ix2,ix3, level, this->levelDepth, neighbors); - for(size_t i=0; i<neighbors.size(); i++) - { - if( ( neighbors[i]->isActive() || includeNotActiveBlocks ) - && neighbors[i]->getLevel() < level-this->maxLevelRatio) - { - throw UbException(UB_EXARGS," not implemented till now"); - return true; - } - } + std::vector<SPtr<Block3D>> neighbors; + grid->getAllNeighbors(ix1, ix2, ix3, level, this->levelDepth, neighbors); + for (size_t i = 0; i < neighbors.size(); i++) { + if ((neighbors[i]->isActive() || includeNotActiveBlocks) && + neighbors[i]->getLevel() < level - this->maxLevelRatio) { + throw UbException(UB_EXARGS, " not implemented till now"); + return true; + } + } - return false; + return false; } ////////////////////////////////////////////////////////////////////////// void RatioSmoothBlockVisitor::setExpandByAdaptation(bool expandBlocks) { - if(this->expandBlocks != expandBlocks) - { - this->expandBlocks = expandBlocks; + if (this->expandBlocks != expandBlocks) { + this->expandBlocks = expandBlocks; - int l1 = Block3DVisitor::getStartLevel(); - int l2 = Block3DVisitor::getStopLevel(); + int l1 = Block3DVisitor::getStartLevel(); + int l2 = Block3DVisitor::getStopLevel(); - if(expandBlocks) { if(l1 < l2) { Block3DVisitor::setStartLevel(l2); Block3DVisitor::setStopLevel(l1); } } - else { if(l2 < l1) { Block3DVisitor::setStartLevel(l2); Block3DVisitor::setStopLevel(l1); } } - } + if (expandBlocks) { + if (l1 < l2) { + Block3DVisitor::setStartLevel(l2); + Block3DVisitor::setStopLevel(l1); + } + } else { + if (l2 < l1) { + Block3DVisitor::setStartLevel(l2); + Block3DVisitor::setStopLevel(l1); + } + } + } } ////////////////////////////////////////////////////////////////////////// void RatioSmoothBlockVisitor::setLevelRatio(int ratio) { - if(ratio < 1) throw UbException(UB_EXARGS,"illegal ratio specified"); - this->maxLevelRatio = ratio; + if (ratio < 1) + throw UbException(UB_EXARGS, "illegal ratio specified"); + this->maxLevelRatio = ratio; } ////////////////////////////////////////////////////////////////////////// std::string RatioSmoothBlockVisitor::getSpecificDescription() { - std::string str("Ratio:"); - return str; + std::string str("Ratio:"); + return str; } ////////////////////////////////////////////////////////////////////////// int RatioSmoothBlockVisitor::getStartLevel() { - int l1 = Block3DVisitor::getStartLevel(); - int l2 = Block3DVisitor::getStopLevel(); + int l1 = Block3DVisitor::getStartLevel(); + int l2 = Block3DVisitor::getStopLevel(); - if(this->expandBlocks) { if(l2 < l1) return(l1); else return(l2); } - else { if(l2 < l1) return(l2); else return(l1); } + if (this->expandBlocks) { + if (l2 < l1) + return (l1); + else + return (l2); + } else { + if (l2 < l1) + return (l2); + else + return (l1); + } } ////////////////////////////////////////////////////////////////////////// int RatioSmoothBlockVisitor::getStopLevel() { - int l1 = Block3DVisitor::getStartLevel(); - int l2 = Block3DVisitor::getStopLevel(); + int l1 = Block3DVisitor::getStartLevel(); + int l2 = Block3DVisitor::getStopLevel(); - if(this->expandBlocks) { if(l2 < l1) return(l2); else return(l1); } - else { if(l2 < l1) return(l1); else return(l2); } + if (this->expandBlocks) { + if (l2 < l1) + return (l2); + else + return (l1); + } else { + if (l2 < l1) + return (l1); + else + return (l2); + } } ////////////////////////////////////////////////////////////////////////// void RatioSmoothBlockVisitor::setStartLevel(int level) { - if(this->expandBlocks) { if(level >= Block3DVisitor::getStopLevel()) Block3DVisitor::setStartLevel(level); } - else { if(level <= Block3DVisitor::getStopLevel()) Block3DVisitor::setStartLevel(level); } + if (this->expandBlocks) { + if (level >= Block3DVisitor::getStopLevel()) + Block3DVisitor::setStartLevel(level); + } else { + if (level <= Block3DVisitor::getStopLevel()) + Block3DVisitor::setStartLevel(level); + } } ////////////////////////////////////////////////////////////////////////// void RatioSmoothBlockVisitor::setStopLevel(int level) { - if(this->expandBlocks) { if(level <= Block3DVisitor::getStartLevel()) Block3DVisitor::setStopLevel(level); } - else { if(level >= Block3DVisitor::getStartLevel()) Block3DVisitor::setStopLevel(level); } + if (this->expandBlocks) { + if (level <= Block3DVisitor::getStartLevel()) + Block3DVisitor::setStopLevel(level); + } else { + if (level >= Block3DVisitor::getStartLevel()) + Block3DVisitor::setStopLevel(level); + } } - diff --git a/src/cpu/VirtualFluidsCore/Visitors/RatioSmoothBlockVisitor.h b/src/cpu/VirtualFluidsCore/Visitors/RatioSmoothBlockVisitor.h index 856e5177911d958615f91dc22033958ccd80f760..b9347c8476683576d4cf4ede0bca7871eab8e559 100644 --- a/src/cpu/VirtualFluidsCore/Visitors/RatioSmoothBlockVisitor.h +++ b/src/cpu/VirtualFluidsCore/Visitors/RatioSmoothBlockVisitor.h @@ -11,39 +11,38 @@ class Block3D; class RatioSmoothBlockVisitor : public Block3DVisitor { public: - RatioSmoothBlockVisitor(int levelDepth, bool includeNotActiveBlocks = false); + RatioSmoothBlockVisitor(int levelDepth, bool includeNotActiveBlocks = false); - ~RatioSmoothBlockVisitor() override = default; + ~RatioSmoothBlockVisitor() override = default; - bool expandsByAdaptation() { return this->expandBlocks; } + bool expandsByAdaptation() { return this->expandBlocks; } - void setExpandByAdaptation(bool expandBlocks); + void setExpandByAdaptation(bool expandBlocks); - int getLevelRatio() { return this->maxLevelRatio; } - bool isIterative() { return true; } + int getLevelRatio() { return this->maxLevelRatio; } + bool isIterative() { return true; } - void setLevelRatio(int ratio); + void setLevelRatio(int ratio); - int getStartLevel(); - int getStopLevel(); + int getStartLevel(); + int getStopLevel(); - void setStartLevel(int level); - void setStopLevel(int level); + void setStartLevel(int level); + void setStopLevel(int level); - std::string getSpecificDescription(); + std::string getSpecificDescription(); - void visit(SPtr<Grid3D> grid, SPtr<Block3D> block) override; + void visit(SPtr<Grid3D> grid, SPtr<Block3D> block) override; protected: - bool lookForExpand(SPtr<Grid3D> grid, const int& ix1, const int& ix2, const int& ix3, const int& level); - bool lookForCollapse(SPtr<Grid3D> grid, const int& ix1, const int& ix2, const int& ix3, const int& level); + bool lookForExpand(SPtr<Grid3D> grid, const int &ix1, const int &ix2, const int &ix3, const int &level); + bool lookForCollapse(SPtr<Grid3D> grid, const int &ix1, const int &ix2, const int &ix3, const int &level); private: - int maxLevelRatio; - bool expandBlocks; - int levelDepth; - bool includeNotActiveBlocks; - + int maxLevelRatio; + bool expandBlocks; + int levelDepth; + bool includeNotActiveBlocks; }; -#endif //RatioSmoothBlockVisitor_H +#endif // RatioSmoothBlockVisitor_H diff --git a/src/cpu/VirtualFluidsCore/Visitors/RefineAroundGbObjectHelper.cpp b/src/cpu/VirtualFluidsCore/Visitors/RefineAroundGbObjectHelper.cpp index 59ffd9dfe64e3c0fa69abbc314ac673c485bbdd6..88ff49408be67b02f9f56cf35287ba17f1216b33 100644 --- a/src/cpu/VirtualFluidsCore/Visitors/RefineAroundGbObjectHelper.cpp +++ b/src/cpu/VirtualFluidsCore/Visitors/RefineAroundGbObjectHelper.cpp @@ -1,54 +1,50 @@ #include "RefineAroundGbObjectHelper.h" +#include "Communicator.h" +#include "OverlapBlockVisitor.h" #include "RatioBlockVisitor.h" #include "RatioSmoothBlockVisitor.h" -#include "OverlapBlockVisitor.h" #include "SetInterpolationDirsBlockVisitor.h" #include <D3Q27System.h> -#include <Grid3D.h> #include <D3Q27TriFaceMeshInteractor.h> -#include "Communicator.h" +#include <Grid3D.h> -RefineAroundGbObjectHelper::RefineAroundGbObjectHelper(SPtr<Grid3D> grid, int refineLevel, SPtr<D3Q27TriFaceMeshInteractor> objectIter, double startDistance, double stopDistance, SPtr<Communicator> comm) : - grid(grid), - refineLevel(refineLevel), - objectIter(objectIter), - startDistance(startDistance), - stopDistance(stopDistance), - comm(comm) +RefineAroundGbObjectHelper::RefineAroundGbObjectHelper(SPtr<Grid3D> grid, int refineLevel, + SPtr<D3Q27TriFaceMeshInteractor> objectIter, + double startDistance, double stopDistance, + SPtr<Communicator> comm) + : grid(grid), refineLevel(refineLevel), objectIter(objectIter), startDistance(startDistance), + stopDistance(stopDistance), comm(comm) { } ////////////////////////////////////////////////////////////////////////// -RefineAroundGbObjectHelper::~RefineAroundGbObjectHelper(void) -= default; +RefineAroundGbObjectHelper::~RefineAroundGbObjectHelper(void) = default; ////////////////////////////////////////////////////////////////////////// void RefineAroundGbObjectHelper::refine() { - UBLOG(logDEBUG5,"RefineCrossAndInsideGbObjectHelper: refine - start"); + UBLOG(logDEBUG5, "RefineCrossAndInsideGbObjectHelper: refine - start"); - int rank = grid->getRank(); - grid->setRank(0); + int rank = grid->getRank(); + grid->setRank(0); - objectIter->refineBlockGridToLevel(refineLevel, startDistance, stopDistance); + objectIter->refineBlockGridToLevel(refineLevel, startDistance, stopDistance); - RatioBlockVisitor ratioVisitor(refineLevel); - grid->accept(ratioVisitor); + RatioBlockVisitor ratioVisitor(refineLevel); + grid->accept(ratioVisitor); - RatioSmoothBlockVisitor ratioSmoothVisitor(refineLevel); - grid->accept(ratioSmoothVisitor); + RatioSmoothBlockVisitor ratioSmoothVisitor(refineLevel); + grid->accept(ratioSmoothVisitor); - OverlapBlockVisitor overlapVisitor(refineLevel, false); - grid->accept(overlapVisitor); + OverlapBlockVisitor overlapVisitor(refineLevel, false); + grid->accept(overlapVisitor); - std::vector<int> dirs; - for (int i=D3Q27System::E; i<=D3Q27System::TS; i++) - { - dirs.push_back(i); - } - SetInterpolationDirsBlockVisitor interDirsVisitor(dirs); - grid->accept(interDirsVisitor); + std::vector<int> dirs; + for (int i = D3Q27System::E; i <= D3Q27System::TS; i++) { + dirs.push_back(i); + } + SetInterpolationDirsBlockVisitor interDirsVisitor(dirs); + grid->accept(interDirsVisitor); - grid->setRank(rank); + grid->setRank(rank); - UBLOG(logDEBUG5,"RefineCrossAndInsideGbObjectHelper: refine - end"); + UBLOG(logDEBUG5, "RefineCrossAndInsideGbObjectHelper: refine - end"); } - diff --git a/src/cpu/VirtualFluidsCore/Visitors/RefineAroundGbObjectHelper.h b/src/cpu/VirtualFluidsCore/Visitors/RefineAroundGbObjectHelper.h index 76a7bb38571908fe732a06f9aaac1cb52e7080c0..766c290a7605eb428449fe5d5f6215157a08e3d4 100644 --- a/src/cpu/VirtualFluidsCore/Visitors/RefineAroundGbObjectHelper.h +++ b/src/cpu/VirtualFluidsCore/Visitors/RefineAroundGbObjectHelper.h @@ -13,22 +13,24 @@ class D3Q27TriFaceMeshInteractor; class RefineAroundGbObjectHelper { public: - //! Constructor - //! \param grid a smart pointer to the grid object - //! \param maxRefineLevel an integer for maximal refinement level - //! \param objectIter a D3Q27TriFaceMeshInteractor object - represent geometry which should be refinement - //! \param startDistance start distance from geometry for refinement - //! \param stopDistance stop distance from geometry for refinement - RefineAroundGbObjectHelper(SPtr<Grid3D> grid, int maxRefineLevel, SPtr<D3Q27TriFaceMeshInteractor> objectIter, double startDistance, double stopDistance, SPtr<Communicator> comm); - virtual ~RefineAroundGbObjectHelper(); - //! start refinement - void refine(); + //! Constructor + //! \param grid a smart pointer to the grid object + //! \param maxRefineLevel an integer for maximal refinement level + //! \param objectIter a D3Q27TriFaceMeshInteractor object - represent geometry which should be refinement + //! \param startDistance start distance from geometry for refinement + //! \param stopDistance stop distance from geometry for refinement + RefineAroundGbObjectHelper(SPtr<Grid3D> grid, int maxRefineLevel, SPtr<D3Q27TriFaceMeshInteractor> objectIter, + double startDistance, double stopDistance, SPtr<Communicator> comm); + virtual ~RefineAroundGbObjectHelper(); + //! start refinement + void refine(); + private: SPtr<Grid3D> grid; SPtr<D3Q27TriFaceMeshInteractor> objectIter; - int refineLevel; - double startDistance, stopDistance; - SPtr<Communicator> comm; + int refineLevel; + double startDistance, stopDistance; + SPtr<Communicator> comm; }; -#endif +#endif diff --git a/src/cpu/VirtualFluidsCore/Visitors/RefineCrossAndInsideGbObjectBlockVisitor.cpp b/src/cpu/VirtualFluidsCore/Visitors/RefineCrossAndInsideGbObjectBlockVisitor.cpp index cb503f368d67d53c58073a2d8e1c53751c2b3a52..9d5126d992ad7257607eb3a4f966fa9248f02848 100644 --- a/src/cpu/VirtualFluidsCore/Visitors/RefineCrossAndInsideGbObjectBlockVisitor.cpp +++ b/src/cpu/VirtualFluidsCore/Visitors/RefineCrossAndInsideGbObjectBlockVisitor.cpp @@ -1,42 +1,35 @@ #include "RefineCrossAndInsideGbObjectBlockVisitor.h" -#include <geometry3d/GbObject3D.h> -#include "Grid3D.h" #include "Block3D.h" +#include "Grid3D.h" +#include <geometry3d/GbObject3D.h> - -RefineCrossAndInsideGbObjectBlockVisitor::RefineCrossAndInsideGbObjectBlockVisitor() -: Block3DVisitor() -{ -} +RefineCrossAndInsideGbObjectBlockVisitor::RefineCrossAndInsideGbObjectBlockVisitor() : Block3DVisitor() {} ////////////////////////////////////////////////////////////////////////// -RefineCrossAndInsideGbObjectBlockVisitor::RefineCrossAndInsideGbObjectBlockVisitor(SPtr<GbObject3D> geoObject, int refineLevel) - : Block3DVisitor(0,refineLevel-1), geoObject(geoObject) +RefineCrossAndInsideGbObjectBlockVisitor::RefineCrossAndInsideGbObjectBlockVisitor(SPtr<GbObject3D> geoObject, + int refineLevel) + : Block3DVisitor(0, refineLevel - 1), geoObject(geoObject) { - } ////////////////////////////////////////////////////////////////////////// -RefineCrossAndInsideGbObjectBlockVisitor::~RefineCrossAndInsideGbObjectBlockVisitor() -= default; +RefineCrossAndInsideGbObjectBlockVisitor::~RefineCrossAndInsideGbObjectBlockVisitor() = default; ////////////////////////////////////////////////////////////////////////// void RefineCrossAndInsideGbObjectBlockVisitor::visit(const SPtr<Grid3D> grid, SPtr<Block3D> block) { - int level = block->getLevel(); - if( notActive && block->isNotActive() ) return; - if( level > this->getStopLevel() ) return; + int level = block->getLevel(); + if (notActive && block->isNotActive()) + return; + if (level > this->getStopLevel()) + return; - UbTupleDouble3 coords = grid->getBlockWorldCoordinates(block); - UbTupleDouble3 deltas = grid->getBlockLengths(block); - if(geoObject->isCellInsideOrCuttingGbObject3D( val<1>(coords) - , val<2>(coords) - , val<3>(coords) - , val<1>(coords)+val<1>(deltas) - , val<2>(coords)+val<2>(deltas) - , val<3>(coords)+val<3>(deltas)) ) - { - grid->expandBlock(block->getX1(),block->getX2(),block->getX3(),level); - } + UbTupleDouble3 coords = grid->getBlockWorldCoordinates(block); + UbTupleDouble3 deltas = grid->getBlockLengths(block); + if (geoObject->isCellInsideOrCuttingGbObject3D(val<1>(coords), val<2>(coords), val<3>(coords), + val<1>(coords) + val<1>(deltas), val<2>(coords) + val<2>(deltas), + val<3>(coords) + val<3>(deltas))) { + grid->expandBlock(block->getX1(), block->getX2(), block->getX3(), level); + } - return; + return; } ////////////////////////////////////////////////////////////////////////// diff --git a/src/cpu/VirtualFluidsCore/Visitors/RefineCrossAndInsideGbObjectBlockVisitor.h b/src/cpu/VirtualFluidsCore/Visitors/RefineCrossAndInsideGbObjectBlockVisitor.h index 07e3e3b70b155cc2a94f9dcb4f481cd39975e74e..9696b447c83d658d9c04b5720ea0260a00c0e6db 100644 --- a/src/cpu/VirtualFluidsCore/Visitors/RefineCrossAndInsideGbObjectBlockVisitor.h +++ b/src/cpu/VirtualFluidsCore/Visitors/RefineCrossAndInsideGbObjectBlockVisitor.h @@ -1,8 +1,8 @@ #ifndef RefineCrossAndInsideGbObjectBlockVisitor_H #define RefineCrossAndInsideGbObjectBlockVisitor_H -#include <vector> #include <PointerDefinitions.h> +#include <vector> #include "Block3DVisitor.h" @@ -11,23 +11,24 @@ class Block3D; class GbObject3D; //! \brief Refine blocks on base of bounding box which is defined with <i>geoObject</i> -//! \details The class uses a geometry object for define a bounding box. Inside and across this bounding box will be grid on block basis refinement. -//! \author K. Kucher +//! \details The class uses a geometry object for define a bounding box. Inside and across this bounding box will be +//! grid on block basis refinement. \author K. Kucher class RefineCrossAndInsideGbObjectBlockVisitor : public Block3DVisitor { public: - //! A default constructor - RefineCrossAndInsideGbObjectBlockVisitor(); - //! A constructor - //! \param geoObject a smart pointer to bounding box - //! \param refineLevel an integer for refine on this level - RefineCrossAndInsideGbObjectBlockVisitor(SPtr<GbObject3D> geoObject, int refineLevel); - ~RefineCrossAndInsideGbObjectBlockVisitor() override; + //! A default constructor + RefineCrossAndInsideGbObjectBlockVisitor(); + //! A constructor + //! \param geoObject a smart pointer to bounding box + //! \param refineLevel an integer for refine on this level + RefineCrossAndInsideGbObjectBlockVisitor(SPtr<GbObject3D> geoObject, int refineLevel); + ~RefineCrossAndInsideGbObjectBlockVisitor() override; + + void visit(SPtr<Grid3D> grid, SPtr<Block3D> block) override; - void visit(SPtr<Grid3D> grid, SPtr<Block3D> block) override; protected: SPtr<GbObject3D> geoObject; - bool notActive{true}; + bool notActive{ true }; }; -#endif +#endif diff --git a/src/cpu/VirtualFluidsCore/Visitors/RefineCrossAndInsideGbObjectHelper.cpp b/src/cpu/VirtualFluidsCore/Visitors/RefineCrossAndInsideGbObjectHelper.cpp index 912a551baebf49dcde72c642cb0010f68800bd3a..14ea2b073e43065d31cecc8b2893503d7fc0ed60 100644 --- a/src/cpu/VirtualFluidsCore/Visitors/RefineCrossAndInsideGbObjectHelper.cpp +++ b/src/cpu/VirtualFluidsCore/Visitors/RefineCrossAndInsideGbObjectHelper.cpp @@ -1,77 +1,70 @@ #include "RefineCrossAndInsideGbObjectHelper.h" -#include "RefineCrossAndInsideGbObjectBlockVisitor.h" -#include "RatioBlockVisitor.h" -#include "RatioSmoothBlockVisitor.h" #include "CheckRatioBlockVisitor.h" +#include "Communicator.h" #include "OverlapBlockVisitor.h" +#include "RatioBlockVisitor.h" +#include "RatioSmoothBlockVisitor.h" +#include "RefineCrossAndInsideGbObjectBlockVisitor.h" #include "SetInterpolationDirsBlockVisitor.h" #include <D3Q27System.h> -#include "Communicator.h" -#include <Grid3D.h> #include <GbObject3D.h> +#include <Grid3D.h> - -RefineCrossAndInsideGbObjectHelper::RefineCrossAndInsideGbObjectHelper(SPtr<Grid3D> grid, int maxRefineLevel, SPtr<Communicator> comm) : - grid(grid), - maxRefineLevel(maxRefineLevel), - comm(comm) +RefineCrossAndInsideGbObjectHelper::RefineCrossAndInsideGbObjectHelper(SPtr<Grid3D> grid, int maxRefineLevel, + SPtr<Communicator> comm) + : grid(grid), maxRefineLevel(maxRefineLevel), comm(comm) { } ////////////////////////////////////////////////////////////////////////// -RefineCrossAndInsideGbObjectHelper::~RefineCrossAndInsideGbObjectHelper(void) -= default; +RefineCrossAndInsideGbObjectHelper::~RefineCrossAndInsideGbObjectHelper(void) = default; ////////////////////////////////////////////////////////////////////////// void RefineCrossAndInsideGbObjectHelper::refine() { - UBLOG(logDEBUG5,"RefineCrossAndInsideGbObjectHelper: refine - start"); - - if (comm->isRoot()) - { - int size = (int)objects.size(); + UBLOG(logDEBUG5, "RefineCrossAndInsideGbObjectHelper: refine - start"); - for (int i = 0; i<size; i++) - { - RefineCrossAndInsideGbObjectBlockVisitor refVisitor(objects[i], levels[i]); - grid->accept(refVisitor); - } + if (comm->isRoot()) { + int size = (int)objects.size(); - //RatioBlockVisitor ratioVisitor(maxRefineLevel); - //grid->accept(ratioVisitor); + for (int i = 0; i < size; i++) { + RefineCrossAndInsideGbObjectBlockVisitor refVisitor(objects[i], levels[i]); + grid->accept(refVisitor); + } - //RatioSmoothBlockVisitor ratioSmoothVisitor(maxRefineLevel); - //grid->accept(ratioSmoothVisitor); + // RatioBlockVisitor ratioVisitor(maxRefineLevel); + // grid->accept(ratioVisitor); - RatioBlockVisitor ratioVisitor(maxRefineLevel); - CheckRatioBlockVisitor checkRatio(maxRefineLevel); - int count = 0; + // RatioSmoothBlockVisitor ratioSmoothVisitor(maxRefineLevel); + // grid->accept(ratioSmoothVisitor); - do { - grid->accept(ratioVisitor); - checkRatio.resetState(); - grid->accept(checkRatio); - UBLOG(logINFO, "count = "<<count++<<" state = "<<checkRatio.getState()); - } while (!checkRatio.getState()); + RatioBlockVisitor ratioVisitor(maxRefineLevel); + CheckRatioBlockVisitor checkRatio(maxRefineLevel); + int count = 0; + do { + grid->accept(ratioVisitor); + checkRatio.resetState(); + grid->accept(checkRatio); + UBLOG(logINFO, "count = " << count++ << " state = " << checkRatio.getState()); + } while (!checkRatio.getState()); - OverlapBlockVisitor overlapVisitor(maxRefineLevel, false); - grid->accept(overlapVisitor); - } + OverlapBlockVisitor overlapVisitor(maxRefineLevel, false); + grid->accept(overlapVisitor); + } - grid->updateDistributedBlocks(comm); + grid->updateDistributedBlocks(comm); - std::vector<int> dirs; + std::vector<int> dirs; - for (int i=D3Q27System::E; i<D3Q27System::ENDDIR; i++) - { - dirs.push_back(i); - } - SetInterpolationDirsBlockVisitor interDirsVisitor(dirs); - grid->accept(interDirsVisitor); - UBLOG(logDEBUG5,"RefineCrossAndInsideGbObjectHelper: refine - end"); + for (int i = D3Q27System::E; i < D3Q27System::ENDDIR; i++) { + dirs.push_back(i); + } + SetInterpolationDirsBlockVisitor interDirsVisitor(dirs); + grid->accept(interDirsVisitor); + UBLOG(logDEBUG5, "RefineCrossAndInsideGbObjectHelper: refine - end"); } ////////////////////////////////////////////////////////////////////////// -void RefineCrossAndInsideGbObjectHelper::addGbObject( SPtr<GbObject3D> object, int refineLevel ) +void RefineCrossAndInsideGbObjectHelper::addGbObject(SPtr<GbObject3D> object, int refineLevel) { - objects.push_back(object); - levels.push_back(refineLevel); + objects.push_back(object); + levels.push_back(refineLevel); } diff --git a/src/cpu/VirtualFluidsCore/Visitors/RefineCrossAndInsideGbObjectHelper.h b/src/cpu/VirtualFluidsCore/Visitors/RefineCrossAndInsideGbObjectHelper.h index c7ea0b3bd7fbec86437077b8ad6b206b3305f3af..fd1fefe3d1e522d5fd3e60a97785d94590247bb0 100644 --- a/src/cpu/VirtualFluidsCore/Visitors/RefineCrossAndInsideGbObjectHelper.h +++ b/src/cpu/VirtualFluidsCore/Visitors/RefineCrossAndInsideGbObjectHelper.h @@ -1,8 +1,8 @@ #ifndef RefineCrossAndInsideGbObjectHelper_H #define RefineCrossAndInsideGbObjectHelper_H -#include <vector> #include <PointerDefinitions.h> +#include <vector> class Communicator; class Grid3D; @@ -14,23 +14,24 @@ class GbObject3D; class RefineCrossAndInsideGbObjectHelper { public: - //! Constructor - //! \param grid a smart pointer to the grid object - //! \param maxRefineLevel an integer for maximal refinement level - RefineCrossAndInsideGbObjectHelper(SPtr<Grid3D> grid, int maxRefineLevel, SPtr<Communicator> comm); - virtual ~RefineCrossAndInsideGbObjectHelper(); - //! add geometric object - //! \param object a smart pointer to bounding box - //! \param refineLevel a value of refinement level for corresponding bounding box - void addGbObject(SPtr<GbObject3D> object, int refineLevel); - //! start refinement - void refine(); + //! Constructor + //! \param grid a smart pointer to the grid object + //! \param maxRefineLevel an integer for maximal refinement level + RefineCrossAndInsideGbObjectHelper(SPtr<Grid3D> grid, int maxRefineLevel, SPtr<Communicator> comm); + virtual ~RefineCrossAndInsideGbObjectHelper(); + //! add geometric object + //! \param object a smart pointer to bounding box + //! \param refineLevel a value of refinement level for corresponding bounding box + void addGbObject(SPtr<GbObject3D> object, int refineLevel); + //! start refinement + void refine(); + private: SPtr<Grid3D> grid; - std::vector<SPtr<GbObject3D> > objects; - std::vector<int> levels; - int maxRefineLevel; - SPtr<Communicator> comm; + std::vector<SPtr<GbObject3D>> objects; + std::vector<int> levels; + int maxRefineLevel; + SPtr<Communicator> comm; }; -#endif +#endif diff --git a/src/cpu/VirtualFluidsCore/Visitors/RefineInterGbObjectsVisitor.cpp b/src/cpu/VirtualFluidsCore/Visitors/RefineInterGbObjectsVisitor.cpp index f7b2b208d9a72a65b0b4506968737cf1e784d03f..7fa6a6283c1a97d07f55405ad3b00af55f1d7690 100644 --- a/src/cpu/VirtualFluidsCore/Visitors/RefineInterGbObjectsVisitor.cpp +++ b/src/cpu/VirtualFluidsCore/Visitors/RefineInterGbObjectsVisitor.cpp @@ -1,68 +1,65 @@ #include "RefineInterGbObjectsVisitor.h" -#include <geometry3d/GbObject3D.h> -#include "Grid3D.h" #include "Block3D.h" +#include "Grid3D.h" +#include <geometry3d/GbObject3D.h> - -RefineInterGbObjectsBlockVisitor::RefineInterGbObjectsBlockVisitor() - : Block3DVisitor(-1, -1) -{ -} +RefineInterGbObjectsBlockVisitor::RefineInterGbObjectsBlockVisitor() : Block3DVisitor(-1, -1) {} ////////////////////////////////////////////////////////////////////////// -RefineInterGbObjectsBlockVisitor::RefineInterGbObjectsBlockVisitor(SPtr<GbObject3D> includeGbObject3D, SPtr<GbObject3D> excludeGbObject3D, int startlevel, int stoplevel) - : Block3DVisitor(startlevel, stoplevel) +RefineInterGbObjectsBlockVisitor::RefineInterGbObjectsBlockVisitor(SPtr<GbObject3D> includeGbObject3D, + SPtr<GbObject3D> excludeGbObject3D, int startlevel, + int stoplevel) + : Block3DVisitor(startlevel, stoplevel) { - this->includeGbObjects3D.push_back(includeGbObject3D); - this->excludeGbObjects3D.push_back(excludeGbObject3D); + this->includeGbObjects3D.push_back(includeGbObject3D); + this->excludeGbObjects3D.push_back(excludeGbObject3D); } ////////////////////////////////////////////////////////////////////////// -RefineInterGbObjectsBlockVisitor::RefineInterGbObjectsBlockVisitor(std::vector<SPtr<GbObject3D>> includeGbObjects3D, std::vector<SPtr<GbObject3D>> excludeGbObjects3D, int startlevel, int stoplevel) - : Block3DVisitor(startlevel, stoplevel) +RefineInterGbObjectsBlockVisitor::RefineInterGbObjectsBlockVisitor(std::vector<SPtr<GbObject3D>> includeGbObjects3D, + std::vector<SPtr<GbObject3D>> excludeGbObjects3D, + int startlevel, int stoplevel) + : Block3DVisitor(startlevel, stoplevel) { - this->includeGbObjects3D = includeGbObjects3D; - this->excludeGbObjects3D = excludeGbObjects3D; + this->includeGbObjects3D = includeGbObjects3D; + this->excludeGbObjects3D = excludeGbObjects3D; } ////////////////////////////////////////////////////////////////////////// void RefineInterGbObjectsBlockVisitor::visit(SPtr<Grid3D> grid, SPtr<Block3D> block) { - UbTupleDouble3 coords = grid->getBlockWorldCoordinates(block); - UbTupleDouble3 delta = grid->getBlockLengths(block); + UbTupleDouble3 coords = grid->getBlockWorldCoordinates(block); + UbTupleDouble3 delta = grid->getBlockLengths(block); - double cellMinX1 = val<1>(coords); - double cellMinX2 = val<2>(coords); - double cellMinX3 = val<3>(coords); - double cellMaxX1 = val<1>(coords)+val<1>(delta); - double cellMaxX2 = val<2>(coords)+val<2>(delta); - double cellMaxX3 = val<3>(coords)+val<3>(delta); + double cellMinX1 = val<1>(coords); + double cellMinX2 = val<2>(coords); + double cellMinX3 = val<3>(coords); + double cellMaxX1 = val<1>(coords) + val<1>(delta); + double cellMaxX2 = val<2>(coords) + val<2>(delta); + double cellMaxX3 = val<3>(coords) + val<3>(delta); - bool insideInclude = false; - for(size_t i=0; i<includeGbObjects3D.size(); i++) - { - if( includeGbObjects3D[i]->isCellInsideOrCuttingGbObject3D(cellMinX1,cellMinX2,cellMinX3,cellMaxX1,cellMaxX2,cellMaxX3) ) - { - insideInclude = true; - break; - } - } + bool insideInclude = false; + for (size_t i = 0; i < includeGbObjects3D.size(); i++) { + if (includeGbObjects3D[i]->isCellInsideOrCuttingGbObject3D(cellMinX1, cellMinX2, cellMinX3, cellMaxX1, + cellMaxX2, cellMaxX3)) { + insideInclude = true; + break; + } + } - bool insideExclude = false; - for(size_t e=0; e<excludeGbObjects3D.size(); e++) - { - if(excludeGbObjects3D[e]->isCellInsideGbObject3D(cellMinX1, cellMinX2, cellMinX3, cellMaxX1, cellMaxX2, cellMaxX3)) - { - insideExclude = true; - break; - } - } + bool insideExclude = false; + for (size_t e = 0; e < excludeGbObjects3D.size(); e++) { + if (excludeGbObjects3D[e]->isCellInsideGbObject3D(cellMinX1, cellMinX2, cellMinX3, cellMaxX1, cellMaxX2, + cellMaxX3)) { + insideExclude = true; + break; + } + } - if(insideInclude && !insideExclude) - { - int ix1, ix2, ix3, level; - ix1 = block->getX1(); - ix2 = block->getX2(); - ix3 = block->getX3(); - level = block->getLevel(); - grid->expandBlock(ix1,ix2,ix3,level); - } + if (insideInclude && !insideExclude) { + int ix1, ix2, ix3, level; + ix1 = block->getX1(); + ix2 = block->getX2(); + ix3 = block->getX3(); + level = block->getLevel(); + grid->expandBlock(ix1, ix2, ix3, level); + } } diff --git a/src/cpu/VirtualFluidsCore/Visitors/RefineInterGbObjectsVisitor.h b/src/cpu/VirtualFluidsCore/Visitors/RefineInterGbObjectsVisitor.h index ed0a850188f2f885ff78394946bd2ea7301badf6..6bcf41e041b03f88dbcfd3c27790c1b45685975c 100644 --- a/src/cpu/VirtualFluidsCore/Visitors/RefineInterGbObjectsVisitor.h +++ b/src/cpu/VirtualFluidsCore/Visitors/RefineInterGbObjectsVisitor.h @@ -1,8 +1,8 @@ #ifndef RefineInterGbObjectsVisirtor_H #define RefineInterGbObjectsVisirtor_H -#include <vector> #include <PointerDefinitions.h> +#include <vector> #include "Block3DVisitor.h" @@ -14,14 +14,16 @@ class GbObject3D; class RefineInterGbObjectsBlockVisitor : public Block3DVisitor { public: - RefineInterGbObjectsBlockVisitor(); - RefineInterGbObjectsBlockVisitor(SPtr<GbObject3D> includeGbObject3D, SPtr<GbObject3D> excludeGbObject3D, int startlevel, int stoplevel); - RefineInterGbObjectsBlockVisitor(std::vector<SPtr<GbObject3D> > includeGbObjects3D, std::vector<SPtr<GbObject3D> > excludeGbObjects3D, int startlevel, int stoplevel); - void visit(SPtr<Grid3D> grid, SPtr<Block3D> block) override; + RefineInterGbObjectsBlockVisitor(); + RefineInterGbObjectsBlockVisitor(SPtr<GbObject3D> includeGbObject3D, SPtr<GbObject3D> excludeGbObject3D, + int startlevel, int stoplevel); + RefineInterGbObjectsBlockVisitor(std::vector<SPtr<GbObject3D>> includeGbObjects3D, + std::vector<SPtr<GbObject3D>> excludeGbObjects3D, int startlevel, int stoplevel); + void visit(SPtr<Grid3D> grid, SPtr<Block3D> block) override; private: - std::vector<SPtr<GbObject3D> > includeGbObjects3D; - std::vector<SPtr<GbObject3D> > excludeGbObjects3D; + std::vector<SPtr<GbObject3D>> includeGbObjects3D; + std::vector<SPtr<GbObject3D>> excludeGbObjects3D; }; -#endif //RefineInterGbObjectsVisirtor_H +#endif // RefineInterGbObjectsVisirtor_H diff --git a/src/cpu/VirtualFluidsCore/Visitors/RenumberBlockVisitor.cpp b/src/cpu/VirtualFluidsCore/Visitors/RenumberBlockVisitor.cpp index 65def194033424645adcba7f47373fb6713e5fd6..538fd95118b0c07069ba854c2fbb8264713907d3 100644 --- a/src/cpu/VirtualFluidsCore/Visitors/RenumberBlockVisitor.cpp +++ b/src/cpu/VirtualFluidsCore/Visitors/RenumberBlockVisitor.cpp @@ -1,22 +1,17 @@ #include "RenumberBlockVisitor.h" +#include "Block3D.h" +#include "Grid3D.h" #include "Grid3DSystem.h" #include "LBMSystem.h" -#include "Grid3D.h" -#include "Block3D.h" int RenumberBlockVisitor::counter = 0; -RenumberBlockVisitor::RenumberBlockVisitor() : -Block3DVisitor(0, Grid3DSystem::MAXLEVEL) -{ - -} +RenumberBlockVisitor::RenumberBlockVisitor() : Block3DVisitor(0, Grid3DSystem::MAXLEVEL) {} ////////////////////////////////////////////////////////////////////////// void RenumberBlockVisitor::visit(SPtr<Grid3D> grid, SPtr<Block3D> block) { - block->setGlobalID(counter); - Grid3D::BlockIDMap blockIdMap = grid->getBlockIDs(); - blockIdMap.insert(std::make_pair(counter, block)); - counter++; + block->setGlobalID(counter); + Grid3D::BlockIDMap blockIdMap = grid->getBlockIDs(); + blockIdMap.insert(std::make_pair(counter, block)); + counter++; } - diff --git a/src/cpu/VirtualFluidsCore/Visitors/RenumberBlockVisitor.h b/src/cpu/VirtualFluidsCore/Visitors/RenumberBlockVisitor.h index 8740395482cb7849db37bc29dc2a478f0c2dbd86..e0ceb4a74bae6b74452f112417a15e632ae109e2 100644 --- a/src/cpu/VirtualFluidsCore/Visitors/RenumberBlockVisitor.h +++ b/src/cpu/VirtualFluidsCore/Visitors/RenumberBlockVisitor.h @@ -1,9 +1,9 @@ /** -* @file RenumberBlockVisitor.h -* @brief Visitor class which renumber blocks. -* @author Konstantin Kutscher -* @date 06.06.2011 -*/ + * @file RenumberBlockVisitor.h + * @brief Visitor class which renumber blocks. + * @author Konstantin Kutscher + * @date 06.06.2011 + */ #ifndef RenumberBlockVisitor_h #define RenumberBlockVisitor_h @@ -14,19 +14,19 @@ class Grid3D; class Block3D; //! \brief Visitor class which renumber blocks. -//! \details Visitor class which renumber blocks. -//! \author Konstantin Kutscher +//! \details Visitor class which renumber blocks. +//! \author Konstantin Kutscher class RenumberBlockVisitor : public Block3DVisitor { public: - RenumberBlockVisitor(); + RenumberBlockVisitor(); - ~RenumberBlockVisitor() override = default; + ~RenumberBlockVisitor() override = default; - void visit(SPtr<Grid3D> grid, SPtr<Block3D> block) override; + void visit(SPtr<Grid3D> grid, SPtr<Block3D> block) override; private: - static int counter; + static int counter; }; #endif diff --git a/src/cpu/VirtualFluidsCore/Visitors/RenumberGridVisitor.cpp b/src/cpu/VirtualFluidsCore/Visitors/RenumberGridVisitor.cpp index 1d01aac238171af7028c8e463be8768e5598a0ce..433e08cea74fcf7c67df0ee0119b34036e19de8c 100644 --- a/src/cpu/VirtualFluidsCore/Visitors/RenumberGridVisitor.cpp +++ b/src/cpu/VirtualFluidsCore/Visitors/RenumberGridVisitor.cpp @@ -1,49 +1,42 @@ #include "RenumberGridVisitor.h" -#include "Grid3DSystem.h" -#include "Grid3D.h" #include "Block3D.h" +#include "Grid3D.h" +#include "Grid3DSystem.h" //#include <mpi.h> -RenumberGridVisitor::RenumberGridVisitor(SPtr<Communicator> com) - : comm(com) -{ -} +RenumberGridVisitor::RenumberGridVisitor(SPtr<Communicator> com) : comm(com) {} ////////////////////////////////////////////////////////////////////////// void RenumberGridVisitor::visit(SPtr<Grid3D> grid) { - int counter = 0; + int counter = 0; - //UBLOG(logDEBUG5, "RenumberGridVisitor::visit() - start"); - std::vector<SPtr<Block3D>> blocks; -// int gridRank = grid->getRank(); - int size; - //MPI_Comm_size(MPI_COMM_WORLD, &size); - size = comm->getNumberOfProcesses(); + // UBLOG(logDEBUG5, "RenumberGridVisitor::visit() - start"); + std::vector<SPtr<Block3D>> blocks; + // int gridRank = grid->getRank(); + int size; + // MPI_Comm_size(MPI_COMM_WORLD, &size); + size = comm->getNumberOfProcesses(); - int minInitLevel = grid->getCoarsestInitializedLevel(); - int maxInitLevel = grid->getFinestInitializedLevel(); + int minInitLevel = grid->getCoarsestInitializedLevel(); + int maxInitLevel = grid->getFinestInitializedLevel(); - Grid3D::BlockIDMap& blockIdMap = grid->getBlockIDs(); - blockIdMap.clear(); + Grid3D::BlockIDMap &blockIdMap = grid->getBlockIDs(); + blockIdMap.clear(); - for(int rank = 0; rank < size; rank++) - { - for (int level = minInitLevel; level <= maxInitLevel; level++) - { - std::vector<SPtr<Block3D>> blockVector; - grid->getBlocks(level, blockVector); - for (SPtr<Block3D> block : blockVector) - { - if(block->getRank() == rank) - { - block->setGlobalID(counter); - blockIdMap.insert(std::make_pair(counter, block)); - counter++; + for (int rank = 0; rank < size; rank++) { + for (int level = minInitLevel; level <= maxInitLevel; level++) { + std::vector<SPtr<Block3D>> blockVector; + grid->getBlocks(level, blockVector); + for (SPtr<Block3D> block : blockVector) { + if (block->getRank() == rank) { + block->setGlobalID(counter); + blockIdMap.insert(std::make_pair(counter, block)); + counter++; + } } - } - } - } + } + } - //UBLOG(logDEBUG5, "RenumberGridVisitor::visit() - end"); + // UBLOG(logDEBUG5, "RenumberGridVisitor::visit() - end"); } diff --git a/src/cpu/VirtualFluidsCore/Visitors/RenumberGridVisitor.h b/src/cpu/VirtualFluidsCore/Visitors/RenumberGridVisitor.h index f4b27b58e5d48324fa9d198e8453a8e500d9a4fe..eabb0cafd06af9588b87dc479f4684393e6afb5c 100644 --- a/src/cpu/VirtualFluidsCore/Visitors/RenumberGridVisitor.h +++ b/src/cpu/VirtualFluidsCore/Visitors/RenumberGridVisitor.h @@ -1,33 +1,33 @@ /** -* @file RenumberGridVisitor.h -* @brief Visitor class which renumber blocks. -* @author Konstantin Kutscher -* @date 06.06.2011 -*/ + * @file RenumberGridVisitor.h + * @brief Visitor class which renumber blocks. + * @author Konstantin Kutscher + * @date 06.06.2011 + */ #ifndef RenumberGridVisitor_h #define RenumberGridVisitor_h -#include "Grid3DVisitor.h" #include "Communicator.h" +#include "Grid3DVisitor.h" class Grid3D; //! \brief Visitor class which renumber blocks in order: rank->level. -//! \details Visitor class which renumber blocks. -//! \author Konstantin Kutscher +//! \details Visitor class which renumber blocks. +//! \author Konstantin Kutscher class RenumberGridVisitor : public Grid3DVisitor { public: - RenumberGridVisitor(SPtr<Communicator> com); + RenumberGridVisitor(SPtr<Communicator> com); - ~RenumberGridVisitor() override = default; + ~RenumberGridVisitor() override = default; - void visit(SPtr<Grid3D> grid) override; + void visit(SPtr<Grid3D> grid) override; private: SPtr<Communicator> comm; -// static int counter; + // static int counter; }; #endif diff --git a/src/cpu/VirtualFluidsCore/Visitors/SetBcBlocksBlockVisitor.cpp b/src/cpu/VirtualFluidsCore/Visitors/SetBcBlocksBlockVisitor.cpp index 3ef67f2892e7ccb69bce6700c8658e6b84c49791..bbccaa785583fdc810865337af46fca8a9872a65 100644 --- a/src/cpu/VirtualFluidsCore/Visitors/SetBcBlocksBlockVisitor.cpp +++ b/src/cpu/VirtualFluidsCore/Visitors/SetBcBlocksBlockVisitor.cpp @@ -1,28 +1,28 @@ //======================================================================================= -// ____ ____ __ ______ __________ __ __ __ __ -// \ \ | | | | | _ \ |___ ___| | | | | / \ | | -// \ \ | | | | | |_) | | | | | | | / \ | | -// \ \ | | | | | _ / | | | | | | / /\ \ | | -// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ -// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| -// \ \ | | ________________________________________________________________ -// \ \ | | | ______________________________________________________________| -// \ \| | | | __ __ __ __ ______ _______ -// \ | | |_____ | | | | | | | | | _ \ / _____) -// \ | | _____| | | | | | | | | | | \ \ \_______ +// ____ ____ __ ______ __________ __ __ __ __ +// \ \ | | | | | _ \ |___ ___| | | | | / \ | | +// \ \ | | | | | |_) | | | | | | | / \ | | +// \ \ | | | | | _ / | | | | | | / /\ \ | | +// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ +// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| +// \ \ | | ________________________________________________________________ +// \ \ | | | ______________________________________________________________| +// \ \| | | | __ __ __ __ ______ _______ +// \ | | |_____ | | | | | | | | | _ \ / _____) +// \ | | _____| | | | | | | | | | | \ \ \_______ // \ | | | | |_____ | \_/ | | | | |_/ / _____ | -// \ _____| |__| |________| \_______/ |__| |______/ (_______/ +// \ _____| |__| |________| \_______/ |__| |______/ (_______/ // -// This file is part of VirtualFluids. VirtualFluids is free software: you can +// This file is part of VirtualFluids. VirtualFluids is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of +// License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. -// -// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// +// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License along // with VirtualFluids (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>. // @@ -33,25 +33,21 @@ #include "SetBcBlocksBlockVisitor.h" -#include "Interactor3D.h" -#include "Grid3DSystem.h" -#include "Grid3D.h" #include "Block3D.h" +#include "Grid3D.h" +#include "Grid3DSystem.h" +#include "Interactor3D.h" -SetBcBlocksBlockVisitor::SetBcBlocksBlockVisitor(SPtr<Interactor3D> interactor) : - Block3DVisitor(0, Grid3DSystem::MAXLEVEL), interactor(interactor) +SetBcBlocksBlockVisitor::SetBcBlocksBlockVisitor(SPtr<Interactor3D> interactor) + : Block3DVisitor(0, Grid3DSystem::MAXLEVEL), interactor(interactor) { - } void SetBcBlocksBlockVisitor::visit(SPtr<Grid3D> grid, SPtr<Block3D> block) { - if(block->getRank() == grid->getRank()) - { - if (block->isActive()) - { - interactor->setBCBlock(block); - } - } + if (block->getRank() == grid->getRank()) { + if (block->isActive()) { + interactor->setBCBlock(block); + } + } } - diff --git a/src/cpu/VirtualFluidsCore/Visitors/SetBcBlocksBlockVisitor.h b/src/cpu/VirtualFluidsCore/Visitors/SetBcBlocksBlockVisitor.h index 5db362a3b9f41ec59606374a7761da934b8f8f10..feda683107e69476e1a60bae3ba1d1b2d235676e 100644 --- a/src/cpu/VirtualFluidsCore/Visitors/SetBcBlocksBlockVisitor.h +++ b/src/cpu/VirtualFluidsCore/Visitors/SetBcBlocksBlockVisitor.h @@ -1,28 +1,28 @@ //======================================================================================= -// ____ ____ __ ______ __________ __ __ __ __ -// \ \ | | | | | _ \ |___ ___| | | | | / \ | | -// \ \ | | | | | |_) | | | | | | | / \ | | -// \ \ | | | | | _ / | | | | | | / /\ \ | | -// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ -// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| -// \ \ | | ________________________________________________________________ -// \ \ | | | ______________________________________________________________| -// \ \| | | | __ __ __ __ ______ _______ -// \ | | |_____ | | | | | | | | | _ \ / _____) -// \ | | _____| | | | | | | | | | | \ \ \_______ +// ____ ____ __ ______ __________ __ __ __ __ +// \ \ | | | | | _ \ |___ ___| | | | | / \ | | +// \ \ | | | | | |_) | | | | | | | / \ | | +// \ \ | | | | | _ / | | | | | | / /\ \ | | +// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ +// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| +// \ \ | | ________________________________________________________________ +// \ \ | | | ______________________________________________________________| +// \ \| | | | __ __ __ __ ______ _______ +// \ | | |_____ | | | | | | | | | _ \ / _____) +// \ | | _____| | | | | | | | | | | \ \ \_______ // \ | | | | |_____ | \_/ | | | | |_/ / _____ | -// \ _____| |__| |________| \_______/ |__| |______/ (_______/ +// \ _____| |__| |________| \_______/ |__| |______/ (_______/ // -// This file is part of VirtualFluids. VirtualFluids is free software: you can +// This file is part of VirtualFluids. VirtualFluids is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of +// License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. -// -// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// +// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License along // with VirtualFluids (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>. // @@ -46,15 +46,12 @@ class Interactor3D; class SetBcBlocksBlockVisitor : public Block3DVisitor { public: - SetBcBlocksBlockVisitor(SPtr<Interactor3D> interactor); - ~SetBcBlocksBlockVisitor() override = default; + SetBcBlocksBlockVisitor(SPtr<Interactor3D> interactor); + ~SetBcBlocksBlockVisitor() override = default; - void visit(SPtr<Grid3D> grid, SPtr<Block3D> block) override; + void visit(SPtr<Grid3D> grid, SPtr<Block3D> block) override; private: - SPtr<Interactor3D> interactor; + SPtr<Interactor3D> interactor; }; #endif // SetBcBlocksBlockVisitor_h__ - - - diff --git a/src/cpu/VirtualFluidsCore/Visitors/SetConnectorsBlockVisitor.cpp b/src/cpu/VirtualFluidsCore/Visitors/SetConnectorsBlockVisitor.cpp index c6f1f9608a34ea25e9d3ebd524050a9ff60b4930..067b93bbaa19731e15587682bb057d6597211d85 100644 --- a/src/cpu/VirtualFluidsCore/Visitors/SetConnectorsBlockVisitor.cpp +++ b/src/cpu/VirtualFluidsCore/Visitors/SetConnectorsBlockVisitor.cpp @@ -1,28 +1,28 @@ //======================================================================================= -// ____ ____ __ ______ __________ __ __ __ __ -// \ \ | | | | | _ \ |___ ___| | | | | / \ | | -// \ \ | | | | | |_) | | | | | | | / \ | | -// \ \ | | | | | _ / | | | | | | / /\ \ | | -// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ -// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| -// \ \ | | ________________________________________________________________ -// \ \ | | | ______________________________________________________________| -// \ \| | | | __ __ __ __ ______ _______ -// \ | | |_____ | | | | | | | | | _ \ / _____) -// \ | | _____| | | | | | | | | | | \ \ \_______ +// ____ ____ __ ______ __________ __ __ __ __ +// \ \ | | | | | _ \ |___ ___| | | | | / \ | | +// \ \ | | | | | |_) | | | | | | | / \ | | +// \ \ | | | | | _ / | | | | | | / /\ \ | | +// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ +// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| +// \ \ | | ________________________________________________________________ +// \ \ | | | ______________________________________________________________| +// \ \| | | | __ __ __ __ ______ _______ +// \ | | |_____ | | | | | | | | | _ \ / _____) +// \ | | _____| | | | | | | | | | | \ \ \_______ // \ | | | | |_____ | \_/ | | | | |_/ / _____ | -// \ _____| |__| |________| \_______/ |__| |______/ (_______/ +// \ _____| |__| |________| \_______/ |__| |______/ (_______/ // -// This file is part of VirtualFluids. VirtualFluids is free software: you can +// This file is part of VirtualFluids. VirtualFluids is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of +// License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. -// -// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// +// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License along // with VirtualFluids (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>. // @@ -32,487 +32,484 @@ //======================================================================================= #include "SetConnectorsBlockVisitor.h" -#include "D3Q27ETFullDirectConnector.h" -#include "D3Q27ETFullVectorConnector.h" #include "D3Q27ETCFOffVectorConnector.h" #include "D3Q27ETFCOffVectorConnector.h" +#include "D3Q27ETFullDirectConnector.h" +#include "D3Q27ETFullVectorConnector.h" #include "Grid3DSystem.h" #include <basics/transmitter/TbTransmitterLocal.h> #include "Communicator.h" #include "InterpolationProcessor.h" -SetConnectorsBlockVisitor::SetConnectorsBlockVisitor(SPtr<Communicator> comm, bool fullConnector, int dirs, - LBMReal nue, InterpolationProcessorPtr iProcessor) : -Block3DVisitor(0, Grid3DSystem::MAXLEVEL), - comm(comm), - fullConnector(fullConnector), - dirs(dirs), - nue(nue), - iProcessor(iProcessor) +SetConnectorsBlockVisitor::SetConnectorsBlockVisitor(SPtr<Communicator> comm, bool fullConnector, int dirs, LBMReal nue, + InterpolationProcessorPtr iProcessor) + : Block3DVisitor(0, Grid3DSystem::MAXLEVEL), comm(comm), fullConnector(fullConnector), dirs(dirs), nue(nue), + iProcessor(iProcessor) { } ////////////////////////////////////////////////////////////////////////// -SetConnectorsBlockVisitor::~SetConnectorsBlockVisitor(void) -= default; +SetConnectorsBlockVisitor::~SetConnectorsBlockVisitor(void) = default; ////////////////////////////////////////////////////////////////////////// void SetConnectorsBlockVisitor::visit(SPtr<Grid3D> grid, SPtr<Block3D> block) { - if(!block) return; + if (!block) + return; - UBLOG(logDEBUG5, "D3Q27SetConnectorsBlockVisitor::visit() - start"); - UBLOG(logDEBUG5, block->toString()); + UBLOG(logDEBUG5, "D3Q27SetConnectorsBlockVisitor::visit() - start"); + UBLOG(logDEBUG5, block->toString()); - gridRank = comm->getProcessID(); - grid->setRank(gridRank); + gridRank = comm->getProcessID(); + grid->setRank(gridRank); - setSameLevelConnectors(grid, block); + setSameLevelConnectors(grid, block); - if(grid->getFinestInitializedLevel() > grid->getCoarsestInitializedLevel()) - setInterpolationConnectors(grid, block); + if (grid->getFinestInitializedLevel() > grid->getCoarsestInitializedLevel()) + setInterpolationConnectors(grid, block); - UBLOG(logDEBUG5, "D3Q27SetConnectorsBlockVisitor::visit() - end"); + UBLOG(logDEBUG5, "D3Q27SetConnectorsBlockVisitor::visit() - end"); } ////////////////////////////////////////////////////////////////////////// void SetConnectorsBlockVisitor::setSameLevelConnectors(SPtr<Grid3D> grid, SPtr<Block3D> block) { - UBLOG(logDEBUG5, "D3Q27SetConnectorsBlockVisitor::setSameLevelConnectors() - start"); - int blockRank = block->getRank(); - if (gridRank == blockRank && block->isActive()) - { - block->clearWeight(); - std::vector<SPtr<Block3D>> neighbors; - int ix1 = block->getX1(); - int ix2 = block->getX2(); - int ix3 = block->getX3(); - int level = block->getLevel(); - //grid->getAllNeighbors(ix1, ix2, ix3, level, level, neighbors); - - //if (block->getGlobalID()==2512) - //{ - // int test = 0; - //} - - for( int dir = 0; dir < dirs; dir++) - { - SPtr<Block3D> neighBlock = grid->getNeighborBlock(dir, ix1, ix2, ix3, level); - - if(neighBlock) - { - int neighBlockRank = neighBlock->getRank(); - if(blockRank == neighBlockRank && neighBlock->isActive()) - { - SPtr<Block3DConnector> connector; - connector = SPtr<Block3DConnector>(new D3Q27ETFullDirectConnector( block, neighBlock, dir)); - block->setConnector(connector); - } - else if(blockRank != neighBlockRank && neighBlock->isActive()) - { - setRemoteConnectors(block, neighBlock, dir, fullConnector); - - if(dir >=0 && dir<=5) - { - int weight = block->getWeight(neighBlockRank); - weight++; - block->setWeight(neighBlockRank, weight); - } - } - } - } - - //if (block->getGlobalID()==2794) - //{ - // UBLOG(logINFO, block->toString()); - //} - - int weight = block->getNumberOfLocalConnectorsForSurfaces(); - weight = 6 - weight; - block->addWeightForAll(weight); - } - UBLOG(logDEBUG5, "D3Q27SetConnectorsBlockVisitor::setSameLevelConnectors() - end"); + UBLOG(logDEBUG5, "D3Q27SetConnectorsBlockVisitor::setSameLevelConnectors() - start"); + int blockRank = block->getRank(); + if (gridRank == blockRank && block->isActive()) { + block->clearWeight(); + std::vector<SPtr<Block3D>> neighbors; + int ix1 = block->getX1(); + int ix2 = block->getX2(); + int ix3 = block->getX3(); + int level = block->getLevel(); + // grid->getAllNeighbors(ix1, ix2, ix3, level, level, neighbors); + + // if (block->getGlobalID()==2512) + //{ + // int test = 0; + //} + + for (int dir = 0; dir < dirs; dir++) { + SPtr<Block3D> neighBlock = grid->getNeighborBlock(dir, ix1, ix2, ix3, level); + + if (neighBlock) { + int neighBlockRank = neighBlock->getRank(); + if (blockRank == neighBlockRank && neighBlock->isActive()) { + SPtr<Block3DConnector> connector; + connector = SPtr<Block3DConnector>(new D3Q27ETFullDirectConnector(block, neighBlock, dir)); + block->setConnector(connector); + } else if (blockRank != neighBlockRank && neighBlock->isActive()) { + setRemoteConnectors(block, neighBlock, dir, fullConnector); + + if (dir >= 0 && dir <= 5) { + int weight = block->getWeight(neighBlockRank); + weight++; + block->setWeight(neighBlockRank, weight); + } + } + } + } + + // if (block->getGlobalID()==2794) + //{ + // UBLOG(logINFO, block->toString()); + //} + + int weight = block->getNumberOfLocalConnectorsForSurfaces(); + weight = 6 - weight; + block->addWeightForAll(weight); + } + UBLOG(logDEBUG5, "D3Q27SetConnectorsBlockVisitor::setSameLevelConnectors() - end"); } ////////////////////////////////////////////////////////////////////////// -void SetConnectorsBlockVisitor::setRemoteConnectors(SPtr<Block3D> sblock, SPtr<Block3D> tblock, int dir, bool /*fullConnector*/) +void SetConnectorsBlockVisitor::setRemoteConnectors(SPtr<Block3D> sblock, SPtr<Block3D> tblock, int dir, + bool /*fullConnector*/) { - UBLOG(logDEBUG5, "D3Q27SetConnectorsBlockVisitor::setRemoteConnectors() - start"); - CreateTransmittersHelper helper; - CreateTransmittersHelper::TransmitterPtr sender, receiver; - helper.createTransmitters(sblock, tblock, dir, CreateTransmittersHelper::NONE, sender, receiver, comm, CreateTransmittersHelper::MPI); - - - SPtr<Block3DConnector> connector; - connector = SPtr<Block3DConnector>(new D3Q27ETFullVectorConnector(sblock, sender, receiver, dir)); - sblock->setConnector(connector); - UBLOG(logDEBUG5, "D3Q27SetConnectorsBlockVisitor::setRemoteConnectors() - end"); + UBLOG(logDEBUG5, "D3Q27SetConnectorsBlockVisitor::setRemoteConnectors() - start"); + CreateTransmittersHelper helper; + CreateTransmittersHelper::TransmitterPtr sender, receiver; + helper.createTransmitters(sblock, tblock, dir, CreateTransmittersHelper::NONE, sender, receiver, comm, + CreateTransmittersHelper::MPI); + + SPtr<Block3DConnector> connector; + connector = SPtr<Block3DConnector>(new D3Q27ETFullVectorConnector(sblock, sender, receiver, dir)); + sblock->setConnector(connector); + UBLOG(logDEBUG5, "D3Q27SetConnectorsBlockVisitor::setRemoteConnectors() - end"); } ////////////////////////////////////////////////////////////////////////// void SetConnectorsBlockVisitor::setInterpolationConnectors(SPtr<Grid3D> grid, SPtr<Block3D> block) { - UBLOG(logDEBUG5, "D3Q27SetConnectorsBlockVisitor::setInterpolationConnectors() - start"); -// int blockRank = block->getRank(); -// if (block->getGlobalID()==394) -// { -// int test=0; -// } - - //search for all blocks with different ranks - if (block->hasInterpolationFlagCF() && block->isActive()) - { - int fbx1 = block->getX1() << 1; - int fbx2 = block->getX2() << 1; - int fbx3 = block->getX3() << 1; - int level = block->getLevel() + 1; - - if( block->hasInterpolationFlagCF(D3Q27System::E)) - { - SPtr<Block3D> fblockSW = grid->getBlock(fbx1+1,fbx2,fbx3,level); - SPtr<Block3D> fblockSE = grid->getBlock(fbx1+1,fbx2+1,fbx3,level); - SPtr<Block3D> fblockNW = grid->getBlock(fbx1+1,fbx2,fbx3+1,level); - SPtr<Block3D> fblockNE = grid->getBlock(fbx1+1,fbx2+1,fbx3+1,level); - - setInterpolationConnectors(fblockSW, fblockSE, fblockNW, fblockNE, block, D3Q27System::E); - } - if( block->hasInterpolationFlagCF(D3Q27System::W)) - { - SPtr<Block3D> fblockSW = grid->getBlock(fbx1,fbx2,fbx3,level); - SPtr<Block3D> fblockSE = grid->getBlock(fbx1,fbx2+1,fbx3,level); - SPtr<Block3D> fblockNW = grid->getBlock(fbx1,fbx2,fbx3+1,level); - SPtr<Block3D> fblockNE = grid->getBlock(fbx1,fbx2+1,fbx3+1,level); - - setInterpolationConnectors(fblockSW, fblockSE, fblockNW, fblockNE, block, D3Q27System::W); - } - if( block->hasInterpolationFlagCF(D3Q27System::N)) - { - SPtr<Block3D> fblockSW = grid->getBlock(fbx1,fbx2+1,fbx3,level); - SPtr<Block3D> fblockSE = grid->getBlock(fbx1+1,fbx2+1,fbx3,level); - SPtr<Block3D> fblockNW = grid->getBlock(fbx1,fbx2+1,fbx3+1,level); - SPtr<Block3D> fblockNE = grid->getBlock(fbx1+1,fbx2+1,fbx3+1,level); - - setInterpolationConnectors(fblockSW, fblockSE, fblockNW, fblockNE, block, D3Q27System::N); - } - if( block->hasInterpolationFlagCF(D3Q27System::S)) - { - SPtr<Block3D> fblockSW = grid->getBlock(fbx1,fbx2,fbx3,level); - SPtr<Block3D> fblockSE = grid->getBlock(fbx1+1,fbx2,fbx3,level); - SPtr<Block3D> fblockNW = grid->getBlock(fbx1,fbx2,fbx3+1,level); - SPtr<Block3D> fblockNE = grid->getBlock(fbx1+1,fbx2,fbx3+1,level); - - setInterpolationConnectors(fblockSW, fblockSE, fblockNW, fblockNE, block, D3Q27System::S); - } - if( block->hasInterpolationFlagCF(D3Q27System::T)) - { - SPtr<Block3D> fblockSW = grid->getBlock(fbx1,fbx2,fbx3+1,level); - SPtr<Block3D> fblockSE = grid->getBlock(fbx1+1,fbx2,fbx3+1,level); - SPtr<Block3D> fblockNW = grid->getBlock(fbx1,fbx2+1,fbx3+1,level); - SPtr<Block3D> fblockNE = grid->getBlock(fbx1+1,fbx2+1,fbx3+1,level); - - setInterpolationConnectors(fblockSW, fblockSE, fblockNW, fblockNE, block, D3Q27System::T); - } - if( block->hasInterpolationFlagCF(D3Q27System::B)) - { - SPtr<Block3D> fblockSW = grid->getBlock(fbx1,fbx2,fbx3,level); - SPtr<Block3D> fblockSE = grid->getBlock(fbx1+1,fbx2,fbx3,level); - SPtr<Block3D> fblockNW = grid->getBlock(fbx1,fbx2+1,fbx3,level); - SPtr<Block3D> fblockNE = grid->getBlock(fbx1+1,fbx2+1,fbx3,level); - - setInterpolationConnectors(fblockSW, fblockSE, fblockNW, fblockNE, block, D3Q27System::B); - } - - //////NE-NW-SE-SW - if( block->hasInterpolationFlagCF(D3Q27System::NE)&&!block->hasInterpolationFlagCF(D3Q27System::N) && !block->hasInterpolationFlagCF(D3Q27System::E)) - { - SPtr<Block3D> fblockSW = grid->getBlock(fbx1+1,fbx2+1,fbx3+0,level); - SPtr<Block3D> fblockSE = grid->getBlock(fbx1+1,fbx2+1,fbx3+1,level); - SPtr<Block3D> fblockNW;// = grid->getBlock(fbx1+1, fbx2+1, fbx3+1, level); - SPtr<Block3D> fblockNE;// = grid->getBlock(fbx1+1, fbx2+1, fbx3+1, level); - - setInterpolationConnectors(fblockSW, fblockSE, fblockNW, fblockNE, block, D3Q27System::NE); - } - if( block->hasInterpolationFlagCF(D3Q27System::SW)&& !block->hasInterpolationFlagCF(D3Q27System::W) && !block->hasInterpolationFlagCF(D3Q27System::S)) - { - SPtr<Block3D> fblockSW = grid->getBlock(fbx1,fbx2,fbx3,level); - SPtr<Block3D> fblockSE = grid->getBlock(fbx1,fbx2,fbx3+1,level); - SPtr<Block3D> fblockNW;// = grid->getBlock(fbx1, fbx2, fbx3+1, level); - SPtr<Block3D> fblockNE;// = grid->getBlock(fbx1, fbx2, fbx3+1, level); - - setInterpolationConnectors(fblockSW, fblockSE, fblockNW, fblockNE, block, D3Q27System::SW); - } - if( block->hasInterpolationFlagCF(D3Q27System::SE)&& !block->hasInterpolationFlagCF(D3Q27System::E) && !block->hasInterpolationFlagCF(D3Q27System::S)) - { - SPtr<Block3D> fblockSW = grid->getBlock(fbx1+1,fbx2,fbx3+0,level); - SPtr<Block3D> fblockSE = grid->getBlock(fbx1+1,fbx2,fbx3+1,level); - SPtr<Block3D> fblockNW;// = grid->getBlock(fbx1+1, fbx2, fbx3+1, level); - SPtr<Block3D> fblockNE;// = grid->getBlock(fbx1+1, fbx2, fbx3+1, level); - - setInterpolationConnectors(fblockSW, fblockSE, fblockNW, fblockNE, block, D3Q27System::SE); - } - if( block->hasInterpolationFlagCF(D3Q27System::NW)&& !block->hasInterpolationFlagCF(D3Q27System::N) && !block->hasInterpolationFlagCF(D3Q27System::W)) - { - SPtr<Block3D> fblockSW = grid->getBlock(fbx1,fbx2+1,fbx3,level); - SPtr<Block3D> fblockSE = grid->getBlock(fbx1,fbx2+1,fbx3+1,level); - SPtr<Block3D> fblockNW;// = grid->getBlock(fbx1, fbx2+1, fbx3+1, level); - SPtr<Block3D> fblockNE;// = grid->getBlock(fbx1, fbx2+1, fbx3+1, level); - - setInterpolationConnectors(fblockSW, fblockSE, fblockNW, fblockNE, block, D3Q27System::NW); - } - - /////////TE-BW-BE-TW 1-0 - if( block->hasInterpolationFlagCF(D3Q27System::TE)&& !block->hasInterpolationFlagCF(D3Q27System::E) && !block->hasInterpolationFlagCF(D3Q27System::T)) - { - SPtr<Block3D> fblockSW = grid->getBlock(fbx1+1,fbx2+0,fbx3+1,level); - SPtr<Block3D> fblockSE = grid->getBlock(fbx1+1,fbx2+1,fbx3+1,level); - SPtr<Block3D> fblockNW;// = grid->getBlock(fbx1+1, fbx2+0, fbx3+1, level); - SPtr<Block3D> fblockNE;// = grid->getBlock(fbx1+1, fbx2+1, fbx3+1, level); - - setInterpolationConnectors(fblockSW, fblockSE, fblockNW, fblockNE, block, D3Q27System::TE); - } - if( block->hasInterpolationFlagCF(D3Q27System::BW)&& !block->hasInterpolationFlagCF(D3Q27System::W) && !block->hasInterpolationFlagCF(D3Q27System::B)) - { - - SPtr<Block3D> fblockSW = grid->getBlock(fbx1,fbx2+0,fbx3,level); - SPtr<Block3D> fblockSE = grid->getBlock(fbx1,fbx2+1,fbx3,level); - SPtr<Block3D> fblockNW;// = grid->getBlock(fbx1, fbx2+0, fbx3, level); - SPtr<Block3D> fblockNE;// = grid->getBlock(fbx1, fbx2+1, fbx3, level); - - setInterpolationConnectors(fblockSW, fblockSE, fblockNW, fblockNE, block, D3Q27System::BW); - } - if( block->hasInterpolationFlagCF(D3Q27System::BE)&& !block->hasInterpolationFlagCF(D3Q27System::E) && !block->hasInterpolationFlagCF(D3Q27System::B)) - { - SPtr<Block3D> fblockSW = grid->getBlock(fbx1+1,fbx2+0,fbx3,level); - SPtr<Block3D> fblockSE = grid->getBlock(fbx1+1,fbx2+1,fbx3,level); - SPtr<Block3D> fblockNW;// = grid->getBlock(fbx1+1, fbx2+0, fbx3, level); - SPtr<Block3D> fblockNE;// = grid->getBlock(fbx1+1, fbx2+1, fbx3, level); - - setInterpolationConnectors(fblockSW, fblockSE, fblockNW, fblockNE, block, D3Q27System::BE); - } - if( block->hasInterpolationFlagCF(D3Q27System::TW)&& !block->hasInterpolationFlagCF(D3Q27System::W) && !block->hasInterpolationFlagCF(D3Q27System::T)) - { - SPtr<Block3D> fblockSW = grid->getBlock(fbx1,fbx2+0,fbx3+1,level); - SPtr<Block3D> fblockSE = grid->getBlock(fbx1,fbx2+1,fbx3+1,level); - SPtr<Block3D> fblockNW;// = grid->getBlock(fbx1, fbx2+0, fbx3+1, level); - SPtr<Block3D> fblockNE;// = grid->getBlock(fbx1, fbx2+1, fbx3+1, level); - - setInterpolationConnectors(fblockSW, fblockSE, fblockNW, fblockNE, block, D3Q27System::TW); - } - - //////TN-BS-BN-TS - if( block->hasInterpolationFlagCF(D3Q27System::TN)&& !block->hasInterpolationFlagCF(D3Q27System::N) && !block->hasInterpolationFlagCF(D3Q27System::T)) - { - SPtr<Block3D> fblockSW = grid->getBlock(fbx1+0,fbx2+1,fbx3+1,level); - SPtr<Block3D> fblockSE = grid->getBlock(fbx1+1,fbx2+1,fbx3+1,level); - SPtr<Block3D> fblockNW;// = grid->getBlock(fbx1+0, fbx2+1, fbx3+1, level); - SPtr<Block3D> fblockNE;// = grid->getBlock(fbx1+1, fbx2+1, fbx3+1, level); - - setInterpolationConnectors(fblockSW, fblockSE, fblockNW, fblockNE, block, D3Q27System::TN); - } - if( block->hasInterpolationFlagCF(D3Q27System::BS)&& !block->hasInterpolationFlagCF(D3Q27System::S) && !block->hasInterpolationFlagCF(D3Q27System::B)) - { - SPtr<Block3D> fblockSW = grid->getBlock(fbx1+0,fbx2,fbx3,level); - SPtr<Block3D> fblockSE = grid->getBlock(fbx1+1,fbx2,fbx3,level); - SPtr<Block3D> fblockNW;// = grid->getBlock(fbx1+0, fbx2, fbx3, level); - SPtr<Block3D> fblockNE;// = grid->getBlock(fbx1+1, fbx2, fbx3, level); - - setInterpolationConnectors(fblockSW, fblockSE, fblockNW, fblockNE, block, D3Q27System::BS); - } - if( block->hasInterpolationFlagCF(D3Q27System::BN)&& !block->hasInterpolationFlagCF(D3Q27System::N) && !block->hasInterpolationFlagCF(D3Q27System::B)) - { - SPtr<Block3D> fblockSW = grid->getBlock(fbx1+0,fbx2+1,fbx3,level); - SPtr<Block3D> fblockSE = grid->getBlock(fbx1+1,fbx2+1,fbx3,level); - SPtr<Block3D> fblockNW;// = grid->getBlock(fbx1+0, fbx2+1, fbx3, level); - SPtr<Block3D> fblockNE;// = grid->getBlock(fbx1+1, fbx2+1, fbx3, level); - - setInterpolationConnectors(fblockSW, fblockSE, fblockNW, fblockNE, block, D3Q27System::BN); - } - if( block->hasInterpolationFlagCF(D3Q27System::TS)&& !block->hasInterpolationFlagCF(D3Q27System::S) && !block->hasInterpolationFlagCF(D3Q27System::T)) - { - SPtr<Block3D> fblockSW = grid->getBlock(fbx1+0,fbx2,fbx3+1,level); - SPtr<Block3D> fblockSE = grid->getBlock(fbx1+1,fbx2,fbx3+1,level); - SPtr<Block3D> fblockNW;// = grid->getBlock(fbx1+0, fbx2, fbx3+1, level); - SPtr<Block3D> fblockNE;// = grid->getBlock(fbx1+1, fbx2, fbx3+1, level); - - setInterpolationConnectors(fblockSW, fblockSE, fblockNW, fblockNE, block, D3Q27System::TS); - } - - - - - //////corners - if (block->hasInterpolationFlagCF(D3Q27System::TNE)&&!block->hasInterpolationFlagCF(D3Q27System::TE)&&!block->hasInterpolationFlagCF(D3Q27System::TN)&&!block->hasInterpolationFlagCF(D3Q27System::NE)&&!block->hasInterpolationFlagCF(D3Q27System::T)&&!block->hasInterpolationFlagCF(D3Q27System::N) && !block->hasInterpolationFlagCF(D3Q27System::E)) - { - SPtr<Block3D> fblockSW = grid->getBlock(fbx1+1, fbx2+1, fbx3+1, level); - SPtr<Block3D> fblockSE;// = grid->getBlock(fbx1+1, fbx2+1, fbx3+0, level); - SPtr<Block3D> fblockNW;// = grid->getBlock(fbx1+1, fbx2+1, fbx3+1, level); - SPtr<Block3D> fblockNE;// = grid->getBlock(fbx1+1, fbx2+1, fbx3+1, level); - - setInterpolationConnectors(fblockSW, fblockSE, fblockNW, fblockNE, block, D3Q27System::TNE); - } - if (block->hasInterpolationFlagCF(D3Q27System::TSW)&&!block->hasInterpolationFlagCF(D3Q27System::TW)&&!block->hasInterpolationFlagCF(D3Q27System::TS)&& !block->hasInterpolationFlagCF(D3Q27System::SW)&& !block->hasInterpolationFlagCF(D3Q27System::T)&& !block->hasInterpolationFlagCF(D3Q27System::W) && !block->hasInterpolationFlagCF(D3Q27System::S)) - { - SPtr<Block3D> fblockSW = grid->getBlock(fbx1, fbx2, fbx3+1, level); - SPtr<Block3D> fblockSE;// = grid->getBlock(fbx1, fbx2, fbx3, level); - SPtr<Block3D> fblockNW;// = grid->getBlock(fbx1, fbx2, fbx3+1, level); - SPtr<Block3D> fblockNE;// = grid->getBlock(fbx1, fbx2, fbx3+1, level); - - setInterpolationConnectors(fblockSW, fblockSE, fblockNW, fblockNE, block, D3Q27System::TSW); - } - if (block->hasInterpolationFlagCF(D3Q27System::TSE)&&!block->hasInterpolationFlagCF(D3Q27System::TE)&&!block->hasInterpolationFlagCF(D3Q27System::TS)&& !block->hasInterpolationFlagCF(D3Q27System::SE)&& !block->hasInterpolationFlagCF(D3Q27System::T)&& !block->hasInterpolationFlagCF(D3Q27System::E) && !block->hasInterpolationFlagCF(D3Q27System::S)) - { - SPtr<Block3D> fblockSW = grid->getBlock(fbx1+1, fbx2, fbx3+1, level); - SPtr<Block3D> fblockSE;// = grid->getBlock(fbx1+1, fbx2, fbx3+0, level); - SPtr<Block3D> fblockNW;// = grid->getBlock(fbx1+1, fbx2, fbx3+1, level); - SPtr<Block3D> fblockNE;// = grid->getBlock(fbx1+1, fbx2, fbx3+1, level); - - setInterpolationConnectors(fblockSW, fblockSE, fblockNW, fblockNE, block, D3Q27System::TSE); - } - if (block->hasInterpolationFlagCF(D3Q27System::TNW)&&!block->hasInterpolationFlagCF(D3Q27System::TW)&&!block->hasInterpolationFlagCF(D3Q27System::TN)&& !block->hasInterpolationFlagCF(D3Q27System::NW)&& !block->hasInterpolationFlagCF(D3Q27System::T)&& !block->hasInterpolationFlagCF(D3Q27System::N) && !block->hasInterpolationFlagCF(D3Q27System::W)) - { - SPtr<Block3D> fblockSW = grid->getBlock(fbx1, fbx2+1, fbx3+1, level); - SPtr<Block3D> fblockSE;// = grid->getBlock(fbx1, fbx2+1, fbx3, level); - SPtr<Block3D> fblockNW;// = grid->getBlock(fbx1, fbx2+1, fbx3+1, level); - SPtr<Block3D> fblockNE;// = grid->getBlock(fbx1, fbx2+1, fbx3+1, level); - - setInterpolationConnectors(fblockSW, fblockSE, fblockNW, fblockNE, block, D3Q27System::TNW); - } - if (block->hasInterpolationFlagCF(D3Q27System::BNE)&&!block->hasInterpolationFlagCF(D3Q27System::BE)&&!block->hasInterpolationFlagCF(D3Q27System::BN)&& !block->hasInterpolationFlagCF(D3Q27System::NE)&&!block->hasInterpolationFlagCF(D3Q27System::B)&&!block->hasInterpolationFlagCF(D3Q27System::N) && !block->hasInterpolationFlagCF(D3Q27System::E)) - { - SPtr<Block3D> fblockSW = grid->getBlock(fbx1+1, fbx2+1, fbx3+0, level); - SPtr<Block3D> fblockSE;// = grid->getBlock(fbx1+1, fbx2+1, fbx3+0, level); - SPtr<Block3D> fblockNW;// = grid->getBlock(fbx1+1, fbx2+1, fbx3+1, level); - SPtr<Block3D> fblockNE;// = grid->getBlock(fbx1+1, fbx2+1, fbx3+1, level); - - setInterpolationConnectors(fblockSW, fblockSE, fblockNW, fblockNE, block, D3Q27System::BNE); - } - if (block->hasInterpolationFlagCF(D3Q27System::BSW)&& !block->hasInterpolationFlagCF(D3Q27System::BS)&& !block->hasInterpolationFlagCF(D3Q27System::BW)&& !block->hasInterpolationFlagCF(D3Q27System::SW)&& !block->hasInterpolationFlagCF(D3Q27System::B)&& !block->hasInterpolationFlagCF(D3Q27System::W) && !block->hasInterpolationFlagCF(D3Q27System::S)) - { - SPtr<Block3D> fblockSW = grid->getBlock(fbx1, fbx2, fbx3+0, level); - SPtr<Block3D> fblockSE;// = grid->getBlock(fbx1, fbx2, fbx3, level); - SPtr<Block3D> fblockNW;// = grid->getBlock(fbx1, fbx2, fbx3+1, level); - SPtr<Block3D> fblockNE;// = grid->getBlock(fbx1, fbx2, fbx3+1, level); - - setInterpolationConnectors(fblockSW, fblockSE, fblockNW, fblockNE, block, D3Q27System::BSW); - } - if (block->hasInterpolationFlagCF(D3Q27System::BSE)&& !block->hasInterpolationFlagCF(D3Q27System::BS)&& !block->hasInterpolationFlagCF(D3Q27System::BE)&& !block->hasInterpolationFlagCF(D3Q27System::SE)&& !block->hasInterpolationFlagCF(D3Q27System::B)&& !block->hasInterpolationFlagCF(D3Q27System::E) && !block->hasInterpolationFlagCF(D3Q27System::S)) - { - SPtr<Block3D> fblockSW = grid->getBlock(fbx1+1, fbx2, fbx3, level); - SPtr<Block3D> fblockSE;// = grid->getBlock(fbx1+1, fbx2, fbx3+0, level); - SPtr<Block3D> fblockNW;// = grid->getBlock(fbx1+1, fbx2, fbx3+1, level); - SPtr<Block3D> fblockNE;// = grid->getBlock(fbx1+1, fbx2, fbx3+1, level); - - setInterpolationConnectors(fblockSW, fblockSE, fblockNW, fblockNE, block, D3Q27System::BSE); - } - if (block->hasInterpolationFlagCF(D3Q27System::BNW)&& !block->hasInterpolationFlagCF(D3Q27System::BN)&& !block->hasInterpolationFlagCF(D3Q27System::BW)&& !block->hasInterpolationFlagCF(D3Q27System::NW)&& !block->hasInterpolationFlagCF(D3Q27System::B)&& !block->hasInterpolationFlagCF(D3Q27System::N) && !block->hasInterpolationFlagCF(D3Q27System::W)) - { - SPtr<Block3D> fblockSW = grid->getBlock(fbx1, fbx2+1, fbx3+0, level); - SPtr<Block3D> fblockSE;// = grid->getBlock(fbx1, fbx2+1, fbx3, level); - SPtr<Block3D> fblockNW;// = grid->getBlock(fbx1, fbx2+1, fbx3+1, level); - SPtr<Block3D> fblockNE;// = grid->getBlock(fbx1, fbx2+1, fbx3+1, level); - - setInterpolationConnectors(fblockSW, fblockSE, fblockNW, fblockNE, block, D3Q27System::BNW); - } - - } - UBLOG(logDEBUG5, "D3Q27SetConnectorsBlockVisitor::setInterpolationConnectors() - end"); + UBLOG(logDEBUG5, "D3Q27SetConnectorsBlockVisitor::setInterpolationConnectors() - start"); + // int blockRank = block->getRank(); + // if (block->getGlobalID()==394) + // { + // int test=0; + // } + + // search for all blocks with different ranks + if (block->hasInterpolationFlagCF() && block->isActive()) { + int fbx1 = block->getX1() << 1; + int fbx2 = block->getX2() << 1; + int fbx3 = block->getX3() << 1; + int level = block->getLevel() + 1; + + if (block->hasInterpolationFlagCF(D3Q27System::E)) { + SPtr<Block3D> fblockSW = grid->getBlock(fbx1 + 1, fbx2, fbx3, level); + SPtr<Block3D> fblockSE = grid->getBlock(fbx1 + 1, fbx2 + 1, fbx3, level); + SPtr<Block3D> fblockNW = grid->getBlock(fbx1 + 1, fbx2, fbx3 + 1, level); + SPtr<Block3D> fblockNE = grid->getBlock(fbx1 + 1, fbx2 + 1, fbx3 + 1, level); + + setInterpolationConnectors(fblockSW, fblockSE, fblockNW, fblockNE, block, D3Q27System::E); + } + if (block->hasInterpolationFlagCF(D3Q27System::W)) { + SPtr<Block3D> fblockSW = grid->getBlock(fbx1, fbx2, fbx3, level); + SPtr<Block3D> fblockSE = grid->getBlock(fbx1, fbx2 + 1, fbx3, level); + SPtr<Block3D> fblockNW = grid->getBlock(fbx1, fbx2, fbx3 + 1, level); + SPtr<Block3D> fblockNE = grid->getBlock(fbx1, fbx2 + 1, fbx3 + 1, level); + + setInterpolationConnectors(fblockSW, fblockSE, fblockNW, fblockNE, block, D3Q27System::W); + } + if (block->hasInterpolationFlagCF(D3Q27System::N)) { + SPtr<Block3D> fblockSW = grid->getBlock(fbx1, fbx2 + 1, fbx3, level); + SPtr<Block3D> fblockSE = grid->getBlock(fbx1 + 1, fbx2 + 1, fbx3, level); + SPtr<Block3D> fblockNW = grid->getBlock(fbx1, fbx2 + 1, fbx3 + 1, level); + SPtr<Block3D> fblockNE = grid->getBlock(fbx1 + 1, fbx2 + 1, fbx3 + 1, level); + + setInterpolationConnectors(fblockSW, fblockSE, fblockNW, fblockNE, block, D3Q27System::N); + } + if (block->hasInterpolationFlagCF(D3Q27System::S)) { + SPtr<Block3D> fblockSW = grid->getBlock(fbx1, fbx2, fbx3, level); + SPtr<Block3D> fblockSE = grid->getBlock(fbx1 + 1, fbx2, fbx3, level); + SPtr<Block3D> fblockNW = grid->getBlock(fbx1, fbx2, fbx3 + 1, level); + SPtr<Block3D> fblockNE = grid->getBlock(fbx1 + 1, fbx2, fbx3 + 1, level); + + setInterpolationConnectors(fblockSW, fblockSE, fblockNW, fblockNE, block, D3Q27System::S); + } + if (block->hasInterpolationFlagCF(D3Q27System::T)) { + SPtr<Block3D> fblockSW = grid->getBlock(fbx1, fbx2, fbx3 + 1, level); + SPtr<Block3D> fblockSE = grid->getBlock(fbx1 + 1, fbx2, fbx3 + 1, level); + SPtr<Block3D> fblockNW = grid->getBlock(fbx1, fbx2 + 1, fbx3 + 1, level); + SPtr<Block3D> fblockNE = grid->getBlock(fbx1 + 1, fbx2 + 1, fbx3 + 1, level); + + setInterpolationConnectors(fblockSW, fblockSE, fblockNW, fblockNE, block, D3Q27System::T); + } + if (block->hasInterpolationFlagCF(D3Q27System::B)) { + SPtr<Block3D> fblockSW = grid->getBlock(fbx1, fbx2, fbx3, level); + SPtr<Block3D> fblockSE = grid->getBlock(fbx1 + 1, fbx2, fbx3, level); + SPtr<Block3D> fblockNW = grid->getBlock(fbx1, fbx2 + 1, fbx3, level); + SPtr<Block3D> fblockNE = grid->getBlock(fbx1 + 1, fbx2 + 1, fbx3, level); + + setInterpolationConnectors(fblockSW, fblockSE, fblockNW, fblockNE, block, D3Q27System::B); + } + + //////NE-NW-SE-SW + if (block->hasInterpolationFlagCF(D3Q27System::NE) && !block->hasInterpolationFlagCF(D3Q27System::N) && + !block->hasInterpolationFlagCF(D3Q27System::E)) { + SPtr<Block3D> fblockSW = grid->getBlock(fbx1 + 1, fbx2 + 1, fbx3 + 0, level); + SPtr<Block3D> fblockSE = grid->getBlock(fbx1 + 1, fbx2 + 1, fbx3 + 1, level); + SPtr<Block3D> fblockNW; // = grid->getBlock(fbx1+1, fbx2+1, fbx3+1, level); + SPtr<Block3D> fblockNE; // = grid->getBlock(fbx1+1, fbx2+1, fbx3+1, level); + + setInterpolationConnectors(fblockSW, fblockSE, fblockNW, fblockNE, block, D3Q27System::NE); + } + if (block->hasInterpolationFlagCF(D3Q27System::SW) && !block->hasInterpolationFlagCF(D3Q27System::W) && + !block->hasInterpolationFlagCF(D3Q27System::S)) { + SPtr<Block3D> fblockSW = grid->getBlock(fbx1, fbx2, fbx3, level); + SPtr<Block3D> fblockSE = grid->getBlock(fbx1, fbx2, fbx3 + 1, level); + SPtr<Block3D> fblockNW; // = grid->getBlock(fbx1, fbx2, fbx3+1, level); + SPtr<Block3D> fblockNE; // = grid->getBlock(fbx1, fbx2, fbx3+1, level); + + setInterpolationConnectors(fblockSW, fblockSE, fblockNW, fblockNE, block, D3Q27System::SW); + } + if (block->hasInterpolationFlagCF(D3Q27System::SE) && !block->hasInterpolationFlagCF(D3Q27System::E) && + !block->hasInterpolationFlagCF(D3Q27System::S)) { + SPtr<Block3D> fblockSW = grid->getBlock(fbx1 + 1, fbx2, fbx3 + 0, level); + SPtr<Block3D> fblockSE = grid->getBlock(fbx1 + 1, fbx2, fbx3 + 1, level); + SPtr<Block3D> fblockNW; // = grid->getBlock(fbx1+1, fbx2, fbx3+1, level); + SPtr<Block3D> fblockNE; // = grid->getBlock(fbx1+1, fbx2, fbx3+1, level); + + setInterpolationConnectors(fblockSW, fblockSE, fblockNW, fblockNE, block, D3Q27System::SE); + } + if (block->hasInterpolationFlagCF(D3Q27System::NW) && !block->hasInterpolationFlagCF(D3Q27System::N) && + !block->hasInterpolationFlagCF(D3Q27System::W)) { + SPtr<Block3D> fblockSW = grid->getBlock(fbx1, fbx2 + 1, fbx3, level); + SPtr<Block3D> fblockSE = grid->getBlock(fbx1, fbx2 + 1, fbx3 + 1, level); + SPtr<Block3D> fblockNW; // = grid->getBlock(fbx1, fbx2+1, fbx3+1, level); + SPtr<Block3D> fblockNE; // = grid->getBlock(fbx1, fbx2+1, fbx3+1, level); + + setInterpolationConnectors(fblockSW, fblockSE, fblockNW, fblockNE, block, D3Q27System::NW); + } + + /////////TE-BW-BE-TW 1-0 + if (block->hasInterpolationFlagCF(D3Q27System::TE) && !block->hasInterpolationFlagCF(D3Q27System::E) && + !block->hasInterpolationFlagCF(D3Q27System::T)) { + SPtr<Block3D> fblockSW = grid->getBlock(fbx1 + 1, fbx2 + 0, fbx3 + 1, level); + SPtr<Block3D> fblockSE = grid->getBlock(fbx1 + 1, fbx2 + 1, fbx3 + 1, level); + SPtr<Block3D> fblockNW; // = grid->getBlock(fbx1+1, fbx2+0, fbx3+1, level); + SPtr<Block3D> fblockNE; // = grid->getBlock(fbx1+1, fbx2+1, fbx3+1, level); + + setInterpolationConnectors(fblockSW, fblockSE, fblockNW, fblockNE, block, D3Q27System::TE); + } + if (block->hasInterpolationFlagCF(D3Q27System::BW) && !block->hasInterpolationFlagCF(D3Q27System::W) && + !block->hasInterpolationFlagCF(D3Q27System::B)) { + + SPtr<Block3D> fblockSW = grid->getBlock(fbx1, fbx2 + 0, fbx3, level); + SPtr<Block3D> fblockSE = grid->getBlock(fbx1, fbx2 + 1, fbx3, level); + SPtr<Block3D> fblockNW; // = grid->getBlock(fbx1, fbx2+0, fbx3, level); + SPtr<Block3D> fblockNE; // = grid->getBlock(fbx1, fbx2+1, fbx3, level); + + setInterpolationConnectors(fblockSW, fblockSE, fblockNW, fblockNE, block, D3Q27System::BW); + } + if (block->hasInterpolationFlagCF(D3Q27System::BE) && !block->hasInterpolationFlagCF(D3Q27System::E) && + !block->hasInterpolationFlagCF(D3Q27System::B)) { + SPtr<Block3D> fblockSW = grid->getBlock(fbx1 + 1, fbx2 + 0, fbx3, level); + SPtr<Block3D> fblockSE = grid->getBlock(fbx1 + 1, fbx2 + 1, fbx3, level); + SPtr<Block3D> fblockNW; // = grid->getBlock(fbx1+1, fbx2+0, fbx3, level); + SPtr<Block3D> fblockNE; // = grid->getBlock(fbx1+1, fbx2+1, fbx3, level); + + setInterpolationConnectors(fblockSW, fblockSE, fblockNW, fblockNE, block, D3Q27System::BE); + } + if (block->hasInterpolationFlagCF(D3Q27System::TW) && !block->hasInterpolationFlagCF(D3Q27System::W) && + !block->hasInterpolationFlagCF(D3Q27System::T)) { + SPtr<Block3D> fblockSW = grid->getBlock(fbx1, fbx2 + 0, fbx3 + 1, level); + SPtr<Block3D> fblockSE = grid->getBlock(fbx1, fbx2 + 1, fbx3 + 1, level); + SPtr<Block3D> fblockNW; // = grid->getBlock(fbx1, fbx2+0, fbx3+1, level); + SPtr<Block3D> fblockNE; // = grid->getBlock(fbx1, fbx2+1, fbx3+1, level); + + setInterpolationConnectors(fblockSW, fblockSE, fblockNW, fblockNE, block, D3Q27System::TW); + } + + //////TN-BS-BN-TS + if (block->hasInterpolationFlagCF(D3Q27System::TN) && !block->hasInterpolationFlagCF(D3Q27System::N) && + !block->hasInterpolationFlagCF(D3Q27System::T)) { + SPtr<Block3D> fblockSW = grid->getBlock(fbx1 + 0, fbx2 + 1, fbx3 + 1, level); + SPtr<Block3D> fblockSE = grid->getBlock(fbx1 + 1, fbx2 + 1, fbx3 + 1, level); + SPtr<Block3D> fblockNW; // = grid->getBlock(fbx1+0, fbx2+1, fbx3+1, level); + SPtr<Block3D> fblockNE; // = grid->getBlock(fbx1+1, fbx2+1, fbx3+1, level); + + setInterpolationConnectors(fblockSW, fblockSE, fblockNW, fblockNE, block, D3Q27System::TN); + } + if (block->hasInterpolationFlagCF(D3Q27System::BS) && !block->hasInterpolationFlagCF(D3Q27System::S) && + !block->hasInterpolationFlagCF(D3Q27System::B)) { + SPtr<Block3D> fblockSW = grid->getBlock(fbx1 + 0, fbx2, fbx3, level); + SPtr<Block3D> fblockSE = grid->getBlock(fbx1 + 1, fbx2, fbx3, level); + SPtr<Block3D> fblockNW; // = grid->getBlock(fbx1+0, fbx2, fbx3, level); + SPtr<Block3D> fblockNE; // = grid->getBlock(fbx1+1, fbx2, fbx3, level); + + setInterpolationConnectors(fblockSW, fblockSE, fblockNW, fblockNE, block, D3Q27System::BS); + } + if (block->hasInterpolationFlagCF(D3Q27System::BN) && !block->hasInterpolationFlagCF(D3Q27System::N) && + !block->hasInterpolationFlagCF(D3Q27System::B)) { + SPtr<Block3D> fblockSW = grid->getBlock(fbx1 + 0, fbx2 + 1, fbx3, level); + SPtr<Block3D> fblockSE = grid->getBlock(fbx1 + 1, fbx2 + 1, fbx3, level); + SPtr<Block3D> fblockNW; // = grid->getBlock(fbx1+0, fbx2+1, fbx3, level); + SPtr<Block3D> fblockNE; // = grid->getBlock(fbx1+1, fbx2+1, fbx3, level); + + setInterpolationConnectors(fblockSW, fblockSE, fblockNW, fblockNE, block, D3Q27System::BN); + } + if (block->hasInterpolationFlagCF(D3Q27System::TS) && !block->hasInterpolationFlagCF(D3Q27System::S) && + !block->hasInterpolationFlagCF(D3Q27System::T)) { + SPtr<Block3D> fblockSW = grid->getBlock(fbx1 + 0, fbx2, fbx3 + 1, level); + SPtr<Block3D> fblockSE = grid->getBlock(fbx1 + 1, fbx2, fbx3 + 1, level); + SPtr<Block3D> fblockNW; // = grid->getBlock(fbx1+0, fbx2, fbx3+1, level); + SPtr<Block3D> fblockNE; // = grid->getBlock(fbx1+1, fbx2, fbx3+1, level); + + setInterpolationConnectors(fblockSW, fblockSE, fblockNW, fblockNE, block, D3Q27System::TS); + } + + //////corners + if (block->hasInterpolationFlagCF(D3Q27System::TNE) && !block->hasInterpolationFlagCF(D3Q27System::TE) && + !block->hasInterpolationFlagCF(D3Q27System::TN) && !block->hasInterpolationFlagCF(D3Q27System::NE) && + !block->hasInterpolationFlagCF(D3Q27System::T) && !block->hasInterpolationFlagCF(D3Q27System::N) && + !block->hasInterpolationFlagCF(D3Q27System::E)) { + SPtr<Block3D> fblockSW = grid->getBlock(fbx1 + 1, fbx2 + 1, fbx3 + 1, level); + SPtr<Block3D> fblockSE; // = grid->getBlock(fbx1+1, fbx2+1, fbx3+0, level); + SPtr<Block3D> fblockNW; // = grid->getBlock(fbx1+1, fbx2+1, fbx3+1, level); + SPtr<Block3D> fblockNE; // = grid->getBlock(fbx1+1, fbx2+1, fbx3+1, level); + + setInterpolationConnectors(fblockSW, fblockSE, fblockNW, fblockNE, block, D3Q27System::TNE); + } + if (block->hasInterpolationFlagCF(D3Q27System::TSW) && !block->hasInterpolationFlagCF(D3Q27System::TW) && + !block->hasInterpolationFlagCF(D3Q27System::TS) && !block->hasInterpolationFlagCF(D3Q27System::SW) && + !block->hasInterpolationFlagCF(D3Q27System::T) && !block->hasInterpolationFlagCF(D3Q27System::W) && + !block->hasInterpolationFlagCF(D3Q27System::S)) { + SPtr<Block3D> fblockSW = grid->getBlock(fbx1, fbx2, fbx3 + 1, level); + SPtr<Block3D> fblockSE; // = grid->getBlock(fbx1, fbx2, fbx3, level); + SPtr<Block3D> fblockNW; // = grid->getBlock(fbx1, fbx2, fbx3+1, level); + SPtr<Block3D> fblockNE; // = grid->getBlock(fbx1, fbx2, fbx3+1, level); + + setInterpolationConnectors(fblockSW, fblockSE, fblockNW, fblockNE, block, D3Q27System::TSW); + } + if (block->hasInterpolationFlagCF(D3Q27System::TSE) && !block->hasInterpolationFlagCF(D3Q27System::TE) && + !block->hasInterpolationFlagCF(D3Q27System::TS) && !block->hasInterpolationFlagCF(D3Q27System::SE) && + !block->hasInterpolationFlagCF(D3Q27System::T) && !block->hasInterpolationFlagCF(D3Q27System::E) && + !block->hasInterpolationFlagCF(D3Q27System::S)) { + SPtr<Block3D> fblockSW = grid->getBlock(fbx1 + 1, fbx2, fbx3 + 1, level); + SPtr<Block3D> fblockSE; // = grid->getBlock(fbx1+1, fbx2, fbx3+0, level); + SPtr<Block3D> fblockNW; // = grid->getBlock(fbx1+1, fbx2, fbx3+1, level); + SPtr<Block3D> fblockNE; // = grid->getBlock(fbx1+1, fbx2, fbx3+1, level); + + setInterpolationConnectors(fblockSW, fblockSE, fblockNW, fblockNE, block, D3Q27System::TSE); + } + if (block->hasInterpolationFlagCF(D3Q27System::TNW) && !block->hasInterpolationFlagCF(D3Q27System::TW) && + !block->hasInterpolationFlagCF(D3Q27System::TN) && !block->hasInterpolationFlagCF(D3Q27System::NW) && + !block->hasInterpolationFlagCF(D3Q27System::T) && !block->hasInterpolationFlagCF(D3Q27System::N) && + !block->hasInterpolationFlagCF(D3Q27System::W)) { + SPtr<Block3D> fblockSW = grid->getBlock(fbx1, fbx2 + 1, fbx3 + 1, level); + SPtr<Block3D> fblockSE; // = grid->getBlock(fbx1, fbx2+1, fbx3, level); + SPtr<Block3D> fblockNW; // = grid->getBlock(fbx1, fbx2+1, fbx3+1, level); + SPtr<Block3D> fblockNE; // = grid->getBlock(fbx1, fbx2+1, fbx3+1, level); + + setInterpolationConnectors(fblockSW, fblockSE, fblockNW, fblockNE, block, D3Q27System::TNW); + } + if (block->hasInterpolationFlagCF(D3Q27System::BNE) && !block->hasInterpolationFlagCF(D3Q27System::BE) && + !block->hasInterpolationFlagCF(D3Q27System::BN) && !block->hasInterpolationFlagCF(D3Q27System::NE) && + !block->hasInterpolationFlagCF(D3Q27System::B) && !block->hasInterpolationFlagCF(D3Q27System::N) && + !block->hasInterpolationFlagCF(D3Q27System::E)) { + SPtr<Block3D> fblockSW = grid->getBlock(fbx1 + 1, fbx2 + 1, fbx3 + 0, level); + SPtr<Block3D> fblockSE; // = grid->getBlock(fbx1+1, fbx2+1, fbx3+0, level); + SPtr<Block3D> fblockNW; // = grid->getBlock(fbx1+1, fbx2+1, fbx3+1, level); + SPtr<Block3D> fblockNE; // = grid->getBlock(fbx1+1, fbx2+1, fbx3+1, level); + + setInterpolationConnectors(fblockSW, fblockSE, fblockNW, fblockNE, block, D3Q27System::BNE); + } + if (block->hasInterpolationFlagCF(D3Q27System::BSW) && !block->hasInterpolationFlagCF(D3Q27System::BS) && + !block->hasInterpolationFlagCF(D3Q27System::BW) && !block->hasInterpolationFlagCF(D3Q27System::SW) && + !block->hasInterpolationFlagCF(D3Q27System::B) && !block->hasInterpolationFlagCF(D3Q27System::W) && + !block->hasInterpolationFlagCF(D3Q27System::S)) { + SPtr<Block3D> fblockSW = grid->getBlock(fbx1, fbx2, fbx3 + 0, level); + SPtr<Block3D> fblockSE; // = grid->getBlock(fbx1, fbx2, fbx3, level); + SPtr<Block3D> fblockNW; // = grid->getBlock(fbx1, fbx2, fbx3+1, level); + SPtr<Block3D> fblockNE; // = grid->getBlock(fbx1, fbx2, fbx3+1, level); + + setInterpolationConnectors(fblockSW, fblockSE, fblockNW, fblockNE, block, D3Q27System::BSW); + } + if (block->hasInterpolationFlagCF(D3Q27System::BSE) && !block->hasInterpolationFlagCF(D3Q27System::BS) && + !block->hasInterpolationFlagCF(D3Q27System::BE) && !block->hasInterpolationFlagCF(D3Q27System::SE) && + !block->hasInterpolationFlagCF(D3Q27System::B) && !block->hasInterpolationFlagCF(D3Q27System::E) && + !block->hasInterpolationFlagCF(D3Q27System::S)) { + SPtr<Block3D> fblockSW = grid->getBlock(fbx1 + 1, fbx2, fbx3, level); + SPtr<Block3D> fblockSE; // = grid->getBlock(fbx1+1, fbx2, fbx3+0, level); + SPtr<Block3D> fblockNW; // = grid->getBlock(fbx1+1, fbx2, fbx3+1, level); + SPtr<Block3D> fblockNE; // = grid->getBlock(fbx1+1, fbx2, fbx3+1, level); + + setInterpolationConnectors(fblockSW, fblockSE, fblockNW, fblockNE, block, D3Q27System::BSE); + } + if (block->hasInterpolationFlagCF(D3Q27System::BNW) && !block->hasInterpolationFlagCF(D3Q27System::BN) && + !block->hasInterpolationFlagCF(D3Q27System::BW) && !block->hasInterpolationFlagCF(D3Q27System::NW) && + !block->hasInterpolationFlagCF(D3Q27System::B) && !block->hasInterpolationFlagCF(D3Q27System::N) && + !block->hasInterpolationFlagCF(D3Q27System::W)) { + SPtr<Block3D> fblockSW = grid->getBlock(fbx1, fbx2 + 1, fbx3 + 0, level); + SPtr<Block3D> fblockSE; // = grid->getBlock(fbx1, fbx2+1, fbx3, level); + SPtr<Block3D> fblockNW; // = grid->getBlock(fbx1, fbx2+1, fbx3+1, level); + SPtr<Block3D> fblockNE; // = grid->getBlock(fbx1, fbx2+1, fbx3+1, level); + + setInterpolationConnectors(fblockSW, fblockSE, fblockNW, fblockNE, block, D3Q27System::BNW); + } + } + UBLOG(logDEBUG5, "D3Q27SetConnectorsBlockVisitor::setInterpolationConnectors() - end"); } ////////////////////////////////////////////////////////////////////////// -void SetConnectorsBlockVisitor::setInterpolationConnectors(SPtr<Block3D> fBlockSW, SPtr<Block3D> fBlockSE, SPtr<Block3D> fBlockNW, SPtr<Block3D> fBlockNE, SPtr<Block3D> cBlock, int dir) +void SetConnectorsBlockVisitor::setInterpolationConnectors(SPtr<Block3D> fBlockSW, SPtr<Block3D> fBlockSE, + SPtr<Block3D> fBlockNW, SPtr<Block3D> fBlockNE, + SPtr<Block3D> cBlock, int dir) { - UBLOG(logDEBUG5, "D3Q27SetConnectorsBlockVisitor::setInterpolationConnectors(...) - start"); - int fBlockSWRank = -999, fBlockSERank = -999, fBlockNWRank = -999, fBlockNERank = -999; - if(fBlockSW) fBlockSWRank = fBlockSW->getRank(); - if(fBlockNW) fBlockNWRank = fBlockNW->getRank(); - if(fBlockSE) fBlockSERank = fBlockSE->getRank(); - if(fBlockNE) fBlockNERank = fBlockNE->getRank(); - int cBlockRank = cBlock->getRank(); - - LBMReal omegaF; - if(fBlockSW) omegaF =LBMSystem::calcCollisionFactor(nue, fBlockSW->getLevel()); - if(fBlockNW) omegaF =LBMSystem::calcCollisionFactor(nue, fBlockNW->getLevel()); - if(fBlockSE) omegaF =LBMSystem::calcCollisionFactor(nue, fBlockSE->getLevel()); - if(fBlockNE) omegaF =LBMSystem::calcCollisionFactor(nue, fBlockNE->getLevel()); - LBMReal omegaC = LBMSystem::calcCollisionFactor(nue, cBlock->getLevel()); - iProcessor->setOmegas(omegaC, omegaF); - - InterpolationProcessorPtr cIProcessor(iProcessor->clone()); - InterpolationProcessorPtr fIProcessorSW(iProcessor->clone()); - InterpolationProcessorPtr fIProcessorSE(iProcessor->clone()); - InterpolationProcessorPtr fIProcessorNW(iProcessor->clone()); - InterpolationProcessorPtr fIProcessorNE(iProcessor->clone()); - - CreateTransmittersHelper::TransmitterPtr senderCFevenEvenSW, receiverCFevenEvenSW, - senderCFevenOddNW, receiverCFevenOddNW, - senderCFoddEvenSE, receiverCFoddEvenSE, - senderCFoddOddNE, receiverCFoddOddNE, - senderFCevenEvenSW, receiverFCevenEvenSW, - senderFCevenOddNW, receiverFCevenOddNW, - senderFCoddEvenSE, receiverFCoddEvenSE, - senderFCoddOddNE, receiverFCoddOddNE; - - if(fBlockSW) createTransmitters(cBlock, fBlockSW, dir, CreateTransmittersHelper::SW, senderCFevenEvenSW, receiverCFevenEvenSW, senderFCevenEvenSW, receiverFCevenEvenSW); - if(fBlockNW) createTransmitters(cBlock, fBlockNW, dir, CreateTransmittersHelper::NW, senderCFevenOddNW, receiverCFevenOddNW, senderFCevenOddNW, receiverFCevenOddNW); - if(fBlockSE) createTransmitters(cBlock, fBlockSE, dir, CreateTransmittersHelper::SE, senderCFoddEvenSE, receiverCFoddEvenSE, senderFCoddEvenSE, receiverFCoddEvenSE); - if(fBlockNE) createTransmitters(cBlock, fBlockNE, dir, CreateTransmittersHelper::NE, senderCFoddOddNE, receiverCFoddOddNE, senderFCoddOddNE, receiverFCoddOddNE); - - if(cBlockRank == gridRank) - { - SPtr<Block3DConnector> connector(new D3Q27ETCFOffVectorConnector< TbTransmitter< CbVector< LBMReal > > >(cBlock, - senderCFevenEvenSW, receiverCFevenEvenSW, senderCFevenOddNW, receiverCFevenOddNW, - senderCFoddEvenSE, receiverCFoddEvenSE, senderCFoddOddNE, receiverCFoddOddNE, - dir, cIProcessor) ); - cBlock->setConnector(connector); - } - if(fBlockSW && fBlockSWRank == gridRank) - { - SPtr<Block3DConnector> connector( new D3Q27ETFCOffVectorConnector< TbTransmitter< CbVector< LBMReal > > >(fBlockSW, - senderFCevenEvenSW, receiverFCevenEvenSW, dir, fIProcessorSW, EvenEvenSW) ); - fBlockSW->setConnector(connector); - } - if(fBlockNW && fBlockNWRank == gridRank) - { - SPtr<Block3DConnector> connector( new D3Q27ETFCOffVectorConnector< TbTransmitter< CbVector< LBMReal > > >(fBlockNW, - senderFCevenOddNW, receiverFCevenOddNW, dir, fIProcessorNW, EvenOddNW) ); - fBlockNW->setConnector(connector); - } - if(fBlockSE && fBlockSERank == gridRank) - { - SPtr<Block3DConnector> connector( new D3Q27ETFCOffVectorConnector< TbTransmitter< CbVector< LBMReal > > >(fBlockSE, - senderFCoddEvenSE, receiverFCoddEvenSE, dir, fIProcessorSE, OddEvenSE) ); - fBlockSE->setConnector(connector); - } - if(fBlockNE && fBlockNERank == gridRank) - { - SPtr<Block3DConnector> connector( new D3Q27ETFCOffVectorConnector< TbTransmitter< CbVector< LBMReal > > >(fBlockNE, - senderFCoddOddNE, receiverFCoddOddNE, dir, fIProcessorNE, OddOddNE) ); - fBlockNE->setConnector(connector); - } - UBLOG(logDEBUG5, "D3Q27SetConnectorsBlockVisitor::setInterpolationConnectors(...) - end"); + UBLOG(logDEBUG5, "D3Q27SetConnectorsBlockVisitor::setInterpolationConnectors(...) - start"); + int fBlockSWRank = -999, fBlockSERank = -999, fBlockNWRank = -999, fBlockNERank = -999; + if (fBlockSW) + fBlockSWRank = fBlockSW->getRank(); + if (fBlockNW) + fBlockNWRank = fBlockNW->getRank(); + if (fBlockSE) + fBlockSERank = fBlockSE->getRank(); + if (fBlockNE) + fBlockNERank = fBlockNE->getRank(); + int cBlockRank = cBlock->getRank(); + + LBMReal omegaF; + if (fBlockSW) + omegaF = LBMSystem::calcCollisionFactor(nue, fBlockSW->getLevel()); + if (fBlockNW) + omegaF = LBMSystem::calcCollisionFactor(nue, fBlockNW->getLevel()); + if (fBlockSE) + omegaF = LBMSystem::calcCollisionFactor(nue, fBlockSE->getLevel()); + if (fBlockNE) + omegaF = LBMSystem::calcCollisionFactor(nue, fBlockNE->getLevel()); + LBMReal omegaC = LBMSystem::calcCollisionFactor(nue, cBlock->getLevel()); + iProcessor->setOmegas(omegaC, omegaF); + + InterpolationProcessorPtr cIProcessor(iProcessor->clone()); + InterpolationProcessorPtr fIProcessorSW(iProcessor->clone()); + InterpolationProcessorPtr fIProcessorSE(iProcessor->clone()); + InterpolationProcessorPtr fIProcessorNW(iProcessor->clone()); + InterpolationProcessorPtr fIProcessorNE(iProcessor->clone()); + + CreateTransmittersHelper::TransmitterPtr senderCFevenEvenSW, receiverCFevenEvenSW, senderCFevenOddNW, + receiverCFevenOddNW, senderCFoddEvenSE, receiverCFoddEvenSE, senderCFoddOddNE, receiverCFoddOddNE, + senderFCevenEvenSW, receiverFCevenEvenSW, senderFCevenOddNW, receiverFCevenOddNW, senderFCoddEvenSE, + receiverFCoddEvenSE, senderFCoddOddNE, receiverFCoddOddNE; + + if (fBlockSW) + createTransmitters(cBlock, fBlockSW, dir, CreateTransmittersHelper::SW, senderCFevenEvenSW, + receiverCFevenEvenSW, senderFCevenEvenSW, receiverFCevenEvenSW); + if (fBlockNW) + createTransmitters(cBlock, fBlockNW, dir, CreateTransmittersHelper::NW, senderCFevenOddNW, receiverCFevenOddNW, + senderFCevenOddNW, receiverFCevenOddNW); + if (fBlockSE) + createTransmitters(cBlock, fBlockSE, dir, CreateTransmittersHelper::SE, senderCFoddEvenSE, receiverCFoddEvenSE, + senderFCoddEvenSE, receiverFCoddEvenSE); + if (fBlockNE) + createTransmitters(cBlock, fBlockNE, dir, CreateTransmittersHelper::NE, senderCFoddOddNE, receiverCFoddOddNE, + senderFCoddOddNE, receiverFCoddOddNE); + + if (cBlockRank == gridRank) { + SPtr<Block3DConnector> connector(new D3Q27ETCFOffVectorConnector<TbTransmitter<CbVector<LBMReal>>>( + cBlock, senderCFevenEvenSW, receiverCFevenEvenSW, senderCFevenOddNW, receiverCFevenOddNW, senderCFoddEvenSE, + receiverCFoddEvenSE, senderCFoddOddNE, receiverCFoddOddNE, dir, cIProcessor)); + cBlock->setConnector(connector); + } + if (fBlockSW && fBlockSWRank == gridRank) { + SPtr<Block3DConnector> connector(new D3Q27ETFCOffVectorConnector<TbTransmitter<CbVector<LBMReal>>>( + fBlockSW, senderFCevenEvenSW, receiverFCevenEvenSW, dir, fIProcessorSW, EvenEvenSW)); + fBlockSW->setConnector(connector); + } + if (fBlockNW && fBlockNWRank == gridRank) { + SPtr<Block3DConnector> connector(new D3Q27ETFCOffVectorConnector<TbTransmitter<CbVector<LBMReal>>>( + fBlockNW, senderFCevenOddNW, receiverFCevenOddNW, dir, fIProcessorNW, EvenOddNW)); + fBlockNW->setConnector(connector); + } + if (fBlockSE && fBlockSERank == gridRank) { + SPtr<Block3DConnector> connector(new D3Q27ETFCOffVectorConnector<TbTransmitter<CbVector<LBMReal>>>( + fBlockSE, senderFCoddEvenSE, receiverFCoddEvenSE, dir, fIProcessorSE, OddEvenSE)); + fBlockSE->setConnector(connector); + } + if (fBlockNE && fBlockNERank == gridRank) { + SPtr<Block3DConnector> connector(new D3Q27ETFCOffVectorConnector<TbTransmitter<CbVector<LBMReal>>>( + fBlockNE, senderFCoddOddNE, receiverFCoddOddNE, dir, fIProcessorNE, OddOddNE)); + fBlockNE->setConnector(connector); + } + UBLOG(logDEBUG5, "D3Q27SetConnectorsBlockVisitor::setInterpolationConnectors(...) - end"); } ////////////////////////////////////////////////////////////////////////// -void SetConnectorsBlockVisitor::createTransmitters(SPtr<Block3D> cBlock, SPtr<Block3D> fBlock, int dir, - CreateTransmittersHelper::IBlock ib, - CreateTransmittersHelper::TransmitterPtr& senderCF, - CreateTransmittersHelper::TransmitterPtr& receiverCF, - CreateTransmittersHelper::TransmitterPtr& senderFC, - CreateTransmittersHelper::TransmitterPtr& receiverFC) +void SetConnectorsBlockVisitor::createTransmitters(SPtr<Block3D> cBlock, SPtr<Block3D> fBlock, int dir, + CreateTransmittersHelper::IBlock ib, + CreateTransmittersHelper::TransmitterPtr &senderCF, + CreateTransmittersHelper::TransmitterPtr &receiverCF, + CreateTransmittersHelper::TransmitterPtr &senderFC, + CreateTransmittersHelper::TransmitterPtr &receiverFC) { - UBLOG(logDEBUG5, "D3Q27SetConnectorsBlockVisitor::createTransmitters(...) - start"); - CreateTransmittersHelper helper; -// bool MPIpool = true; -// bool orthogonal = false; - int fBlockRank = fBlock->getRank(); - int cBlockRank = cBlock->getRank(); - if(fBlockRank == cBlockRank && fBlockRank == gridRank) - { - senderCF = receiverFC = CreateTransmittersHelper::TransmitterPtr( new TbLocalTransmitter< CbVector< LBMReal > >()); - senderFC = receiverCF = CreateTransmittersHelper::TransmitterPtr( new TbLocalTransmitter< CbVector< LBMReal > >()); - } - else if(cBlockRank == gridRank) - { - helper.createTransmitters(cBlock, fBlock, dir, ib, senderCF, receiverCF, comm, CreateTransmittersHelper::MPI); - } - else if(fBlockRank == gridRank) - { - helper.createTransmitters(fBlock, cBlock, dir, ib, senderFC, receiverFC, comm, CreateTransmittersHelper::MPI); - } - UBLOG(logDEBUG5, "D3Q27SetConnectorsBlockVisitor::createTransmitters(...) - end"); + UBLOG(logDEBUG5, "D3Q27SetConnectorsBlockVisitor::createTransmitters(...) - start"); + CreateTransmittersHelper helper; + // bool MPIpool = true; + // bool orthogonal = false; + int fBlockRank = fBlock->getRank(); + int cBlockRank = cBlock->getRank(); + if (fBlockRank == cBlockRank && fBlockRank == gridRank) { + senderCF = receiverFC = CreateTransmittersHelper::TransmitterPtr(new TbLocalTransmitter<CbVector<LBMReal>>()); + senderFC = receiverCF = CreateTransmittersHelper::TransmitterPtr(new TbLocalTransmitter<CbVector<LBMReal>>()); + } else if (cBlockRank == gridRank) { + helper.createTransmitters(cBlock, fBlock, dir, ib, senderCF, receiverCF, comm, CreateTransmittersHelper::MPI); + } else if (fBlockRank == gridRank) { + helper.createTransmitters(fBlock, cBlock, dir, ib, senderFC, receiverFC, comm, CreateTransmittersHelper::MPI); + } + UBLOG(logDEBUG5, "D3Q27SetConnectorsBlockVisitor::createTransmitters(...) - end"); } - diff --git a/src/cpu/VirtualFluidsCore/Visitors/SetConnectorsBlockVisitor.h b/src/cpu/VirtualFluidsCore/Visitors/SetConnectorsBlockVisitor.h index 7e7f13931b2d9ecf4200ed7987bb03ca04e5f9f4..9d855de05e419cbec8cb98422bbefcb851d3ddde 100644 --- a/src/cpu/VirtualFluidsCore/Visitors/SetConnectorsBlockVisitor.h +++ b/src/cpu/VirtualFluidsCore/Visitors/SetConnectorsBlockVisitor.h @@ -1,28 +1,28 @@ //======================================================================================= -// ____ ____ __ ______ __________ __ __ __ __ -// \ \ | | | | | _ \ |___ ___| | | | | / \ | | -// \ \ | | | | | |_) | | | | | | | / \ | | -// \ \ | | | | | _ / | | | | | | / /\ \ | | -// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ -// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| -// \ \ | | ________________________________________________________________ -// \ \ | | | ______________________________________________________________| -// \ \| | | | __ __ __ __ ______ _______ -// \ | | |_____ | | | | | | | | | _ \ / _____) -// \ | | _____| | | | | | | | | | | \ \ \_______ +// ____ ____ __ ______ __________ __ __ __ __ +// \ \ | | | | | _ \ |___ ___| | | | | / \ | | +// \ \ | | | | | |_) | | | | | | | / \ | | +// \ \ | | | | | _ / | | | | | | / /\ \ | | +// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ +// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| +// \ \ | | ________________________________________________________________ +// \ \ | | | ______________________________________________________________| +// \ \| | | | __ __ __ __ ______ _______ +// \ | | |_____ | | | | | | | | | _ \ / _____) +// \ | | _____| | | | | | | | | | | \ \ \_______ // \ | | | | |_____ | \_/ | | | | |_/ / _____ | -// \ _____| |__| |________| \_______/ |__| |______/ (_______/ +// \ _____| |__| |________| \_______/ |__| |______/ (_______/ // -// This file is part of VirtualFluids. VirtualFluids is free software: you can +// This file is part of VirtualFluids. VirtualFluids is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of +// License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. -// -// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// +// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License along // with VirtualFluids (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>. // @@ -50,27 +50,28 @@ class InterpolationProcessor; class SetConnectorsBlockVisitor : public Block3DVisitor { public: - SetConnectorsBlockVisitor(SPtr<Communicator> comm, bool fullConnector, int dirs, LBMReal nue, SPtr<InterpolationProcessor> iProcessor); - ~SetConnectorsBlockVisitor() override; - void visit(SPtr<Grid3D> grid, SPtr<Block3D> block) override; - ////////////////////////////////////////////////////////////////////////// + SetConnectorsBlockVisitor(SPtr<Communicator> comm, bool fullConnector, int dirs, LBMReal nue, + SPtr<InterpolationProcessor> iProcessor); + ~SetConnectorsBlockVisitor() override; + void visit(SPtr<Grid3D> grid, SPtr<Block3D> block) override; + ////////////////////////////////////////////////////////////////////////// protected: - void setSameLevelConnectors(SPtr<Grid3D> grid, SPtr<Block3D> block); - void setRemoteConnectors(SPtr<Block3D> sblock, SPtr<Block3D> tblock, int dir, bool fullConnector); - void setInterpolationConnectors(SPtr<Grid3D> grid, SPtr<Block3D> block); - void setInterpolationConnectors(SPtr<Block3D> fBlockSW, SPtr<Block3D> fBlockSE, SPtr<Block3D> fBlockNW, SPtr<Block3D> fBlockNE, SPtr<Block3D> cBlock, int dir); - void createTransmitters(SPtr<Block3D> cBlock, SPtr<Block3D> fBlock, int dir, - CreateTransmittersHelper::IBlock ib, - CreateTransmittersHelper::TransmitterPtr& senderCF, - CreateTransmittersHelper::TransmitterPtr& receiverCF, - CreateTransmittersHelper::TransmitterPtr& senderFC, - CreateTransmittersHelper::TransmitterPtr& receiverFC); + void setSameLevelConnectors(SPtr<Grid3D> grid, SPtr<Block3D> block); + void setRemoteConnectors(SPtr<Block3D> sblock, SPtr<Block3D> tblock, int dir, bool fullConnector); + void setInterpolationConnectors(SPtr<Grid3D> grid, SPtr<Block3D> block); + void setInterpolationConnectors(SPtr<Block3D> fBlockSW, SPtr<Block3D> fBlockSE, SPtr<Block3D> fBlockNW, + SPtr<Block3D> fBlockNE, SPtr<Block3D> cBlock, int dir); + void createTransmitters(SPtr<Block3D> cBlock, SPtr<Block3D> fBlock, int dir, CreateTransmittersHelper::IBlock ib, + CreateTransmittersHelper::TransmitterPtr &senderCF, + CreateTransmittersHelper::TransmitterPtr &receiverCF, + CreateTransmittersHelper::TransmitterPtr &senderFC, + CreateTransmittersHelper::TransmitterPtr &receiverFC); SPtr<Communicator> comm; - bool fullConnector; - int dirs; - int gridRank; - LBMReal nue; + bool fullConnector; + int dirs; + int gridRank; + LBMReal nue; SPtr<InterpolationProcessor> iProcessor; }; -#endif //SETCONNECTORSBLOCKVISITOR_H +#endif // SETCONNECTORSBLOCKVISITOR_H diff --git a/src/cpu/VirtualFluidsCore/Visitors/SetForcingBlockVisitor.cpp b/src/cpu/VirtualFluidsCore/Visitors/SetForcingBlockVisitor.cpp index ec83d8de4786d24f712ca9aaa5aeb8b31294c593..679b63de44dd451f030aaf866bc259579efab8ef 100644 --- a/src/cpu/VirtualFluidsCore/Visitors/SetForcingBlockVisitor.cpp +++ b/src/cpu/VirtualFluidsCore/Visitors/SetForcingBlockVisitor.cpp @@ -1,70 +1,64 @@ #include "SetForcingBlockVisitor.h" +#include "Block3D.h" +#include "Grid3D.h" #include "Grid3DSystem.h" #include "LBMSystem.h" -#include "Grid3D.h" -#include "Block3D.h" -SetForcingBlockVisitor::SetForcingBlockVisitor(LBMReal forcingX1, LBMReal forcingX2, LBMReal forcingX3) : - Block3DVisitor(0, Grid3DSystem::MAXLEVEL), forcingX1(forcingX1), - forcingX2(forcingX2), - forcingX3(forcingX3) +SetForcingBlockVisitor::SetForcingBlockVisitor(LBMReal forcingX1, LBMReal forcingX2, LBMReal forcingX3) + : Block3DVisitor(0, Grid3DSystem::MAXLEVEL), forcingX1(forcingX1), forcingX2(forcingX2), forcingX3(forcingX3) { - ftype = 0; + ftype = 0; } ////////////////////////////////////////////////////////////////////////// -SetForcingBlockVisitor::SetForcingBlockVisitor(const mu::Parser& muForcingX1, const mu::Parser& muForcingX2, const mu::Parser& muForcingX3) : - Block3DVisitor(0, Grid3DSystem::MAXLEVEL), muForcingX1(muForcingX1), - muForcingX2(muForcingX2), - muForcingX3(muForcingX3) +SetForcingBlockVisitor::SetForcingBlockVisitor(const mu::Parser &muForcingX1, const mu::Parser &muForcingX2, + const mu::Parser &muForcingX3) + : Block3DVisitor(0, Grid3DSystem::MAXLEVEL), muForcingX1(muForcingX1), muForcingX2(muForcingX2), + muForcingX3(muForcingX3) { - ftype = 1; + ftype = 1; } ////////////////////////////////////////////////////////////////////////// -SetForcingBlockVisitor::SetForcingBlockVisitor(const std::string& sForcingX1, const std::string& sForcingX2, const std::string& sForcingX3) : - Block3DVisitor(0, Grid3DSystem::MAXLEVEL), sForcingX1(sForcingX1), - sForcingX2(sForcingX2), - sForcingX3(sForcingX3) +SetForcingBlockVisitor::SetForcingBlockVisitor(const std::string &sForcingX1, const std::string &sForcingX2, + const std::string &sForcingX3) + : Block3DVisitor(0, Grid3DSystem::MAXLEVEL), sForcingX1(sForcingX1), sForcingX2(sForcingX2), sForcingX3(sForcingX3) { - ftype = 2; + ftype = 2; } ////////////////////////////////////////////////////////////////////////// void SetForcingBlockVisitor::visit(SPtr<Grid3D> grid, SPtr<Block3D> block) { - if(block->getRank() == grid->getRank()) - { - SPtr<LBMKernel> kernel = dynamicPointerCast<LBMKernel>(block->getKernel()); - if (!kernel) - throw UbException(UB_EXARGS, "LBMKernel is not exist"); + if (block->getRank() == grid->getRank()) { + SPtr<LBMKernel> kernel = dynamicPointerCast<LBMKernel>(block->getKernel()); + if (!kernel) + throw UbException(UB_EXARGS, "LBMKernel is not exist"); - switch (ftype) - { - case 0: - kernel->setForcingX1(forcingX1); - kernel->setForcingX2(forcingX2); - kernel->setForcingX3(forcingX3); - kernel->setWithForcing(true); - break; - case 1: - kernel->setForcingX1(muForcingX1); - kernel->setForcingX2(muForcingX2); - kernel->setForcingX3(muForcingX3); - kernel->setWithForcing(true); - break; - case 2: - kernel->setForcingX1(sForcingX1); - kernel->setForcingX2(sForcingX2); - kernel->setForcingX3(sForcingX3); - kernel->setWithForcing(true); - break; - default: - kernel->setForcingX1(0.0); - kernel->setForcingX2(0.0); - kernel->setForcingX3(0.0); - kernel->setWithForcing(false); - break; - } - } + switch (ftype) { + case 0: + kernel->setForcingX1(forcingX1); + kernel->setForcingX2(forcingX2); + kernel->setForcingX3(forcingX3); + kernel->setWithForcing(true); + break; + case 1: + kernel->setForcingX1(muForcingX1); + kernel->setForcingX2(muForcingX2); + kernel->setForcingX3(muForcingX3); + kernel->setWithForcing(true); + break; + case 2: + kernel->setForcingX1(sForcingX1); + kernel->setForcingX2(sForcingX2); + kernel->setForcingX3(sForcingX3); + kernel->setWithForcing(true); + break; + default: + kernel->setForcingX1(0.0); + kernel->setForcingX2(0.0); + kernel->setForcingX3(0.0); + kernel->setWithForcing(false); + break; + } + } } - diff --git a/src/cpu/VirtualFluidsCore/Visitors/SetForcingBlockVisitor.h b/src/cpu/VirtualFluidsCore/Visitors/SetForcingBlockVisitor.h index ac8936a138bf476b2da25f16271822e5945fe93b..a6d13c2a702f7ceca6122a78dda1b34f63caf376 100644 --- a/src/cpu/VirtualFluidsCore/Visitors/SetForcingBlockVisitor.h +++ b/src/cpu/VirtualFluidsCore/Visitors/SetForcingBlockVisitor.h @@ -8,32 +8,32 @@ class Block3D; class Grid3D; //! \brief Set forcing for all kernels of grid -//! \details This visitor is useful if you need to set or reset forcing in kernels (e.g. after restart because forcing is not serializable). -//! \author K. Kucher +//! \details This visitor is useful if you need to set or reset forcing in kernels (e.g. after restart because forcing +//! is not serializable). \author K. Kucher class SetForcingBlockVisitor : public Block3DVisitor { public: - SetForcingBlockVisitor(LBMReal forcingX1, LBMReal forcingX2, LBMReal forcingX3); - - SetForcingBlockVisitor(const mu::Parser& muForcingX1, const mu::Parser& muForcingX2, const mu::Parser& muForcingX3); + SetForcingBlockVisitor(LBMReal forcingX1, LBMReal forcingX2, LBMReal forcingX3); - SetForcingBlockVisitor(const std::string& sForcingX1, const std::string& sForcingX2, const std::string& sForcingX3); + SetForcingBlockVisitor(const mu::Parser &muForcingX1, const mu::Parser &muForcingX2, const mu::Parser &muForcingX3); - ~SetForcingBlockVisitor() override = default; + SetForcingBlockVisitor(const std::string &sForcingX1, const std::string &sForcingX2, const std::string &sForcingX3); - void visit(SPtr<Grid3D> grid, SPtr<Block3D> block) override; + ~SetForcingBlockVisitor() override = default; + + void visit(SPtr<Grid3D> grid, SPtr<Block3D> block) override; private: - int ftype; - LBMReal forcingX1; - LBMReal forcingX2; - LBMReal forcingX3; - mu::Parser muForcingX1; - mu::Parser muForcingX2; - mu::Parser muForcingX3; - std::string sForcingX1; - std::string sForcingX2; - std::string sForcingX3; + int ftype; + LBMReal forcingX1; + LBMReal forcingX2; + LBMReal forcingX3; + mu::Parser muForcingX1; + mu::Parser muForcingX2; + mu::Parser muForcingX3; + std::string sForcingX1; + std::string sForcingX2; + std::string sForcingX3; }; #endif diff --git a/src/cpu/VirtualFluidsCore/Visitors/SetInterpolationDirsBlockVisitor.cpp b/src/cpu/VirtualFluidsCore/Visitors/SetInterpolationDirsBlockVisitor.cpp index eeb1ba6911ac7c29fbfe6f8fa82a74213f4d1f8d..bb1ae79620179f65abd51672bd9958f471c398c7 100644 --- a/src/cpu/VirtualFluidsCore/Visitors/SetInterpolationDirsBlockVisitor.cpp +++ b/src/cpu/VirtualFluidsCore/Visitors/SetInterpolationDirsBlockVisitor.cpp @@ -1,131 +1,148 @@ #include "SetInterpolationDirsBlockVisitor.h" +#include "Block3D.h" +#include "Grid3D.h" #include "Grid3DSystem.h" #include <D3Q27System.h> -#include "Grid3D.h" -#include "Block3D.h" - -SetInterpolationDirsBlockVisitor::SetInterpolationDirsBlockVisitor(std::vector<int>& dirs) : - Block3DVisitor(0, Grid3DSystem::MAXLEVEL), dirs(dirs) +SetInterpolationDirsBlockVisitor::SetInterpolationDirsBlockVisitor(std::vector<int> &dirs) + : Block3DVisitor(0, Grid3DSystem::MAXLEVEL), dirs(dirs) { - } ////////////////////////////////////////////////////////////////////////// void SetInterpolationDirsBlockVisitor::visit(SPtr<Grid3D> grid, SPtr<Block3D> block) { - int ix1, ix2, ix3, level; - ix1 = block->getX1(); - ix2 = block->getX2(); - ix3 = block->getX3(); - level = block->getLevel(); - using namespace D3Q27System; - if(level==0) return; + int ix1, ix2, ix3, level; + ix1 = block->getX1(); + ix2 = block->getX2(); + ix3 = block->getX3(); + level = block->getLevel(); + using namespace D3Q27System; + if (level == 0) + return; - SPtr<Block3D> parentblock = grid->getSuperBlock(ix1,ix2,ix3,level); - if(!parentblock) return; + SPtr<Block3D> parentblock = grid->getSuperBlock(ix1, ix2, ix3, level); + if (!parentblock) + return; - for(int dir : dirs) - { - SPtr<Block3D> nblock = grid->getNeighborBlock(dir, ix1, ix2, ix3, level); - if(!nblock) - { - SPtr<Block3D> p_nblock = grid->getNeighborBlock(dir, parentblock); + for (int dir : dirs) { + SPtr<Block3D> nblock = grid->getNeighborBlock(dir, ix1, ix2, ix3, level); + if (!nblock) { + SPtr<Block3D> p_nblock = grid->getNeighborBlock(dir, parentblock); - if (p_nblock) - { - bool flagDir; - switch (dir) - { - case NE: - checkFlagDir(grid, E, N, flagDir, ix1, ix2, ix3, level); - if(!flagDir) continue; - break; - case SW: - checkFlagDir(grid, W, S, flagDir, ix1, ix2, ix3, level); - if(!flagDir) continue; - break; - case SE: - checkFlagDir(grid, E, S, flagDir, ix1, ix2, ix3, level); - if(!flagDir) continue; - break; - case NW: - checkFlagDir(grid, W, N, flagDir, ix1, ix2, ix3, level); - if(!flagDir) continue; - break; - case TE: - checkFlagDir(grid, E, T, flagDir, ix1, ix2, ix3, level); - if(!flagDir)continue; - break; - case BW: - checkFlagDir(grid, W, B, flagDir, ix1, ix2, ix3, level); - if(!flagDir) continue; - break; - case BE: - checkFlagDir(grid, E, B, flagDir, ix1, ix2, ix3, level); - if(!flagDir) continue; - break; - case TW: - checkFlagDir(grid, W, T, flagDir, ix1, ix2, ix3, level); - if(!flagDir) continue; - break; - case TN: - checkFlagDir(grid, N, T, flagDir, ix1, ix2, ix3, level); - if(!flagDir) continue; - break; - case BS: - checkFlagDir(grid, S, B, flagDir, ix1, ix2, ix3, level); - if(!flagDir) continue; - break; - case BN: - checkFlagDir(grid, N, B, flagDir, ix1, ix2, ix3, level); - if(!flagDir) continue; - break; - case TS: - checkFlagDir(grid, S, T, flagDir, ix1, ix2, ix3, level); - if(!flagDir) continue; - break; - case TNE: - checkFlagDir(grid, E, N, T, flagDir, ix1, ix2, ix3, level); - if (!flagDir) continue; - break; - case TSW: - checkFlagDir(grid, W, S, T, flagDir, ix1, ix2, ix3, level); - if (!flagDir) continue; - break; - case TSE: - checkFlagDir(grid, E, S, T, flagDir, ix1, ix2, ix3, level); - if (!flagDir) continue; - break; - case TNW: - checkFlagDir(grid, W, N, T, flagDir, ix1, ix2, ix3, level); - if (!flagDir) continue; - break; - case BNE: - checkFlagDir(grid, E, N, B, flagDir, ix1, ix2, ix3, level); - if (!flagDir) continue; - break; - case BSW: - checkFlagDir(grid, W, S, B, flagDir, ix1, ix2, ix3, level); - if (!flagDir) continue; - break; - case BSE: - checkFlagDir(grid, E, S, B, flagDir, ix1, ix2, ix3, level); - if (!flagDir) continue; - break; - case BNW: - checkFlagDir(grid, W, N, B, flagDir, ix1, ix2, ix3, level); - if (!flagDir) continue; - break; - } + if (p_nblock) { + bool flagDir; + switch (dir) { + case NE: + checkFlagDir(grid, E, N, flagDir, ix1, ix2, ix3, level); + if (!flagDir) + continue; + break; + case SW: + checkFlagDir(grid, W, S, flagDir, ix1, ix2, ix3, level); + if (!flagDir) + continue; + break; + case SE: + checkFlagDir(grid, E, S, flagDir, ix1, ix2, ix3, level); + if (!flagDir) + continue; + break; + case NW: + checkFlagDir(grid, W, N, flagDir, ix1, ix2, ix3, level); + if (!flagDir) + continue; + break; + case TE: + checkFlagDir(grid, E, T, flagDir, ix1, ix2, ix3, level); + if (!flagDir) + continue; + break; + case BW: + checkFlagDir(grid, W, B, flagDir, ix1, ix2, ix3, level); + if (!flagDir) + continue; + break; + case BE: + checkFlagDir(grid, E, B, flagDir, ix1, ix2, ix3, level); + if (!flagDir) + continue; + break; + case TW: + checkFlagDir(grid, W, T, flagDir, ix1, ix2, ix3, level); + if (!flagDir) + continue; + break; + case TN: + checkFlagDir(grid, N, T, flagDir, ix1, ix2, ix3, level); + if (!flagDir) + continue; + break; + case BS: + checkFlagDir(grid, S, B, flagDir, ix1, ix2, ix3, level); + if (!flagDir) + continue; + break; + case BN: + checkFlagDir(grid, N, B, flagDir, ix1, ix2, ix3, level); + if (!flagDir) + continue; + break; + case TS: + checkFlagDir(grid, S, T, flagDir, ix1, ix2, ix3, level); + if (!flagDir) + continue; + break; + case TNE: + checkFlagDir(grid, E, N, T, flagDir, ix1, ix2, ix3, level); + if (!flagDir) + continue; + break; + case TSW: + checkFlagDir(grid, W, S, T, flagDir, ix1, ix2, ix3, level); + if (!flagDir) + continue; + break; + case TSE: + checkFlagDir(grid, E, S, T, flagDir, ix1, ix2, ix3, level); + if (!flagDir) + continue; + break; + case TNW: + checkFlagDir(grid, W, N, T, flagDir, ix1, ix2, ix3, level); + if (!flagDir) + continue; + break; + case BNE: + checkFlagDir(grid, E, N, B, flagDir, ix1, ix2, ix3, level); + if (!flagDir) + continue; + break; + case BSW: + checkFlagDir(grid, W, S, B, flagDir, ix1, ix2, ix3, level); + if (!flagDir) + continue; + break; + case BSE: + checkFlagDir(grid, E, S, B, flagDir, ix1, ix2, ix3, level); + if (!flagDir) + continue; + break; + case BNW: + checkFlagDir(grid, W, N, B, flagDir, ix1, ix2, ix3, level); + if (!flagDir) + continue; + break; + } - block->setInterpolationFlagFC(dir); - parentblock->setInterpolationFlagCF(dir); - } - } - } + block->setInterpolationFlagFC(dir); + parentblock->setInterpolationFlagCF(dir); + } + } + } } ////////////////////////////////////////////////////////////////////////// -//void SetInterpolationDirsBlockVisitor::checkFlagDir(SPtr<Grid3D> grid, int dir1, int dir2, bool &flagDirection, int ix1, int ix2, int ix3, int level) +// void SetInterpolationDirsBlockVisitor::checkFlagDir(SPtr<Grid3D> grid, int dir1, int dir2, bool &flagDirection, int +// ix1, int ix2, int ix3, int level) //{ // SPtr<Block3D> block1 = grid->getNeighborBlock(dir1, ix1, ix2, ix3, level); // SPtr<Block3D> block2 = grid->getNeighborBlock(dir2, ix1, ix2, ix3, level); @@ -135,28 +152,30 @@ void SetInterpolationDirsBlockVisitor::visit(SPtr<Grid3D> grid, SPtr<Block3D> bl // flagDirection = true; //} -void SetInterpolationDirsBlockVisitor::checkFlagDir(SPtr<Grid3D> grid, int dir1, int dir2, bool &flagDirection, int ix1, int ix2, int ix3, int level) +void SetInterpolationDirsBlockVisitor::checkFlagDir(SPtr<Grid3D> grid, int dir1, int dir2, bool &flagDirection, int ix1, + int ix2, int ix3, int level) { - SPtr<Block3D> block1 = grid->getNeighborBlock(dir1, ix1, ix2, ix3, level); - SPtr<Block3D> block2 = grid->getNeighborBlock(dir2, ix1, ix2, ix3, level); + SPtr<Block3D> block1 = grid->getNeighborBlock(dir1, ix1, ix2, ix3, level); + SPtr<Block3D> block2 = grid->getNeighborBlock(dir2, ix1, ix2, ix3, level); - SPtr<Block3D> pblock = grid->getSuperBlock(ix1,ix2,ix3,level); - SPtr<Block3D> pblock1 = grid->getNeighborBlock(dir1, pblock); - SPtr<Block3D> pblock2 = grid->getNeighborBlock(dir2, pblock); + SPtr<Block3D> pblock = grid->getSuperBlock(ix1, ix2, ix3, level); + SPtr<Block3D> pblock1 = grid->getNeighborBlock(dir1, pblock); + SPtr<Block3D> pblock2 = grid->getNeighborBlock(dir2, pblock); - if (!((block1 && block2)||(!block1 && !block2)) || !((pblock1 && pblock2)||(!pblock1 && !pblock2))) - flagDirection = false; - else - flagDirection = true; + if (!((block1 && block2) || (!block1 && !block2)) || !((pblock1 && pblock2) || (!pblock1 && !pblock2))) + flagDirection = false; + else + flagDirection = true; } ////////////////////////////////////////////////////////////////////////// -void SetInterpolationDirsBlockVisitor::checkFlagDir(SPtr<Grid3D> grid, int dir1, int dir2, int dir3, bool &flagDirection, int ix1, int ix2, int ix3, int level) +void SetInterpolationDirsBlockVisitor::checkFlagDir(SPtr<Grid3D> grid, int dir1, int dir2, int dir3, + bool &flagDirection, int ix1, int ix2, int ix3, int level) { - SPtr<Block3D> block1 = grid->getNeighborBlock(dir1, ix1, ix2, ix3, level); - SPtr<Block3D> block2 = grid->getNeighborBlock(dir2, ix1, ix2, ix3, level); - SPtr<Block3D> block3 = grid->getNeighborBlock(dir3, ix1, ix2, ix3, level); - if (!((block1 && block2 && block3) || (!block1 && !block2 && !block3))) - flagDirection=false; - else - flagDirection=true; + SPtr<Block3D> block1 = grid->getNeighborBlock(dir1, ix1, ix2, ix3, level); + SPtr<Block3D> block2 = grid->getNeighborBlock(dir2, ix1, ix2, ix3, level); + SPtr<Block3D> block3 = grid->getNeighborBlock(dir3, ix1, ix2, ix3, level); + if (!((block1 && block2 && block3) || (!block1 && !block2 && !block3))) + flagDirection = false; + else + flagDirection = true; } diff --git a/src/cpu/VirtualFluidsCore/Visitors/SetInterpolationDirsBlockVisitor.h b/src/cpu/VirtualFluidsCore/Visitors/SetInterpolationDirsBlockVisitor.h index 75dafc89949bc41deef5c1f3ae9f89e31a96576a..078a06766d7a7b351ca36bdc79e604f9201bab6c 100644 --- a/src/cpu/VirtualFluidsCore/Visitors/SetInterpolationDirsBlockVisitor.h +++ b/src/cpu/VirtualFluidsCore/Visitors/SetInterpolationDirsBlockVisitor.h @@ -1,8 +1,8 @@ #ifndef SetInterpolationDirsBlockVisitor_h #define SetInterpolationDirsBlockVisitor_h -#include <vector> #include <PointerDefinitions.h> +#include <vector> #include "Block3DVisitor.h" @@ -12,16 +12,17 @@ class Block3D; class SetInterpolationDirsBlockVisitor : public Block3DVisitor { public: - SetInterpolationDirsBlockVisitor(std::vector<int>& dirs); + SetInterpolationDirsBlockVisitor(std::vector<int> &dirs); - ~SetInterpolationDirsBlockVisitor() override = default; + ~SetInterpolationDirsBlockVisitor() override = default; - void visit(SPtr<Grid3D> grid, SPtr<Block3D> block) override; + void visit(SPtr<Grid3D> grid, SPtr<Block3D> block) override; private: - std::vector<int> dirs; - void checkFlagDir(SPtr<Grid3D> grid, int dir1, int dir2, bool &flagDirection, int ix1, int ix2, int ix3, int level); - void checkFlagDir(SPtr<Grid3D> grid, int dir1, int dir2, int dir3, bool &flagDirection, int ix1, int ix2, int ix3, int level); + std::vector<int> dirs; + void checkFlagDir(SPtr<Grid3D> grid, int dir1, int dir2, bool &flagDirection, int ix1, int ix2, int ix3, int level); + void checkFlagDir(SPtr<Grid3D> grid, int dir1, int dir2, int dir3, bool &flagDirection, int ix1, int ix2, int ix3, + int level); }; #endif diff --git a/src/cpu/VirtualFluidsCore/Visitors/SetKernelBlockVisitor.cpp b/src/cpu/VirtualFluidsCore/Visitors/SetKernelBlockVisitor.cpp index d3ec9e85ec58b977008e6fee49e5c5b64786e3c4..5c813d28951b24269735b0dbf1f84fdfb360cf31 100644 --- a/src/cpu/VirtualFluidsCore/Visitors/SetKernelBlockVisitor.cpp +++ b/src/cpu/VirtualFluidsCore/Visitors/SetKernelBlockVisitor.cpp @@ -1,29 +1,29 @@ #include "MemoryUtil.h" //======================================================================================= -// ____ ____ __ ______ __________ __ __ __ __ -// \ \ | | | | | _ \ |___ ___| | | | | / \ | | -// \ \ | | | | | |_) | | | | | | | / \ | | -// \ \ | | | | | _ / | | | | | | / /\ \ | | -// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ -// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| -// \ \ | | ________________________________________________________________ -// \ \ | | | ______________________________________________________________| -// \ \| | | | __ __ __ __ ______ _______ -// \ | | |_____ | | | | | | | | | _ \ / _____) -// \ | | _____| | | | | | | | | | | \ \ \_______ +// ____ ____ __ ______ __________ __ __ __ __ +// \ \ | | | | | _ \ |___ ___| | | | | / \ | | +// \ \ | | | | | |_) | | | | | | | / \ | | +// \ \ | | | | | _ / | | | | | | / /\ \ | | +// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ +// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| +// \ \ | | ________________________________________________________________ +// \ \ | | | ______________________________________________________________| +// \ \| | | | __ __ __ __ ______ _______ +// \ | | |_____ | | | | | | | | | _ \ / _____) +// \ | | _____| | | | | | | | | | | \ \ \_______ // \ | | | | |_____ | \_/ | | | | |_/ / _____ | -// \ _____| |__| |________| \_______/ |__| |______/ (_______/ +// \ _____| |__| |________| \_______/ |__| |______/ (_______/ // -// This file is part of VirtualFluids. VirtualFluids is free software: you can +// This file is part of VirtualFluids. VirtualFluids is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of +// License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. -// -// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// +// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License along // with VirtualFluids (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>. // @@ -34,111 +34,90 @@ #include "SetKernelBlockVisitor.h" -#include <utility> -#include "Grid3DSystem.h" -#include "LBMSystem.h" -#include "DataSet3D.h" #include "BCProcessor.h" -#include "Grid3D.h" #include "Block3D.h" +#include "DataSet3D.h" +#include "Grid3D.h" +#include "Grid3DSystem.h" #include "LBMKernel.h" +#include "LBMSystem.h" +#include <utility> ////////////////////////////////////////////////////////////////////////// SetKernelBlockVisitor::SetKernelBlockVisitor(SPtr<LBMKernel> kernel, LBMReal nue, double availMem, double needMem, - SetKernelBlockVisitor::Action action) : Block3DVisitor(0, - Grid3DSystem::MAXLEVEL), - kernel(std::move(kernel)), nue(nue), - action(action), dataSetFlag(true) + SetKernelBlockVisitor::Action action) + : Block3DVisitor(0, Grid3DSystem::MAXLEVEL), kernel(std::move(kernel)), nue(nue), action(action), dataSetFlag(true) { - if (needMem > availMem) - { + if (needMem > availMem) { throw UbException(UB_EXARGS, "SetKernelBlockVisitor: Not enough memory!!!"); } } -SetKernelBlockVisitor::SetKernelBlockVisitor(SPtr<LBMKernel> kernel, - LBMReal nue, - int &numberOfProcesses, - SetKernelBlockVisitor::Action action) : Block3DVisitor(0, - Grid3DSystem::MAXLEVEL), - kernel(std::move(kernel)), - nue(nue), - action(action), - dataSetFlag(true), - numberOfProcesses( - numberOfProcesses) -{} +SetKernelBlockVisitor::SetKernelBlockVisitor(SPtr<LBMKernel> kernel, LBMReal nue, int &numberOfProcesses, + SetKernelBlockVisitor::Action action) + : Block3DVisitor(0, Grid3DSystem::MAXLEVEL), kernel(std::move(kernel)), nue(nue), action(action), dataSetFlag(true), + numberOfProcesses(numberOfProcesses) +{ +} ////////////////////////////////////////////////////////////////////////// void SetKernelBlockVisitor::visit(SPtr<Grid3D> grid, SPtr<Block3D> block) { throwExceptionIfNotEnoughMemory(grid); - if (kernel && (block->getRank() == grid->getRank())) - { + if (kernel && (block->getRank() == grid->getRank())) { LBMReal collFactor = LBMSystem::calcCollisionFactor(nue, block->getLevel()); kernel->setCollisionFactor(collFactor); kernel->setIndex(block->getX1(), block->getX2(), block->getX3()); kernel->setDeltaT(LBMSystem::getDeltaT(block->getLevel())); kernel->setBlock(block); UbTupleInt3 blockNX = grid->getBlockNX(); - kernel->setNX(std::array<int, 3>{{val<1>(blockNX), val<2>(blockNX), val<3>(blockNX)}}); + kernel->setNX(std::array<int, 3>{ { val<1>(blockNX), val<2>(blockNX), val<3>(blockNX) } }); SPtr<LBMKernel> newKernel = kernel->clone(); - switch (action) - { + switch (action) { case SetKernelBlockVisitor::NewKernel: block->setKernel(newKernel); break; - case SetKernelBlockVisitor::ChangeKernel: - { + case SetKernelBlockVisitor::ChangeKernel: { SPtr<DataSet3D> dataSet = block->getKernel()->getDataSet(); - if (!dataSet) - { - UB_THROW(UbException(UB_EXARGS, - "It is not possible to change a DataSet in kernel! Old DataSet is not exist!")); + if (!dataSet) { + UB_THROW(UbException( + UB_EXARGS, "It is not possible to change a DataSet in kernel! Old DataSet is not exist!")); } newKernel->setDataSet(dataSet); SPtr<BCProcessor> bcProc = block->getKernel()->getBCProcessor(); - if (!bcProc) - { - UB_THROW(UbException(UB_EXARGS, - "It is not possible to change a BCProcessor in kernel! Old BCProcessor is not exist!")); + if (!bcProc) { + UB_THROW(UbException( + UB_EXARGS, + "It is not possible to change a BCProcessor in kernel! Old BCProcessor is not exist!")); } newKernel->setBCProcessor(bcProc); block->setKernel(newKernel); - } - break; + } break; - case SetKernelBlockVisitor::ChangeKernelWithData: - { + case SetKernelBlockVisitor::ChangeKernelWithData: { SPtr<BCProcessor> bcProc = block->getKernel()->getBCProcessor(); - if (!bcProc) - { - UB_THROW(UbException(UB_EXARGS, - "It is not possible to change a BCProcessor in kernel! Old BCProcessor is not exist!")); + if (!bcProc) { + UB_THROW(UbException( + UB_EXARGS, + "It is not possible to change a BCProcessor in kernel! Old BCProcessor is not exist!")); } newKernel->setBCProcessor(bcProc); block->setKernel(newKernel); - } - break; + } break; } - } } - -void SetKernelBlockVisitor::setNoDataSetFlag(bool flag) -{ - dataSetFlag = flag; -} +void SetKernelBlockVisitor::setNoDataSetFlag(bool flag) { dataSetFlag = flag; } void SetKernelBlockVisitor::throwExceptionIfNotEnoughMemory(const SPtr<Grid3D> &grid) { auto availableMemory = Utilities::getTotalPhysMem(); - auto requiredMemory = getRequiredPhysicalMemory(grid); + auto requiredMemory = getRequiredPhysicalMemory(grid); if (requiredMemory > availableMemory) throw UbException(UB_EXARGS, "SetKernelBlockVisitor: Not enough memory!!!"); } @@ -146,20 +125,15 @@ void SetKernelBlockVisitor::throwExceptionIfNotEnoughMemory(const SPtr<Grid3D> & double SetKernelBlockVisitor::getRequiredPhysicalMemory(const SPtr<Grid3D> &grid) const { unsigned long long numberOfNodesPerBlockWithGhostLayer; - auto numberOfBlocks = (unsigned long long) grid->getNumberOfBlocks(); - auto blockNx = grid->getBlockNX(); - int ghostLayer = 3; + auto numberOfBlocks = (unsigned long long)grid->getNumberOfBlocks(); + auto blockNx = grid->getBlockNX(); + int ghostLayer = 3; - numberOfNodesPerBlockWithGhostLayer = numberOfBlocks - * (val<1>(blockNx) + ghostLayer) - * (val<2>(blockNx) + ghostLayer) - * (val<3>(blockNx) + ghostLayer); + numberOfNodesPerBlockWithGhostLayer = numberOfBlocks * (val<1>(blockNx) + ghostLayer) * + (val<2>(blockNx) + ghostLayer) * (val<3>(blockNx) + ghostLayer); - auto needMemAll = double(numberOfNodesPerBlockWithGhostLayer - * (27 * sizeof(double) - + sizeof(int) - + sizeof(float) * 4)); + auto needMemAll = + double(numberOfNodesPerBlockWithGhostLayer * (27 * sizeof(double) + sizeof(int) + sizeof(float) * 4)); return needMemAll / double(numberOfProcesses); } - diff --git a/src/cpu/VirtualFluidsCore/Visitors/SetKernelBlockVisitor.h b/src/cpu/VirtualFluidsCore/Visitors/SetKernelBlockVisitor.h index e676d3f7e6c73f37192bad8627f827f83bd90bc8..6eb8f6577e0c467df469667900d43e1a38ea15b1 100644 --- a/src/cpu/VirtualFluidsCore/Visitors/SetKernelBlockVisitor.h +++ b/src/cpu/VirtualFluidsCore/Visitors/SetKernelBlockVisitor.h @@ -1,28 +1,28 @@ //======================================================================================= -// ____ ____ __ ______ __________ __ __ __ __ -// \ \ | | | | | _ \ |___ ___| | | | | / \ | | -// \ \ | | | | | |_) | | | | | | | / \ | | -// \ \ | | | | | _ / | | | | | | / /\ \ | | -// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ -// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| -// \ \ | | ________________________________________________________________ -// \ \ | | | ______________________________________________________________| -// \ \| | | | __ __ __ __ ______ _______ -// \ | | |_____ | | | | | | | | | _ \ / _____) -// \ | | _____| | | | | | | | | | | \ \ \_______ +// ____ ____ __ ______ __________ __ __ __ __ +// \ \ | | | | | _ \ |___ ___| | | | | / \ | | +// \ \ | | | | | |_) | | | | | | | / \ | | +// \ \ | | | | | _ / | | | | | | / /\ \ | | +// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ +// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| +// \ \ | | ________________________________________________________________ +// \ \ | | | ______________________________________________________________| +// \ \| | | | __ __ __ __ ______ _______ +// \ | | |_____ | | | | | | | | | _ \ / _____) +// \ | | _____| | | | | | | | | | | \ \ \_______ // \ | | | | |_____ | \_/ | | | | |_/ / _____ | -// \ _____| |__| |________| \_______/ |__| |______/ (_______/ +// \ _____| |__| |________| \_______/ |__| |______/ (_______/ // -// This file is part of VirtualFluids. VirtualFluids is free software: you can +// This file is part of VirtualFluids. VirtualFluids is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of +// License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. -// -// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// +// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License along // with VirtualFluids (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>. // @@ -47,14 +47,11 @@ class LBMKernel; class SetKernelBlockVisitor : public Block3DVisitor { public: - enum Action - { - NewKernel, ChangeKernel, ChangeKernelWithData - }; + enum Action { NewKernel, ChangeKernel, ChangeKernelWithData }; - //SetKernelBlockVisitor(LBMKernel3DPtr kernel, LBMReal nue); + // SetKernelBlockVisitor(LBMKernel3DPtr kernel, LBMReal nue); - //SetKernelBlockVisitor(LBMKernel3DPtr kernel, LBMReal nue, double availMem, double needMem); + // SetKernelBlockVisitor(LBMKernel3DPtr kernel, LBMReal nue, double availMem, double needMem); SetKernelBlockVisitor(SPtr<LBMKernel> kernel, LBMReal nue, double availMem, double needMem, SetKernelBlockVisitor::Action action = SetKernelBlockVisitor::NewKernel); @@ -74,7 +71,7 @@ private: Action action; bool dataSetFlag; - int numberOfProcesses{1}; + int numberOfProcesses{ 1 }; double getRequiredPhysicalMemory(const SPtr<Grid3D> &grid) const; diff --git a/src/cpu/VirtualFluidsCore/Visitors/SetSolidBlocksBlockVisitor.cpp b/src/cpu/VirtualFluidsCore/Visitors/SetSolidBlocksBlockVisitor.cpp index de9edef09deb391a772651bb590f7bdbde703522..3354755f22f18df700523d795c8fced0d0f19628 100644 --- a/src/cpu/VirtualFluidsCore/Visitors/SetSolidBlocksBlockVisitor.cpp +++ b/src/cpu/VirtualFluidsCore/Visitors/SetSolidBlocksBlockVisitor.cpp @@ -1,28 +1,28 @@ //======================================================================================= -// ____ ____ __ ______ __________ __ __ __ __ -// \ \ | | | | | _ \ |___ ___| | | | | / \ | | -// \ \ | | | | | |_) | | | | | | | / \ | | -// \ \ | | | | | _ / | | | | | | / /\ \ | | -// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ -// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| -// \ \ | | ________________________________________________________________ -// \ \ | | | ______________________________________________________________| -// \ \| | | | __ __ __ __ ______ _______ -// \ | | |_____ | | | | | | | | | _ \ / _____) -// \ | | _____| | | | | | | | | | | \ \ \_______ +// ____ ____ __ ______ __________ __ __ __ __ +// \ \ | | | | | _ \ |___ ___| | | | | / \ | | +// \ \ | | | | | |_) | | | | | | | / \ | | +// \ \ | | | | | _ / | | | | | | / /\ \ | | +// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ +// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| +// \ \ | | ________________________________________________________________ +// \ \ | | | ______________________________________________________________| +// \ \| | | | __ __ __ __ ______ _______ +// \ | | |_____ | | | | | | | | | _ \ / _____) +// \ | | _____| | | | | | | | | | | \ \ \_______ // \ | | | | |_____ | \_/ | | | | |_/ / _____ | -// \ _____| |__| |________| \_______/ |__| |______/ (_______/ +// \ _____| |__| |________| \_______/ |__| |______/ (_______/ // -// This file is part of VirtualFluids. VirtualFluids is free software: you can +// This file is part of VirtualFluids. VirtualFluids is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of +// License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. -// -// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// +// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License along // with VirtualFluids (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>. // @@ -35,24 +35,21 @@ #include <utility> -#include "Interactor3D.h" -#include "Grid3DSystem.h" -#include "Grid3D.h" #include "Block3D.h" +#include "Grid3D.h" +#include "Grid3DSystem.h" +#include "Interactor3D.h" -SetSolidBlocksBlockVisitor::SetSolidBlocksBlockVisitor(SPtr<Interactor3D> interactor) : - Block3DVisitor(0, Grid3DSystem::MAXLEVEL), interactor(std::move(interactor)) +SetSolidBlocksBlockVisitor::SetSolidBlocksBlockVisitor(SPtr<Interactor3D> interactor) + : Block3DVisitor(0, Grid3DSystem::MAXLEVEL), interactor(std::move(interactor)) { - } void SetSolidBlocksBlockVisitor::visit(SPtr<Grid3D> grid, SPtr<Block3D> block) { - if (block->getRank() == grid->getRank()) - { - if (block->isActive()) - { - interactor->setSolidBlock(block); - } - } + if (block->getRank() == grid->getRank()) { + if (block->isActive()) { + interactor->setSolidBlock(block); + } + } } \ No newline at end of file diff --git a/src/cpu/VirtualFluidsCore/Visitors/SetSolidBlocksBlockVisitor.h b/src/cpu/VirtualFluidsCore/Visitors/SetSolidBlocksBlockVisitor.h index fe5456be9d021b5676aca18e97eb47af92188929..fcbb3de0cc7cd04c1f3d3aa15a048b78eacd95be 100644 --- a/src/cpu/VirtualFluidsCore/Visitors/SetSolidBlocksBlockVisitor.h +++ b/src/cpu/VirtualFluidsCore/Visitors/SetSolidBlocksBlockVisitor.h @@ -1,28 +1,28 @@ //======================================================================================= -// ____ ____ __ ______ __________ __ __ __ __ -// \ \ | | | | | _ \ |___ ___| | | | | / \ | | -// \ \ | | | | | |_) | | | | | | | / \ | | -// \ \ | | | | | _ / | | | | | | / /\ \ | | -// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ -// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| -// \ \ | | ________________________________________________________________ -// \ \ | | | ______________________________________________________________| -// \ \| | | | __ __ __ __ ______ _______ -// \ | | |_____ | | | | | | | | | _ \ / _____) -// \ | | _____| | | | | | | | | | | \ \ \_______ +// ____ ____ __ ______ __________ __ __ __ __ +// \ \ | | | | | _ \ |___ ___| | | | | / \ | | +// \ \ | | | | | |_) | | | | | | | / \ | | +// \ \ | | | | | _ / | | | | | | / /\ \ | | +// \ \ | | | | | | \ \ | | | \__/ | / ____ \ | |____ +// \ \ | | |__| |__| \__\ |__| \________/ /__/ \__\ |_______| +// \ \ | | ________________________________________________________________ +// \ \ | | | ______________________________________________________________| +// \ \| | | | __ __ __ __ ______ _______ +// \ | | |_____ | | | | | | | | | _ \ / _____) +// \ | | _____| | | | | | | | | | | \ \ \_______ // \ | | | | |_____ | \_/ | | | | |_/ / _____ | -// \ _____| |__| |________| \_______/ |__| |______/ (_______/ +// \ _____| |__| |________| \_______/ |__| |______/ (_______/ // -// This file is part of VirtualFluids. VirtualFluids is free software: you can +// This file is part of VirtualFluids. VirtualFluids is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public -// License as published by the Free Software Foundation, either version 3 of +// License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. -// -// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT -// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +// +// VirtualFluids is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. -// +// // You should have received a copy of the GNU General Public License along // with VirtualFluids (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>. // @@ -46,13 +46,13 @@ class Interactor3D; class SetSolidBlocksBlockVisitor : public Block3DVisitor { public: - SetSolidBlocksBlockVisitor(SPtr<Interactor3D> interactor); - ~SetSolidBlocksBlockVisitor() override = default; + SetSolidBlocksBlockVisitor(SPtr<Interactor3D> interactor); + ~SetSolidBlocksBlockVisitor() override = default; - void visit(SPtr<Grid3D> grid, SPtr<Block3D> block) override; + void visit(SPtr<Grid3D> grid, SPtr<Block3D> block) override; private: - SPtr<Interactor3D> interactor; + SPtr<Interactor3D> interactor; } #endif // SetSolidBlocksBlockVisitor_h__ ; diff --git a/src/cpu/VirtualFluidsCore/Visitors/SetSpongeLayerBlockVisitor.cpp b/src/cpu/VirtualFluidsCore/Visitors/SetSpongeLayerBlockVisitor.cpp index 68c338d86aae39a852cf4b69d4df368b4615a024..040f54b0fd645a206952ce2c992d4abeea3ace85 100644 --- a/src/cpu/VirtualFluidsCore/Visitors/SetSpongeLayerBlockVisitor.cpp +++ b/src/cpu/VirtualFluidsCore/Visitors/SetSpongeLayerBlockVisitor.cpp @@ -2,28 +2,24 @@ #include "Grid3DSystem.h" #include "LBMSystem.h" -#include "LBMKernel.h" -#include "Grid3D.h" #include "Block3D.h" +#include "Grid3D.h" +#include "LBMKernel.h" -SetSpongeLayerBlockVisitor::SetSpongeLayerBlockVisitor( const mu::Parser& spongeLayer ) : Block3DVisitor(0, Grid3DSystem::MAXLEVEL), spongeLayer(spongeLayer) +SetSpongeLayerBlockVisitor::SetSpongeLayerBlockVisitor(const mu::Parser &spongeLayer) + : Block3DVisitor(0, Grid3DSystem::MAXLEVEL), spongeLayer(spongeLayer) { - } ////////////////////////////////////////////////////////////////////////// -SetSpongeLayerBlockVisitor::~SetSpongeLayerBlockVisitor() -= default; +SetSpongeLayerBlockVisitor::~SetSpongeLayerBlockVisitor() = default; ////////////////////////////////////////////////////////////////////////// -void SetSpongeLayerBlockVisitor::visit( SPtr<Grid3D> grid, SPtr<Block3D> block ) +void SetSpongeLayerBlockVisitor::visit(SPtr<Grid3D> grid, SPtr<Block3D> block) { - if(block->getRank() == grid->getRank()) - { - SPtr<LBMKernel> kernel = dynamicPointerCast<LBMKernel>(block->getKernel()); - if (!kernel) - throw std::runtime_error("SetSpongeLayerBlockVisitor: Kernel is not a LBMKernel"); - kernel->setWithSpongeLayer(true); - kernel->setSpongeLayer(spongeLayer); - } + if (block->getRank() == grid->getRank()) { + SPtr<LBMKernel> kernel = dynamicPointerCast<LBMKernel>(block->getKernel()); + if (!kernel) + throw std::runtime_error("SetSpongeLayerBlockVisitor: Kernel is not a LBMKernel"); + kernel->setWithSpongeLayer(true); + kernel->setSpongeLayer(spongeLayer); + } } - - diff --git a/src/cpu/VirtualFluidsCore/Visitors/SetSpongeLayerBlockVisitor.h b/src/cpu/VirtualFluidsCore/Visitors/SetSpongeLayerBlockVisitor.h index 27d48a1cf2372aa62ca5c56f9f3fef15f3536cca..dfa4fdda84e98c0f76e258fd22eb2f22416f4122 100644 --- a/src/cpu/VirtualFluidsCore/Visitors/SetSpongeLayerBlockVisitor.h +++ b/src/cpu/VirtualFluidsCore/Visitors/SetSpongeLayerBlockVisitor.h @@ -11,18 +11,19 @@ class Grid3D; class Block3D; //! \brief Set sponge layer for all kernels of grid -//! \details This visitor is useful if you need to set or reset sponge layer in kernels (e.g. after restart because sponge layer is not serializable). -//! \author K. Kucher +//! \details This visitor is useful if you need to set or reset sponge layer in kernels (e.g. after restart because +//! sponge layer is not serializable). \author K. Kucher class SetSpongeLayerBlockVisitor : public Block3DVisitor { public: - SetSpongeLayerBlockVisitor(const mu::Parser& spongeLayer); - ~SetSpongeLayerBlockVisitor() override; + SetSpongeLayerBlockVisitor(const mu::Parser &spongeLayer); + ~SetSpongeLayerBlockVisitor() override; + + void visit(SPtr<Grid3D> grid, SPtr<Block3D> block) override; - void visit(SPtr<Grid3D> grid, SPtr<Block3D> block) override; protected: private: - mu::Parser spongeLayer; + mu::Parser spongeLayer; }; #endif // SetSpongeLayerBlockVisitor_h__ diff --git a/src/cpu/VirtualFluidsCore/Visitors/SetUndefinedNodesBlockVisitor.cpp b/src/cpu/VirtualFluidsCore/Visitors/SetUndefinedNodesBlockVisitor.cpp index 66b200c2241abbfa5fd5f618e2d1e0a9823a6fb7..15c8b82bae5c95f6783f73c7e7a70004f3c76574 100644 --- a/src/cpu/VirtualFluidsCore/Visitors/SetUndefinedNodesBlockVisitor.cpp +++ b/src/cpu/VirtualFluidsCore/Visitors/SetUndefinedNodesBlockVisitor.cpp @@ -1,682 +1,676 @@ #include "SetUndefinedNodesBlockVisitor.h" #include "BCArray3D.h" -#include "BoundaryConditions.h" #include "BCProcessor.h" -#include "Grid3DSystem.h" +#include "Block3D.h" +#include "BoundaryConditions.h" #include "D3Q27System.h" -#include "BCArray3D.h" #include "Grid3D.h" -#include "Block3D.h" +#include "Grid3DSystem.h" #include "ILBMKernel.h" - -SetUndefinedNodesBlockVisitor::SetUndefinedNodesBlockVisitor(bool twoTypeOfConnectorsCheck) : Block3DVisitor(0, Grid3DSystem::MAXLEVEL), twoTypeOfConnectorsCheck(twoTypeOfConnectorsCheck) +SetUndefinedNodesBlockVisitor::SetUndefinedNodesBlockVisitor(bool twoTypeOfConnectorsCheck) + : Block3DVisitor(0, Grid3DSystem::MAXLEVEL), twoTypeOfConnectorsCheck(twoTypeOfConnectorsCheck) { - } ////////////////////////////////////////////////////////////////////////// void SetUndefinedNodesBlockVisitor::visit(SPtr<Grid3D> grid, SPtr<Block3D> block) { - if(!block->hasInterpolationFlag()) return; + if (!block->hasInterpolationFlag()) + return; - SPtr<ILBMKernel> kernel = block->getKernel(); + SPtr<ILBMKernel> kernel = block->getKernel(); - if(!kernel && (block->getRank() != grid->getRank())) return; + if (!kernel && (block->getRank() != grid->getRank())) + return; - //width of ghost layer - //int gl = kernel->getGhostLayerWidth(); - int gl = 0; - - SPtr<BCArray3D> bcMatrix = kernel->getBCProcessor()->getBCArray(); + // width of ghost layer + // int gl = kernel->getGhostLayerWidth(); + int gl = 0; - int minX1 = gl; - int minX2 = gl; - int minX3 = gl; + SPtr<BCArray3D> bcMatrix = kernel->getBCProcessor()->getBCArray(); - int maxX1 = static_cast<int>(bcMatrix->getNX1())-1-gl; - int maxX2 = static_cast<int>(bcMatrix->getNX2())-1-gl; - int maxX3 = static_cast<int>(bcMatrix->getNX3())-1-gl; + int minX1 = gl; + int minX2 = gl; + int minX3 = gl; - //int offset = 2; - int offset = 3; + int maxX1 = static_cast<int>(bcMatrix->getNX1()) - 1 - gl; + int maxX2 = static_cast<int>(bcMatrix->getNX2()) - 1 - gl; + int maxX3 = static_cast<int>(bcMatrix->getNX3()) - 1 - gl; - if(block->hasInterpolationFlag(D3Q27System::E)) - { - int startix1 = maxX1; - int endix1 = maxX1; - if(block->hasInterpolationFlagCF()) startix1 = startix1-offset; - int startix2 = minX2; - int endix2 = maxX2; - int startix3 = minX3; - int endix3 = maxX3; - this->setNodesUndefined(startix1, endix1, startix2, endix2, startix3, endix3, bcMatrix); - } - if(block->hasInterpolationFlag(D3Q27System::W)) - { - int startix1 = minX1; - int endix1 = minX1; - if(block->hasInterpolationFlagCF()) endix1 = endix1+offset; - int startix2 = minX2; - int endix2 = maxX2; - int startix3 = minX3; - int endix3 = maxX3; - this->setNodesUndefined(startix1, endix1, startix2, endix2, startix3, endix3, bcMatrix); - } - if(block->hasInterpolationFlag(D3Q27System::N)) - { - int startix1 = minX1; - int endix1 = maxX1; - int startix2 = maxX2; - int endix2 = maxX2; - if(block->hasInterpolationFlagCF()) startix2 = startix2-offset; - int startix3 = minX3; - int endix3 = maxX3; - this->setNodesUndefined(startix1, endix1, startix2, endix2, startix3, endix3, bcMatrix); - } - if(block->hasInterpolationFlag(D3Q27System::S)) - { - int startix1 = minX1; - int endix1 = maxX1; - int startix2 = minX2; - int endix2 = minX2; - if(block->hasInterpolationFlagCF()) endix2 = endix2+offset; - int startix3 = minX3; - int endix3 = maxX3; - this->setNodesUndefined(startix1, endix1, startix2, endix2, startix3, endix3, bcMatrix); - } - if(block->hasInterpolationFlag(D3Q27System::T)) - { - int startix1 = minX1; - int endix1 = maxX1; - int startix2 = minX2; - int endix2 = maxX2; - int startix3 = maxX3; - int endix3 = maxX3; - if(block->hasInterpolationFlagCF()) startix3 = startix3-offset; - this->setNodesUndefined(startix1, endix1, startix2, endix2, startix3, endix3, bcMatrix); - } - if(block->hasInterpolationFlag(D3Q27System::B)) - { - int startix1 = minX1; - int endix1 = maxX1; - int startix2 = minX2; - int endix2 = maxX2; - int startix3 = minX3; - int endix3 = minX3; - if(block->hasInterpolationFlagCF()) endix3 = endix3+offset; - this->setNodesUndefined(startix1, endix1, startix2, endix2, startix3, endix3, bcMatrix); - } - if(block->hasInterpolationFlag(D3Q27System::NE)) - { - int startix1 = maxX1; - int endix1 = maxX1; - if(block->hasInterpolationFlagCF()) startix1 = startix1-offset; - int startix2 = maxX2; - int endix2 = maxX2; - if(block->hasInterpolationFlagCF()) startix2 = startix2-offset; - int startix3 = minX3; - int endix3 = maxX3; - this->setNodesUndefined(startix1, endix1, startix2, endix2, startix3, endix3, bcMatrix); - } - if(block->hasInterpolationFlag(D3Q27System::SW)) - { - int startix1 = minX1; - int endix1 = minX1; - if(block->hasInterpolationFlagCF()) endix1 = endix1+offset; - int startix2 = minX2; - int endix2 = minX2; - if(block->hasInterpolationFlagCF()) endix2 = endix2+offset; - int startix3 = minX3; - int endix3 = maxX3; - this->setNodesUndefined(startix1, endix1, startix2, endix2, startix3, endix3, bcMatrix); - } - if(block->hasInterpolationFlag(D3Q27System::SE)) - { - int startix1 = maxX1; - int endix1 = maxX1; - if(block->hasInterpolationFlagCF()) startix1 = startix1-offset; - int startix2 = minX2; - int endix2 = minX2; - if(block->hasInterpolationFlagCF()) endix2 = endix2+offset; - int startix3 = minX3; - int endix3 = maxX3; - this->setNodesUndefined(startix1, endix1, startix2, endix2, startix3, endix3, bcMatrix); - } - if(block->hasInterpolationFlag(D3Q27System::NW)) - { - int startix1 = minX1; - int endix1 = minX1; - if(block->hasInterpolationFlagCF()) endix1 = endix1+offset; - int startix2 = maxX2; - int endix2 = maxX2; - if(block->hasInterpolationFlagCF()) startix2 = startix2-offset; - int startix3 = minX3; - int endix3 = maxX3; - this->setNodesUndefined(startix1, endix1, startix2, endix2, startix3, endix3, bcMatrix); - } - if(block->hasInterpolationFlag(D3Q27System::TE)) - { - int startix1 = maxX1; - int endix1 = maxX1; - if(block->hasInterpolationFlagCF()) startix1 = startix1-offset; - int startix2 = minX2; - int endix2 = maxX2; - int startix3 = maxX3; - int endix3 = maxX3; - if(block->hasInterpolationFlagCF()) startix3 = startix3-offset; - this->setNodesUndefined(startix1, endix1, startix2, endix2, startix3, endix3, bcMatrix); - } - if(block->hasInterpolationFlag(D3Q27System::BW)) - { - int startix1 = minX1; - int endix1 = minX1; - if(block->hasInterpolationFlagCF()) endix1 = endix1+offset; - int startix2 = minX2; - int endix2 = maxX2; - int startix3 = minX3; - int endix3 = minX3; - if(block->hasInterpolationFlagCF()) endix3 = endix3+offset; - this->setNodesUndefined(startix1, endix1, startix2, endix2, startix3, endix3, bcMatrix); - } - if(block->hasInterpolationFlag(D3Q27System::BE)) - { - int startix1 = maxX1; - int endix1 = maxX1; - if(block->hasInterpolationFlagCF()) startix1 = startix1-offset; - int startix2 = minX2; - int endix2 = maxX2; - int startix3 = minX3; - int endix3 = minX3; - if(block->hasInterpolationFlagCF()) endix3 = endix3+offset; - this->setNodesUndefined(startix1, endix1, startix2, endix2, startix3, endix3, bcMatrix); - } - if(block->hasInterpolationFlag(D3Q27System::TW)) - { - int startix1 = minX1; - int endix1 = minX1; - if(block->hasInterpolationFlagCF()) endix1 = endix1+offset; - int startix2 = minX2; - int endix2 = maxX2; - int startix3 = maxX3; - int endix3 = maxX3; - if(block->hasInterpolationFlagCF()) startix3 = startix3-offset; - this->setNodesUndefined(startix1, endix1, startix2, endix2, startix3, endix3, bcMatrix); - } - if(block->hasInterpolationFlag(D3Q27System::TN)) - { - int startix1 = minX1; - int endix1 = maxX1; - int startix2 = maxX2; - int endix2 = maxX2; - if(block->hasInterpolationFlagCF()) startix2 = startix2-offset; - int startix3 = maxX3; - int endix3 = maxX3; - if(block->hasInterpolationFlagCF()) startix3 = startix3-offset; - this->setNodesUndefined(startix1, endix1, startix2, endix2, startix3, endix3, bcMatrix); - } - if(block->hasInterpolationFlag(D3Q27System::BS)) - { - int startix1 = minX1; - int endix1 = maxX1; - int startix2 = minX2; - int endix2 = minX2; - if(block->hasInterpolationFlagCF()) endix2 = endix2+offset; - int startix3 = minX3; - int endix3 = minX3; - if(block->hasInterpolationFlagCF()) endix3 = endix3+offset; - this->setNodesUndefined(startix1, endix1, startix2, endix2, startix3, endix3, bcMatrix); - } - if(block->hasInterpolationFlag(D3Q27System::BN)) - { - int startix1 = minX1; - int endix1 = maxX1; - int startix2 = maxX2; - int endix2 = maxX2; - if(block->hasInterpolationFlagCF()) startix2 = startix2-offset; - int startix3 = minX3; - int endix3 = minX3; - if(block->hasInterpolationFlagCF()) endix3 = endix3+offset; - this->setNodesUndefined(startix1, endix1, startix2, endix2, startix3, endix3, bcMatrix); - } - if(block->hasInterpolationFlag(D3Q27System::TS)) - { - int startix1 = minX1; - int endix1 = maxX1; - int startix2 = minX2; - int endix2 = minX2; - if(block->hasInterpolationFlagCF()) endix2 = endix2+offset; - int startix3 = maxX3; - int endix3 = maxX3; - if(block->hasInterpolationFlagCF()) startix3 = startix3-offset; - this->setNodesUndefined(startix1, endix1, startix2, endix2, startix3, endix3, bcMatrix); - } - if(block->hasInterpolationFlag(D3Q27System::TNE)) - { - int startix1 = maxX1; - int endix1 = maxX1; - if(block->hasInterpolationFlagCF()) startix1 = startix1-offset; - int startix2 = maxX2; - int endix2 = maxX2; - if(block->hasInterpolationFlagCF()) startix2 = startix2-offset; - int startix3 = maxX3; - int endix3 = maxX3; - if(block->hasInterpolationFlagCF()) startix3 = startix3-offset; - this->setNodesUndefined(startix1, endix1, startix2, endix2, startix3, endix3, bcMatrix); - } - if(block->hasInterpolationFlag(D3Q27System::TNW)) - { - int startix1 = minX1; - int endix1 = minX1; - if(block->hasInterpolationFlagCF()) endix1 = endix1+offset; - int startix2 = maxX2; - int endix2 = maxX2; - if(block->hasInterpolationFlagCF()) startix2 = startix2-offset; - int startix3 = maxX3; - int endix3 = maxX3; - if(block->hasInterpolationFlagCF()) startix3 = startix3-offset; - this->setNodesUndefined(startix1, endix1, startix2, endix2, startix3, endix3, bcMatrix); - } - if(block->hasInterpolationFlag(D3Q27System::TSE)) - { - int startix1 = maxX1; - int endix1 = maxX1; - if(block->hasInterpolationFlagCF()) startix1 = startix1-offset; - int startix2 = minX2; - int endix2 = minX2; - if(block->hasInterpolationFlagCF()) endix2 = endix2+offset; - int startix3 = maxX3; - int endix3 = maxX3; - if(block->hasInterpolationFlagCF()) startix3 = startix3-offset; - this->setNodesUndefined(startix1, endix1, startix2, endix2, startix3, endix3, bcMatrix); - } - if(block->hasInterpolationFlag(D3Q27System::TSW)) - { - int startix1 = minX1; - int endix1 = minX1; - if(block->hasInterpolationFlagCF()) endix1 = endix1+offset; - int startix2 = minX2; - int endix2 = minX2; - if(block->hasInterpolationFlagCF()) endix2 = endix2+offset; - int startix3 = maxX3; - int endix3 = maxX3; - if(block->hasInterpolationFlagCF()) startix3 = startix3-offset; - this->setNodesUndefined(startix1, endix1, startix2, endix2, startix3, endix3, bcMatrix); - } - if(block->hasInterpolationFlag(D3Q27System::BNE)) - { - int startix1 = maxX1; - int endix1 = maxX1; - if(block->hasInterpolationFlagCF()) startix1 = startix1-offset; - int startix2 = maxX2; - int endix2 = maxX2; - if(block->hasInterpolationFlagCF()) startix2 = startix2-offset; - int startix3 = minX3; - int endix3 = minX3; - if(block->hasInterpolationFlagCF()) endix3 = endix3+offset; - this->setNodesUndefined(startix1, endix1, startix2, endix2, startix3, endix3, bcMatrix); - } - if(block->hasInterpolationFlag(D3Q27System::BNW)) - { - int startix1 = minX1; - int endix1 = minX1; - if(block->hasInterpolationFlagCF()) endix1 = endix1+offset; - int startix2 = maxX2; - int endix2 = maxX2; - if(block->hasInterpolationFlagCF()) startix2 = startix2-offset; - int startix3 = minX3; - int endix3 = minX3; - if(block->hasInterpolationFlagCF()) endix3 = endix3+offset; - this->setNodesUndefined(startix1, endix1, startix2, endix2, startix3, endix3, bcMatrix); - } - if(block->hasInterpolationFlag(D3Q27System::BSE)) - { - int startix1 = maxX1; - int endix1 = maxX1; - if(block->hasInterpolationFlagCF()) startix1 = startix1-offset; - int startix2 = minX2; - int endix2 = minX2; - if(block->hasInterpolationFlagCF()) endix2 = endix2+offset; - int startix3 = minX3; - int endix3 = minX3; - if(block->hasInterpolationFlagCF()) endix3 = endix3+offset; - this->setNodesUndefined(startix1, endix1, startix2, endix2, startix3, endix3, bcMatrix); - } - if(block->hasInterpolationFlag(D3Q27System::BSW)) - { - int startix1 = minX1; - int endix1 = minX1; - if(block->hasInterpolationFlagCF()) endix1 = endix1+offset; - int startix2 = minX2; - int endix2 = minX2; - if(block->hasInterpolationFlagCF()) endix2 = endix2+offset; - int startix3 = minX3; - int endix3 = minX3; - if(block->hasInterpolationFlagCF()) endix3 = endix3+offset; - this->setNodesUndefined(startix1, endix1, startix2, endix2, startix3, endix3, bcMatrix); - } + // int offset = 2; + int offset = 3; + if (block->hasInterpolationFlag(D3Q27System::E)) { + int startix1 = maxX1; + int endix1 = maxX1; + if (block->hasInterpolationFlagCF()) + startix1 = startix1 - offset; + int startix2 = minX2; + int endix2 = maxX2; + int startix3 = minX3; + int endix3 = maxX3; + this->setNodesUndefined(startix1, endix1, startix2, endix2, startix3, endix3, bcMatrix); + } + if (block->hasInterpolationFlag(D3Q27System::W)) { + int startix1 = minX1; + int endix1 = minX1; + if (block->hasInterpolationFlagCF()) + endix1 = endix1 + offset; + int startix2 = minX2; + int endix2 = maxX2; + int startix3 = minX3; + int endix3 = maxX3; + this->setNodesUndefined(startix1, endix1, startix2, endix2, startix3, endix3, bcMatrix); + } + if (block->hasInterpolationFlag(D3Q27System::N)) { + int startix1 = minX1; + int endix1 = maxX1; + int startix2 = maxX2; + int endix2 = maxX2; + if (block->hasInterpolationFlagCF()) + startix2 = startix2 - offset; + int startix3 = minX3; + int endix3 = maxX3; + this->setNodesUndefined(startix1, endix1, startix2, endix2, startix3, endix3, bcMatrix); + } + if (block->hasInterpolationFlag(D3Q27System::S)) { + int startix1 = minX1; + int endix1 = maxX1; + int startix2 = minX2; + int endix2 = minX2; + if (block->hasInterpolationFlagCF()) + endix2 = endix2 + offset; + int startix3 = minX3; + int endix3 = maxX3; + this->setNodesUndefined(startix1, endix1, startix2, endix2, startix3, endix3, bcMatrix); + } + if (block->hasInterpolationFlag(D3Q27System::T)) { + int startix1 = minX1; + int endix1 = maxX1; + int startix2 = minX2; + int endix2 = maxX2; + int startix3 = maxX3; + int endix3 = maxX3; + if (block->hasInterpolationFlagCF()) + startix3 = startix3 - offset; + this->setNodesUndefined(startix1, endix1, startix2, endix2, startix3, endix3, bcMatrix); + } + if (block->hasInterpolationFlag(D3Q27System::B)) { + int startix1 = minX1; + int endix1 = maxX1; + int startix2 = minX2; + int endix2 = maxX2; + int startix3 = minX3; + int endix3 = minX3; + if (block->hasInterpolationFlagCF()) + endix3 = endix3 + offset; + this->setNodesUndefined(startix1, endix1, startix2, endix2, startix3, endix3, bcMatrix); + } + if (block->hasInterpolationFlag(D3Q27System::NE)) { + int startix1 = maxX1; + int endix1 = maxX1; + if (block->hasInterpolationFlagCF()) + startix1 = startix1 - offset; + int startix2 = maxX2; + int endix2 = maxX2; + if (block->hasInterpolationFlagCF()) + startix2 = startix2 - offset; + int startix3 = minX3; + int endix3 = maxX3; + this->setNodesUndefined(startix1, endix1, startix2, endix2, startix3, endix3, bcMatrix); + } + if (block->hasInterpolationFlag(D3Q27System::SW)) { + int startix1 = minX1; + int endix1 = minX1; + if (block->hasInterpolationFlagCF()) + endix1 = endix1 + offset; + int startix2 = minX2; + int endix2 = minX2; + if (block->hasInterpolationFlagCF()) + endix2 = endix2 + offset; + int startix3 = minX3; + int endix3 = maxX3; + this->setNodesUndefined(startix1, endix1, startix2, endix2, startix3, endix3, bcMatrix); + } + if (block->hasInterpolationFlag(D3Q27System::SE)) { + int startix1 = maxX1; + int endix1 = maxX1; + if (block->hasInterpolationFlagCF()) + startix1 = startix1 - offset; + int startix2 = minX2; + int endix2 = minX2; + if (block->hasInterpolationFlagCF()) + endix2 = endix2 + offset; + int startix3 = minX3; + int endix3 = maxX3; + this->setNodesUndefined(startix1, endix1, startix2, endix2, startix3, endix3, bcMatrix); + } + if (block->hasInterpolationFlag(D3Q27System::NW)) { + int startix1 = minX1; + int endix1 = minX1; + if (block->hasInterpolationFlagCF()) + endix1 = endix1 + offset; + int startix2 = maxX2; + int endix2 = maxX2; + if (block->hasInterpolationFlagCF()) + startix2 = startix2 - offset; + int startix3 = minX3; + int endix3 = maxX3; + this->setNodesUndefined(startix1, endix1, startix2, endix2, startix3, endix3, bcMatrix); + } + if (block->hasInterpolationFlag(D3Q27System::TE)) { + int startix1 = maxX1; + int endix1 = maxX1; + if (block->hasInterpolationFlagCF()) + startix1 = startix1 - offset; + int startix2 = minX2; + int endix2 = maxX2; + int startix3 = maxX3; + int endix3 = maxX3; + if (block->hasInterpolationFlagCF()) + startix3 = startix3 - offset; + this->setNodesUndefined(startix1, endix1, startix2, endix2, startix3, endix3, bcMatrix); + } + if (block->hasInterpolationFlag(D3Q27System::BW)) { + int startix1 = minX1; + int endix1 = minX1; + if (block->hasInterpolationFlagCF()) + endix1 = endix1 + offset; + int startix2 = minX2; + int endix2 = maxX2; + int startix3 = minX3; + int endix3 = minX3; + if (block->hasInterpolationFlagCF()) + endix3 = endix3 + offset; + this->setNodesUndefined(startix1, endix1, startix2, endix2, startix3, endix3, bcMatrix); + } + if (block->hasInterpolationFlag(D3Q27System::BE)) { + int startix1 = maxX1; + int endix1 = maxX1; + if (block->hasInterpolationFlagCF()) + startix1 = startix1 - offset; + int startix2 = minX2; + int endix2 = maxX2; + int startix3 = minX3; + int endix3 = minX3; + if (block->hasInterpolationFlagCF()) + endix3 = endix3 + offset; + this->setNodesUndefined(startix1, endix1, startix2, endix2, startix3, endix3, bcMatrix); + } + if (block->hasInterpolationFlag(D3Q27System::TW)) { + int startix1 = minX1; + int endix1 = minX1; + if (block->hasInterpolationFlagCF()) + endix1 = endix1 + offset; + int startix2 = minX2; + int endix2 = maxX2; + int startix3 = maxX3; + int endix3 = maxX3; + if (block->hasInterpolationFlagCF()) + startix3 = startix3 - offset; + this->setNodesUndefined(startix1, endix1, startix2, endix2, startix3, endix3, bcMatrix); + } + if (block->hasInterpolationFlag(D3Q27System::TN)) { + int startix1 = minX1; + int endix1 = maxX1; + int startix2 = maxX2; + int endix2 = maxX2; + if (block->hasInterpolationFlagCF()) + startix2 = startix2 - offset; + int startix3 = maxX3; + int endix3 = maxX3; + if (block->hasInterpolationFlagCF()) + startix3 = startix3 - offset; + this->setNodesUndefined(startix1, endix1, startix2, endix2, startix3, endix3, bcMatrix); + } + if (block->hasInterpolationFlag(D3Q27System::BS)) { + int startix1 = minX1; + int endix1 = maxX1; + int startix2 = minX2; + int endix2 = minX2; + if (block->hasInterpolationFlagCF()) + endix2 = endix2 + offset; + int startix3 = minX3; + int endix3 = minX3; + if (block->hasInterpolationFlagCF()) + endix3 = endix3 + offset; + this->setNodesUndefined(startix1, endix1, startix2, endix2, startix3, endix3, bcMatrix); + } + if (block->hasInterpolationFlag(D3Q27System::BN)) { + int startix1 = minX1; + int endix1 = maxX1; + int startix2 = maxX2; + int endix2 = maxX2; + if (block->hasInterpolationFlagCF()) + startix2 = startix2 - offset; + int startix3 = minX3; + int endix3 = minX3; + if (block->hasInterpolationFlagCF()) + endix3 = endix3 + offset; + this->setNodesUndefined(startix1, endix1, startix2, endix2, startix3, endix3, bcMatrix); + } + if (block->hasInterpolationFlag(D3Q27System::TS)) { + int startix1 = minX1; + int endix1 = maxX1; + int startix2 = minX2; + int endix2 = minX2; + if (block->hasInterpolationFlagCF()) + endix2 = endix2 + offset; + int startix3 = maxX3; + int endix3 = maxX3; + if (block->hasInterpolationFlagCF()) + startix3 = startix3 - offset; + this->setNodesUndefined(startix1, endix1, startix2, endix2, startix3, endix3, bcMatrix); + } + if (block->hasInterpolationFlag(D3Q27System::TNE)) { + int startix1 = maxX1; + int endix1 = maxX1; + if (block->hasInterpolationFlagCF()) + startix1 = startix1 - offset; + int startix2 = maxX2; + int endix2 = maxX2; + if (block->hasInterpolationFlagCF()) + startix2 = startix2 - offset; + int startix3 = maxX3; + int endix3 = maxX3; + if (block->hasInterpolationFlagCF()) + startix3 = startix3 - offset; + this->setNodesUndefined(startix1, endix1, startix2, endix2, startix3, endix3, bcMatrix); + } + if (block->hasInterpolationFlag(D3Q27System::TNW)) { + int startix1 = minX1; + int endix1 = minX1; + if (block->hasInterpolationFlagCF()) + endix1 = endix1 + offset; + int startix2 = maxX2; + int endix2 = maxX2; + if (block->hasInterpolationFlagCF()) + startix2 = startix2 - offset; + int startix3 = maxX3; + int endix3 = maxX3; + if (block->hasInterpolationFlagCF()) + startix3 = startix3 - offset; + this->setNodesUndefined(startix1, endix1, startix2, endix2, startix3, endix3, bcMatrix); + } + if (block->hasInterpolationFlag(D3Q27System::TSE)) { + int startix1 = maxX1; + int endix1 = maxX1; + if (block->hasInterpolationFlagCF()) + startix1 = startix1 - offset; + int startix2 = minX2; + int endix2 = minX2; + if (block->hasInterpolationFlagCF()) + endix2 = endix2 + offset; + int startix3 = maxX3; + int endix3 = maxX3; + if (block->hasInterpolationFlagCF()) + startix3 = startix3 - offset; + this->setNodesUndefined(startix1, endix1, startix2, endix2, startix3, endix3, bcMatrix); + } + if (block->hasInterpolationFlag(D3Q27System::TSW)) { + int startix1 = minX1; + int endix1 = minX1; + if (block->hasInterpolationFlagCF()) + endix1 = endix1 + offset; + int startix2 = minX2; + int endix2 = minX2; + if (block->hasInterpolationFlagCF()) + endix2 = endix2 + offset; + int startix3 = maxX3; + int endix3 = maxX3; + if (block->hasInterpolationFlagCF()) + startix3 = startix3 - offset; + this->setNodesUndefined(startix1, endix1, startix2, endix2, startix3, endix3, bcMatrix); + } + if (block->hasInterpolationFlag(D3Q27System::BNE)) { + int startix1 = maxX1; + int endix1 = maxX1; + if (block->hasInterpolationFlagCF()) + startix1 = startix1 - offset; + int startix2 = maxX2; + int endix2 = maxX2; + if (block->hasInterpolationFlagCF()) + startix2 = startix2 - offset; + int startix3 = minX3; + int endix3 = minX3; + if (block->hasInterpolationFlagCF()) + endix3 = endix3 + offset; + this->setNodesUndefined(startix1, endix1, startix2, endix2, startix3, endix3, bcMatrix); + } + if (block->hasInterpolationFlag(D3Q27System::BNW)) { + int startix1 = minX1; + int endix1 = minX1; + if (block->hasInterpolationFlagCF()) + endix1 = endix1 + offset; + int startix2 = maxX2; + int endix2 = maxX2; + if (block->hasInterpolationFlagCF()) + startix2 = startix2 - offset; + int startix3 = minX3; + int endix3 = minX3; + if (block->hasInterpolationFlagCF()) + endix3 = endix3 + offset; + this->setNodesUndefined(startix1, endix1, startix2, endix2, startix3, endix3, bcMatrix); + } + if (block->hasInterpolationFlag(D3Q27System::BSE)) { + int startix1 = maxX1; + int endix1 = maxX1; + if (block->hasInterpolationFlagCF()) + startix1 = startix1 - offset; + int startix2 = minX2; + int endix2 = minX2; + if (block->hasInterpolationFlagCF()) + endix2 = endix2 + offset; + int startix3 = minX3; + int endix3 = minX3; + if (block->hasInterpolationFlagCF()) + endix3 = endix3 + offset; + this->setNodesUndefined(startix1, endix1, startix2, endix2, startix3, endix3, bcMatrix); + } + if (block->hasInterpolationFlag(D3Q27System::BSW)) { + int startix1 = minX1; + int endix1 = minX1; + if (block->hasInterpolationFlagCF()) + endix1 = endix1 + offset; + int startix2 = minX2; + int endix2 = minX2; + if (block->hasInterpolationFlagCF()) + endix2 = endix2 + offset; + int startix3 = minX3; + int endix3 = minX3; + if (block->hasInterpolationFlagCF()) + endix3 = endix3 + offset; + this->setNodesUndefined(startix1, endix1, startix2, endix2, startix3, endix3, bcMatrix); + } + ////////////////////////////////////////////////////////////////////////// + int offset2 = 1; + int ll = 0; - ////////////////////////////////////////////////////////////////////////// - int offset2 = 1; - int ll = 0; + minX1 = ll; + minX2 = ll; + minX3 = ll; - minX1 = ll; - minX2 = ll; - minX3 = ll; + maxX1 = static_cast<int>(bcMatrix->getNX1()) - 1 - ll; + maxX2 = static_cast<int>(bcMatrix->getNX2()) - 1 - ll; + maxX3 = static_cast<int>(bcMatrix->getNX3()) - 1 - ll; - maxX1 = static_cast<int>(bcMatrix->getNX1())-1-ll; - maxX2 = static_cast<int>(bcMatrix->getNX2())-1-ll; - maxX3 = static_cast<int>(bcMatrix->getNX3())-1-ll; + if (block->hasInterpolationFlagFC(D3Q27System::E)) { + int startix1 = maxX1 - offset2; + int endix1 = maxX1; + int startix2 = minX2; + int endix2 = maxX2; + int startix3 = minX3; + int endix3 = maxX3; + this->setNodesUndefined(startix1, endix1, startix2, endix2, startix3, endix3, bcMatrix); + } + if (block->hasInterpolationFlagFC(D3Q27System::W)) { + int startix1 = minX1; + int endix1 = minX1 + offset2; + int startix2 = minX2; + int endix2 = maxX2; + int startix3 = minX3; + int endix3 = maxX3; + this->setNodesUndefined(startix1, endix1, startix2, endix2, startix3, endix3, bcMatrix); + } + if (block->hasInterpolationFlagFC(D3Q27System::N)) { + int startix1 = minX1; + int endix1 = maxX1; + int startix2 = maxX2 - offset2; + int endix2 = maxX2; + int startix3 = minX3; + int endix3 = maxX3; + this->setNodesUndefined(startix1, endix1, startix2, endix2, startix3, endix3, bcMatrix); + } + if (block->hasInterpolationFlagFC(D3Q27System::S)) { + int startix1 = minX1; + int endix1 = maxX1; + int startix2 = minX2; + int endix2 = minX2 + offset2; + int startix3 = minX3; + int endix3 = maxX3; + this->setNodesUndefined(startix1, endix1, startix2, endix2, startix3, endix3, bcMatrix); + } + if (block->hasInterpolationFlagFC(D3Q27System::T)) { + int startix1 = minX1; + int endix1 = maxX1; + int startix2 = minX2; + int endix2 = maxX2; + int startix3 = maxX3 - offset2; + int endix3 = maxX3; + this->setNodesUndefined(startix1, endix1, startix2, endix2, startix3, endix3, bcMatrix); + } + if (block->hasInterpolationFlagFC(D3Q27System::B)) { + int startix1 = minX1; + int endix1 = maxX1; + int startix2 = minX2; + int endix2 = maxX2; + int startix3 = minX3; + int endix3 = minX3 + offset2; + this->setNodesUndefined(startix1, endix1, startix2, endix2, startix3, endix3, bcMatrix); + } + if (block->hasInterpolationFlagFC(D3Q27System::NE)) { + int startix1 = maxX1 - offset2; + int endix1 = maxX1; + int startix2 = maxX2 - offset2; + int endix2 = maxX2; + int startix3 = minX3; + int endix3 = maxX3; + this->setNodesUndefined(startix1, endix1, startix2, endix2, startix3, endix3, bcMatrix); + } + if (block->hasInterpolationFlagFC(D3Q27System::SW)) { + int startix1 = minX1; + int endix1 = minX1 + offset2; + int startix2 = minX2; + int endix2 = minX2 + offset2; + int startix3 = minX3; + int endix3 = maxX3; + this->setNodesUndefined(startix1, endix1, startix2, endix2, startix3, endix3, bcMatrix); + } + if (block->hasInterpolationFlagFC(D3Q27System::SE)) { + int startix1 = maxX1 - offset2; + int endix1 = maxX1; + int startix2 = minX2; + int endix2 = minX2 + offset2; + int startix3 = minX3; + int endix3 = maxX3; + this->setNodesUndefined(startix1, endix1, startix2, endix2, startix3, endix3, bcMatrix); + } + if (block->hasInterpolationFlagFC(D3Q27System::NW)) { + int startix1 = minX1; + int endix1 = minX1 + offset2; + int startix2 = maxX2 - offset2; + int endix2 = maxX2; + int startix3 = minX3; + int endix3 = maxX3; + this->setNodesUndefined(startix1, endix1, startix2, endix2, startix3, endix3, bcMatrix); + } + if (block->hasInterpolationFlagFC(D3Q27System::TE)) { + int startix1 = maxX1 - offset2; + int endix1 = maxX1; + int startix2 = minX2; + int endix2 = maxX2; + int startix3 = maxX3 - offset2; + int endix3 = maxX3; + this->setNodesUndefined(startix1, endix1, startix2, endix2, startix3, endix3, bcMatrix); + } + if (block->hasInterpolationFlagFC(D3Q27System::BW)) { + int startix1 = minX1; + int endix1 = minX1 + offset2; + int startix2 = minX2; + int endix2 = maxX2; + int startix3 = minX3; + int endix3 = minX3 + offset2; + this->setNodesUndefined(startix1, endix1, startix2, endix2, startix3, endix3, bcMatrix); + } + if (block->hasInterpolationFlagFC(D3Q27System::BE)) { + int startix1 = maxX1 - offset2; + int endix1 = maxX1; + int startix2 = minX2; + int endix2 = maxX2; + int startix3 = minX3; + int endix3 = minX3 + offset2; + this->setNodesUndefined(startix1, endix1, startix2, endix2, startix3, endix3, bcMatrix); + } + if (block->hasInterpolationFlagFC(D3Q27System::TW)) { + int startix1 = minX1; + int endix1 = minX1 + offset2; + int startix2 = minX2; + int endix2 = maxX2; + int startix3 = maxX3 - offset2; + int endix3 = maxX3; + this->setNodesUndefined(startix1, endix1, startix2, endix2, startix3, endix3, bcMatrix); + } + if (block->hasInterpolationFlagFC(D3Q27System::TN)) { + int startix1 = minX1; + int endix1 = maxX1; + int startix2 = maxX2 - offset2; + int endix2 = maxX2; + int startix3 = maxX3 - offset2; + int endix3 = maxX3; + this->setNodesUndefined(startix1, endix1, startix2, endix2, startix3, endix3, bcMatrix); + } + if (block->hasInterpolationFlagFC(D3Q27System::BS)) { + int startix1 = minX1; + int endix1 = maxX1; + int startix2 = minX2; + int endix2 = minX2 + offset2; + int startix3 = minX3; + int endix3 = minX3 + offset2; + this->setNodesUndefined(startix1, endix1, startix2, endix2, startix3, endix3, bcMatrix); + } + if (block->hasInterpolationFlagFC(D3Q27System::BN)) { + int startix1 = minX1; + int endix1 = maxX1; + int startix2 = maxX2 - offset2; + int endix2 = maxX2; + int startix3 = minX3; + int endix3 = minX3 + offset2; + this->setNodesUndefined(startix1, endix1, startix2, endix2, startix3, endix3, bcMatrix); + } + if (block->hasInterpolationFlagFC(D3Q27System::TS)) { + int startix1 = minX1; + int endix1 = maxX1; + int startix2 = minX2; + int endix2 = minX2 + offset2; + int startix3 = maxX3 - offset2; + int endix3 = maxX3; + this->setNodesUndefined(startix1, endix1, startix2, endix2, startix3, endix3, bcMatrix); + } + if (block->hasInterpolationFlagFC(D3Q27System::TNE)) { + int startix1 = maxX1 - offset2; + int endix1 = maxX1; + int startix2 = maxX2 - offset2; + int endix2 = maxX2; + int startix3 = maxX3 - offset2; + int endix3 = maxX3; + this->setNodesUndefined(startix1, endix1, startix2, endix2, startix3, endix3, bcMatrix); + } + if (block->hasInterpolationFlagFC(D3Q27System::TNW)) { + int startix1 = minX1; + int endix1 = minX1 + offset2; + int startix2 = maxX2 - offset2; + int endix2 = maxX2; + int startix3 = maxX3 - offset2; + int endix3 = maxX3; + this->setNodesUndefined(startix1, endix1, startix2, endix2, startix3, endix3, bcMatrix); + } + if (block->hasInterpolationFlagFC(D3Q27System::TSE)) { + int startix1 = maxX1 - offset2; + int endix1 = maxX1; + int startix2 = minX2; + int endix2 = minX2 + offset2; + int startix3 = maxX3 - offset2; + int endix3 = maxX3; + this->setNodesUndefined(startix1, endix1, startix2, endix2, startix3, endix3, bcMatrix); + } + if (block->hasInterpolationFlagFC(D3Q27System::TSW)) { + int startix1 = minX1; + int endix1 = minX1 + offset2; + int startix2 = minX2; + int endix2 = minX2 + offset2; + int startix3 = maxX3 - offset2; + int endix3 = maxX3; + this->setNodesUndefined(startix1, endix1, startix2, endix2, startix3, endix3, bcMatrix); + } + if (block->hasInterpolationFlagFC(D3Q27System::BNE)) { + int startix1 = maxX1 - offset2; + int endix1 = maxX1; + int startix2 = maxX2 - offset2; + int endix2 = maxX2; + int startix3 = minX3; + int endix3 = minX3 + offset2; + this->setNodesUndefined(startix1, endix1, startix2, endix2, startix3, endix3, bcMatrix); + } + if (block->hasInterpolationFlagFC(D3Q27System::BNW)) { + int startix1 = minX1; + int endix1 = minX1 + offset2; + int startix2 = maxX2 - offset2; + int endix2 = maxX2; + int startix3 = minX3; + int endix3 = minX3 + offset2; + this->setNodesUndefined(startix1, endix1, startix2, endix2, startix3, endix3, bcMatrix); + } + if (block->hasInterpolationFlagFC(D3Q27System::BSE)) { + int startix1 = maxX1 - offset2; + int endix1 = maxX1; + int startix2 = minX2; + int endix2 = minX2 + offset2; + int startix3 = minX3; + int endix3 = minX3 + offset2; + this->setNodesUndefined(startix1, endix1, startix2, endix2, startix3, endix3, bcMatrix); + } + if (block->hasInterpolationFlagFC(D3Q27System::BSW)) { + int startix1 = minX1; + int endix1 = minX1 + offset2; + int startix2 = minX2; + int endix2 = minX2 + offset2; + int startix3 = minX3; + int endix3 = minX3 + offset2; + this->setNodesUndefined(startix1, endix1, startix2, endix2, startix3, endix3, bcMatrix); + } - if(block->hasInterpolationFlagFC(D3Q27System::E)) - { - int startix1 = maxX1-offset2; - int endix1 = maxX1; - int startix2 = minX2; - int endix2 = maxX2; - int startix3 = minX3; - int endix3 = maxX3; - this->setNodesUndefined(startix1, endix1, startix2, endix2, startix3, endix3, bcMatrix); - } - if(block->hasInterpolationFlagFC(D3Q27System::W)) - { - int startix1 = minX1; - int endix1 = minX1+offset2; - int startix2 = minX2; - int endix2 = maxX2; - int startix3 = minX3; - int endix3 = maxX3; - this->setNodesUndefined(startix1, endix1, startix2, endix2, startix3, endix3, bcMatrix); - } - if(block->hasInterpolationFlagFC(D3Q27System::N)) - { - int startix1 = minX1; - int endix1 = maxX1; - int startix2 = maxX2-offset2; - int endix2 = maxX2; - int startix3 = minX3; - int endix3 = maxX3; - this->setNodesUndefined(startix1, endix1, startix2, endix2, startix3, endix3, bcMatrix); - } - if(block->hasInterpolationFlagFC(D3Q27System::S)) - { - int startix1 = minX1; - int endix1 = maxX1; - int startix2 = minX2; - int endix2 = minX2+offset2; - int startix3 = minX3; - int endix3 = maxX3; - this->setNodesUndefined(startix1, endix1, startix2, endix2, startix3, endix3, bcMatrix); - } - if(block->hasInterpolationFlagFC(D3Q27System::T)) - { - int startix1 = minX1; - int endix1 = maxX1; - int startix2 = minX2; - int endix2 = maxX2; - int startix3 = maxX3-offset2; - int endix3 = maxX3; - this->setNodesUndefined(startix1, endix1, startix2, endix2, startix3, endix3, bcMatrix); - } - if(block->hasInterpolationFlagFC(D3Q27System::B)) - { - int startix1 = minX1; - int endix1 = maxX1; - int startix2 = minX2; - int endix2 = maxX2; - int startix3 = minX3; - int endix3 = minX3+offset2; - this->setNodesUndefined(startix1, endix1, startix2, endix2, startix3, endix3, bcMatrix); - } - if(block->hasInterpolationFlagFC(D3Q27System::NE)) - { - int startix1 = maxX1-offset2; - int endix1 = maxX1; - int startix2 = maxX2-offset2; - int endix2 = maxX2; - int startix3 = minX3; - int endix3 = maxX3; - this->setNodesUndefined(startix1, endix1, startix2, endix2, startix3, endix3, bcMatrix); - } - if(block->hasInterpolationFlagFC(D3Q27System::SW)) - { - int startix1 = minX1; - int endix1 = minX1+offset2; - int startix2 = minX2; - int endix2 = minX2+offset2; - int startix3 = minX3; - int endix3 = maxX3; - this->setNodesUndefined(startix1, endix1, startix2, endix2, startix3, endix3, bcMatrix); - } - if(block->hasInterpolationFlagFC(D3Q27System::SE)) - { - int startix1 = maxX1-offset2; - int endix1 = maxX1; - int startix2 = minX2; - int endix2 = minX2+offset2; - int startix3 = minX3; - int endix3 = maxX3; - this->setNodesUndefined(startix1, endix1, startix2, endix2, startix3, endix3, bcMatrix); - } - if(block->hasInterpolationFlagFC(D3Q27System::NW)) - { - int startix1 = minX1; - int endix1 = minX1+offset2; - int startix2 = maxX2-offset2; - int endix2 = maxX2; - int startix3 = minX3; - int endix3 = maxX3; - this->setNodesUndefined(startix1, endix1, startix2, endix2, startix3, endix3, bcMatrix); - } - if(block->hasInterpolationFlagFC(D3Q27System::TE)) - { - int startix1 = maxX1-offset2; - int endix1 = maxX1; - int startix2 = minX2; - int endix2 = maxX2; - int startix3 = maxX3-offset2; - int endix3 = maxX3; - this->setNodesUndefined(startix1, endix1, startix2, endix2, startix3, endix3, bcMatrix); - } - if(block->hasInterpolationFlagFC(D3Q27System::BW)) - { - int startix1 = minX1; - int endix1 = minX1+offset2; - int startix2 = minX2; - int endix2 = maxX2; - int startix3 = minX3; - int endix3 = minX3+offset2; - this->setNodesUndefined(startix1, endix1, startix2, endix2, startix3, endix3, bcMatrix); - } - if(block->hasInterpolationFlagFC(D3Q27System::BE)) - { - int startix1 = maxX1-offset2; - int endix1 = maxX1; - int startix2 = minX2; - int endix2 = maxX2; - int startix3 = minX3; - int endix3 = minX3+offset2; - this->setNodesUndefined(startix1, endix1, startix2, endix2, startix3, endix3, bcMatrix); - } - if(block->hasInterpolationFlagFC(D3Q27System::TW)) - { - int startix1 = minX1; - int endix1 = minX1+offset2; - int startix2 = minX2; - int endix2 = maxX2; - int startix3 = maxX3-offset2; - int endix3 = maxX3; - this->setNodesUndefined(startix1, endix1, startix2, endix2, startix3, endix3, bcMatrix); - } - if(block->hasInterpolationFlagFC(D3Q27System::TN)) - { - int startix1 = minX1; - int endix1 = maxX1; - int startix2 = maxX2-offset2; - int endix2 = maxX2; - int startix3 = maxX3-offset2; - int endix3 = maxX3; - this->setNodesUndefined(startix1, endix1, startix2, endix2, startix3, endix3, bcMatrix); - } - if(block->hasInterpolationFlagFC(D3Q27System::BS)) - { - int startix1 = minX1; - int endix1 = maxX1; - int startix2 = minX2; - int endix2 = minX2+offset2; - int startix3 = minX3; - int endix3 = minX3+offset2; - this->setNodesUndefined(startix1, endix1, startix2, endix2, startix3, endix3, bcMatrix); - } - if(block->hasInterpolationFlagFC(D3Q27System::BN)) - { - int startix1 = minX1; - int endix1 = maxX1; - int startix2 = maxX2-offset2; - int endix2 = maxX2; - int startix3 = minX3; - int endix3 = minX3+offset2; - this->setNodesUndefined(startix1, endix1, startix2, endix2, startix3, endix3, bcMatrix); - } - if(block->hasInterpolationFlagFC(D3Q27System::TS)) - { - int startix1 = minX1; - int endix1 = maxX1; - int startix2 = minX2; - int endix2 = minX2+offset2; - int startix3 = maxX3-offset2; - int endix3 = maxX3; - this->setNodesUndefined(startix1, endix1, startix2, endix2, startix3, endix3, bcMatrix); - } - if(block->hasInterpolationFlagFC(D3Q27System::TNE)) - { - int startix1 = maxX1-offset2; - int endix1 = maxX1; - int startix2 = maxX2-offset2; - int endix2 = maxX2; - int startix3 = maxX3-offset2; - int endix3 = maxX3; - this->setNodesUndefined(startix1, endix1, startix2, endix2, startix3, endix3, bcMatrix); - } - if(block->hasInterpolationFlagFC(D3Q27System::TNW)) - { - int startix1 = minX1; - int endix1 = minX1+offset2; - int startix2 = maxX2-offset2; - int endix2 = maxX2; - int startix3 = maxX3-offset2; - int endix3 = maxX3; - this->setNodesUndefined(startix1, endix1, startix2, endix2, startix3, endix3, bcMatrix); - } - if(block->hasInterpolationFlagFC(D3Q27System::TSE)) - { - int startix1 = maxX1-offset2; - int endix1 = maxX1; - int startix2 = minX2; - int endix2 = minX2+offset2; - int startix3 = maxX3-offset2; - int endix3 = maxX3; - this->setNodesUndefined(startix1, endix1, startix2, endix2, startix3, endix3, bcMatrix); - } - if(block->hasInterpolationFlagFC(D3Q27System::TSW)) - { - int startix1 = minX1; - int endix1 = minX1+offset2; - int startix2 = minX2; - int endix2 = minX2+offset2; - int startix3 = maxX3-offset2; - int endix3 = maxX3; - this->setNodesUndefined(startix1, endix1, startix2, endix2, startix3, endix3, bcMatrix); - } - if(block->hasInterpolationFlagFC(D3Q27System::BNE)) - { - int startix1 = maxX1-offset2; - int endix1 = maxX1; - int startix2 = maxX2-offset2; - int endix2 = maxX2; - int startix3 = minX3; - int endix3 = minX3+offset2; - this->setNodesUndefined(startix1, endix1, startix2, endix2, startix3, endix3, bcMatrix); - } - if(block->hasInterpolationFlagFC(D3Q27System::BNW)) - { - int startix1 = minX1; - int endix1 = minX1+offset2; - int startix2 = maxX2-offset2; - int endix2 = maxX2; - int startix3 = minX3; - int endix3 = minX3+offset2; - this->setNodesUndefined(startix1, endix1, startix2, endix2, startix3, endix3, bcMatrix); - } - if(block->hasInterpolationFlagFC(D3Q27System::BSE)) - { - int startix1 = maxX1-offset2; - int endix1 = maxX1; - int startix2 = minX2; - int endix2 = minX2+offset2; - int startix3 = minX3; - int endix3 = minX3+offset2; - this->setNodesUndefined(startix1, endix1, startix2, endix2, startix3, endix3, bcMatrix); - } - if(block->hasInterpolationFlagFC(D3Q27System::BSW)) - { - int startix1 = minX1; - int endix1 = minX1+offset2; - int startix2 = minX2; - int endix2 = minX2+offset2; - int startix3 = minX3; - int endix3 = minX3+offset2; - this->setNodesUndefined(startix1, endix1, startix2, endix2, startix3, endix3, bcMatrix); - } - - //invert scaleCF blocks - if(block->hasInterpolationFlagCF()) - { - if(block->hasInterpolationFlagFC() && twoTypeOfConnectorsCheck) - { - for (int i = D3Q27System::E; i <= D3Q27System::BSW; i++) - { - UBLOG(logINFO, "FC in dir="<<i<<" "<<block->hasInterpolationFlagFC(i)); - } - for (int i = D3Q27System::E; i<=D3Q27System::BSW; i++) - { - UBLOG(logINFO, "CF in dir="<<i<<" "<<block->hasInterpolationFlagCF(i)); - } - throw UbException(UB_EXARGS, "block "+block->toString()+" has CF and FC"); - } + // invert scaleCF blocks + if (block->hasInterpolationFlagCF()) { + if (block->hasInterpolationFlagFC() && twoTypeOfConnectorsCheck) { + for (int i = D3Q27System::E; i <= D3Q27System::BSW; i++) { + UBLOG(logINFO, "FC in dir=" << i << " " << block->hasInterpolationFlagFC(i)); + } + for (int i = D3Q27System::E; i <= D3Q27System::BSW; i++) { + UBLOG(logINFO, "CF in dir=" << i << " " << block->hasInterpolationFlagCF(i)); + } + throw UbException(UB_EXARGS, "block " + block->toString() + " has CF and FC"); + } - minX1 = gl; - minX2 = gl; - minX3 = gl; + minX1 = gl; + minX2 = gl; + minX3 = gl; - maxX1 = static_cast<int>(bcMatrix->getNX1())-1-gl; - maxX2 = static_cast<int>(bcMatrix->getNX2())-1-gl; - maxX3 = static_cast<int>(bcMatrix->getNX3())-1-gl; + maxX1 = static_cast<int>(bcMatrix->getNX1()) - 1 - gl; + maxX2 = static_cast<int>(bcMatrix->getNX2()) - 1 - gl; + maxX3 = static_cast<int>(bcMatrix->getNX3()) - 1 - gl; - for (int ix3=minX3; ix3<=maxX3; ix3++) { - for (int ix2=minX2; ix2<=maxX2; ix2++) { - for (int ix1=minX1; ix1<=maxX1; ix1++) - { - if(bcMatrix->isUndefined(ix1, ix2, ix3)) - bcMatrix->setFluid(ix1, ix2, ix3); - else - bcMatrix->setUndefined(ix1, ix2, ix3); + for (int ix3 = minX3; ix3 <= maxX3; ix3++) { + for (int ix2 = minX2; ix2 <= maxX2; ix2++) { + for (int ix1 = minX1; ix1 <= maxX1; ix1++) { + if (bcMatrix->isUndefined(ix1, ix2, ix3)) + bcMatrix->setFluid(ix1, ix2, ix3); + else + bcMatrix->setUndefined(ix1, ix2, ix3); + } } - } - } - - return; - } + } + return; + } } ////////////////////////////////////////////////////////////////////////// -void SetUndefinedNodesBlockVisitor::setNodesUndefined( int startix1, int endix1, int startix2, int endix2, int startix3, int endix3, SPtr<BCArray3D> bcMatrix ) +void SetUndefinedNodesBlockVisitor::setNodesUndefined(int startix1, int endix1, int startix2, int endix2, int startix3, + int endix3, SPtr<BCArray3D> bcMatrix) { - for (int ix3=startix3; ix3<=endix3; ix3++) - for (int ix2=startix2; ix2<=endix2; ix2++) - for (int ix1=startix1; ix1<=endix1; ix1++) - { - bcMatrix->setUndefined(ix1, ix2, ix3); - } + for (int ix3 = startix3; ix3 <= endix3; ix3++) + for (int ix2 = startix2; ix2 <= endix2; ix2++) + for (int ix1 = startix1; ix1 <= endix1; ix1++) { + bcMatrix->setUndefined(ix1, ix2, ix3); + } } diff --git a/src/cpu/VirtualFluidsCore/Visitors/SetUndefinedNodesBlockVisitor.h b/src/cpu/VirtualFluidsCore/Visitors/SetUndefinedNodesBlockVisitor.h index 8e40ada1222ea811498fb9984c8471e078620f1b..329662ec8aeb6405c8f8f4b06645c9d1500a59e6 100644 --- a/src/cpu/VirtualFluidsCore/Visitors/SetUndefinedNodesBlockVisitor.h +++ b/src/cpu/VirtualFluidsCore/Visitors/SetUndefinedNodesBlockVisitor.h @@ -12,15 +12,17 @@ class BCArray3D; class SetUndefinedNodesBlockVisitor : public Block3DVisitor { public: - SetUndefinedNodesBlockVisitor(bool twoTypeOfConnectorsCheck=true); + SetUndefinedNodesBlockVisitor(bool twoTypeOfConnectorsCheck = true); - ~SetUndefinedNodesBlockVisitor() override = default; + ~SetUndefinedNodesBlockVisitor() override = default; + + void visit(SPtr<Grid3D> grid, SPtr<Block3D> block) override; - void visit(SPtr<Grid3D> grid, SPtr<Block3D> block) override; protected: - void setNodesUndefined( int startix1, int endix1, int startix2, int endix2, int startix3, int endix3, SPtr<BCArray3D> bcMatix ); -private: - bool twoTypeOfConnectorsCheck; + void setNodesUndefined(int startix1, int endix1, int startix2, int endix2, int startix3, int endix3, + SPtr<BCArray3D> bcMatix); +private: + bool twoTypeOfConnectorsCheck; }; #endif diff --git a/src/cpu/VirtualFluidsCore/Visitors/SpongeLayerBlockVisitor.cpp b/src/cpu/VirtualFluidsCore/Visitors/SpongeLayerBlockVisitor.cpp index bc88929681f2cbc6138a4cfdf38d94164f4662bb..c5dce4102bb0fe118e9d47442d476e6a3eed6462 100644 --- a/src/cpu/VirtualFluidsCore/Visitors/SpongeLayerBlockVisitor.cpp +++ b/src/cpu/VirtualFluidsCore/Visitors/SpongeLayerBlockVisitor.cpp @@ -2,120 +2,101 @@ #include "Grid3DSystem.h" #include "LBMSystem.h" -#include "Grid3D.h" +#include "BCArray3D.h" +#include "BCProcessor.h" #include "Block3D.h" +#include "D3Q27System.h" +#include "Grid3D.h" #include "LBMKernel.h" #include "UbException.h" -#include "D3Q27System.h" -#include "BCArray3D.h" -#include "BCProcessor.h" #include <geometry3d/GbCuboid3D.h> using namespace std; -SpongeLayerBlockVisitor::SpongeLayerBlockVisitor(SPtr<GbCuboid3D> boundingBox, SPtr<LBMKernel> kernel, double nue, int dir) : - Block3DVisitor(0, Grid3DSystem::MAXLEVEL), - boundingBox(boundingBox), - kernel(kernel), - nue(nue), - dir(dir) +SpongeLayerBlockVisitor::SpongeLayerBlockVisitor(SPtr<GbCuboid3D> boundingBox, SPtr<LBMKernel> kernel, double nue, + int dir) + : Block3DVisitor(0, Grid3DSystem::MAXLEVEL), boundingBox(boundingBox), kernel(kernel), nue(nue), dir(dir) { - } ////////////////////////////////////////////////////////////////////////// -SpongeLayerBlockVisitor::~SpongeLayerBlockVisitor() -= default; +SpongeLayerBlockVisitor::~SpongeLayerBlockVisitor() = default; ////////////////////////////////////////////////////////////////////////// void SpongeLayerBlockVisitor::visit(SPtr<Grid3D> grid, SPtr<Block3D> block) { - if (!boundingBox) - { - UB_THROW(UbException(UB_EXARGS, "The bounding box isn't set!")); - } - if (!kernel) - { - UB_THROW(UbException(UB_EXARGS, "The kernel isn't set!")); - } - if (kernel && (block->getRank() == grid->getRank())) - { - UbTupleDouble3 org = grid->getBlockWorldCoordinates(block); - UbTupleDouble3 blockLengths = grid->getBlockLengths(block); - - double minX1 = val<1>(org); - double minX2 = val<2>(org); - double minX3 = val<3>(org); - double maxX1 = val<1>(org)+val<1>(blockLengths); - double maxX2 = val<2>(org)+val<2>(blockLengths); - double maxX3 = val<3>(org)+val<3>(blockLengths); - - if (boundingBox->isCellInsideGbObject3D(minX1, minX2, minX3, maxX1, maxX2, maxX3)) - { - LBMReal collFactor = LBMSystem::calcCollisionFactor(nue, block->getLevel()); - kernel->setCollisionFactor(collFactor); - kernel->setIndex(block->getX1(), block->getX2(), block->getX3()); - kernel->setDeltaT(LBMSystem::getDeltaT(block->getLevel())); - kernel->setBlock(block); - SPtr<LBMKernel> newKernel = kernel->clone(); - - SPtr<DataSet3D> dataSet = block->getKernel()->getDataSet(); - if (!dataSet) - { - UB_THROW(UbException(UB_EXARGS, "It is not possible to change a DataSet in kernel! Old DataSet is not exist!")); - } - - newKernel->setDataSet(dataSet); - - SPtr<BCProcessor> bcProc = block->getKernel()->getBCProcessor(); - if (!bcProc) - { - UB_THROW(UbException(UB_EXARGS, "It is not possible to change a BCProcessor in kernel! Old BCProcessor is not exist!")); - } - newKernel->setBCProcessor(bcProc); - - double oldCollFactor = newKernel->getCollisionFactor(); - - - UbTupleInt3 ixMin = grid->getBlockIndexes(boundingBox->getX1Minimum(),boundingBox->getX2Minimum(),boundingBox->getX3Minimum()); - UbTupleInt3 ixMax = grid->getBlockIndexes(boundingBox->getX1Maximum(),boundingBox->getX2Maximum(),boundingBox->getX3Maximum()); - - double newCollFactor; - - if (dir == D3Q27System::E) - { - int ibX1 = block->getX1(); - int ibMax = val<1>(ixMax)-val<1>(ixMin)+1; - double index = (double)(ibX1-val<1>(ixMin)+1); - newCollFactor = oldCollFactor - (oldCollFactor-1.0)/(double)(ibMax)*index; - } - else if (dir == D3Q27System::W) - { - int ibX1 = block->getX1(); - int ibMax = val<1>(ixMax)-val<1>(ixMin)+1; - double index = (double)(ibX1-val<1>(ixMin)+1); - newCollFactor = (oldCollFactor-1.0)/(double)(ibMax)*index; - } - else if (dir == D3Q27System::T) - { - int ibX3 = block->getX3(); - int ibMax = val<3>(ixMax)-val<3>(ixMin)+1; - double index = (double)(ibX3-val<3>(ixMin)+1); - newCollFactor = oldCollFactor - (oldCollFactor-1.0)/(double)(ibMax)*index; - } - else if (dir == D3Q27System::B) - { - int ibX3 = block->getX3(); - int ibMax = val<3>(ixMax)-val<3>(ixMin)+1; - double index = (double)(ibX3-val<3>(ixMin)+1); - newCollFactor = (oldCollFactor-1.0)/(double)(ibMax)*index; - } - - - newKernel->setCollisionFactor(newCollFactor); - block->setKernel(newKernel); - } - } + if (!boundingBox) { + UB_THROW(UbException(UB_EXARGS, "The bounding box isn't set!")); + } + if (!kernel) { + UB_THROW(UbException(UB_EXARGS, "The kernel isn't set!")); + } + if (kernel && (block->getRank() == grid->getRank())) { + UbTupleDouble3 org = grid->getBlockWorldCoordinates(block); + UbTupleDouble3 blockLengths = grid->getBlockLengths(block); + + double minX1 = val<1>(org); + double minX2 = val<2>(org); + double minX3 = val<3>(org); + double maxX1 = val<1>(org) + val<1>(blockLengths); + double maxX2 = val<2>(org) + val<2>(blockLengths); + double maxX3 = val<3>(org) + val<3>(blockLengths); + + if (boundingBox->isCellInsideGbObject3D(minX1, minX2, minX3, maxX1, maxX2, maxX3)) { + LBMReal collFactor = LBMSystem::calcCollisionFactor(nue, block->getLevel()); + kernel->setCollisionFactor(collFactor); + kernel->setIndex(block->getX1(), block->getX2(), block->getX3()); + kernel->setDeltaT(LBMSystem::getDeltaT(block->getLevel())); + kernel->setBlock(block); + SPtr<LBMKernel> newKernel = kernel->clone(); + + SPtr<DataSet3D> dataSet = block->getKernel()->getDataSet(); + if (!dataSet) { + UB_THROW(UbException(UB_EXARGS, + "It is not possible to change a DataSet in kernel! Old DataSet is not exist!")); + } + + newKernel->setDataSet(dataSet); + + SPtr<BCProcessor> bcProc = block->getKernel()->getBCProcessor(); + if (!bcProc) { + UB_THROW(UbException( + UB_EXARGS, "It is not possible to change a BCProcessor in kernel! Old BCProcessor is not exist!")); + } + newKernel->setBCProcessor(bcProc); + + double oldCollFactor = newKernel->getCollisionFactor(); + + UbTupleInt3 ixMin = grid->getBlockIndexes(boundingBox->getX1Minimum(), boundingBox->getX2Minimum(), + boundingBox->getX3Minimum()); + UbTupleInt3 ixMax = grid->getBlockIndexes(boundingBox->getX1Maximum(), boundingBox->getX2Maximum(), + boundingBox->getX3Maximum()); + + double newCollFactor; + + if (dir == D3Q27System::E) { + int ibX1 = block->getX1(); + int ibMax = val<1>(ixMax) - val<1>(ixMin) + 1; + double index = (double)(ibX1 - val<1>(ixMin) + 1); + newCollFactor = oldCollFactor - (oldCollFactor - 1.0) / (double)(ibMax)*index; + } else if (dir == D3Q27System::W) { + int ibX1 = block->getX1(); + int ibMax = val<1>(ixMax) - val<1>(ixMin) + 1; + double index = (double)(ibX1 - val<1>(ixMin) + 1); + newCollFactor = (oldCollFactor - 1.0) / (double)(ibMax)*index; + } else if (dir == D3Q27System::T) { + int ibX3 = block->getX3(); + int ibMax = val<3>(ixMax) - val<3>(ixMin) + 1; + double index = (double)(ibX3 - val<3>(ixMin) + 1); + newCollFactor = oldCollFactor - (oldCollFactor - 1.0) / (double)(ibMax)*index; + } else if (dir == D3Q27System::B) { + int ibX3 = block->getX3(); + int ibMax = val<3>(ixMax) - val<3>(ixMin) + 1; + double index = (double)(ibX3 - val<3>(ixMin) + 1); + newCollFactor = (oldCollFactor - 1.0) / (double)(ibMax)*index; + } + + newKernel->setCollisionFactor(newCollFactor); + block->setKernel(newKernel); + } + } } ////////////////////////////////////////////////////////////////////////// - - - diff --git a/src/cpu/VirtualFluidsCore/Visitors/SpongeLayerBlockVisitor.h b/src/cpu/VirtualFluidsCore/Visitors/SpongeLayerBlockVisitor.h index 43ee4e614d5bf5961fd9457a462a0ad755051ac1..0896db06577fa57f3ae3a137430c69eac214e24f 100644 --- a/src/cpu/VirtualFluidsCore/Visitors/SpongeLayerBlockVisitor.h +++ b/src/cpu/VirtualFluidsCore/Visitors/SpongeLayerBlockVisitor.h @@ -10,15 +10,15 @@ class GbCuboid3D; class LBMKernel; //! \brief Set sponge layer for all blocks inside boundingBox -//! \details This visitor sets viscosity gradient inside bounding box. +//! \details This visitor sets viscosity gradient inside bounding box. //! \author K. Kutscher class SpongeLayerBlockVisitor : public Block3DVisitor { public: - SpongeLayerBlockVisitor(SPtr<GbCuboid3D> boundingBox, SPtr<LBMKernel> kernel, double nue, int dir); - ~SpongeLayerBlockVisitor() override; + SpongeLayerBlockVisitor(SPtr<GbCuboid3D> boundingBox, SPtr<LBMKernel> kernel, double nue, int dir); + ~SpongeLayerBlockVisitor() override; - void visit(SPtr<Grid3D> grid, SPtr<Block3D> block) override; + void visit(SPtr<Grid3D> grid, SPtr<Block3D> block) override; private: SPtr<GbCuboid3D> boundingBox; diff --git a/src/cpu/VirtualFluidsCore/Visitors/ViscosityBlockVisitor.cpp b/src/cpu/VirtualFluidsCore/Visitors/ViscosityBlockVisitor.cpp index ba1002ef82ebf4359af88e4e2e239614fef34809..67d185d6ac401909d85b99b74ef1ede2d0054a6a 100644 --- a/src/cpu/VirtualFluidsCore/Visitors/ViscosityBlockVisitor.cpp +++ b/src/cpu/VirtualFluidsCore/Visitors/ViscosityBlockVisitor.cpp @@ -1,22 +1,16 @@ #include "ViscosityBlockVisitor.h" -#include "Grid3DSystem.h" -#include "LBMSystem.h" #include "Block3D.h" #include "Grid3D.h" +#include "Grid3DSystem.h" #include "ILBMKernel.h" +#include "LBMSystem.h" -ViscosityBlockVisitor::ViscosityBlockVisitor(LBMReal nu) : -Block3DVisitor(0, Grid3DSystem::MAXLEVEL), nu(nu) -{ - -} +ViscosityBlockVisitor::ViscosityBlockVisitor(LBMReal nu) : Block3DVisitor(0, Grid3DSystem::MAXLEVEL), nu(nu) {} ////////////////////////////////////////////////////////////////////////// void ViscosityBlockVisitor::visit(SPtr<Grid3D> grid, SPtr<Block3D> block) { - if (block->getRank() == grid->getRank()) - { - LBMReal collFactor = LBMSystem::calcCollisionFactor(nu, block->getLevel()); - block->getKernel()->setCollisionFactor(collFactor); - } + if (block->getRank() == grid->getRank()) { + LBMReal collFactor = LBMSystem::calcCollisionFactor(nu, block->getLevel()); + block->getKernel()->setCollisionFactor(collFactor); + } } - diff --git a/src/cpu/VirtualFluidsCore/Visitors/ViscosityBlockVisitor.h b/src/cpu/VirtualFluidsCore/Visitors/ViscosityBlockVisitor.h index 603a474623bda9578a7769ff015921171a7cf36b..003bd41e1a02a547386cbde878564cf0b2bf8209 100644 --- a/src/cpu/VirtualFluidsCore/Visitors/ViscosityBlockVisitor.h +++ b/src/cpu/VirtualFluidsCore/Visitors/ViscosityBlockVisitor.h @@ -12,14 +12,14 @@ class Block3D; class ViscosityBlockVisitor : public Block3DVisitor { public: - ViscosityBlockVisitor(LBMReal nu); + ViscosityBlockVisitor(LBMReal nu); - ~ViscosityBlockVisitor() override = default; + ~ViscosityBlockVisitor() override = default; - void visit(SPtr<Grid3D> grid, SPtr<Block3D> block) override; + void visit(SPtr<Grid3D> grid, SPtr<Block3D> block) override; private: - LBMReal nu; + LBMReal nu; }; #endif diff --git a/src/cpu/VirtualFluidsCore/Visitors/ZoltanPartitioningGridVisitor.cpp b/src/cpu/VirtualFluidsCore/Visitors/ZoltanPartitioningGridVisitor.cpp index ebbc5ec54aa236fe588d509a7b6035901dbf96e6..9a148a4f9bb799240a5ad0ba087d4354b8d0342a 100644 --- a/src/cpu/VirtualFluidsCore/Visitors/ZoltanPartitioningGridVisitor.cpp +++ b/src/cpu/VirtualFluidsCore/Visitors/ZoltanPartitioningGridVisitor.cpp @@ -1,148 +1,132 @@ #if defined VF_ZOLTAN && defined VF_MPI #include "ZoltanPartitioningGridVisitor.h" -#include <vector> -#include "UbLogger.h" -#include "UbException.h" -#include "Grid3D.h" #include "Block3D.h" +#include "Grid3D.h" +#include "UbException.h" +#include "UbLogger.h" +#include <vector> using namespace std; -ZoltanPartitioningGridVisitor::ZoltanPartitioningGridVisitor(SPtr<Communicator> comm, int numOfDirs, int numOfLocalParts) : -comm(comm), -numOfDirs(numOfDirs), -numOfLocalParts(numOfLocalParts) +ZoltanPartitioningGridVisitor::ZoltanPartitioningGridVisitor(SPtr<Communicator> comm, int numOfDirs, + int numOfLocalParts) + : comm(comm), numOfDirs(numOfDirs), numOfLocalParts(numOfLocalParts) { } ////////////////////////////////////////////////////////////////////////// -ZoltanPartitioningGridVisitor::~ZoltanPartitioningGridVisitor() -{ - -} +ZoltanPartitioningGridVisitor::~ZoltanPartitioningGridVisitor() {} ////////////////////////////////////////////////////////////////////////// void ZoltanPartitioningGridVisitor::visit(SPtr<Grid3D> grid) { - UBLOG(logDEBUG5, "ZoltanPartitioningPatchVisitor::visit() - start"); + UBLOG(logDEBUG5, "ZoltanPartitioningPatchVisitor::visit() - start"); + + // MPI_Comm mpi_comm = *((MPI_Comm*) comm->getNativeCommunicator()); - //MPI_Comm mpi_comm = *((MPI_Comm*) comm->getNativeCommunicator()); + // ZoltanPartitioner zp(mpi_comm, comm->getProcessID(), numOfLocalParts); + // + // graph = zp.getGraphData(); - //ZoltanPartitioner zp(mpi_comm, comm->getProcessID(), numOfLocalParts); - // - //graph = zp.getGraphData(); - - collectData(grid); + collectData(grid); - //zp.partition(); + // zp.partition(); - //repartGrid(grid, zp); + // repartGrid(grid, zp); - UBLOG(logDEBUG5, "ZoltanPartitioningPatchVisitor::visit() - end"); + UBLOG(logDEBUG5, "ZoltanPartitioningPatchVisitor::visit() - end"); } ////////////////////////////////////////////////////////////////////////// void ZoltanPartitioningGridVisitor::collectData(SPtr<Grid3D> grid) { - int myRank = comm->getProcessID(); - int numOfProc = comm->getNumberOfProcesses(); - - if (numOfProc < 2) - { - return; - } - - int minInitLevel = grid->getCoarsestInitializedLevel(); - int maxInitLevel = grid->getFinestInitializedLevel(); - - for (int l = minInitLevel; l<=maxInitLevel; l++) - { - MPI_Comm mpi_comm = *((MPI_Comm*)comm->getNativeCommunicator()); - ZoltanPartitioner zp(mpi_comm, comm->getProcessID(), numOfLocalParts); - graph = zp.getGraphData(); - - int n = 0; - vector<SPtr<Block3D>> blockVector; - grid->getBlocks(l, blockVector); - - if (blockVector.size() == 0) - { - UB_THROW(UbException(UB_EXARGS, "Blocks for decomposition don't exist!")); - } - - //Verteilung von Ranks - int rank = 0; - for(SPtr<Block3D> block : blockVector) - { - block->setRank(rank); - block->setPart(rank); - rank++; - if (rank > numOfProc - 1) - rank = 0; - } - - int vertices = 0; - - for(SPtr<Block3D> block : blockVector) - { - if (block->getRank() == myRank) - { - vertices++; - - vertexGID.push_back(block->getGlobalID()); - - int edges = 0; - for (int dir = 0; dir <= numOfDirs; dir++) - { - SPtr<Block3D> neighBlock = (grid->getNeighborBlock(dir, - block->getX1(), block->getX2(), block->getX3(), l)); - - if (neighBlock) - { - edges++; - nborGID.push_back(neighBlock->getGlobalID()); - nborProc.push_back(neighBlock->getRank()); - } + int myRank = comm->getProcessID(); + int numOfProc = comm->getNumberOfProcesses(); + + if (numOfProc < 2) { + return; + } + + int minInitLevel = grid->getCoarsestInitializedLevel(); + int maxInitLevel = grid->getFinestInitializedLevel(); + + for (int l = minInitLevel; l <= maxInitLevel; l++) { + MPI_Comm mpi_comm = *((MPI_Comm *)comm->getNativeCommunicator()); + ZoltanPartitioner zp(mpi_comm, comm->getProcessID(), numOfLocalParts); + graph = zp.getGraphData(); + + int n = 0; + vector<SPtr<Block3D>> blockVector; + grid->getBlocks(l, blockVector); + + if (blockVector.size() == 0) { + UB_THROW(UbException(UB_EXARGS, "Blocks for decomposition don't exist!")); + } + + // Verteilung von Ranks + int rank = 0; + for (SPtr<Block3D> block : blockVector) { + block->setRank(rank); + block->setPart(rank); + rank++; + if (rank > numOfProc - 1) + rank = 0; + } + + int vertices = 0; + + for (SPtr<Block3D> block : blockVector) { + if (block->getRank() == myRank) { + vertices++; + + vertexGID.push_back(block->getGlobalID()); + + int edges = 0; + for (int dir = 0; dir <= numOfDirs; dir++) { + SPtr<Block3D> neighBlock = + (grid->getNeighborBlock(dir, block->getX1(), block->getX2(), block->getX3(), l)); + + if (neighBlock) { + edges++; + nborGID.push_back(neighBlock->getGlobalID()); + nborProc.push_back(neighBlock->getRank()); + } + } + numEdges.push_back(edges); } - numEdges.push_back(edges); - } - } - graph->numLocalVertices = vertices; - graph->vnumEdges = numEdges; - graph->vvertexGID = vertexGID; - graph->vnborGID = nborGID; - graph->vnborProc = nborProc; - - zp.partition(); - repartGrid(grid, zp); - } + } + graph->numLocalVertices = vertices; + graph->vnumEdges = numEdges; + graph->vvertexGID = vertexGID; + graph->vnborGID = nborGID; + graph->vnborProc = nborProc; + + zp.partition(); + repartGrid(grid, zp); + } } ////////////////////////////////////////////////////////////////////////// -void ZoltanPartitioningGridVisitor::repartGrid(SPtr<Grid3D> grid, ZoltanPartitioner& zp) +void ZoltanPartitioningGridVisitor::repartGrid(SPtr<Grid3D> grid, ZoltanPartitioner &zp) { - if (zp.areChanges()) - { - UBLOG(logDEBUG5, "ZoltanPartitioningPatchVisitor::repartGrid - start" ); - vector<int> sExportGlobalGids, sExportToPart, sExportProcs; - vector<int> rExportGlobalGids, rExportToPart, rExportProcs; - - zp.getExportData(sExportGlobalGids, sExportToPart, sExportProcs); - - comm->allGather(sExportGlobalGids, rExportGlobalGids); - comm->allGather(sExportToPart, rExportToPart); - comm->allGather(sExportProcs, rExportProcs); - - for (int i = 0; i < (int)rExportGlobalGids.size(); i++) - { - if (rExportGlobalGids[i] != -1) - { - SPtr<Block3D> block = grid->getBlock(rExportGlobalGids[i]); - if(block) - { - block->setRank(rExportProcs[i]); - block->setPart(rExportToPart[i]); + if (zp.areChanges()) { + UBLOG(logDEBUG5, "ZoltanPartitioningPatchVisitor::repartGrid - start"); + vector<int> sExportGlobalGids, sExportToPart, sExportProcs; + vector<int> rExportGlobalGids, rExportToPart, rExportProcs; + + zp.getExportData(sExportGlobalGids, sExportToPart, sExportProcs); + + comm->allGather(sExportGlobalGids, rExportGlobalGids); + comm->allGather(sExportToPart, rExportToPart); + comm->allGather(sExportProcs, rExportProcs); + + for (int i = 0; i < (int)rExportGlobalGids.size(); i++) { + if (rExportGlobalGids[i] != -1) { + SPtr<Block3D> block = grid->getBlock(rExportGlobalGids[i]); + if (block) { + block->setRank(rExportProcs[i]); + block->setPart(rExportToPart[i]); + } } - } - } - UBLOG(logDEBUG5, "ZoltanPartitioningPatchVisitor::repartGrid - end" ); - } + } + UBLOG(logDEBUG5, "ZoltanPartitioningPatchVisitor::repartGrid - end"); + } } #endif diff --git a/src/cpu/VirtualFluidsCore/Visitors/ZoltanPartitioningGridVisitor.h b/src/cpu/VirtualFluidsCore/Visitors/ZoltanPartitioningGridVisitor.h index f99134e4f5099b6ac5f9d634d5f65749529b6f3e..4d9cd63c5c4c4a34bc8a1d5935b895fd9c5a2129 100644 --- a/src/cpu/VirtualFluidsCore/Visitors/ZoltanPartitioningGridVisitor.h +++ b/src/cpu/VirtualFluidsCore/Visitors/ZoltanPartitioningGridVisitor.h @@ -1,37 +1,39 @@ /** -* @file ZoltanPartitioningPatchVisitor.h -* @brief Visitor class wich apply Zoltan library partitioning. -* @author Kostyantyn Kucher -* @date 10.06.2011 -*/ + * @file ZoltanPartitioningPatchVisitor.h + * @brief Visitor class wich apply Zoltan library partitioning. + * @author Kostyantyn Kucher + * @date 10.06.2011 + */ #ifndef ZoltanPartitioningGridVisitor_H #define ZoltanPartitioningGridVisitor_H #if defined VF_ZOLTAN && defined VF_MPI -#include "Grid3DVisitor.h" #include "Communicator.h" +#include "Grid3DVisitor.h" #include "ZoltanPartitioner.h" class ZoltanPartitioningGridVisitor : public Grid3DVisitor { public: - ZoltanPartitioningGridVisitor(SPtr<Communicator> comm, int numOfDirs, int numOfLocalParts = 1); - ~ZoltanPartitioningGridVisitor(); - void visit(SPtr<Grid3D> grid); + ZoltanPartitioningGridVisitor(SPtr<Communicator> comm, int numOfDirs, int numOfLocalParts = 1); + ~ZoltanPartitioningGridVisitor(); + void visit(SPtr<Grid3D> grid); + protected: - void collectData(SPtr<Grid3D> grid); - void repartGrid(SPtr<Grid3D> grid, ZoltanPartitioner& zp); + void collectData(SPtr<Grid3D> grid); + void repartGrid(SPtr<Grid3D> grid, ZoltanPartitioner &zp); + private: - SPtr<Communicator> comm; - int numOfDirs; - int numOfLocalParts; - ZoltanGraph *graph; - std::vector<int> vertexGID; - std::vector<int> numEdges; - std::vector<int> nborGID; - std::vector<int> nborProc; + SPtr<Communicator> comm; + int numOfDirs; + int numOfLocalParts; + ZoltanGraph *graph; + std::vector<int> vertexGID; + std::vector<int> numEdges; + std::vector<int> nborGID; + std::vector<int> nborProc; }; #endif